From 4574f36bdceec1ea9051415522085f8b89915f94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jacek=20J=2E=20=C5=81akis?= Date: Wed, 8 Feb 2017 14:57:52 +0100 Subject: [PATCH] deps: vendor code for streaming packages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jacek J. Łakis --- lock.json | 173 +- vendor/github.com/Azure/go-ansiterm/LICENSE | 21 + vendor/github.com/Azure/go-ansiterm/README.md | 12 + .../github.com/Azure/go-ansiterm/constants.go | 188 + .../github.com/Azure/go-ansiterm/context.go | 7 + .../Azure/go-ansiterm/csi_entry_state.go | 49 + .../Azure/go-ansiterm/csi_param_state.go | 38 + .../go-ansiterm/escape_intermediate_state.go | 36 + .../Azure/go-ansiterm/escape_state.go | 47 + .../Azure/go-ansiterm/event_handler.go | 90 + .../Azure/go-ansiterm/ground_state.go | 24 + .../Azure/go-ansiterm/osc_string_state.go | 31 + vendor/github.com/Azure/go-ansiterm/parser.go | 136 + .../go-ansiterm/parser_action_helpers.go | 103 + .../Azure/go-ansiterm/parser_actions.go | 122 + .../Azure/go-ansiterm/parser_test.go | 141 + .../go-ansiterm/parser_test_helpers_test.go | 114 + .../go-ansiterm/parser_test_utilities_test.go | 66 + vendor/github.com/Azure/go-ansiterm/states.go | 71 + .../go-ansiterm/test_event_handler_test.go | 173 + .../github.com/Azure/go-ansiterm/utilities.go | 21 + .../Azure/go-ansiterm/winterm/ansi.go | 182 + .../Azure/go-ansiterm/winterm/api.go | 322 + .../go-ansiterm/winterm/attr_translation.go | 100 + .../go-ansiterm/winterm/cursor_helpers.go | 101 + .../go-ansiterm/winterm/erase_helpers.go | 84 + .../go-ansiterm/winterm/scroll_helper.go | 118 + .../Azure/go-ansiterm/winterm/utilities.go | 9 + .../go-ansiterm/winterm/win_event_handler.go | 726 + .../github.com/PuerkitoBio/purell/.gitignore | 5 + .../github.com/PuerkitoBio/purell/.travis.yml | 7 + vendor/github.com/PuerkitoBio/purell/LICENSE | 12 + .../github.com/PuerkitoBio/purell/README.md | 187 + .../PuerkitoBio/purell/bench_test.go | 57 + .../PuerkitoBio/purell/benchmarks/v0.1.0 | 9 + .../PuerkitoBio/purell/example_test.go | 35 + .../github.com/PuerkitoBio/purell/purell.go | 379 + .../PuerkitoBio/purell/purell_test.go | 768 + .../PuerkitoBio/purell/urlnorm_test.go | 53 + .../github.com/PuerkitoBio/urlesc/.travis.yml | 11 + vendor/github.com/PuerkitoBio/urlesc/LICENSE | 27 + .../github.com/PuerkitoBio/urlesc/README.md | 16 + .../github.com/PuerkitoBio/urlesc/urlesc.go | 180 + .../PuerkitoBio/urlesc/urlesc_test.go | 641 + vendor/github.com/davecgh/go-spew/.gitignore | 22 + vendor/github.com/davecgh/go-spew/.travis.yml | 14 + vendor/github.com/davecgh/go-spew/LICENSE | 15 + vendor/github.com/davecgh/go-spew/README.md | 205 + .../github.com/davecgh/go-spew/cov_report.sh | 22 + .../github.com/davecgh/go-spew/spew/bypass.go | 152 + .../davecgh/go-spew/spew/bypasssafe.go | 38 + .../github.com/davecgh/go-spew/spew/common.go | 341 + .../davecgh/go-spew/spew/common_test.go | 298 + .../github.com/davecgh/go-spew/spew/config.go | 306 + vendor/github.com/davecgh/go-spew/spew/doc.go | 211 + .../github.com/davecgh/go-spew/spew/dump.go | 509 + .../davecgh/go-spew/spew/dump_test.go | 1042 + .../davecgh/go-spew/spew/dumpcgo_test.go | 99 + .../davecgh/go-spew/spew/dumpnocgo_test.go | 26 + .../davecgh/go-spew/spew/example_test.go | 226 + .../github.com/davecgh/go-spew/spew/format.go | 419 + .../davecgh/go-spew/spew/format_test.go | 1558 + .../davecgh/go-spew/spew/internal_test.go | 87 + .../go-spew/spew/internalunsafe_test.go | 102 + .../github.com/davecgh/go-spew/spew/spew.go | 148 + .../davecgh/go-spew/spew/spew_test.go | 320 + .../davecgh/go-spew/spew/testdata/dumpcgo.go | 82 + .../davecgh/go-spew/test_coverage.txt | 61 + .../docker/spdystream/CONTRIBUTING.md | 13 + vendor/github.com/docker/spdystream/LICENSE | 191 + .../github.com/docker/spdystream/LICENSE.docs | 425 + .../github.com/docker/spdystream/MAINTAINERS | 28 + vendor/github.com/docker/spdystream/README.md | 77 + .../docker/spdystream/connection.go | 959 + .../github.com/docker/spdystream/handlers.go | 38 + .../github.com/docker/spdystream/priority.go | 98 + .../docker/spdystream/priority_test.go | 108 + .../docker/spdystream/spdy/dictionary.go | 187 + .../github.com/docker/spdystream/spdy/read.go | 348 + .../docker/spdystream/spdy/spdy_test.go | 644 + .../docker/spdystream/spdy/types.go | 275 + .../docker/spdystream/spdy/write.go | 318 + .../docker/spdystream/spdy_bench_test.go | 113 + .../github.com/docker/spdystream/spdy_test.go | 1171 + vendor/github.com/docker/spdystream/stream.go | 327 + vendor/github.com/docker/spdystream/utils.go | 16 + .../docker/spdystream/ws/connection.go | 65 + .../docker/spdystream/ws/ws_test.go | 175 + .../github.com/emicklei/go-restful/.gitignore | 70 + .../github.com/emicklei/go-restful/CHANGES.md | 220 + vendor/github.com/emicklei/go-restful/LICENSE | 22 + .../github.com/emicklei/go-restful/README.md | 74 + vendor/github.com/emicklei/go-restful/Srcfile | 1 + .../emicklei/go-restful/bench_curly_test.go | 51 + .../emicklei/go-restful/bench_test.go | 43 + .../emicklei/go-restful/bench_test.sh | 10 + .../emicklei/go-restful/compress.go | 123 + .../emicklei/go-restful/compress_test.go | 125 + .../emicklei/go-restful/compressor_cache.go | 103 + .../emicklei/go-restful/compressor_pools.go | 91 + .../emicklei/go-restful/compressors.go | 53 + .../emicklei/go-restful/constants.go | 30 + .../emicklei/go-restful/container.go | 366 + .../emicklei/go-restful/container_test.go | 83 + .../emicklei/go-restful/cors_filter.go | 202 + .../emicklei/go-restful/cors_filter_test.go | 129 + .../emicklei/go-restful/coverage.sh | 2 + .../github.com/emicklei/go-restful/curly.go | 164 + .../emicklei/go-restful/curly_route.go | 52 + .../emicklei/go-restful/curly_test.go | 231 + vendor/github.com/emicklei/go-restful/doc.go | 185 + .../emicklei/go-restful/doc_examples_test.go | 41 + .../emicklei/go-restful/entity_accessors.go | 163 + .../go-restful/entity_accessors_test.go | 69 + .../emicklei/go-restful/examples/.goconvey | 1 + .../examples/google_app_engine/.goconvey | 1 + .../examples/google_app_engine/app.yaml | 20 + .../google_app_engine/datastore/.goconvey | 1 + .../google_app_engine/datastore/app.yaml | 18 + .../google_app_engine/datastore/main.go | 266 + .../restful-appstats-integration.go | 12 + .../google_app_engine/restful-user-service.go | 161 + .../emicklei/go-restful/examples/home.html | 7 + .../examples/msgpack/msgpack_entity.go | 34 + .../examples/msgpack/msgpack_entity_test.go | 160 + .../examples/restful-CORS-filter.go | 68 + .../examples/restful-NCSA-logging.go | 54 + .../examples/restful-basic-authentication.go | 35 + .../examples/restful-cpuprofiler-service.go | 65 + .../examples/restful-curly-router.go | 107 + .../examples/restful-curly-router_test.go | 149 + .../examples/restful-encoding-filter.go | 61 + .../go-restful/examples/restful-filters.go | 114 + .../examples/restful-form-handling.go | 62 + .../examples/restful-hello-world.go | 22 + .../examples/restful-html-template.go | 35 + .../examples/restful-multi-containers.go | 43 + .../examples/restful-no-cache-filter.go | 24 + .../examples/restful-options-filter.go | 51 + .../go-restful/examples/restful-path-tail.go | 26 + .../examples/restful-pre-post-filters.go | 98 + .../examples/restful-resource-functions.go | 63 + .../go-restful/examples/restful-route_test.go | 39 + .../examples/restful-routefunction_test.go | 29 + .../examples/restful-serve-static.go | 47 + .../go-restful/examples/restful-swagger.go | 61 + .../examples/restful-user-resource.go | 152 + .../examples/restful-user-service.go | 143 + .../github.com/emicklei/go-restful/filter.go | 35 + .../emicklei/go-restful/filter_test.go | 141 + .../github.com/emicklei/go-restful/install.sh | 10 + .../github.com/emicklei/go-restful/jsr311.go | 248 + .../emicklei/go-restful/jsr311_test.go | 212 + .../github.com/emicklei/go-restful/log/log.go | 31 + .../github.com/emicklei/go-restful/logger.go | 32 + vendor/github.com/emicklei/go-restful/mime.go | 45 + .../emicklei/go-restful/mime_test.go | 17 + .../emicklei/go-restful/options_filter.go | 26 + .../go-restful/options_filter_test.go | 34 + .../emicklei/go-restful/parameter.go | 114 + .../emicklei/go-restful/path_expression.go | 69 + .../go-restful/path_expression_test.go | 37 + .../github.com/emicklei/go-restful/request.go | 113 + .../emicklei/go-restful/request_test.go | 141 + .../emicklei/go-restful/response.go | 235 + .../emicklei/go-restful/response_test.go | 213 + .../github.com/emicklei/go-restful/route.go | 183 + .../emicklei/go-restful/route_builder.go | 255 + .../emicklei/go-restful/route_builder_test.go | 58 + .../emicklei/go-restful/route_test.go | 127 + .../github.com/emicklei/go-restful/router.go | 18 + .../emicklei/go-restful/service_error.go | 23 + .../emicklei/go-restful/tracer_test.go | 18 + .../emicklei/go-restful/web_service.go | 290 + .../go-restful/web_service_container.go | 39 + .../emicklei/go-restful/web_service_test.go | 343 + .../go-openapi/jsonpointer/.editorconfig | 26 + .../jsonpointer/.github/CONTRIBUTING.md | 117 + .../go-openapi/jsonpointer/.gitignore | 1 + .../go-openapi/jsonpointer/.travis.yml | 13 + .../go-openapi/jsonpointer/CODE_OF_CONDUCT.md | 74 + .../github.com/go-openapi/jsonpointer/LICENSE | 202 + .../go-openapi/jsonpointer/README.md | 15 + .../go-openapi/jsonpointer/pointer.go | 390 + .../go-openapi/jsonpointer/pointer_test.go | 573 + .../jsonreference/.github/CONTRIBUTING.md | 117 + .../go-openapi/jsonreference/.gitignore | 1 + .../go-openapi/jsonreference/.travis.yml | 14 + .../jsonreference/CODE_OF_CONDUCT.md | 74 + .../go-openapi/jsonreference/LICENSE | 202 + .../go-openapi/jsonreference/README.md | 15 + .../go-openapi/jsonreference/reference.go | 156 + .../jsonreference/reference_test.go | 420 + .../github.com/go-openapi/spec/.editorconfig | 26 + .../go-openapi/spec/.github/CONTRIBUTING.md | 117 + vendor/github.com/go-openapi/spec/.gitignore | 2 + vendor/github.com/go-openapi/spec/.travis.yml | 16 + .../go-openapi/spec/CODE_OF_CONDUCT.md | 74 + vendor/github.com/go-openapi/spec/LICENSE | 202 + vendor/github.com/go-openapi/spec/README.md | 5 + .../github.com/go-openapi/spec/auth_test.go | 128 + vendor/github.com/go-openapi/spec/bindata.go | 260 + .../go-openapi/spec/contact_info.go | 24 + .../go-openapi/spec/contact_info_test.go | 37 + vendor/github.com/go-openapi/spec/expander.go | 857 + .../go-openapi/spec/expander_test.go | 1133 + .../go-openapi/spec/external_docs.go | 24 + .../go-openapi/spec/external_docs_test.go | 29 + .../fixtures/expansion/all-the-things.json | 254 + .../spec/fixtures/expansion/circularRefs.json | 54 + .../spec/fixtures/expansion/circularSpec.json | 1 + .../spec/fixtures/expansion/circularSpec.yaml | 67 + .../spec/fixtures/expansion/clickmeter.json | 1 + .../spec/fixtures/expansion/clickmeter.yaml | 6461 ++ .../spec/fixtures/expansion/invalid-refs.json | 85 + .../spec/fixtures/expansion/overflow.json | 124 + .../spec/fixtures/expansion/params.json | 25 + .../spec/fixtures/expansion/schemas1.json | 127 + .../spec/fixtures/expansion/schemas2.json | 161 + .../spec/fixtures/local_expansion/item.json | 18 + .../spec/fixtures/local_expansion/spec.json | 46 + .../spec/fixtures/specs/deeper/arrayProp.json | 6 + .../fixtures/specs/deeper/stringProp.json | 3 + .../go-openapi/spec/fixtures/specs/refed.json | 224 + .../spec/fixtures/specs/resolution.json | 14 + .../spec/fixtures/specs/resolution2.json | 9 + vendor/github.com/go-openapi/spec/header.go | 195 + .../github.com/go-openapi/spec/header_test.go | 90 + vendor/github.com/go-openapi/spec/info.go | 168 + .../github.com/go-openapi/spec/info_test.go | 65 + vendor/github.com/go-openapi/spec/items.go | 219 + .../github.com/go-openapi/spec/items_test.go | 81 + vendor/github.com/go-openapi/spec/license.go | 23 + .../go-openapi/spec/license_test.go | 28 + .../github.com/go-openapi/spec/operation.go | 233 + .../go-openapi/spec/operation_test.go | 85 + .../github.com/go-openapi/spec/parameter.go | 301 + .../go-openapi/spec/parameters_test.go | 156 + .../github.com/go-openapi/spec/path_item.go | 90 + .../go-openapi/spec/path_item_test.go | 81 + vendor/github.com/go-openapi/spec/paths.go | 97 + .../github.com/go-openapi/spec/paths_test.go | 43 + .../go-openapi/spec/properties_test.go | 58 + vendor/github.com/go-openapi/spec/ref.go | 171 + vendor/github.com/go-openapi/spec/response.go | 134 + .../go-openapi/spec/response_test.go | 53 + .../github.com/go-openapi/spec/responses.go | 122 + vendor/github.com/go-openapi/spec/schema.go | 628 + .../github.com/go-openapi/spec/schema_test.go | 205 + .../spec/schemas/jsonschema-draft-04.json | 150 + .../go-openapi/spec/schemas/v2/README.md | 5 + .../go-openapi/spec/schemas/v2/schema.json | 1607 + .../go-openapi/spec/security_scheme.go | 142 + vendor/github.com/go-openapi/spec/spec.go | 86 + .../go-openapi/spec/structs_test.go | 110 + vendor/github.com/go-openapi/spec/swagger.go | 317 + .../go-openapi/spec/swagger_test.go | 365 + vendor/github.com/go-openapi/spec/tag.go | 73 + .../github.com/go-openapi/spec/xml_object.go | 68 + .../go-openapi/spec/xml_object_test.go | 65 + .../github.com/go-openapi/swag/.editorconfig | 26 + .../go-openapi/swag/.github/CONTRIBUTING.md | 117 + vendor/github.com/go-openapi/swag/.gitignore | 1 + vendor/github.com/go-openapi/swag/.travis.yml | 13 + .../go-openapi/swag/CODE_OF_CONDUCT.md | 74 + vendor/github.com/go-openapi/swag/LICENSE | 202 + vendor/github.com/go-openapi/swag/README.md | 12 + vendor/github.com/go-openapi/swag/convert.go | 188 + .../go-openapi/swag/convert_test.go | 215 + .../go-openapi/swag/convert_types.go | 595 + .../go-openapi/swag/convert_types_test.go | 579 + vendor/github.com/go-openapi/swag/json.go | 291 + .../github.com/go-openapi/swag/json_test.go | 163 + vendor/github.com/go-openapi/swag/loading.go | 74 + .../go-openapi/swag/loading_test.go | 47 + vendor/github.com/go-openapi/swag/net.go | 24 + vendor/github.com/go-openapi/swag/net_test.go | 30 + vendor/github.com/go-openapi/swag/path.go | 56 + .../github.com/go-openapi/swag/path_test.go | 118 + vendor/github.com/go-openapi/swag/util.go | 336 + .../github.com/go-openapi/swag/util_test.go | 277 + vendor/github.com/google/gofuzz/.travis.yml | 13 + .../github.com/google/gofuzz/CONTRIBUTING.md | 67 + vendor/github.com/google/gofuzz/LICENSE | 202 + vendor/github.com/google/gofuzz/README.md | 71 + vendor/github.com/google/gofuzz/doc.go | 18 + .../github.com/google/gofuzz/example_test.go | 225 + vendor/github.com/google/gofuzz/fuzz.go | 453 + vendor/github.com/google/gofuzz/fuzz_test.go | 428 + vendor/github.com/mailru/easyjson/.gitignore | 4 + vendor/github.com/mailru/easyjson/.travis.yml | 8 + vendor/github.com/mailru/easyjson/LICENSE | 7 + vendor/github.com/mailru/easyjson/Makefile | 54 + vendor/github.com/mailru/easyjson/README.md | 193 + .../mailru/easyjson/benchmark/codec_test.go | 279 + .../mailru/easyjson/benchmark/data.go | 148 + .../mailru/easyjson/benchmark/data_codec.go | 6911 ++ .../mailru/easyjson/benchmark/data_ffjson.go | 6723 ++ .../mailru/easyjson/benchmark/data_var.go | 350 + .../mailru/easyjson/benchmark/default_test.go | 118 + .../mailru/easyjson/benchmark/dummy_test.go | 11 + .../easyjson/benchmark/easyjson_test.go | 184 + .../mailru/easyjson/benchmark/example.json | 415 + .../mailru/easyjson/benchmark/ffjson_test.go | 190 + .../mailru/easyjson/benchmark/ujson.sh | 7 + .../mailru/easyjson/bootstrap/bootstrap.go | 180 + .../github.com/mailru/easyjson/buffer/pool.go | 207 + .../mailru/easyjson/buffer/pool_test.go | 79 + .../mailru/easyjson/easyjson/main.go | 99 + .../github.com/mailru/easyjson/gen/decoder.go | 458 + .../github.com/mailru/easyjson/gen/encoder.go | 351 + .../mailru/easyjson/gen/generator.go | 438 + .../mailru/easyjson/gen/generator_test.go | 65 + vendor/github.com/mailru/easyjson/helpers.go | 78 + .../mailru/easyjson/jlexer/error.go | 15 + .../mailru/easyjson/jlexer/lexer.go | 1121 + .../mailru/easyjson/jlexer/lexer_test.go | 251 + .../mailru/easyjson/jwriter/writer.go | 302 + .../mailru/easyjson/opt/gotemplate_Bool.go | 79 + .../mailru/easyjson/opt/gotemplate_Float32.go | 79 + .../mailru/easyjson/opt/gotemplate_Float64.go | 79 + .../mailru/easyjson/opt/gotemplate_Int.go | 79 + .../mailru/easyjson/opt/gotemplate_Int16.go | 79 + .../mailru/easyjson/opt/gotemplate_Int32.go | 79 + .../mailru/easyjson/opt/gotemplate_Int64.go | 79 + .../mailru/easyjson/opt/gotemplate_Int8.go | 79 + .../mailru/easyjson/opt/gotemplate_String.go | 79 + .../mailru/easyjson/opt/gotemplate_Uint.go | 79 + .../mailru/easyjson/opt/gotemplate_Uint16.go | 79 + .../mailru/easyjson/opt/gotemplate_Uint32.go | 79 + .../mailru/easyjson/opt/gotemplate_Uint64.go | 79 + .../mailru/easyjson/opt/gotemplate_Uint8.go | 79 + .../mailru/easyjson/opt/optional/opt.go | 80 + vendor/github.com/mailru/easyjson/opt/opts.go | 22 + .../mailru/easyjson/parser/parser.go | 91 + .../mailru/easyjson/parser/parser_unix.go | 33 + .../mailru/easyjson/parser/parser_windows.go | 37 + vendor/github.com/mailru/easyjson/raw.go | 45 + .../mailru/easyjson/tests/basic_test.go | 221 + .../github.com/mailru/easyjson/tests/data.go | 650 + .../mailru/easyjson/tests/errors.go | 23 + .../mailru/easyjson/tests/errors_test.go | 243 + .../mailru/easyjson/tests/named_type.go | 22 + .../mailru/easyjson/tests/nested_easy.go | 25 + .../mailru/easyjson/tests/nothing.go | 3 + .../mailru/easyjson/tests/omitempty.go | 12 + .../mailru/easyjson/tests/required_test.go | 28 + .../github.com/mailru/easyjson/tests/snake.go | 10 + .../mitchellh/go-wordwrap/LICENSE.md | 21 + .../mitchellh/go-wordwrap/README.md | 39 + .../mitchellh/go-wordwrap/wordwrap.go | 73 + .../mitchellh/go-wordwrap/wordwrap_test.go | 85 + .../opencontainers/runc/Godeps/Godeps.json | 87 + .../opencontainers/runc/Godeps/Readme | 5 + .../runc/Godeps/_workspace/.gitignore | 2 + .../src/github.com/Sirupsen/logrus/.gitignore | 1 + .../github.com/Sirupsen/logrus/.travis.yml | 8 + .../github.com/Sirupsen/logrus/CHANGELOG.md | 7 + .../src/github.com/Sirupsen/logrus/LICENSE | 21 + .../src/github.com/Sirupsen/logrus/README.md | 349 + .../src/github.com/Sirupsen/logrus/entry.go | 252 + .../Sirupsen/logrus/examples/basic/basic.go | 50 + .../Sirupsen/logrus/examples/hook/hook.go | 30 + .../github.com/Sirupsen/logrus/exported.go | 188 + .../github.com/Sirupsen/logrus/formatter.go | 48 + .../logrus/formatters/logstash/logstash.go | 56 + .../src/github.com/Sirupsen/logrus/hooks.go | 34 + .../logrus/hooks/airbrake/airbrake.go | 54 + .../Sirupsen/logrus/hooks/bugsnag/bugsnag.go | 68 + .../logrus/hooks/papertrail/README.md | 28 + .../logrus/hooks/papertrail/papertrail.go | 55 + .../Sirupsen/logrus/hooks/sentry/README.md | 61 + .../Sirupsen/logrus/hooks/sentry/sentry.go | 100 + .../Sirupsen/logrus/hooks/syslog/README.md | 20 + .../Sirupsen/logrus/hooks/syslog/syslog.go | 59 + .../Sirupsen/logrus/json_formatter.go | 40 + .../src/github.com/Sirupsen/logrus/logger.go | 203 + .../src/github.com/Sirupsen/logrus/logrus.go | 94 + .../Sirupsen/logrus/terminal_darwin.go | 12 + .../Sirupsen/logrus/terminal_freebsd.go | 20 + .../Sirupsen/logrus/terminal_linux.go | 12 + .../Sirupsen/logrus/terminal_notwindows.go | 21 + .../Sirupsen/logrus/terminal_openbsd.go | 7 + .../Sirupsen/logrus/terminal_windows.go | 27 + .../Sirupsen/logrus/text_formatter.go | 149 + .../src/github.com/Sirupsen/logrus/writer.go | 31 + .../src/github.com/coreos/go-systemd/LICENSE | 191 + .../coreos/go-systemd/activation/files.go | 52 + .../coreos/go-systemd/activation/listeners.go | 60 + .../go-systemd/activation/packetconns.go | 37 + .../github.com/coreos/go-systemd/dbus/dbus.go | 213 + .../coreos/go-systemd/dbus/methods.go | 565 + .../coreos/go-systemd/dbus/properties.go | 237 + .../github.com/coreos/go-systemd/dbus/set.go | 47 + .../coreos/go-systemd/dbus/subscription.go | 250 + .../go-systemd/dbus/subscription_set.go | 57 + .../github.com/coreos/go-systemd/util/util.go | 90 + .../coreos/go-systemd/util/util_cgo.go | 174 + .../coreos/go-systemd/util/util_stub.go | 23 + .../src/github.com/coreos/pkg/LICENSE | 202 + .../src/github.com/coreos/pkg/NOTICE | 5 + .../github.com/coreos/pkg/dlopen/dlopen.go | 82 + .../coreos/pkg/dlopen/dlopen_example.go | 56 + .../src/github.com/docker/docker/LICENSE | 191 + .../src/github.com/docker/docker/NOTICE | 19 + .../docker/docker/contrib/syntax/vim/LICENSE | 22 + .../docker/docs/project/images/red_notice.png | Bin 0 -> 45387 bytes .../docker/docker/pkg/mflag/LICENSE | 27 + .../docker/docker/pkg/mount/flags.go | 69 + .../docker/docker/pkg/mount/flags_freebsd.go | 48 + .../docker/docker/pkg/mount/flags_linux.go | 85 + .../docker/pkg/mount/flags_unsupported.go | 30 + .../docker/docker/pkg/mount/mount.go | 74 + .../docker/pkg/mount/mounter_freebsd.go | 59 + .../docker/docker/pkg/mount/mounter_linux.go | 21 + .../docker/pkg/mount/mounter_unsupported.go | 11 + .../docker/docker/pkg/mount/mountinfo.go | 40 + .../docker/pkg/mount/mountinfo_freebsd.go | 41 + .../docker/pkg/mount/mountinfo_linux.go | 95 + .../docker/pkg/mount/mountinfo_unsupported.go | 12 + .../docker/pkg/mount/sharedsubtree_linux.go | 70 + .../docker/docker/pkg/symlink/LICENSE.APACHE | 191 + .../docker/docker/pkg/symlink/LICENSE.BSD | 27 + .../docker/docker/pkg/symlink/README.md | 5 + .../docker/docker/pkg/symlink/fs.go | 131 + .../docker/docker/pkg/term/tc_linux_cgo.go | 48 + .../docker/docker/pkg/term/tc_other.go | 19 + .../github.com/docker/docker/pkg/term/term.go | 118 + .../docker/docker/pkg/term/term_windows.go | 139 + .../docker/docker/pkg/term/termios_darwin.go | 65 + .../docker/docker/pkg/term/termios_freebsd.go | 65 + .../docker/docker/pkg/term/termios_linux.go | 46 + .../pkg/term/winconsole/console_windows.go | 1053 + .../pkg/term/winconsole/term_emulator.go | 234 + .../src/github.com/docker/go-units/LICENSE | 191 + .../src/github.com/docker/go-units/README.md | 11 + .../github.com/docker/go-units/duration.go | 33 + .../src/github.com/docker/go-units/size.go | 95 + .../github.com/godbus/dbus/CONTRIBUTING.md | 50 + .../src/github.com/godbus/dbus/LICENSE | 25 + .../src/github.com/godbus/dbus/MAINTAINERS | 2 + .../github.com/godbus/dbus/README.markdown | 41 + .../src/github.com/godbus/dbus/auth.go | 253 + .../github.com/godbus/dbus/auth_external.go | 26 + .../src/github.com/godbus/dbus/auth_sha1.go | 102 + .../src/github.com/godbus/dbus/call.go | 36 + .../src/github.com/godbus/dbus/conn.go | 625 + .../src/github.com/godbus/dbus/conn_darwin.go | 21 + .../src/github.com/godbus/dbus/conn_other.go | 27 + .../src/github.com/godbus/dbus/dbus.go | 258 + .../src/github.com/godbus/dbus/decoder.go | 228 + .../src/github.com/godbus/dbus/doc.go | 63 + .../src/github.com/godbus/dbus/encoder.go | 208 + .../src/github.com/godbus/dbus/export.go | 411 + .../src/github.com/godbus/dbus/homedir.go | 28 + .../github.com/godbus/dbus/homedir_dynamic.go | 15 + .../github.com/godbus/dbus/homedir_static.go | 45 + .../github.com/godbus/dbus/introspect/call.go | 27 + .../godbus/dbus/introspect/introspect.go | 86 + .../godbus/dbus/introspect/introspectable.go | 76 + .../src/github.com/godbus/dbus/message.go | 346 + .../src/github.com/godbus/dbus/object.go | 126 + .../src/github.com/godbus/dbus/prop/prop.go | 264 + .../src/github.com/godbus/dbus/sig.go | 257 + .../godbus/dbus/transport_darwin.go | 6 + .../godbus/dbus/transport_generic.go | 35 + .../github.com/godbus/dbus/transport_unix.go | 196 + .../dbus/transport_unixcred_dragonfly.go | 95 + .../godbus/dbus/transport_unixcred_linux.go | 25 + .../src/github.com/godbus/dbus/variant.go | 139 + .../github.com/godbus/dbus/variant_lexer.go | 284 + .../github.com/godbus/dbus/variant_parser.go | 817 + .../src/github.com/golang/protobuf/LICENSE | 31 + .../github.com/golang/protobuf/proto/Makefile | 43 + .../github.com/golang/protobuf/proto/clone.go | 197 + .../golang/protobuf/proto/decode.go | 821 + .../golang/protobuf/proto/encode.go | 1286 + .../github.com/golang/protobuf/proto/equal.go | 256 + .../golang/protobuf/proto/extensions.go | 362 + .../github.com/golang/protobuf/proto/lib.go | 759 + .../golang/protobuf/proto/message_set.go | 287 + .../golang/protobuf/proto/pointer_reflect.go | 479 + .../golang/protobuf/proto/pointer_unsafe.go | 266 + .../golang/protobuf/proto/properties.go | 737 + .../protobuf/proto/proto3_proto/Makefile | 44 + .../protobuf/proto/proto3_proto/proto3.proto | 58 + .../github.com/golang/protobuf/proto/text.go | 789 + .../golang/protobuf/proto/text_parser.go | 757 + .../src/github.com/mrunalp/fileutils/LICENSE | 191 + .../github.com/mrunalp/fileutils/README.md | 5 + .../github.com/mrunalp/fileutils/fileutils.go | 161 + .../github.com/mrunalp/fileutils/idtools.go | 49 + .../opencontainers/runtime-spec/LICENSE | 191 + .../runtime-spec/specs-go/config.go | 535 + .../runtime-spec/specs-go/state.go | 17 + .../runtime-spec/specs-go/version.go | 18 + .../src/github.com/pquerna/ffjson/LICENSE | 202 + .../src/github.com/pquerna/ffjson/NOTICE | 8 + .../pquerna/ffjson/fflib/v1/buffer.go | 414 + .../pquerna/ffjson/fflib/v1/buffer_nopool.go | 11 + .../pquerna/ffjson/fflib/v1/buffer_pool.go | 105 + .../pquerna/ffjson/fflib/v1/bytenum.go | 88 + .../pquerna/ffjson/fflib/v1/decimal.go | 378 + .../pquerna/ffjson/fflib/v1/extfloat.go | 668 + .../pquerna/ffjson/fflib/v1/fold.go | 121 + .../pquerna/ffjson/fflib/v1/ftoa.go | 542 + .../pquerna/ffjson/fflib/v1/internal/atof.go | 936 + .../pquerna/ffjson/fflib/v1/internal/atoi.go | 213 + .../ffjson/fflib/v1/internal/extfloat.go | 668 + .../pquerna/ffjson/fflib/v1/internal/ftoa.go | 475 + .../pquerna/ffjson/fflib/v1/iota.go | 161 + .../pquerna/ffjson/fflib/v1/jsonstring.go | 512 + .../pquerna/ffjson/fflib/v1/lexer.go | 944 + .../pquerna/ffjson/fflib/v1/reader.go | 509 + .../ffjson/fflib/v1/reader_scan_amd64.go | 49 + .../ffjson/fflib/v1/reader_scan_amd64.s | 22 + .../ffjson/fflib/v1/reader_scan_generic.go | 36 + .../seccomp/libseccomp-golang/LICENSE | 22 + .../seccomp/libseccomp-golang/README | 26 + .../seccomp/libseccomp-golang/seccomp.go | 857 + .../libseccomp-golang/seccomp_internal.go | 506 + .../github.com/syndtr/gocapability/LICENSE | 24 + .../gocapability/capability/capability.go | 72 + .../capability/capability_linux.go | 650 + .../capability/capability_noop.go | 19 + .../syndtr/gocapability/capability/enum.go | 268 + .../gocapability/capability/enum_gen.go | 129 + .../gocapability/capability/enumgen/gen.go | 92 + .../gocapability/capability/syscall_linux.go | 154 + .../src/github.com/urfave/cli/.gitignore | 2 + .../src/github.com/urfave/cli/.travis.yml | 36 + .../src/github.com/urfave/cli/CHANGELOG.md | 336 + .../src/github.com/urfave/cli/LICENSE | 21 + .../src/github.com/urfave/cli/README.md | 1313 + .../github.com/urfave/cli/altsrc/altsrc.go | 3 + .../src/github.com/urfave/cli/altsrc/flag.go | 263 + .../urfave/cli/altsrc/flag_generated.go | 256 + .../urfave/cli/altsrc/input_source_context.go | 21 + .../urfave/cli/altsrc/map_input_source.go | 248 + .../urfave/cli/altsrc/toml_file_loader.go | 113 + .../urfave/cli/altsrc/yaml_file_loader.go | 84 + .../src/github.com/urfave/cli/app.go | 502 + .../src/github.com/urfave/cli/appveyor.yml | 24 + .../urfave/cli/autocomplete/bash_autocomplete | 14 + .../urfave/cli/autocomplete/zsh_autocomplete | 5 + .../src/github.com/urfave/cli/category.go | 44 + .../src/github.com/urfave/cli/cli.go | 21 + .../src/github.com/urfave/cli/command.go | 284 + .../src/github.com/urfave/cli/context.go | 264 + .../src/github.com/urfave/cli/errors.go | 98 + .../src/github.com/urfave/cli/flag-types.json | 93 + .../src/github.com/urfave/cli/flag.go | 621 + .../github.com/urfave/cli/flag_generated.go | 627 + .../src/github.com/urfave/cli/funcs.go | 28 + .../github.com/urfave/cli/generate-flag-types | 248 + .../src/github.com/urfave/cli/help.go | 267 + .../src/github.com/urfave/cli/runtests | 122 + .../vishvananda/netlink/.travis.yml | 3 + .../github.com/vishvananda/netlink/LICENSE | 192 + .../github.com/vishvananda/netlink/Makefile | 29 + .../github.com/vishvananda/netlink/README.md | 89 + .../github.com/vishvananda/netlink/addr.go | 43 + .../vishvananda/netlink/addr_linux.go | 128 + .../github.com/vishvananda/netlink/filter.go | 55 + .../vishvananda/netlink/filter_linux.go | 191 + .../github.com/vishvananda/netlink/link.go | 223 + .../vishvananda/netlink/link_linux.go | 750 + .../github.com/vishvananda/netlink/neigh.go | 22 + .../vishvananda/netlink/neigh_linux.go | 189 + .../github.com/vishvananda/netlink/netlink.go | 39 + .../netlink/netlink_unspecified.go | 143 + .../vishvananda/netlink/nl/addr_linux.go | 47 + .../vishvananda/netlink/nl/link_linux.go | 104 + .../vishvananda/netlink/nl/nl_linux.go | 418 + .../vishvananda/netlink/nl/route_linux.go | 42 + .../vishvananda/netlink/nl/tc_linux.go | 359 + .../vishvananda/netlink/nl/xfrm_linux.go | 258 + .../netlink/nl/xfrm_policy_linux.go | 119 + .../netlink/nl/xfrm_state_linux.go | 221 + .../vishvananda/netlink/protinfo.go | 53 + .../vishvananda/netlink/protinfo_linux.go | 60 + .../github.com/vishvananda/netlink/qdisc.go | 138 + .../vishvananda/netlink/qdisc_linux.go | 263 + .../github.com/vishvananda/netlink/route.go | 35 + .../vishvananda/netlink/route_linux.go | 225 + .../github.com/vishvananda/netlink/xfrm.go | 64 + .../vishvananda/netlink/xfrm_policy.go | 59 + .../vishvananda/netlink/xfrm_policy_linux.go | 127 + .../vishvananda/netlink/xfrm_state.go | 53 + .../vishvananda/netlink/xfrm_state_linux.go | 181 + vendor/github.com/spf13/pflag/.gitignore | 2 + vendor/github.com/spf13/pflag/.travis.yml | 20 + vendor/github.com/spf13/pflag/LICENSE | 28 + vendor/github.com/spf13/pflag/README.md | 277 + vendor/github.com/spf13/pflag/bool.go | 94 + vendor/github.com/spf13/pflag/bool_slice.go | 147 + .../github.com/spf13/pflag/bool_slice_test.go | 215 + vendor/github.com/spf13/pflag/bool_test.go | 179 + vendor/github.com/spf13/pflag/count.go | 94 + vendor/github.com/spf13/pflag/count_test.go | 52 + vendor/github.com/spf13/pflag/duration.go | 86 + vendor/github.com/spf13/pflag/example_test.go | 77 + vendor/github.com/spf13/pflag/export_test.go | 29 + vendor/github.com/spf13/pflag/flag.go | 1063 + vendor/github.com/spf13/pflag/flag_test.go | 1006 + vendor/github.com/spf13/pflag/float32.go | 88 + vendor/github.com/spf13/pflag/float64.go | 84 + vendor/github.com/spf13/pflag/golangflag.go | 101 + .../github.com/spf13/pflag/golangflag_test.go | 39 + vendor/github.com/spf13/pflag/int.go | 84 + vendor/github.com/spf13/pflag/int32.go | 88 + vendor/github.com/spf13/pflag/int64.go | 84 + vendor/github.com/spf13/pflag/int8.go | 88 + vendor/github.com/spf13/pflag/int_slice.go | 128 + .../github.com/spf13/pflag/int_slice_test.go | 165 + vendor/github.com/spf13/pflag/ip.go | 94 + vendor/github.com/spf13/pflag/ip_slice.go | 148 + .../github.com/spf13/pflag/ip_slice_test.go | 222 + vendor/github.com/spf13/pflag/ip_test.go | 63 + vendor/github.com/spf13/pflag/ipmask.go | 122 + vendor/github.com/spf13/pflag/ipnet.go | 98 + vendor/github.com/spf13/pflag/ipnet_test.go | 70 + vendor/github.com/spf13/pflag/string.go | 80 + vendor/github.com/spf13/pflag/string_array.go | 103 + .../spf13/pflag/string_array_test.go | 233 + vendor/github.com/spf13/pflag/string_slice.go | 129 + .../spf13/pflag/string_slice_test.go | 253 + vendor/github.com/spf13/pflag/uint.go | 88 + vendor/github.com/spf13/pflag/uint16.go | 88 + vendor/github.com/spf13/pflag/uint32.go | 88 + vendor/github.com/spf13/pflag/uint64.go | 88 + vendor/github.com/spf13/pflag/uint8.go | 88 + vendor/github.com/spf13/pflag/uint_slice.go | 126 + .../github.com/spf13/pflag/uint_slice_test.go | 161 + vendor/github.com/spf13/pflag/verify/all.sh | 69 + vendor/github.com/spf13/pflag/verify/gofmt.sh | 19 + .../github.com/spf13/pflag/verify/golint.sh | 15 + vendor/github.com/ugorji/go/LICENSE | 22 + vendor/github.com/ugorji/go/README.md | 20 + vendor/github.com/ugorji/go/codec/0doc.go | 199 + vendor/github.com/ugorji/go/codec/README.md | 148 + vendor/github.com/ugorji/go/codec/binc.go | 929 + vendor/github.com/ugorji/go/codec/cbor.go | 592 + .../github.com/ugorji/go/codec/cbor_test.go | 205 + .../github.com/ugorji/go/codec/codec_test.go | 1508 + .../ugorji/go/codec/codecgen/README.md | 37 + .../ugorji/go/codec/codecgen/gen.go | 317 + .../github.com/ugorji/go/codec/codecgen/z.go | 3 + .../ugorji/go/codec/codecgen_test.go | 24 + vendor/github.com/ugorji/go/codec/decode.go | 2066 + .../github.com/ugorji/go/codec/decode_go.go | 16 + .../github.com/ugorji/go/codec/decode_go14.go | 14 + vendor/github.com/ugorji/go/codec/encode.go | 1461 + .../ugorji/go/codec/fast-path.generated.go | 39352 ++++++++ .../ugorji/go/codec/fast-path.go.tmpl | 527 + .../ugorji/go/codec/fast-path.not.go | 34 + .../ugorji/go/codec/gen-dec-array.go.tmpl | 104 + .../ugorji/go/codec/gen-dec-map.go.tmpl | 58 + .../ugorji/go/codec/gen-helper.generated.go | 243 + .../ugorji/go/codec/gen-helper.go.tmpl | 372 + .../ugorji/go/codec/gen.generated.go | 175 + vendor/github.com/ugorji/go/codec/gen.go | 2014 + vendor/github.com/ugorji/go/codec/gen_15.go | 12 + vendor/github.com/ugorji/go/codec/gen_16.go | 12 + vendor/github.com/ugorji/go/codec/gen_17.go | 10 + vendor/github.com/ugorji/go/codec/helper.go | 1314 + .../ugorji/go/codec/helper_internal.go | 242 + .../ugorji/go/codec/helper_not_unsafe.go | 20 + .../github.com/ugorji/go/codec/helper_test.go | 259 + .../ugorji/go/codec/helper_unsafe.go | 49 + vendor/github.com/ugorji/go/codec/json.go | 1234 + vendor/github.com/ugorji/go/codec/msgpack.go | 852 + vendor/github.com/ugorji/go/codec/noop.go | 213 + vendor/github.com/ugorji/go/codec/prebuild.go | 3 + vendor/github.com/ugorji/go/codec/prebuild.sh | 199 + vendor/github.com/ugorji/go/codec/py_test.go | 30 + vendor/github.com/ugorji/go/codec/rpc.go | 180 + vendor/github.com/ugorji/go/codec/simple.go | 526 + .../ugorji/go/codec/test-cbor-goldens.json | 639 + vendor/github.com/ugorji/go/codec/test.py | 126 + vendor/github.com/ugorji/go/codec/tests.sh | 107 + vendor/github.com/ugorji/go/codec/time.go | 233 + .../github.com/ugorji/go/codec/values_test.go | 203 + vendor/github.com/ugorji/go/msgpack.org.md | 47 + vendor/golang.org/x/text/.gitattributes | 10 + vendor/golang.org/x/text/.gitignore | 3 + vendor/golang.org/x/text/AUTHORS | 3 + vendor/golang.org/x/text/CONTRIBUTING.md | 31 + vendor/golang.org/x/text/CONTRIBUTORS | 3 + vendor/golang.org/x/text/LICENSE | 27 + vendor/golang.org/x/text/PATENTS | 22 + vendor/golang.org/x/text/README | 23 + vendor/golang.org/x/text/cases/cases.go | 162 + vendor/golang.org/x/text/cases/context.go | 376 + .../golang.org/x/text/cases/context_test.go | 438 + .../golang.org/x/text/cases/example_test.go | 53 + vendor/golang.org/x/text/cases/fold.go | 34 + vendor/golang.org/x/text/cases/fold_test.go | 51 + vendor/golang.org/x/text/cases/gen.go | 839 + vendor/golang.org/x/text/cases/gen_trieval.go | 219 + vendor/golang.org/x/text/cases/icu.go | 61 + vendor/golang.org/x/text/cases/icu_test.go | 210 + vendor/golang.org/x/text/cases/info.go | 82 + vendor/golang.org/x/text/cases/map.go | 816 + vendor/golang.org/x/text/cases/map_test.go | 950 + vendor/golang.org/x/text/cases/tables.go | 2211 + vendor/golang.org/x/text/cases/tables_test.go | 1154 + vendor/golang.org/x/text/cases/trieval.go | 215 + vendor/golang.org/x/text/cmd/gotext/doc.go | 35 + .../golang.org/x/text/cmd/gotext/extract.go | 195 + vendor/golang.org/x/text/cmd/gotext/main.go | 356 + .../golang.org/x/text/cmd/gotext/message.go | 127 + vendor/golang.org/x/text/codereview.cfg | 1 + .../x/text/collate/build/builder.go | 703 + .../x/text/collate/build/builder_test.go | 290 + .../x/text/collate/build/colelem.go | 294 + .../x/text/collate/build/colelem_test.go | 215 + .../x/text/collate/build/contract.go | 309 + .../x/text/collate/build/contract_test.go | 266 + .../golang.org/x/text/collate/build/order.go | 393 + .../x/text/collate/build/order_test.go | 229 + .../golang.org/x/text/collate/build/table.go | 81 + .../golang.org/x/text/collate/build/trie.go | 290 + .../x/text/collate/build/trie_test.go | 107 + vendor/golang.org/x/text/collate/collate.go | 403 + .../golang.org/x/text/collate/collate_test.go | 482 + .../golang.org/x/text/collate/export_test.go | 51 + vendor/golang.org/x/text/collate/index.go | 32 + .../golang.org/x/text/collate/maketables.go | 553 + vendor/golang.org/x/text/collate/option.go | 239 + .../golang.org/x/text/collate/option_test.go | 209 + vendor/golang.org/x/text/collate/reg_test.go | 230 + vendor/golang.org/x/text/collate/sort.go | 81 + vendor/golang.org/x/text/collate/sort_test.go | 55 + .../golang.org/x/text/collate/table_test.go | 291 + vendor/golang.org/x/text/collate/tables.go | 73789 ++++++++++++++++ .../x/text/collate/tools/colcmp/Makefile | 7 + .../x/text/collate/tools/colcmp/chars.go | 1156 + .../x/text/collate/tools/colcmp/col.go | 97 + .../x/text/collate/tools/colcmp/colcmp.go | 529 + .../x/text/collate/tools/colcmp/darwin.go | 111 + .../x/text/collate/tools/colcmp/gen.go | 183 + .../x/text/collate/tools/colcmp/icu.go | 209 + vendor/golang.org/x/text/currency/common.go | 66 + vendor/golang.org/x/text/currency/currency.go | 185 + .../x/text/currency/currency_test.go | 171 + .../x/text/currency/example_test.go | 27 + vendor/golang.org/x/text/currency/format.go | 215 + .../golang.org/x/text/currency/format_test.go | 70 + vendor/golang.org/x/text/currency/gen.go | 400 + .../golang.org/x/text/currency/gen_common.go | 70 + vendor/golang.org/x/text/currency/query.go | 152 + .../golang.org/x/text/currency/query_test.go | 107 + vendor/golang.org/x/text/currency/tables.go | 2573 + .../golang.org/x/text/currency/tables_test.go | 93 + vendor/golang.org/x/text/doc.go | 13 + .../x/text/encoding/charmap/charmap.go | 209 + .../x/text/encoding/charmap/charmap_test.go | 56 + .../x/text/encoding/charmap/maketables.go | 556 + .../x/text/encoding/charmap/tables.go | 7410 ++ vendor/golang.org/x/text/encoding/encoding.go | 335 + .../x/text/encoding/encoding_test.go | 1148 + .../x/text/encoding/example_test.go | 42 + .../x/text/encoding/htmlindex/gen.go | 170 + .../x/text/encoding/htmlindex/htmlindex.go | 86 + .../text/encoding/htmlindex/htmlindex_test.go | 144 + .../x/text/encoding/htmlindex/map.go | 105 + .../x/text/encoding/htmlindex/tables.go | 352 + .../x/text/encoding/ianaindex/example_test.go | 26 + .../x/text/encoding/ianaindex/ianaindex.go | 67 + .../text/encoding/internal/identifier/gen.go | 137 + .../internal/identifier/identifier.go | 81 + .../text/encoding/internal/identifier/mib.go | 1621 + .../x/text/encoding/internal/internal.go | 75 + .../x/text/encoding/japanese/all.go | 12 + .../x/text/encoding/japanese/all_test.go | 80 + .../x/text/encoding/japanese/eucjp.go | 211 + .../x/text/encoding/japanese/iso2022jp.go | 296 + .../x/text/encoding/japanese/maketables.go | 161 + .../x/text/encoding/japanese/shiftjis.go | 189 + .../x/text/encoding/japanese/tables.go | 26971 ++++++ .../x/text/encoding/korean/all_test.go | 47 + .../x/text/encoding/korean/euckr.go | 178 + .../x/text/encoding/korean/maketables.go | 143 + .../x/text/encoding/korean/tables.go | 34152 +++++++ .../x/text/encoding/simplifiedchinese/all.go | 12 + .../encoding/simplifiedchinese/all_test.go | 50 + .../x/text/encoding/simplifiedchinese/gbk.go | 281 + .../encoding/simplifiedchinese/hzgb2312.go | 240 + .../encoding/simplifiedchinese/maketables.go | 161 + .../text/encoding/simplifiedchinese/tables.go | 43999 +++++++++ .../encoding/testdata/candide-gb18030.txt | 510 + .../encoding/testdata/candide-utf-16le.txt | Bin 0 -> 51932 bytes .../encoding/testdata/candide-utf-32be.txt | Bin 0 -> 103864 bytes .../text/encoding/testdata/candide-utf-8.txt | 510 + .../testdata/candide-windows-1252.txt | 510 + .../encoding/testdata/rashomon-euc-jp.txt | 178 + .../testdata/rashomon-iso-2022-jp.txt | 178 + .../encoding/testdata/rashomon-shift-jis.txt | 178 + .../text/encoding/testdata/rashomon-utf-8.txt | 178 + ...nzi-bingfa-gb-levels-1-and-2-hz-gb2312.txt | 107 + .../sunzi-bingfa-gb-levels-1-and-2-utf-8.txt | 107 + .../testdata/sunzi-bingfa-simplified-gbk.txt | 107 + .../sunzi-bingfa-simplified-utf-8.txt | 107 + .../sunzi-bingfa-traditional-big5.txt | 106 + .../sunzi-bingfa-traditional-utf-8.txt | 106 + .../testdata/unsu-joh-eun-nal-euc-kr.txt | 175 + .../testdata/unsu-joh-eun-nal-utf-8.txt | 175 + .../encoding/traditionalchinese/all_test.go | 45 + .../text/encoding/traditionalchinese/big5.go | 198 + .../encoding/traditionalchinese/maketables.go | 140 + .../encoding/traditionalchinese/tables.go | 37142 ++++++++ .../x/text/encoding/unicode/override.go | 82 + .../x/text/encoding/unicode/unicode.go | 434 + .../x/text/encoding/unicode/unicode_test.go | 178 + .../x/text/encoding/unicode/utf32/utf32.go | 296 + .../text/encoding/unicode/utf32/utf32_test.go | 210 + vendor/golang.org/x/text/gen.go | 284 + .../x/text/internal/colltab/collate_test.go | 121 + .../x/text/internal/colltab/collelem.go | 371 + .../x/text/internal/colltab/collelem_test.go | 183 + .../x/text/internal/colltab/colltab.go | 105 + .../x/text/internal/colltab/colltab_test.go | 64 + .../x/text/internal/colltab/contract.go | 145 + .../x/text/internal/colltab/contract_test.go | 131 + .../x/text/internal/colltab/iter.go | 178 + .../x/text/internal/colltab/iter_test.go | 63 + .../x/text/internal/colltab/numeric.go | 236 + .../x/text/internal/colltab/numeric_test.go | 159 + .../x/text/internal/colltab/table.go | 275 + .../x/text/internal/colltab/trie.go | 159 + .../x/text/internal/colltab/trie_test.go | 106 + .../x/text/internal/colltab/weighter.go | 31 + .../x/text/internal/colltab/weighter_test.go | 42 + .../golang.org/x/text/internal/export/README | 4 + .../text/internal/export/idna/common_test.go | 55 + .../x/text/internal/export/idna/gen.go | 259 + .../x/text/internal/export/idna/gen_common.go | 59 + .../x/text/internal/export/idna/gen_test.go | 82 + .../text/internal/export/idna/gen_trieval.go | 118 + .../x/text/internal/export/idna/idna.go | 519 + .../x/text/internal/export/idna/idna_test.go | 250 + .../x/text/internal/export/idna/punycode.go | 201 + .../internal/export/idna/punycode_test.go | 198 + .../x/text/internal/export/idna/tables.go | 4477 + .../x/text/internal/export/idna/trie.go | 69 + .../x/text/internal/export/idna/trieval.go | 114 + .../x/text/internal/format/format.go | 43 + .../x/text/internal/format/plural/plural.go | 38 + vendor/golang.org/x/text/internal/gen.go | 52 + vendor/golang.org/x/text/internal/gen/code.go | 351 + vendor/golang.org/x/text/internal/gen/gen.go | 281 + vendor/golang.org/x/text/internal/gen_test.go | 38 + vendor/golang.org/x/text/internal/internal.go | 51 + .../x/text/internal/internal_test.go | 38 + vendor/golang.org/x/text/internal/match.go | 67 + .../golang.org/x/text/internal/match_test.go | 56 + .../x/text/internal/number/common.go | 92 + .../x/text/internal/number/data_test.go | 194 + .../x/text/internal/number/decimal.go | 416 + .../x/text/internal/number/extfloat.go | 671 + .../golang.org/x/text/internal/number/ftoa.go | 448 + .../golang.org/x/text/internal/number/gen.go | 466 + .../x/text/internal/number/gen_common.go | 96 + .../x/text/internal/number/gen_plural.go | 471 + .../golang.org/x/text/internal/number/itoa.go | 111 + .../x/text/internal/number/number.go | 145 + .../x/text/internal/number/number_test.go | 90 + .../x/text/internal/number/pattern.go | 386 + .../x/text/internal/number/pattern_test.go | 300 + .../x/text/internal/number/plural.go | 119 + .../x/text/internal/number/plural_test.go | 110 + .../x/text/internal/number/tables.go | 1652 + .../x/text/internal/number/tables_test.go | 125 + .../x/text/internal/stringset/set.go | 86 + .../x/text/internal/stringset/set_test.go | 53 + vendor/golang.org/x/text/internal/tables.go | 116 + vendor/golang.org/x/text/internal/tag/tag.go | 100 + .../x/text/internal/tag/tag_test.go | 67 + .../x/text/internal/testtext/codesize.go | 53 + .../x/text/internal/testtext/flag.go | 22 + .../golang.org/x/text/internal/testtext/gc.go | 14 + .../x/text/internal/testtext/gccgo.go | 11 + .../x/text/internal/testtext/go1_6.go | 23 + .../x/text/internal/testtext/go1_7.go | 17 + .../x/text/internal/testtext/text.go | 105 + .../x/text/internal/triegen/compact.go | 58 + .../x/text/internal/triegen/data_test.go | 875 + .../internal/triegen/example_compact_test.go | 71 + .../x/text/internal/triegen/example_test.go | 148 + .../x/text/internal/triegen/gen_test.go | 68 + .../x/text/internal/triegen/print.go | 251 + .../x/text/internal/triegen/triegen.go | 494 + .../x/text/internal/ucd/example_test.go | 81 + vendor/golang.org/x/text/internal/ucd/ucd.go | 376 + .../x/text/internal/ucd/ucd_test.go | 105 + .../internal/utf8internal/utf8internal.go | 87 + vendor/golang.org/x/text/language/Makefile | 16 + vendor/golang.org/x/text/language/common.go | 16 + vendor/golang.org/x/text/language/coverage.go | 197 + .../x/text/language/coverage_test.go | 154 + .../golang.org/x/text/language/data_test.go | 416 + .../x/text/language/display/dict.go | 92 + .../x/text/language/display/dict_test.go | 39 + .../x/text/language/display/display.go | 343 + .../x/text/language/display/display_test.go | 651 + .../x/text/language/display/examples_test.go | 98 + .../x/text/language/display/lookup.go | 251 + .../x/text/language/display/maketables.go | 596 + .../x/text/language/display/tables.go | 50345 +++++++++++ .../x/text/language/examples_test.go | 396 + .../golang.org/x/text/language/gen_common.go | 20 + .../golang.org/x/text/language/gen_index.go | 162 + vendor/golang.org/x/text/language/go1_1.go | 38 + vendor/golang.org/x/text/language/go1_2.go | 11 + .../x/text/language/httpexample_test.go | 48 + vendor/golang.org/x/text/language/index.go | 767 + vendor/golang.org/x/text/language/language.go | 975 + .../x/text/language/language_test.go | 878 + vendor/golang.org/x/text/language/lookup.go | 396 + .../golang.org/x/text/language/lookup_test.go | 457 + .../golang.org/x/text/language/maketables.go | 1648 + vendor/golang.org/x/text/language/match.go | 841 + .../golang.org/x/text/language/match_test.go | 409 + vendor/golang.org/x/text/language/parse.go | 859 + .../golang.org/x/text/language/parse_test.go | 517 + vendor/golang.org/x/text/language/tables.go | 3547 + vendor/golang.org/x/text/language/tags.go | 143 + vendor/golang.org/x/text/message/catalog.go | 113 + .../golang.org/x/text/message/catalog_test.go | 98 + vendor/golang.org/x/text/message/message.go | 185 + .../golang.org/x/text/message/message_test.go | 149 + vendor/golang.org/x/text/runes/cond.go | 187 + vendor/golang.org/x/text/runes/cond_test.go | 282 + .../golang.org/x/text/runes/example_test.go | 60 + vendor/golang.org/x/text/runes/runes.go | 355 + vendor/golang.org/x/text/runes/runes_test.go | 664 + vendor/golang.org/x/text/search/index.go | 35 + vendor/golang.org/x/text/search/pattern.go | 155 + .../golang.org/x/text/search/pattern_test.go | 357 + vendor/golang.org/x/text/search/search.go | 237 + vendor/golang.org/x/text/search/tables.go | 12448 +++ .../x/text/secure/bidirule/bench_test.go | 54 + .../x/text/secure/bidirule/bidirule.go | 342 + .../x/text/secure/bidirule/bidirule_test.go | 825 + vendor/golang.org/x/text/secure/doc.go | 6 + .../x/text/secure/precis/benchmark_test.go | 82 + .../golang.org/x/text/secure/precis/class.go | 36 + .../x/text/secure/precis/class_test.go | 50 + .../x/text/secure/precis/context.go | 139 + vendor/golang.org/x/text/secure/precis/doc.go | 14 + .../x/text/secure/precis/enforce_test.go | 320 + vendor/golang.org/x/text/secure/precis/gen.go | 310 + .../x/text/secure/precis/gen_trieval.go | 68 + .../x/text/secure/precis/nickname.go | 70 + .../x/text/secure/precis/options.go | 153 + .../x/text/secure/precis/profile.go | 388 + .../x/text/secure/precis/profile_test.go | 142 + .../x/text/secure/precis/profiles.go | 69 + .../golang.org/x/text/secure/precis/tables.go | 3788 + .../x/text/secure/precis/tables_test.go | 69 + .../x/text/secure/precis/transformer.go | 32 + .../x/text/secure/precis/trieval.go | 64 + .../x/text/transform/examples_test.go | 37 + .../golang.org/x/text/transform/transform.go | 705 + .../x/text/transform/transform_test.go | 1317 + vendor/golang.org/x/text/unicode/bidi/bidi.go | 198 + .../golang.org/x/text/unicode/bidi/bracket.go | 335 + vendor/golang.org/x/text/unicode/bidi/core.go | 1058 + .../x/text/unicode/bidi/core_test.go | 224 + vendor/golang.org/x/text/unicode/bidi/gen.go | 133 + .../x/text/unicode/bidi/gen_ranges.go | 57 + .../x/text/unicode/bidi/gen_trieval.go | 64 + vendor/golang.org/x/text/unicode/bidi/prop.go | 206 + .../x/text/unicode/bidi/ranges_test.go | 53 + .../golang.org/x/text/unicode/bidi/tables.go | 1779 + .../x/text/unicode/bidi/tables_test.go | 82 + .../golang.org/x/text/unicode/bidi/trieval.go | 60 + vendor/golang.org/x/text/unicode/cldr/base.go | 100 + vendor/golang.org/x/text/unicode/cldr/cldr.go | 130 + .../x/text/unicode/cldr/cldr_test.go | 27 + .../golang.org/x/text/unicode/cldr/collate.go | 359 + .../x/text/unicode/cldr/collate_test.go | 275 + .../x/text/unicode/cldr/data_test.go | 186 + .../golang.org/x/text/unicode/cldr/decode.go | 171 + .../x/text/unicode/cldr/examples_test.go | 21 + .../golang.org/x/text/unicode/cldr/makexml.go | 400 + .../golang.org/x/text/unicode/cldr/resolve.go | 602 + .../x/text/unicode/cldr/resolve_test.go | 368 + .../golang.org/x/text/unicode/cldr/slice.go | 144 + .../x/text/unicode/cldr/slice_test.go | 175 + vendor/golang.org/x/text/unicode/cldr/xml.go | 1456 + vendor/golang.org/x/text/unicode/doc.go | 8 + .../x/text/unicode/norm/composition.go | 514 + .../x/text/unicode/norm/composition_test.go | 130 + .../x/text/unicode/norm/example_iter_test.go | 82 + .../x/text/unicode/norm/example_test.go | 27 + .../x/text/unicode/norm/forminfo.go | 259 + .../x/text/unicode/norm/forminfo_test.go | 54 + .../golang.org/x/text/unicode/norm/input.go | 105 + vendor/golang.org/x/text/unicode/norm/iter.go | 450 + .../x/text/unicode/norm/iter_test.go | 98 + .../x/text/unicode/norm/maketables.go | 978 + .../x/text/unicode/norm/norm_test.go | 14 + .../x/text/unicode/norm/normalize.go | 608 + .../x/text/unicode/norm/normalize_test.go | 1226 + .../x/text/unicode/norm/readwriter.go | 125 + .../x/text/unicode/norm/readwriter_test.go | 56 + .../golang.org/x/text/unicode/norm/tables.go | 7627 ++ .../x/text/unicode/norm/transform.go | 88 + .../x/text/unicode/norm/transform_test.go | 101 + vendor/golang.org/x/text/unicode/norm/trie.go | 54 + .../golang.org/x/text/unicode/norm/triegen.go | 117 + .../x/text/unicode/norm/ucd_test.go | 275 + .../x/text/unicode/rangetable/gen.go | 113 + .../x/text/unicode/rangetable/merge.go | 260 + .../x/text/unicode/rangetable/merge_test.go | 184 + .../x/text/unicode/rangetable/rangetable.go | 70 + .../unicode/rangetable/rangetable_test.go | 55 + .../x/text/unicode/rangetable/tables.go | 5735 ++ .../x/text/unicode/runenames/bits.go | 59 + .../x/text/unicode/runenames/example_test.go | 118 + .../x/text/unicode/runenames/gen.go | 195 + .../x/text/unicode/runenames/gen_bits.go | 63 + .../x/text/unicode/runenames/runenames.go | 48 + .../text/unicode/runenames/runenames_test.go | 46 + .../x/text/unicode/runenames/tables.go | 15514 ++++ vendor/golang.org/x/text/width/common_test.go | 92 + .../golang.org/x/text/width/example_test.go | 52 + vendor/golang.org/x/text/width/gen.go | 115 + vendor/golang.org/x/text/width/gen_common.go | 96 + vendor/golang.org/x/text/width/gen_trieval.go | 34 + vendor/golang.org/x/text/width/kind_string.go | 16 + vendor/golang.org/x/text/width/runes_test.go | 461 + vendor/golang.org/x/text/width/tables.go | 1284 + vendor/golang.org/x/text/width/tables_test.go | 59 + vendor/golang.org/x/text/width/transform.go | 239 + .../golang.org/x/text/width/transform_test.go | 701 + vendor/golang.org/x/text/width/trieval.go | 30 + vendor/golang.org/x/text/width/width.go | 206 + vendor/gopkg.in/inf.v0/LICENSE | 28 + vendor/gopkg.in/inf.v0/benchmark_test.go | 210 + vendor/gopkg.in/inf.v0/dec.go | 615 + vendor/gopkg.in/inf.v0/dec_go1_2_test.go | 33 + vendor/gopkg.in/inf.v0/dec_internal_test.go | 40 + vendor/gopkg.in/inf.v0/dec_test.go | 379 + vendor/gopkg.in/inf.v0/example_test.go | 62 + vendor/gopkg.in/inf.v0/rounder.go | 145 + .../gopkg.in/inf.v0/rounder_example_test.go | 72 + vendor/gopkg.in/inf.v0/rounder_test.go | 109 + vendor/k8s.io/apiserver/.import-restrictions | 10 + vendor/k8s.io/apiserver/LICENSE | 202 + vendor/k8s.io/apiserver/OWNERS | 42 + vendor/k8s.io/apiserver/README.md | 29 + vendor/k8s.io/apiserver/filter-branch-sha | 1 + .../apiserver/hack/sync-from-kubernetes.sh | 61 + vendor/k8s.io/apiserver/kubernetes-sha | 1 + vendor/k8s.io/apiserver/pkg/admission/OWNERS | 10 + .../apiserver/pkg/admission/attributes.go | 85 + .../k8s.io/apiserver/pkg/admission/chain.go | 49 + .../apiserver/pkg/admission/chain_test.go | 154 + .../k8s.io/apiserver/pkg/admission/errors.go | 66 + .../k8s.io/apiserver/pkg/admission/handler.go | 85 + .../apiserver/pkg/admission/interfaces.go | 90 + .../k8s.io/apiserver/pkg/admission/plugins.go | 177 + .../k8s.io/apiserver/pkg/apis/example/doc.go | 22 + .../pkg/apis/example/fuzzer/fuzzer.go | 99 + .../pkg/apis/example/install/install.go | 44 + .../apiserver/pkg/apis/example/register.go | 53 + .../apiserver/pkg/apis/example/types.go | 134 + .../pkg/apis/example/v1/conversion.go | 26 + .../apiserver/pkg/apis/example/v1/defaults.go | 26 + .../apiserver/pkg/apis/example/v1/doc.go | 23 + .../pkg/apis/example/v1/generated.pb.go | 1992 + .../pkg/apis/example/v1/generated.proto | 212 + .../apiserver/pkg/apis/example/v1/register.go | 53 + .../pkg/apis/example/v1/types.generated.go | 22 + .../apiserver/pkg/apis/example/v1/types.go | 192 + .../example/v1/types_swagger_doc_generated.go | 17 + .../example/v1/zz_generated.conversion.go | 216 + .../apis/example/v1/zz_generated.deepcopy.go | 150 + .../apis/example/v1/zz_generated.defaults.go | 21 + .../pkg/apis/example/zz_generated.deepcopy.go | 150 + .../authenticator/interfaces.go | 68 + .../authenticatorfactory/delegating.go | 115 + .../authenticatorfactory/loopback.go | 29 + .../authenticatorfactory/requestheader.go | 31 + .../pkg/authentication/group/group_adder.go | 50 + .../authentication/group/group_adder_test.go | 42 + .../request/anonymous/anonymous.go | 36 + .../request/anonymous/anonymous_test.go | 42 + .../request/bearertoken/bearertoken.go | 63 + .../request/bearertoken/bearertoken_test.go | 105 + .../request/headerrequest/requestheader.go | 178 + .../headerrequest/requestheader_test.go | 159 + .../pkg/authentication/request/union/union.go | 72 + .../request/union/unionauth_test.go | 166 + .../pkg/authentication/request/x509/doc.go | 19 + .../request/x509/testdata/client-expired.pem | 11 + .../request/x509/testdata/client-valid.pem | 11 + .../request/x509/testdata/client.config.json | 24 + .../request/x509/testdata/client.csr.json | 3 + .../request/x509/testdata/generate.sh | 24 + .../x509/testdata/intermediate.config.json | 18 + .../x509/testdata/intermediate.csr.json | 6 + .../request/x509/testdata/intermediate.pem | 11 + .../request/x509/testdata/root.csr.json | 6 + .../request/x509/testdata/root.pem | 11 + .../pkg/authentication/request/x509/x509.go | 185 + .../authentication/request/x509/x509_test.go | 933 + .../pkg/authentication/serviceaccount/util.go | 73 + .../serviceaccount/util_test.go | 82 + .../token/tokenfile/tokenfile.go | 91 + .../token/tokenfile/tokenfile_test.go | 141 + .../apiserver/pkg/authentication/user/doc.go | 19 + .../apiserver/pkg/authentication/user/user.go | 82 + .../authorization/authorizer/interfaces.go | 140 + .../authorization/authorizerfactory/OWNERS | 4 + .../authorizerfactory/authz_test.go | 56 + .../authorizerfactory/builtin.go | 87 + .../authorizerfactory/delegating.go | 47 + .../pkg/authorization/union/union.go | 57 + .../pkg/authorization/union/union_test.go | 83 + .../pkg/endpoints/handlers/negotiation/doc.go | 18 + .../endpoints/handlers/negotiation/errors.go | 61 + .../handlers/negotiation/negotiate.go | 305 + .../handlers/negotiation/negotiate_test.go | 245 + .../apiserver/pkg/endpoints/metrics/OWNERS | 3 + .../pkg/endpoints/metrics/metrics.go | 245 + .../apiserver/pkg/endpoints/request/OWNERS | 2 + .../pkg/endpoints/request/context.go | 145 + .../pkg/endpoints/request/context_test.go | 134 + .../apiserver/pkg/endpoints/request/doc.go | 20 + .../pkg/endpoints/request/requestcontext.go | 117 + .../pkg/endpoints/request/requestinfo.go | 241 + .../pkg/endpoints/request/requestinfo_test.go | 196 + .../apiserver/pkg/features/kube_features.go | 47 + vendor/k8s.io/apiserver/pkg/server/doc.go | 18 + .../apiserver/pkg/server/filters/OWNERS | 3 + .../apiserver/pkg/server/filters/cors.go | 98 + .../apiserver/pkg/server/filters/cors_test.go | 183 + .../apiserver/pkg/server/filters/doc.go | 19 + .../pkg/server/filters/longrunning.go | 40 + .../pkg/server/filters/maxinflight.go | 111 + .../pkg/server/filters/maxinflight_test.go | 240 + .../apiserver/pkg/server/filters/timeout.go | 271 + .../pkg/server/filters/timeout_test.go | 85 + .../apiserver/pkg/server/filters/wrap.go | 76 + .../apiserver/pkg/server/healthz/doc.go | 21 + .../apiserver/pkg/server/healthz/healthz.go | 133 + .../pkg/server/healthz/healthz_test.go | 82 + .../apiserver/pkg/server/httplog/doc.go | 19 + .../apiserver/pkg/server/httplog/log.go | 225 + .../apiserver/pkg/server/httplog/log_test.go | 175 + .../apiserver/pkg/server/options/OWNERS | 14 + .../pkg/server/options/authentication.go | 175 + .../pkg/server/options/authorization.go | 114 + .../apiserver/pkg/server/options/doc.go | 21 + .../apiserver/pkg/server/options/etcd.go | 88 + .../pkg/server/options/server_run_options.go | 204 + .../apiserver/pkg/server/options/serving.go | 220 + .../pkg/server/routes/data/README.md | 12 + .../server/routes/data/swagger/datafile.go | 17087 ++++ vendor/k8s.io/apiserver/pkg/storage/OWNERS | 41 + vendor/k8s.io/apiserver/pkg/storage/cacher.go | 958 + .../pkg/storage/cacher_whitebox_test.go | 56 + vendor/k8s.io/apiserver/pkg/storage/doc.go | 18 + vendor/k8s.io/apiserver/pkg/storage/errors.go | 170 + .../pkg/storage/etcd/metrics/metrics.go | 113 + .../apiserver/pkg/storage/interfaces.go | 181 + .../apiserver/pkg/storage/names/generate.go | 54 + .../pkg/storage/names/generate_test.go | 29 + .../pkg/storage/selection_predicate.go | 90 + .../pkg/storage/selection_predicate_test.go | 119 + .../pkg/storage/storagebackend/OWNERS | 6 + .../pkg/storage/storagebackend/config.go | 48 + .../apiserver/pkg/storage/time_budget.go | 95 + .../apiserver/pkg/storage/time_budget_test.go | 53 + vendor/k8s.io/apiserver/pkg/storage/util.go | 161 + .../k8s.io/apiserver/pkg/storage/util_test.go | 136 + .../apiserver/pkg/storage/watch_cache.go | 468 + .../apiserver/pkg/storage/watch_cache_test.go | 367 + .../k8s.io/apiserver/pkg/util/cache/cache.go | 83 + .../apiserver/pkg/util/cache/cache_test.go | 90 + .../pkg/util/cache/lruexpirecache.go | 85 + .../pkg/util/cache/lruexpirecache_test.go | 68 + .../pkg/util/feature/feature_gate.go | 232 + .../pkg/util/feature/feature_gate_test.go | 159 + .../pkg/util/flag/configuration_map.go | 53 + .../k8s.io/apiserver/pkg/util/flag/flags.go | 51 + .../pkg/util/flag/namedcertkey_flag.go | 113 + .../pkg/util/flag/namedcertkey_flag_test.go | 139 + .../apiserver/pkg/util/flag/string_flag.go | 56 + .../apiserver/pkg/util/flag/tristate.go | 83 + .../apiserver/pkg/util/flushwriter/doc.go | 19 + .../apiserver/pkg/util/flushwriter/writer.go | 53 + .../pkg/util/flushwriter/writer_test.go | 86 + .../k8s.io/apiserver/pkg/util/proxy/dial.go | 106 + .../apiserver/pkg/util/proxy/dial_test.go | 171 + vendor/k8s.io/apiserver/pkg/util/proxy/doc.go | 18 + .../apiserver/pkg/util/proxy/transport.go | 241 + .../pkg/util/proxy/transport_test.go | 261 + .../k8s.io/apiserver/pkg/util/trace/trace.go | 72 + vendor/k8s.io/apiserver/pkg/util/trie/trie.go | 79 + .../apiserver/pkg/util/webhook/webhook.go | 105 + .../apiserver/pkg/util/wsstream/conn.go | 349 + .../apiserver/pkg/util/wsstream/conn_test.go | 272 + .../k8s.io/apiserver/pkg/util/wsstream/doc.go | 21 + .../apiserver/pkg/util/wsstream/stream.go | 177 + .../pkg/util/wsstream/stream_test.go | 294 + .../apiserver/plugin/pkg/authenticator/doc.go | 18 + .../pkg/authenticator/password/allow/allow.go | 38 + .../password/allow/allow_test.go | 47 + .../plugin/pkg/authenticator/password/doc.go | 18 + .../authenticator/password/keystone/doc.go | 20 + .../password/keystone/keystone.go | 94 + .../password/passwordfile/passwordfile.go | 90 + .../passwordfile/passwordfile_test.go | 160 + .../request/basicauth/basicauth.go | 43 + .../request/basicauth/basicauth_test.go | 123 + .../authenticator/token/anytoken/anytoken.go | 42 + .../token/anytoken/anytoken_test.go | 71 + .../pkg/authenticator/token/oidc/OWNERS | 4 + .../pkg/authenticator/token/oidc/oidc.go | 282 + .../pkg/authenticator/token/oidc/oidc_test.go | 336 + .../token/oidc/testing/provider.go | 200 + .../token/tokentest/tokentest.go | 36 + .../authenticator/token/webhook/certs_test.go | 211 + .../authenticator/token/webhook/webhook.go | 131 + .../token/webhook/webhook_test.go | 564 + .../pkg/authorizer/webhook/certs_test.go | 211 + .../plugin/pkg/authorizer/webhook/gencerts.sh | 102 + .../plugin/pkg/authorizer/webhook/webhook.go | 229 + .../pkg/authorizer/webhook/webhook_test.go | 620 + 1234 files changed, 632418 insertions(+), 4 deletions(-) create mode 100644 vendor/github.com/Azure/go-ansiterm/LICENSE create mode 100644 vendor/github.com/Azure/go-ansiterm/README.md create mode 100644 vendor/github.com/Azure/go-ansiterm/constants.go create mode 100644 vendor/github.com/Azure/go-ansiterm/context.go create mode 100644 vendor/github.com/Azure/go-ansiterm/csi_entry_state.go create mode 100644 vendor/github.com/Azure/go-ansiterm/csi_param_state.go create mode 100644 vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go create mode 100644 vendor/github.com/Azure/go-ansiterm/escape_state.go create mode 100644 vendor/github.com/Azure/go-ansiterm/event_handler.go create mode 100644 vendor/github.com/Azure/go-ansiterm/ground_state.go create mode 100644 vendor/github.com/Azure/go-ansiterm/osc_string_state.go create mode 100644 vendor/github.com/Azure/go-ansiterm/parser.go create mode 100644 vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go create mode 100644 vendor/github.com/Azure/go-ansiterm/parser_actions.go create mode 100644 vendor/github.com/Azure/go-ansiterm/parser_test.go create mode 100644 vendor/github.com/Azure/go-ansiterm/parser_test_helpers_test.go create mode 100644 vendor/github.com/Azure/go-ansiterm/parser_test_utilities_test.go create mode 100644 vendor/github.com/Azure/go-ansiterm/states.go create mode 100644 vendor/github.com/Azure/go-ansiterm/test_event_handler_test.go create mode 100644 vendor/github.com/Azure/go-ansiterm/utilities.go create mode 100644 vendor/github.com/Azure/go-ansiterm/winterm/ansi.go create mode 100644 vendor/github.com/Azure/go-ansiterm/winterm/api.go create mode 100644 vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go create mode 100644 vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go create mode 100644 vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go create mode 100644 vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go create mode 100644 vendor/github.com/Azure/go-ansiterm/winterm/utilities.go create mode 100644 vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go create mode 100644 vendor/github.com/PuerkitoBio/purell/.gitignore create mode 100644 vendor/github.com/PuerkitoBio/purell/.travis.yml create mode 100644 vendor/github.com/PuerkitoBio/purell/LICENSE create mode 100644 vendor/github.com/PuerkitoBio/purell/README.md create mode 100644 vendor/github.com/PuerkitoBio/purell/bench_test.go create mode 100644 vendor/github.com/PuerkitoBio/purell/benchmarks/v0.1.0 create mode 100644 vendor/github.com/PuerkitoBio/purell/example_test.go create mode 100644 vendor/github.com/PuerkitoBio/purell/purell.go create mode 100644 vendor/github.com/PuerkitoBio/purell/purell_test.go create mode 100644 vendor/github.com/PuerkitoBio/purell/urlnorm_test.go create mode 100644 vendor/github.com/PuerkitoBio/urlesc/.travis.yml create mode 100644 vendor/github.com/PuerkitoBio/urlesc/LICENSE create mode 100644 vendor/github.com/PuerkitoBio/urlesc/README.md create mode 100644 vendor/github.com/PuerkitoBio/urlesc/urlesc.go create mode 100644 vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go create mode 100644 vendor/github.com/davecgh/go-spew/.gitignore create mode 100644 vendor/github.com/davecgh/go-spew/.travis.yml create mode 100644 vendor/github.com/davecgh/go-spew/LICENSE create mode 100644 vendor/github.com/davecgh/go-spew/README.md create mode 100644 vendor/github.com/davecgh/go-spew/cov_report.sh create mode 100644 vendor/github.com/davecgh/go-spew/spew/bypass.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/bypasssafe.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/common.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/common_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/config.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/doc.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/dump.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/dump_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/example_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/format.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/format_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/internal_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/spew.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/spew_test.go create mode 100644 vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go create mode 100644 vendor/github.com/davecgh/go-spew/test_coverage.txt create mode 100644 vendor/github.com/docker/spdystream/CONTRIBUTING.md create mode 100644 vendor/github.com/docker/spdystream/LICENSE create mode 100644 vendor/github.com/docker/spdystream/LICENSE.docs create mode 100644 vendor/github.com/docker/spdystream/MAINTAINERS create mode 100644 vendor/github.com/docker/spdystream/README.md create mode 100644 vendor/github.com/docker/spdystream/connection.go create mode 100644 vendor/github.com/docker/spdystream/handlers.go create mode 100644 vendor/github.com/docker/spdystream/priority.go create mode 100644 vendor/github.com/docker/spdystream/priority_test.go create mode 100644 vendor/github.com/docker/spdystream/spdy/dictionary.go create mode 100644 vendor/github.com/docker/spdystream/spdy/read.go create mode 100644 vendor/github.com/docker/spdystream/spdy/spdy_test.go create mode 100644 vendor/github.com/docker/spdystream/spdy/types.go create mode 100644 vendor/github.com/docker/spdystream/spdy/write.go create mode 100644 vendor/github.com/docker/spdystream/spdy_bench_test.go create mode 100644 vendor/github.com/docker/spdystream/spdy_test.go create mode 100644 vendor/github.com/docker/spdystream/stream.go create mode 100644 vendor/github.com/docker/spdystream/utils.go create mode 100644 vendor/github.com/docker/spdystream/ws/connection.go create mode 100644 vendor/github.com/docker/spdystream/ws/ws_test.go create mode 100644 vendor/github.com/emicklei/go-restful/.gitignore create mode 100644 vendor/github.com/emicklei/go-restful/CHANGES.md create mode 100644 vendor/github.com/emicklei/go-restful/LICENSE create mode 100644 vendor/github.com/emicklei/go-restful/README.md create mode 100644 vendor/github.com/emicklei/go-restful/Srcfile create mode 100644 vendor/github.com/emicklei/go-restful/bench_curly_test.go create mode 100644 vendor/github.com/emicklei/go-restful/bench_test.go create mode 100644 vendor/github.com/emicklei/go-restful/bench_test.sh create mode 100644 vendor/github.com/emicklei/go-restful/compress.go create mode 100644 vendor/github.com/emicklei/go-restful/compress_test.go create mode 100644 vendor/github.com/emicklei/go-restful/compressor_cache.go create mode 100644 vendor/github.com/emicklei/go-restful/compressor_pools.go create mode 100644 vendor/github.com/emicklei/go-restful/compressors.go create mode 100644 vendor/github.com/emicklei/go-restful/constants.go create mode 100644 vendor/github.com/emicklei/go-restful/container.go create mode 100644 vendor/github.com/emicklei/go-restful/container_test.go create mode 100644 vendor/github.com/emicklei/go-restful/cors_filter.go create mode 100644 vendor/github.com/emicklei/go-restful/cors_filter_test.go create mode 100644 vendor/github.com/emicklei/go-restful/coverage.sh create mode 100644 vendor/github.com/emicklei/go-restful/curly.go create mode 100644 vendor/github.com/emicklei/go-restful/curly_route.go create mode 100644 vendor/github.com/emicklei/go-restful/curly_test.go create mode 100644 vendor/github.com/emicklei/go-restful/doc.go create mode 100644 vendor/github.com/emicklei/go-restful/doc_examples_test.go create mode 100644 vendor/github.com/emicklei/go-restful/entity_accessors.go create mode 100644 vendor/github.com/emicklei/go-restful/entity_accessors_test.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/.goconvey create mode 100644 vendor/github.com/emicklei/go-restful/examples/google_app_engine/.goconvey create mode 100644 vendor/github.com/emicklei/go-restful/examples/google_app_engine/app.yaml create mode 100644 vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/.goconvey create mode 100644 vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/app.yaml create mode 100644 vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/main.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-appstats-integration.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-user-service.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/home.html create mode 100644 vendor/github.com/emicklei/go-restful/examples/msgpack/msgpack_entity.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/msgpack/msgpack_entity_test.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-CORS-filter.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-NCSA-logging.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-basic-authentication.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-cpuprofiler-service.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-curly-router.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-curly-router_test.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-encoding-filter.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-filters.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-form-handling.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-hello-world.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-html-template.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-multi-containers.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-no-cache-filter.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-options-filter.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-path-tail.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-pre-post-filters.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-resource-functions.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-route_test.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-routefunction_test.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-serve-static.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-swagger.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-user-resource.go create mode 100644 vendor/github.com/emicklei/go-restful/examples/restful-user-service.go create mode 100644 vendor/github.com/emicklei/go-restful/filter.go create mode 100644 vendor/github.com/emicklei/go-restful/filter_test.go create mode 100644 vendor/github.com/emicklei/go-restful/install.sh create mode 100644 vendor/github.com/emicklei/go-restful/jsr311.go create mode 100644 vendor/github.com/emicklei/go-restful/jsr311_test.go create mode 100644 vendor/github.com/emicklei/go-restful/log/log.go create mode 100644 vendor/github.com/emicklei/go-restful/logger.go create mode 100644 vendor/github.com/emicklei/go-restful/mime.go create mode 100644 vendor/github.com/emicklei/go-restful/mime_test.go create mode 100644 vendor/github.com/emicklei/go-restful/options_filter.go create mode 100644 vendor/github.com/emicklei/go-restful/options_filter_test.go create mode 100644 vendor/github.com/emicklei/go-restful/parameter.go create mode 100644 vendor/github.com/emicklei/go-restful/path_expression.go create mode 100644 vendor/github.com/emicklei/go-restful/path_expression_test.go create mode 100644 vendor/github.com/emicklei/go-restful/request.go create mode 100644 vendor/github.com/emicklei/go-restful/request_test.go create mode 100644 vendor/github.com/emicklei/go-restful/response.go create mode 100644 vendor/github.com/emicklei/go-restful/response_test.go create mode 100644 vendor/github.com/emicklei/go-restful/route.go create mode 100644 vendor/github.com/emicklei/go-restful/route_builder.go create mode 100644 vendor/github.com/emicklei/go-restful/route_builder_test.go create mode 100644 vendor/github.com/emicklei/go-restful/route_test.go create mode 100644 vendor/github.com/emicklei/go-restful/router.go create mode 100644 vendor/github.com/emicklei/go-restful/service_error.go create mode 100644 vendor/github.com/emicklei/go-restful/tracer_test.go create mode 100644 vendor/github.com/emicklei/go-restful/web_service.go create mode 100644 vendor/github.com/emicklei/go-restful/web_service_container.go create mode 100644 vendor/github.com/emicklei/go-restful/web_service_test.go create mode 100644 vendor/github.com/go-openapi/jsonpointer/.editorconfig create mode 100644 vendor/github.com/go-openapi/jsonpointer/.github/CONTRIBUTING.md create mode 100644 vendor/github.com/go-openapi/jsonpointer/.gitignore create mode 100644 vendor/github.com/go-openapi/jsonpointer/.travis.yml create mode 100644 vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md create mode 100644 vendor/github.com/go-openapi/jsonpointer/LICENSE create mode 100644 vendor/github.com/go-openapi/jsonpointer/README.md create mode 100644 vendor/github.com/go-openapi/jsonpointer/pointer.go create mode 100644 vendor/github.com/go-openapi/jsonpointer/pointer_test.go create mode 100644 vendor/github.com/go-openapi/jsonreference/.github/CONTRIBUTING.md create mode 100644 vendor/github.com/go-openapi/jsonreference/.gitignore create mode 100644 vendor/github.com/go-openapi/jsonreference/.travis.yml create mode 100644 vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md create mode 100644 vendor/github.com/go-openapi/jsonreference/LICENSE create mode 100644 vendor/github.com/go-openapi/jsonreference/README.md create mode 100644 vendor/github.com/go-openapi/jsonreference/reference.go create mode 100644 vendor/github.com/go-openapi/jsonreference/reference_test.go create mode 100644 vendor/github.com/go-openapi/spec/.editorconfig create mode 100644 vendor/github.com/go-openapi/spec/.github/CONTRIBUTING.md create mode 100644 vendor/github.com/go-openapi/spec/.gitignore create mode 100644 vendor/github.com/go-openapi/spec/.travis.yml create mode 100644 vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md create mode 100644 vendor/github.com/go-openapi/spec/LICENSE create mode 100644 vendor/github.com/go-openapi/spec/README.md create mode 100644 vendor/github.com/go-openapi/spec/auth_test.go create mode 100644 vendor/github.com/go-openapi/spec/bindata.go create mode 100644 vendor/github.com/go-openapi/spec/contact_info.go create mode 100644 vendor/github.com/go-openapi/spec/contact_info_test.go create mode 100644 vendor/github.com/go-openapi/spec/expander.go create mode 100644 vendor/github.com/go-openapi/spec/expander_test.go create mode 100644 vendor/github.com/go-openapi/spec/external_docs.go create mode 100644 vendor/github.com/go-openapi/spec/external_docs_test.go create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/all-the-things.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/circularRefs.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.yaml create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.yaml create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/invalid-refs.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/overflow.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/params.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/schemas1.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/expansion/schemas2.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/local_expansion/item.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/local_expansion/spec.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/specs/deeper/arrayProp.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/specs/deeper/stringProp.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/specs/refed.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/specs/resolution.json create mode 100644 vendor/github.com/go-openapi/spec/fixtures/specs/resolution2.json create mode 100644 vendor/github.com/go-openapi/spec/header.go create mode 100644 vendor/github.com/go-openapi/spec/header_test.go create mode 100644 vendor/github.com/go-openapi/spec/info.go create mode 100644 vendor/github.com/go-openapi/spec/info_test.go create mode 100644 vendor/github.com/go-openapi/spec/items.go create mode 100644 vendor/github.com/go-openapi/spec/items_test.go create mode 100644 vendor/github.com/go-openapi/spec/license.go create mode 100644 vendor/github.com/go-openapi/spec/license_test.go create mode 100644 vendor/github.com/go-openapi/spec/operation.go create mode 100644 vendor/github.com/go-openapi/spec/operation_test.go create mode 100644 vendor/github.com/go-openapi/spec/parameter.go create mode 100644 vendor/github.com/go-openapi/spec/parameters_test.go create mode 100644 vendor/github.com/go-openapi/spec/path_item.go create mode 100644 vendor/github.com/go-openapi/spec/path_item_test.go create mode 100644 vendor/github.com/go-openapi/spec/paths.go create mode 100644 vendor/github.com/go-openapi/spec/paths_test.go create mode 100644 vendor/github.com/go-openapi/spec/properties_test.go create mode 100644 vendor/github.com/go-openapi/spec/ref.go create mode 100644 vendor/github.com/go-openapi/spec/response.go create mode 100644 vendor/github.com/go-openapi/spec/response_test.go create mode 100644 vendor/github.com/go-openapi/spec/responses.go create mode 100644 vendor/github.com/go-openapi/spec/schema.go create mode 100644 vendor/github.com/go-openapi/spec/schema_test.go create mode 100644 vendor/github.com/go-openapi/spec/schemas/jsonschema-draft-04.json create mode 100644 vendor/github.com/go-openapi/spec/schemas/v2/README.md create mode 100644 vendor/github.com/go-openapi/spec/schemas/v2/schema.json create mode 100644 vendor/github.com/go-openapi/spec/security_scheme.go create mode 100644 vendor/github.com/go-openapi/spec/spec.go create mode 100644 vendor/github.com/go-openapi/spec/structs_test.go create mode 100644 vendor/github.com/go-openapi/spec/swagger.go create mode 100644 vendor/github.com/go-openapi/spec/swagger_test.go create mode 100644 vendor/github.com/go-openapi/spec/tag.go create mode 100644 vendor/github.com/go-openapi/spec/xml_object.go create mode 100644 vendor/github.com/go-openapi/spec/xml_object_test.go create mode 100644 vendor/github.com/go-openapi/swag/.editorconfig create mode 100644 vendor/github.com/go-openapi/swag/.github/CONTRIBUTING.md create mode 100644 vendor/github.com/go-openapi/swag/.gitignore create mode 100644 vendor/github.com/go-openapi/swag/.travis.yml create mode 100644 vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md create mode 100644 vendor/github.com/go-openapi/swag/LICENSE create mode 100644 vendor/github.com/go-openapi/swag/README.md create mode 100644 vendor/github.com/go-openapi/swag/convert.go create mode 100644 vendor/github.com/go-openapi/swag/convert_test.go create mode 100644 vendor/github.com/go-openapi/swag/convert_types.go create mode 100644 vendor/github.com/go-openapi/swag/convert_types_test.go create mode 100644 vendor/github.com/go-openapi/swag/json.go create mode 100644 vendor/github.com/go-openapi/swag/json_test.go create mode 100644 vendor/github.com/go-openapi/swag/loading.go create mode 100644 vendor/github.com/go-openapi/swag/loading_test.go create mode 100644 vendor/github.com/go-openapi/swag/net.go create mode 100644 vendor/github.com/go-openapi/swag/net_test.go create mode 100644 vendor/github.com/go-openapi/swag/path.go create mode 100644 vendor/github.com/go-openapi/swag/path_test.go create mode 100644 vendor/github.com/go-openapi/swag/util.go create mode 100644 vendor/github.com/go-openapi/swag/util_test.go create mode 100644 vendor/github.com/google/gofuzz/.travis.yml create mode 100644 vendor/github.com/google/gofuzz/CONTRIBUTING.md create mode 100644 vendor/github.com/google/gofuzz/LICENSE create mode 100644 vendor/github.com/google/gofuzz/README.md create mode 100644 vendor/github.com/google/gofuzz/doc.go create mode 100644 vendor/github.com/google/gofuzz/example_test.go create mode 100644 vendor/github.com/google/gofuzz/fuzz.go create mode 100644 vendor/github.com/google/gofuzz/fuzz_test.go create mode 100644 vendor/github.com/mailru/easyjson/.gitignore create mode 100644 vendor/github.com/mailru/easyjson/.travis.yml create mode 100644 vendor/github.com/mailru/easyjson/LICENSE create mode 100644 vendor/github.com/mailru/easyjson/Makefile create mode 100644 vendor/github.com/mailru/easyjson/README.md create mode 100644 vendor/github.com/mailru/easyjson/benchmark/codec_test.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/data.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/data_codec.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/data_ffjson.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/data_var.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/default_test.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/dummy_test.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/easyjson_test.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/example.json create mode 100644 vendor/github.com/mailru/easyjson/benchmark/ffjson_test.go create mode 100755 vendor/github.com/mailru/easyjson/benchmark/ujson.sh create mode 100644 vendor/github.com/mailru/easyjson/bootstrap/bootstrap.go create mode 100644 vendor/github.com/mailru/easyjson/buffer/pool.go create mode 100644 vendor/github.com/mailru/easyjson/buffer/pool_test.go create mode 100644 vendor/github.com/mailru/easyjson/easyjson/main.go create mode 100644 vendor/github.com/mailru/easyjson/gen/decoder.go create mode 100644 vendor/github.com/mailru/easyjson/gen/encoder.go create mode 100644 vendor/github.com/mailru/easyjson/gen/generator.go create mode 100644 vendor/github.com/mailru/easyjson/gen/generator_test.go create mode 100644 vendor/github.com/mailru/easyjson/helpers.go create mode 100644 vendor/github.com/mailru/easyjson/jlexer/error.go create mode 100644 vendor/github.com/mailru/easyjson/jlexer/lexer.go create mode 100644 vendor/github.com/mailru/easyjson/jlexer/lexer_test.go create mode 100644 vendor/github.com/mailru/easyjson/jwriter/writer.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Bool.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Float32.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Float64.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Int.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Int16.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Int32.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Int64.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Int8.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_String.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Uint.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Uint16.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Uint32.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Uint64.go create mode 100644 vendor/github.com/mailru/easyjson/opt/gotemplate_Uint8.go create mode 100644 vendor/github.com/mailru/easyjson/opt/optional/opt.go create mode 100644 vendor/github.com/mailru/easyjson/opt/opts.go create mode 100644 vendor/github.com/mailru/easyjson/parser/parser.go create mode 100644 vendor/github.com/mailru/easyjson/parser/parser_unix.go create mode 100644 vendor/github.com/mailru/easyjson/parser/parser_windows.go create mode 100644 vendor/github.com/mailru/easyjson/raw.go create mode 100644 vendor/github.com/mailru/easyjson/tests/basic_test.go create mode 100644 vendor/github.com/mailru/easyjson/tests/data.go create mode 100644 vendor/github.com/mailru/easyjson/tests/errors.go create mode 100644 vendor/github.com/mailru/easyjson/tests/errors_test.go create mode 100644 vendor/github.com/mailru/easyjson/tests/named_type.go create mode 100644 vendor/github.com/mailru/easyjson/tests/nested_easy.go create mode 100644 vendor/github.com/mailru/easyjson/tests/nothing.go create mode 100644 vendor/github.com/mailru/easyjson/tests/omitempty.go create mode 100644 vendor/github.com/mailru/easyjson/tests/required_test.go create mode 100644 vendor/github.com/mailru/easyjson/tests/snake.go create mode 100644 vendor/github.com/mitchellh/go-wordwrap/LICENSE.md create mode 100644 vendor/github.com/mitchellh/go-wordwrap/README.md create mode 100644 vendor/github.com/mitchellh/go-wordwrap/wordwrap.go create mode 100644 vendor/github.com/mitchellh/go-wordwrap/wordwrap_test.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/Godeps.json create mode 100644 vendor/github.com/opencontainers/runc/Godeps/Readme create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/.gitignore create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_darwin.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_freebsd.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_openbsd.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/files.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/listeners.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/packetconns.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/dbus.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/methods.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/properties.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/set.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_set.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util_cgo.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util_stub.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/NOTICE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/dlopen/dlopen.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/dlopen/dlopen_example.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/NOTICE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/contrib/syntax/vim/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/docs/project/images/red_notice.png create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mflag/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_freebsd.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_unsupported.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_freebsd.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_unsupported.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/LICENSE.APACHE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/LICENSE.BSD create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/fs.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/tc_linux_cgo.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/tc_other.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/term.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/term_windows.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_darwin.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_freebsd.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/console_windows.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/term_emulator.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/duration.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/size.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/CONTRIBUTING.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/MAINTAINERS create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/README.markdown create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/auth.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/auth_external.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/auth_sha1.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/call.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/conn.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/conn_darwin.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/conn_other.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/dbus.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/decoder.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/doc.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/encoder.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/export.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/homedir.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/homedir_dynamic.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/homedir_static.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/introspect/call.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/introspect/introspect.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/introspect/introspectable.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/message.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/object.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/prop/prop.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/sig.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/transport_darwin.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/transport_generic.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/transport_unix.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/transport_unixcred_dragonfly.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/transport_unixcred_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/variant.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/variant_lexer.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/variant_parser.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/Makefile create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/mrunalp/fileutils/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/mrunalp/fileutils/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/mrunalp/fileutils/fileutils.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/mrunalp/fileutils/idtools.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/config.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/state.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/version.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/NOTICE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/buffer.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/buffer_nopool.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/buffer_pool.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/bytenum.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/decimal.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/extfloat.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/fold.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/ftoa.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/internal/atof.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/internal/atoi.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/internal/extfloat.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/internal/ftoa.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/iota.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/jsonstring.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/lexer.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/reader.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/reader_scan_amd64.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/reader_scan_amd64.s create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/pquerna/ffjson/fflib/v1/reader_scan_generic.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/seccomp/libseccomp-golang/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/seccomp/libseccomp-golang/README create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/seccomp/libseccomp-golang/seccomp.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/seccomp/libseccomp-golang/seccomp_internal.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/syndtr/gocapability/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_noop.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enum.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enum_gen.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enumgen/gen.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/syscall_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/.gitignore create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/.travis.yml create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/CHANGELOG.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/altsrc/altsrc.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/altsrc/flag.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/altsrc/flag_generated.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/altsrc/input_source_context.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/altsrc/map_input_source.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/altsrc/toml_file_loader.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/altsrc/yaml_file_loader.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/app.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/appveyor.yml create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/autocomplete/bash_autocomplete create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/autocomplete/zsh_autocomplete create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/category.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/cli.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/command.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/context.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/errors.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/flag-types.json create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/flag.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/flag_generated.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/funcs.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/generate-flag-types create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/help.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/urfave/cli/runtests create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/.travis.yml create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/LICENSE create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/Makefile create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/README.md create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/addr.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/addr_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/filter.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/filter_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/link.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/link_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink_unspecified.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/addr_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/link_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/route_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/tc_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_state_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/protinfo.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/protinfo_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/route.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/route_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_policy.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_policy_linux.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state.go create mode 100644 vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_linux.go create mode 100644 vendor/github.com/spf13/pflag/.gitignore create mode 100644 vendor/github.com/spf13/pflag/.travis.yml create mode 100644 vendor/github.com/spf13/pflag/LICENSE create mode 100644 vendor/github.com/spf13/pflag/README.md create mode 100644 vendor/github.com/spf13/pflag/bool.go create mode 100644 vendor/github.com/spf13/pflag/bool_slice.go create mode 100644 vendor/github.com/spf13/pflag/bool_slice_test.go create mode 100644 vendor/github.com/spf13/pflag/bool_test.go create mode 100644 vendor/github.com/spf13/pflag/count.go create mode 100644 vendor/github.com/spf13/pflag/count_test.go create mode 100644 vendor/github.com/spf13/pflag/duration.go create mode 100644 vendor/github.com/spf13/pflag/example_test.go create mode 100644 vendor/github.com/spf13/pflag/export_test.go create mode 100644 vendor/github.com/spf13/pflag/flag.go create mode 100644 vendor/github.com/spf13/pflag/flag_test.go create mode 100644 vendor/github.com/spf13/pflag/float32.go create mode 100644 vendor/github.com/spf13/pflag/float64.go create mode 100644 vendor/github.com/spf13/pflag/golangflag.go create mode 100644 vendor/github.com/spf13/pflag/golangflag_test.go create mode 100644 vendor/github.com/spf13/pflag/int.go create mode 100644 vendor/github.com/spf13/pflag/int32.go create mode 100644 vendor/github.com/spf13/pflag/int64.go create mode 100644 vendor/github.com/spf13/pflag/int8.go create mode 100644 vendor/github.com/spf13/pflag/int_slice.go create mode 100644 vendor/github.com/spf13/pflag/int_slice_test.go create mode 100644 vendor/github.com/spf13/pflag/ip.go create mode 100644 vendor/github.com/spf13/pflag/ip_slice.go create mode 100644 vendor/github.com/spf13/pflag/ip_slice_test.go create mode 100644 vendor/github.com/spf13/pflag/ip_test.go create mode 100644 vendor/github.com/spf13/pflag/ipmask.go create mode 100644 vendor/github.com/spf13/pflag/ipnet.go create mode 100644 vendor/github.com/spf13/pflag/ipnet_test.go create mode 100644 vendor/github.com/spf13/pflag/string.go create mode 100644 vendor/github.com/spf13/pflag/string_array.go create mode 100644 vendor/github.com/spf13/pflag/string_array_test.go create mode 100644 vendor/github.com/spf13/pflag/string_slice.go create mode 100644 vendor/github.com/spf13/pflag/string_slice_test.go create mode 100644 vendor/github.com/spf13/pflag/uint.go create mode 100644 vendor/github.com/spf13/pflag/uint16.go create mode 100644 vendor/github.com/spf13/pflag/uint32.go create mode 100644 vendor/github.com/spf13/pflag/uint64.go create mode 100644 vendor/github.com/spf13/pflag/uint8.go create mode 100644 vendor/github.com/spf13/pflag/uint_slice.go create mode 100644 vendor/github.com/spf13/pflag/uint_slice_test.go create mode 100755 vendor/github.com/spf13/pflag/verify/all.sh create mode 100755 vendor/github.com/spf13/pflag/verify/gofmt.sh create mode 100755 vendor/github.com/spf13/pflag/verify/golint.sh create mode 100644 vendor/github.com/ugorji/go/LICENSE create mode 100644 vendor/github.com/ugorji/go/README.md create mode 100644 vendor/github.com/ugorji/go/codec/0doc.go create mode 100644 vendor/github.com/ugorji/go/codec/README.md create mode 100644 vendor/github.com/ugorji/go/codec/binc.go create mode 100644 vendor/github.com/ugorji/go/codec/cbor.go create mode 100644 vendor/github.com/ugorji/go/codec/cbor_test.go create mode 100644 vendor/github.com/ugorji/go/codec/codec_test.go create mode 100644 vendor/github.com/ugorji/go/codec/codecgen/README.md create mode 100644 vendor/github.com/ugorji/go/codec/codecgen/gen.go create mode 100644 vendor/github.com/ugorji/go/codec/codecgen/z.go create mode 100644 vendor/github.com/ugorji/go/codec/codecgen_test.go create mode 100644 vendor/github.com/ugorji/go/codec/decode.go create mode 100644 vendor/github.com/ugorji/go/codec/decode_go.go create mode 100644 vendor/github.com/ugorji/go/codec/decode_go14.go create mode 100644 vendor/github.com/ugorji/go/codec/encode.go create mode 100644 vendor/github.com/ugorji/go/codec/fast-path.generated.go create mode 100644 vendor/github.com/ugorji/go/codec/fast-path.go.tmpl create mode 100644 vendor/github.com/ugorji/go/codec/fast-path.not.go create mode 100644 vendor/github.com/ugorji/go/codec/gen-dec-array.go.tmpl create mode 100644 vendor/github.com/ugorji/go/codec/gen-dec-map.go.tmpl create mode 100644 vendor/github.com/ugorji/go/codec/gen-helper.generated.go create mode 100644 vendor/github.com/ugorji/go/codec/gen-helper.go.tmpl create mode 100644 vendor/github.com/ugorji/go/codec/gen.generated.go create mode 100644 vendor/github.com/ugorji/go/codec/gen.go create mode 100644 vendor/github.com/ugorji/go/codec/gen_15.go create mode 100644 vendor/github.com/ugorji/go/codec/gen_16.go create mode 100644 vendor/github.com/ugorji/go/codec/gen_17.go create mode 100644 vendor/github.com/ugorji/go/codec/helper.go create mode 100644 vendor/github.com/ugorji/go/codec/helper_internal.go create mode 100644 vendor/github.com/ugorji/go/codec/helper_not_unsafe.go create mode 100644 vendor/github.com/ugorji/go/codec/helper_test.go create mode 100644 vendor/github.com/ugorji/go/codec/helper_unsafe.go create mode 100644 vendor/github.com/ugorji/go/codec/json.go create mode 100644 vendor/github.com/ugorji/go/codec/msgpack.go create mode 100644 vendor/github.com/ugorji/go/codec/noop.go create mode 100644 vendor/github.com/ugorji/go/codec/prebuild.go create mode 100755 vendor/github.com/ugorji/go/codec/prebuild.sh create mode 100644 vendor/github.com/ugorji/go/codec/py_test.go create mode 100644 vendor/github.com/ugorji/go/codec/rpc.go create mode 100644 vendor/github.com/ugorji/go/codec/simple.go create mode 100644 vendor/github.com/ugorji/go/codec/test-cbor-goldens.json create mode 100755 vendor/github.com/ugorji/go/codec/test.py create mode 100755 vendor/github.com/ugorji/go/codec/tests.sh create mode 100644 vendor/github.com/ugorji/go/codec/time.go create mode 100644 vendor/github.com/ugorji/go/codec/values_test.go create mode 100644 vendor/github.com/ugorji/go/msgpack.org.md create mode 100644 vendor/golang.org/x/text/.gitattributes create mode 100644 vendor/golang.org/x/text/.gitignore create mode 100644 vendor/golang.org/x/text/AUTHORS create mode 100644 vendor/golang.org/x/text/CONTRIBUTING.md create mode 100644 vendor/golang.org/x/text/CONTRIBUTORS create mode 100644 vendor/golang.org/x/text/LICENSE create mode 100644 vendor/golang.org/x/text/PATENTS create mode 100644 vendor/golang.org/x/text/README create mode 100644 vendor/golang.org/x/text/cases/cases.go create mode 100644 vendor/golang.org/x/text/cases/context.go create mode 100644 vendor/golang.org/x/text/cases/context_test.go create mode 100644 vendor/golang.org/x/text/cases/example_test.go create mode 100644 vendor/golang.org/x/text/cases/fold.go create mode 100644 vendor/golang.org/x/text/cases/fold_test.go create mode 100644 vendor/golang.org/x/text/cases/gen.go create mode 100644 vendor/golang.org/x/text/cases/gen_trieval.go create mode 100644 vendor/golang.org/x/text/cases/icu.go create mode 100644 vendor/golang.org/x/text/cases/icu_test.go create mode 100644 vendor/golang.org/x/text/cases/info.go create mode 100644 vendor/golang.org/x/text/cases/map.go create mode 100644 vendor/golang.org/x/text/cases/map_test.go create mode 100644 vendor/golang.org/x/text/cases/tables.go create mode 100644 vendor/golang.org/x/text/cases/tables_test.go create mode 100644 vendor/golang.org/x/text/cases/trieval.go create mode 100644 vendor/golang.org/x/text/cmd/gotext/doc.go create mode 100644 vendor/golang.org/x/text/cmd/gotext/extract.go create mode 100644 vendor/golang.org/x/text/cmd/gotext/main.go create mode 100644 vendor/golang.org/x/text/cmd/gotext/message.go create mode 100644 vendor/golang.org/x/text/codereview.cfg create mode 100644 vendor/golang.org/x/text/collate/build/builder.go create mode 100644 vendor/golang.org/x/text/collate/build/builder_test.go create mode 100644 vendor/golang.org/x/text/collate/build/colelem.go create mode 100644 vendor/golang.org/x/text/collate/build/colelem_test.go create mode 100644 vendor/golang.org/x/text/collate/build/contract.go create mode 100644 vendor/golang.org/x/text/collate/build/contract_test.go create mode 100644 vendor/golang.org/x/text/collate/build/order.go create mode 100644 vendor/golang.org/x/text/collate/build/order_test.go create mode 100644 vendor/golang.org/x/text/collate/build/table.go create mode 100644 vendor/golang.org/x/text/collate/build/trie.go create mode 100644 vendor/golang.org/x/text/collate/build/trie_test.go create mode 100644 vendor/golang.org/x/text/collate/collate.go create mode 100644 vendor/golang.org/x/text/collate/collate_test.go create mode 100644 vendor/golang.org/x/text/collate/export_test.go create mode 100644 vendor/golang.org/x/text/collate/index.go create mode 100644 vendor/golang.org/x/text/collate/maketables.go create mode 100644 vendor/golang.org/x/text/collate/option.go create mode 100644 vendor/golang.org/x/text/collate/option_test.go create mode 100644 vendor/golang.org/x/text/collate/reg_test.go create mode 100644 vendor/golang.org/x/text/collate/sort.go create mode 100644 vendor/golang.org/x/text/collate/sort_test.go create mode 100644 vendor/golang.org/x/text/collate/table_test.go create mode 100644 vendor/golang.org/x/text/collate/tables.go create mode 100644 vendor/golang.org/x/text/collate/tools/colcmp/Makefile create mode 100644 vendor/golang.org/x/text/collate/tools/colcmp/chars.go create mode 100644 vendor/golang.org/x/text/collate/tools/colcmp/col.go create mode 100644 vendor/golang.org/x/text/collate/tools/colcmp/colcmp.go create mode 100644 vendor/golang.org/x/text/collate/tools/colcmp/darwin.go create mode 100644 vendor/golang.org/x/text/collate/tools/colcmp/gen.go create mode 100644 vendor/golang.org/x/text/collate/tools/colcmp/icu.go create mode 100644 vendor/golang.org/x/text/currency/common.go create mode 100644 vendor/golang.org/x/text/currency/currency.go create mode 100644 vendor/golang.org/x/text/currency/currency_test.go create mode 100644 vendor/golang.org/x/text/currency/example_test.go create mode 100644 vendor/golang.org/x/text/currency/format.go create mode 100644 vendor/golang.org/x/text/currency/format_test.go create mode 100644 vendor/golang.org/x/text/currency/gen.go create mode 100644 vendor/golang.org/x/text/currency/gen_common.go create mode 100644 vendor/golang.org/x/text/currency/query.go create mode 100644 vendor/golang.org/x/text/currency/query_test.go create mode 100644 vendor/golang.org/x/text/currency/tables.go create mode 100644 vendor/golang.org/x/text/currency/tables_test.go create mode 100644 vendor/golang.org/x/text/doc.go create mode 100644 vendor/golang.org/x/text/encoding/charmap/charmap.go create mode 100644 vendor/golang.org/x/text/encoding/charmap/charmap_test.go create mode 100644 vendor/golang.org/x/text/encoding/charmap/maketables.go create mode 100644 vendor/golang.org/x/text/encoding/charmap/tables.go create mode 100644 vendor/golang.org/x/text/encoding/encoding.go create mode 100644 vendor/golang.org/x/text/encoding/encoding_test.go create mode 100644 vendor/golang.org/x/text/encoding/example_test.go create mode 100644 vendor/golang.org/x/text/encoding/htmlindex/gen.go create mode 100644 vendor/golang.org/x/text/encoding/htmlindex/htmlindex.go create mode 100644 vendor/golang.org/x/text/encoding/htmlindex/htmlindex_test.go create mode 100644 vendor/golang.org/x/text/encoding/htmlindex/map.go create mode 100644 vendor/golang.org/x/text/encoding/htmlindex/tables.go create mode 100644 vendor/golang.org/x/text/encoding/ianaindex/example_test.go create mode 100644 vendor/golang.org/x/text/encoding/ianaindex/ianaindex.go create mode 100644 vendor/golang.org/x/text/encoding/internal/identifier/gen.go create mode 100644 vendor/golang.org/x/text/encoding/internal/identifier/identifier.go create mode 100644 vendor/golang.org/x/text/encoding/internal/identifier/mib.go create mode 100644 vendor/golang.org/x/text/encoding/internal/internal.go create mode 100644 vendor/golang.org/x/text/encoding/japanese/all.go create mode 100644 vendor/golang.org/x/text/encoding/japanese/all_test.go create mode 100644 vendor/golang.org/x/text/encoding/japanese/eucjp.go create mode 100644 vendor/golang.org/x/text/encoding/japanese/iso2022jp.go create mode 100644 vendor/golang.org/x/text/encoding/japanese/maketables.go create mode 100644 vendor/golang.org/x/text/encoding/japanese/shiftjis.go create mode 100644 vendor/golang.org/x/text/encoding/japanese/tables.go create mode 100644 vendor/golang.org/x/text/encoding/korean/all_test.go create mode 100644 vendor/golang.org/x/text/encoding/korean/euckr.go create mode 100644 vendor/golang.org/x/text/encoding/korean/maketables.go create mode 100644 vendor/golang.org/x/text/encoding/korean/tables.go create mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/all.go create mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/all_test.go create mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/gbk.go create mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/hzgb2312.go create mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/maketables.go create mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/tables.go create mode 100644 vendor/golang.org/x/text/encoding/testdata/candide-gb18030.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/candide-utf-16le.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/candide-utf-32be.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/candide-utf-8.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/candide-windows-1252.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/rashomon-euc-jp.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/rashomon-iso-2022-jp.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/rashomon-shift-jis.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/rashomon-utf-8.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/sunzi-bingfa-gb-levels-1-and-2-hz-gb2312.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/sunzi-bingfa-gb-levels-1-and-2-utf-8.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/sunzi-bingfa-simplified-gbk.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/sunzi-bingfa-simplified-utf-8.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/sunzi-bingfa-traditional-big5.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/sunzi-bingfa-traditional-utf-8.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/unsu-joh-eun-nal-euc-kr.txt create mode 100644 vendor/golang.org/x/text/encoding/testdata/unsu-joh-eun-nal-utf-8.txt create mode 100644 vendor/golang.org/x/text/encoding/traditionalchinese/all_test.go create mode 100644 vendor/golang.org/x/text/encoding/traditionalchinese/big5.go create mode 100644 vendor/golang.org/x/text/encoding/traditionalchinese/maketables.go create mode 100644 vendor/golang.org/x/text/encoding/traditionalchinese/tables.go create mode 100644 vendor/golang.org/x/text/encoding/unicode/override.go create mode 100644 vendor/golang.org/x/text/encoding/unicode/unicode.go create mode 100644 vendor/golang.org/x/text/encoding/unicode/unicode_test.go create mode 100644 vendor/golang.org/x/text/encoding/unicode/utf32/utf32.go create mode 100644 vendor/golang.org/x/text/encoding/unicode/utf32/utf32_test.go create mode 100644 vendor/golang.org/x/text/gen.go create mode 100644 vendor/golang.org/x/text/internal/colltab/collate_test.go create mode 100644 vendor/golang.org/x/text/internal/colltab/collelem.go create mode 100644 vendor/golang.org/x/text/internal/colltab/collelem_test.go create mode 100644 vendor/golang.org/x/text/internal/colltab/colltab.go create mode 100644 vendor/golang.org/x/text/internal/colltab/colltab_test.go create mode 100644 vendor/golang.org/x/text/internal/colltab/contract.go create mode 100644 vendor/golang.org/x/text/internal/colltab/contract_test.go create mode 100644 vendor/golang.org/x/text/internal/colltab/iter.go create mode 100644 vendor/golang.org/x/text/internal/colltab/iter_test.go create mode 100644 vendor/golang.org/x/text/internal/colltab/numeric.go create mode 100644 vendor/golang.org/x/text/internal/colltab/numeric_test.go create mode 100644 vendor/golang.org/x/text/internal/colltab/table.go create mode 100644 vendor/golang.org/x/text/internal/colltab/trie.go create mode 100644 vendor/golang.org/x/text/internal/colltab/trie_test.go create mode 100644 vendor/golang.org/x/text/internal/colltab/weighter.go create mode 100644 vendor/golang.org/x/text/internal/colltab/weighter_test.go create mode 100644 vendor/golang.org/x/text/internal/export/README create mode 100644 vendor/golang.org/x/text/internal/export/idna/common_test.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/gen.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/gen_common.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/gen_test.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/gen_trieval.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/idna.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/idna_test.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/punycode.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/punycode_test.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/tables.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/trie.go create mode 100644 vendor/golang.org/x/text/internal/export/idna/trieval.go create mode 100644 vendor/golang.org/x/text/internal/format/format.go create mode 100644 vendor/golang.org/x/text/internal/format/plural/plural.go create mode 100644 vendor/golang.org/x/text/internal/gen.go create mode 100644 vendor/golang.org/x/text/internal/gen/code.go create mode 100644 vendor/golang.org/x/text/internal/gen/gen.go create mode 100644 vendor/golang.org/x/text/internal/gen_test.go create mode 100644 vendor/golang.org/x/text/internal/internal.go create mode 100644 vendor/golang.org/x/text/internal/internal_test.go create mode 100644 vendor/golang.org/x/text/internal/match.go create mode 100644 vendor/golang.org/x/text/internal/match_test.go create mode 100644 vendor/golang.org/x/text/internal/number/common.go create mode 100644 vendor/golang.org/x/text/internal/number/data_test.go create mode 100644 vendor/golang.org/x/text/internal/number/decimal.go create mode 100644 vendor/golang.org/x/text/internal/number/extfloat.go create mode 100644 vendor/golang.org/x/text/internal/number/ftoa.go create mode 100644 vendor/golang.org/x/text/internal/number/gen.go create mode 100644 vendor/golang.org/x/text/internal/number/gen_common.go create mode 100644 vendor/golang.org/x/text/internal/number/gen_plural.go create mode 100644 vendor/golang.org/x/text/internal/number/itoa.go create mode 100644 vendor/golang.org/x/text/internal/number/number.go create mode 100644 vendor/golang.org/x/text/internal/number/number_test.go create mode 100644 vendor/golang.org/x/text/internal/number/pattern.go create mode 100644 vendor/golang.org/x/text/internal/number/pattern_test.go create mode 100644 vendor/golang.org/x/text/internal/number/plural.go create mode 100644 vendor/golang.org/x/text/internal/number/plural_test.go create mode 100644 vendor/golang.org/x/text/internal/number/tables.go create mode 100644 vendor/golang.org/x/text/internal/number/tables_test.go create mode 100644 vendor/golang.org/x/text/internal/stringset/set.go create mode 100644 vendor/golang.org/x/text/internal/stringset/set_test.go create mode 100644 vendor/golang.org/x/text/internal/tables.go create mode 100644 vendor/golang.org/x/text/internal/tag/tag.go create mode 100644 vendor/golang.org/x/text/internal/tag/tag_test.go create mode 100644 vendor/golang.org/x/text/internal/testtext/codesize.go create mode 100644 vendor/golang.org/x/text/internal/testtext/flag.go create mode 100644 vendor/golang.org/x/text/internal/testtext/gc.go create mode 100644 vendor/golang.org/x/text/internal/testtext/gccgo.go create mode 100644 vendor/golang.org/x/text/internal/testtext/go1_6.go create mode 100644 vendor/golang.org/x/text/internal/testtext/go1_7.go create mode 100644 vendor/golang.org/x/text/internal/testtext/text.go create mode 100644 vendor/golang.org/x/text/internal/triegen/compact.go create mode 100644 vendor/golang.org/x/text/internal/triegen/data_test.go create mode 100644 vendor/golang.org/x/text/internal/triegen/example_compact_test.go create mode 100644 vendor/golang.org/x/text/internal/triegen/example_test.go create mode 100644 vendor/golang.org/x/text/internal/triegen/gen_test.go create mode 100644 vendor/golang.org/x/text/internal/triegen/print.go create mode 100644 vendor/golang.org/x/text/internal/triegen/triegen.go create mode 100644 vendor/golang.org/x/text/internal/ucd/example_test.go create mode 100644 vendor/golang.org/x/text/internal/ucd/ucd.go create mode 100644 vendor/golang.org/x/text/internal/ucd/ucd_test.go create mode 100644 vendor/golang.org/x/text/internal/utf8internal/utf8internal.go create mode 100644 vendor/golang.org/x/text/language/Makefile create mode 100644 vendor/golang.org/x/text/language/common.go create mode 100644 vendor/golang.org/x/text/language/coverage.go create mode 100644 vendor/golang.org/x/text/language/coverage_test.go create mode 100644 vendor/golang.org/x/text/language/data_test.go create mode 100644 vendor/golang.org/x/text/language/display/dict.go create mode 100644 vendor/golang.org/x/text/language/display/dict_test.go create mode 100644 vendor/golang.org/x/text/language/display/display.go create mode 100644 vendor/golang.org/x/text/language/display/display_test.go create mode 100644 vendor/golang.org/x/text/language/display/examples_test.go create mode 100644 vendor/golang.org/x/text/language/display/lookup.go create mode 100644 vendor/golang.org/x/text/language/display/maketables.go create mode 100644 vendor/golang.org/x/text/language/display/tables.go create mode 100644 vendor/golang.org/x/text/language/examples_test.go create mode 100644 vendor/golang.org/x/text/language/gen_common.go create mode 100644 vendor/golang.org/x/text/language/gen_index.go create mode 100644 vendor/golang.org/x/text/language/go1_1.go create mode 100644 vendor/golang.org/x/text/language/go1_2.go create mode 100644 vendor/golang.org/x/text/language/httpexample_test.go create mode 100644 vendor/golang.org/x/text/language/index.go create mode 100644 vendor/golang.org/x/text/language/language.go create mode 100644 vendor/golang.org/x/text/language/language_test.go create mode 100644 vendor/golang.org/x/text/language/lookup.go create mode 100644 vendor/golang.org/x/text/language/lookup_test.go create mode 100644 vendor/golang.org/x/text/language/maketables.go create mode 100644 vendor/golang.org/x/text/language/match.go create mode 100644 vendor/golang.org/x/text/language/match_test.go create mode 100644 vendor/golang.org/x/text/language/parse.go create mode 100644 vendor/golang.org/x/text/language/parse_test.go create mode 100644 vendor/golang.org/x/text/language/tables.go create mode 100644 vendor/golang.org/x/text/language/tags.go create mode 100644 vendor/golang.org/x/text/message/catalog.go create mode 100644 vendor/golang.org/x/text/message/catalog_test.go create mode 100644 vendor/golang.org/x/text/message/message.go create mode 100644 vendor/golang.org/x/text/message/message_test.go create mode 100644 vendor/golang.org/x/text/runes/cond.go create mode 100644 vendor/golang.org/x/text/runes/cond_test.go create mode 100644 vendor/golang.org/x/text/runes/example_test.go create mode 100644 vendor/golang.org/x/text/runes/runes.go create mode 100644 vendor/golang.org/x/text/runes/runes_test.go create mode 100644 vendor/golang.org/x/text/search/index.go create mode 100644 vendor/golang.org/x/text/search/pattern.go create mode 100644 vendor/golang.org/x/text/search/pattern_test.go create mode 100644 vendor/golang.org/x/text/search/search.go create mode 100644 vendor/golang.org/x/text/search/tables.go create mode 100644 vendor/golang.org/x/text/secure/bidirule/bench_test.go create mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule.go create mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule_test.go create mode 100644 vendor/golang.org/x/text/secure/doc.go create mode 100644 vendor/golang.org/x/text/secure/precis/benchmark_test.go create mode 100644 vendor/golang.org/x/text/secure/precis/class.go create mode 100644 vendor/golang.org/x/text/secure/precis/class_test.go create mode 100644 vendor/golang.org/x/text/secure/precis/context.go create mode 100644 vendor/golang.org/x/text/secure/precis/doc.go create mode 100644 vendor/golang.org/x/text/secure/precis/enforce_test.go create mode 100644 vendor/golang.org/x/text/secure/precis/gen.go create mode 100644 vendor/golang.org/x/text/secure/precis/gen_trieval.go create mode 100644 vendor/golang.org/x/text/secure/precis/nickname.go create mode 100644 vendor/golang.org/x/text/secure/precis/options.go create mode 100644 vendor/golang.org/x/text/secure/precis/profile.go create mode 100644 vendor/golang.org/x/text/secure/precis/profile_test.go create mode 100644 vendor/golang.org/x/text/secure/precis/profiles.go create mode 100644 vendor/golang.org/x/text/secure/precis/tables.go create mode 100644 vendor/golang.org/x/text/secure/precis/tables_test.go create mode 100644 vendor/golang.org/x/text/secure/precis/transformer.go create mode 100644 vendor/golang.org/x/text/secure/precis/trieval.go create mode 100644 vendor/golang.org/x/text/transform/examples_test.go create mode 100644 vendor/golang.org/x/text/transform/transform.go create mode 100644 vendor/golang.org/x/text/transform/transform_test.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/bidi.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/bracket.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/core.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/core_test.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/gen.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_ranges.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_trieval.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/prop.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/ranges_test.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/tables.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/tables_test.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/trieval.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/base.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/cldr.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/cldr_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/collate.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/collate_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/data_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/decode.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/examples_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/makexml.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/resolve.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/resolve_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/slice.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/slice_test.go create mode 100644 vendor/golang.org/x/text/unicode/cldr/xml.go create mode 100644 vendor/golang.org/x/text/unicode/doc.go create mode 100644 vendor/golang.org/x/text/unicode/norm/composition.go create mode 100644 vendor/golang.org/x/text/unicode/norm/composition_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/example_iter_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/example_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo.go create mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/input.go create mode 100644 vendor/golang.org/x/text/unicode/norm/iter.go create mode 100644 vendor/golang.org/x/text/unicode/norm/iter_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/maketables.go create mode 100644 vendor/golang.org/x/text/unicode/norm/norm_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/normalize.go create mode 100644 vendor/golang.org/x/text/unicode/norm/normalize_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter.go create mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/tables.go create mode 100644 vendor/golang.org/x/text/unicode/norm/transform.go create mode 100644 vendor/golang.org/x/text/unicode/norm/transform_test.go create mode 100644 vendor/golang.org/x/text/unicode/norm/trie.go create mode 100644 vendor/golang.org/x/text/unicode/norm/triegen.go create mode 100644 vendor/golang.org/x/text/unicode/norm/ucd_test.go create mode 100644 vendor/golang.org/x/text/unicode/rangetable/gen.go create mode 100644 vendor/golang.org/x/text/unicode/rangetable/merge.go create mode 100644 vendor/golang.org/x/text/unicode/rangetable/merge_test.go create mode 100644 vendor/golang.org/x/text/unicode/rangetable/rangetable.go create mode 100644 vendor/golang.org/x/text/unicode/rangetable/rangetable_test.go create mode 100644 vendor/golang.org/x/text/unicode/rangetable/tables.go create mode 100644 vendor/golang.org/x/text/unicode/runenames/bits.go create mode 100644 vendor/golang.org/x/text/unicode/runenames/example_test.go create mode 100644 vendor/golang.org/x/text/unicode/runenames/gen.go create mode 100644 vendor/golang.org/x/text/unicode/runenames/gen_bits.go create mode 100644 vendor/golang.org/x/text/unicode/runenames/runenames.go create mode 100644 vendor/golang.org/x/text/unicode/runenames/runenames_test.go create mode 100644 vendor/golang.org/x/text/unicode/runenames/tables.go create mode 100644 vendor/golang.org/x/text/width/common_test.go create mode 100644 vendor/golang.org/x/text/width/example_test.go create mode 100644 vendor/golang.org/x/text/width/gen.go create mode 100644 vendor/golang.org/x/text/width/gen_common.go create mode 100644 vendor/golang.org/x/text/width/gen_trieval.go create mode 100644 vendor/golang.org/x/text/width/kind_string.go create mode 100644 vendor/golang.org/x/text/width/runes_test.go create mode 100644 vendor/golang.org/x/text/width/tables.go create mode 100644 vendor/golang.org/x/text/width/tables_test.go create mode 100644 vendor/golang.org/x/text/width/transform.go create mode 100644 vendor/golang.org/x/text/width/transform_test.go create mode 100644 vendor/golang.org/x/text/width/trieval.go create mode 100644 vendor/golang.org/x/text/width/width.go create mode 100644 vendor/gopkg.in/inf.v0/LICENSE create mode 100644 vendor/gopkg.in/inf.v0/benchmark_test.go create mode 100644 vendor/gopkg.in/inf.v0/dec.go create mode 100644 vendor/gopkg.in/inf.v0/dec_go1_2_test.go create mode 100644 vendor/gopkg.in/inf.v0/dec_internal_test.go create mode 100644 vendor/gopkg.in/inf.v0/dec_test.go create mode 100644 vendor/gopkg.in/inf.v0/example_test.go create mode 100644 vendor/gopkg.in/inf.v0/rounder.go create mode 100644 vendor/gopkg.in/inf.v0/rounder_example_test.go create mode 100644 vendor/gopkg.in/inf.v0/rounder_test.go create mode 100644 vendor/k8s.io/apiserver/.import-restrictions create mode 100644 vendor/k8s.io/apiserver/LICENSE create mode 100644 vendor/k8s.io/apiserver/OWNERS create mode 100644 vendor/k8s.io/apiserver/README.md create mode 100644 vendor/k8s.io/apiserver/filter-branch-sha create mode 100755 vendor/k8s.io/apiserver/hack/sync-from-kubernetes.sh create mode 100644 vendor/k8s.io/apiserver/kubernetes-sha create mode 100644 vendor/k8s.io/apiserver/pkg/admission/OWNERS create mode 100644 vendor/k8s.io/apiserver/pkg/admission/attributes.go create mode 100644 vendor/k8s.io/apiserver/pkg/admission/chain.go create mode 100644 vendor/k8s.io/apiserver/pkg/admission/chain_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/admission/errors.go create mode 100644 vendor/k8s.io/apiserver/pkg/admission/handler.go create mode 100644 vendor/k8s.io/apiserver/pkg/admission/interfaces.go create mode 100644 vendor/k8s.io/apiserver/pkg/admission/plugins.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/fuzzer/fuzzer.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/install/install.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/register.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/types.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/conversion.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/defaults.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/generated.pb.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/generated.proto create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/register.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/types.generated.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/types.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/types_swagger_doc_generated.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/zz_generated.conversion.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/zz_generated.deepcopy.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/v1/zz_generated.defaults.go create mode 100644 vendor/k8s.io/apiserver/pkg/apis/example/zz_generated.deepcopy.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/authenticator/interfaces.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/authenticatorfactory/delegating.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/authenticatorfactory/loopback.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/authenticatorfactory/requestheader.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/group/group_adder.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/group/group_adder_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/anonymous/anonymous.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/anonymous/anonymous_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/bearertoken/bearertoken.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/bearertoken/bearertoken_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/union/union.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/union/unionauth_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/client-expired.pem create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/client-valid.pem create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/client.config.json create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/client.csr.json create mode 100755 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/generate.sh create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/intermediate.config.json create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/intermediate.csr.json create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/intermediate.pem create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/root.csr.json create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/testdata/root.pem create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/x509.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/request/x509/x509_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/token/tokenfile/tokenfile.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/token/tokenfile/tokenfile_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/user/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/authentication/user/user.go create mode 100644 vendor/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go create mode 100755 vendor/k8s.io/apiserver/pkg/authorization/authorizerfactory/OWNERS create mode 100644 vendor/k8s.io/apiserver/pkg/authorization/authorizerfactory/authz_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go create mode 100644 vendor/k8s.io/apiserver/pkg/authorization/authorizerfactory/delegating.go create mode 100644 vendor/k8s.io/apiserver/pkg/authorization/union/union.go create mode 100644 vendor/k8s.io/apiserver/pkg/authorization/union/union_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate_test.go create mode 100755 vendor/k8s.io/apiserver/pkg/endpoints/metrics/OWNERS create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go create mode 100755 vendor/k8s.io/apiserver/pkg/endpoints/request/OWNERS create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/request/context.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/request/context_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/request/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/request/requestcontext.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go create mode 100644 vendor/k8s.io/apiserver/pkg/endpoints/request/requestinfo_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/features/kube_features.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/doc.go create mode 100755 vendor/k8s.io/apiserver/pkg/server/filters/OWNERS create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/cors.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/cors_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/longrunning.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/maxinflight.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/maxinflight_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/timeout.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/timeout_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/filters/wrap.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/healthz/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/healthz/healthz.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/healthz/healthz_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/httplog/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/httplog/log.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/httplog/log_test.go create mode 100755 vendor/k8s.io/apiserver/pkg/server/options/OWNERS create mode 100644 vendor/k8s.io/apiserver/pkg/server/options/authentication.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/options/authorization.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/options/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/options/etcd.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/options/server_run_options.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/options/serving.go create mode 100644 vendor/k8s.io/apiserver/pkg/server/routes/data/README.md create mode 100644 vendor/k8s.io/apiserver/pkg/server/routes/data/swagger/datafile.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/OWNERS create mode 100644 vendor/k8s.io/apiserver/pkg/storage/cacher.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/cacher_whitebox_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/errors.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/etcd/metrics/metrics.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/interfaces.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/names/generate.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/names/generate_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/selection_predicate.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/selection_predicate_test.go create mode 100755 vendor/k8s.io/apiserver/pkg/storage/storagebackend/OWNERS create mode 100644 vendor/k8s.io/apiserver/pkg/storage/storagebackend/config.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/time_budget.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/time_budget_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/util.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/util_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/watch_cache.go create mode 100644 vendor/k8s.io/apiserver/pkg/storage/watch_cache_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/cache/cache.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/cache/cache_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/cache/lruexpirecache.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/cache/lruexpirecache_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/feature/feature_gate.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/feature/feature_gate_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flag/configuration_map.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flag/flags.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flag/namedcertkey_flag.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flag/namedcertkey_flag_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flag/string_flag.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flag/tristate.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flushwriter/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flushwriter/writer.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/flushwriter/writer_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/proxy/dial.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/proxy/dial_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/proxy/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/proxy/transport.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/proxy/transport_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/trace/trace.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/trie/trie.go create mode 100755 vendor/k8s.io/apiserver/pkg/util/webhook/webhook.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/wsstream/conn.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/wsstream/conn_test.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/wsstream/doc.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/wsstream/stream.go create mode 100644 vendor/k8s.io/apiserver/pkg/util/wsstream/stream_test.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/doc.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/password/allow/allow.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/password/allow/allow_test.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/password/doc.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/password/keystone/doc.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/password/keystone/keystone.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/password/passwordfile/passwordfile.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/password/passwordfile/passwordfile_test.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/request/basicauth/basicauth.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/request/basicauth/basicauth_test.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/anytoken/anytoken.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/anytoken/anytoken_test.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/OWNERS create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc_test.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/testing/provider.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/tokentest/tokentest.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/certs_test.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook_test.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authorizer/webhook/certs_test.go create mode 100755 vendor/k8s.io/apiserver/plugin/pkg/authorizer/webhook/gencerts.sh create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go create mode 100644 vendor/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook_test.go diff --git a/lock.json b/lock.json index f2c449d6..437c7d71 100644 --- a/lock.json +++ b/lock.json @@ -1,6 +1,15 @@ { "memo": "0d3077faf280e4e13e18e56f085053d4ced593c2fcfcb09d7df1aea8f0bba403", "projects": [ + { + "name": "github.com/Azure/go-ansiterm", + "branch": "master", + "revision": "fa152c58bc15761d0200cb75fe958b89a9d4888e", + "packages": [ + ".", + "winterm" + ] + }, { "name": "github.com/BurntSushi/toml", "version": "v0.2.0", @@ -27,6 +36,22 @@ "." ] }, + { + "name": "github.com/PuerkitoBio/purell", + "version": "v1.1.0", + "revision": "0bcb03f4b4d0a9428594752bd2a3b9aa0a9d4bd4", + "packages": [ + "." + ] + }, + { + "name": "github.com/PuerkitoBio/urlesc", + "branch": "master", + "revision": "5bd2802263f21d8788851d5305584c82a5c75d7e", + "packages": [ + "." + ] + }, { "name": "github.com/Sirupsen/logrus", "branch": "master", @@ -128,6 +153,14 @@ "dbus" ] }, + { + "name": "github.com/davecgh/go-spew", + "version": "v1.1.0", + "revision": "346938d642f2ec3594ed81d874461961cd0faa76", + "packages": [ + "spew" + ] + }, { "name": "github.com/docker/distribution", "branch": "master", @@ -175,6 +208,7 @@ "pkg/symlink", "pkg/system", "pkg/tlsconfig", + "pkg/term", "pkg/truncindex", "utils/templates" ] @@ -204,12 +238,27 @@ "packages": [ "." ] + }, + "name": "github.com/docker/spdystream", + "branch": "master", + "revision": "ed496381df8283605c435b86d4fdd6f4f20b8c6e", + "packages": [ + "." + ] + }, + { + "name": "github.com/emicklei/go-restful", + "version": "2.0.0", + "revision": "24f362968e4ac4f9f0a7f6c74ac4d66369716e16", + "packages": [ + "." + ] }, { "name": "github.com/fsnotify/fsnotify", "branch": "master", "revision": "7d7316ed6e1ed2de075aab8dfc76de5d158d66e1", - "packages": [ + "packages": [ "." ] }, @@ -228,6 +277,37 @@ "packages": [ "." ] + }, + "name": "github.com/go-openapi/jsonpointer", + "branch": "master", + "revision": "779f45308c19820f1a69e9a4cd965f496e0da10f", + "packages": [ + "." + ] + }, + { + "name": "github.com/go-openapi/jsonreference", + "branch": "master", + "revision": "36d33bfe519efae5632669801b180bf1a245da3b", + "packages": [ + "." + ] + }, + { + "name": "github.com/go-openapi/spec", + "branch": "master", + "revision": "02fb9cd3430ed0581e0ceb4804d5d4b3cc702694", + "packages": [ + "." + ] + }, + { + "name": "github.com/go-openapi/swag", + "branch": "master", + "revision": "d5f8ebc3b1c55a4cf6489eeae7354f338cfe299e", + "packages": [ + "." + ] }, { "name": "github.com/gogo/protobuf", @@ -248,6 +328,14 @@ "proto" ] }, + { + "name": "github.com/google/gofuzz", + "branch": "master", + "revision": "44d81051d367757e1c7c6a5a86423ece9afcf63c", + "packages": [ + "." + ] + }, { "name": "github.com/gorilla/context", "version": "v1.1", @@ -272,6 +360,15 @@ "." ] }, + { + "name": "github.com/mailru/easyjson", + "branch": "master", + "revision": "99e922cf9de1bc0ab38310c277cff32c2147e747", + "packages": [ + "jlexer", + "jwriter" + ] + }, { "name": "github.com/mattn/go-runewidth", "version": "v0.0.1", @@ -296,6 +393,14 @@ "." ] }, + { + "name": "github.com/mitchellh/go-wordwrap", + "branch": "master", + "revision": "ad45545899c7b13c020ea92b2072220eefad42b8", + "packages": [ + "." + ] + }, { "name": "github.com/mtrmac/gpgme", "branch": "master", @@ -374,6 +479,14 @@ "." ] }, + { + "name": "github.com/spf13/pflag", + "branch": "master", + "revision": "9ff6c6923cfffbcd502984b8e0c80539a94968b7", + "packages": [ + "." + ] + }, { "name": "github.com/syndtr/gocapability", "branch": "master", @@ -390,6 +503,14 @@ "patricia" ] }, + { + "name": "github.com/ugorji/go", + "branch": "master", + "revision": "d23841a297e5489e787e72fceffabf9d2994b52a", + "packages": [ + "codec" + ] + }, { "name": "github.com/urfave/cli", "version": "v1.19.1", @@ -435,7 +556,8 @@ "internal/timeseries", "lex/httplex", "proxy", - "trace" + "trace", + "websocket" ] }, { @@ -447,6 +569,15 @@ "windows" ] }, + { + "name": "golang.org/x/text", + "branch": "master", + "revision": "dafb3384ad25363d928a9e97ce4ad3a2f0667e34", + "packages": [ + "unicode/norm", + "width" + ] + }, { "name": "google.golang.org/grpc", "version": "v1.0.1-GA", @@ -471,6 +602,14 @@ "." ] }, + { + "name": "gopkg.in/inf.v0", + "version": "v0.9.0", + "revision": "3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4", + "packages": [ + "." + ] + }, { "name": "gopkg.in/yaml.v2", "branch": "v2", @@ -484,8 +623,31 @@ "branch": "master", "revision": "21807b270ec15d19215659a5caa08b17f66d6f44", "packages": [ + "pkg/api/errors", + "pkg/api/meta", + "pkg/apimachinery/announced", + "pkg/apimachinery/registered", + "pkg/apis/meta/v1", + "pkg/conversion", "pkg/fields", - "pkg/selection" + "pkg/labels", + "pkg/openapi", + "pkg/runtime", + "pkg/runtime/schema", + "pkg/runtime/serializer", + "pkg/selection", + "pkg/types", + "pkg/util/runtime", + "pkg/util/sets" + ] + }, + { + "name": "k8s.io/apiserver", + "branch": "master", + "revision": "18254ddaaab8024609bdf570493103036d72f86d", + "packages": [ + "pkg/server/httplog", + "pkg/util/wsstream" ] }, { @@ -493,6 +655,7 @@ "branch": "master", "revision": "b766ef93a46ce6dc863462254658ca2861a53314", "packages": [ + "util/clock", "util/homedir" ] }, @@ -501,7 +664,9 @@ "branch": "master", "revision": "760d8e98e8f6ad27aaf50b1a030cb9e7b6859aab", "packages": [ - "pkg/kubelet/api/v1alpha1/runtime" + "pkg/kubelet/api/v1alpha1/runtime", + "pkg/kubelet/server/streaming", + "staging/src/k8s.io/apimachinery/pkg/fields" ] } ] diff --git a/vendor/github.com/Azure/go-ansiterm/LICENSE b/vendor/github.com/Azure/go-ansiterm/LICENSE new file mode 100644 index 00000000..e3d9a64d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Microsoft Corporation + +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/Azure/go-ansiterm/README.md b/vendor/github.com/Azure/go-ansiterm/README.md new file mode 100644 index 00000000..261c041e --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/README.md @@ -0,0 +1,12 @@ +# go-ansiterm + +This is a cross platform Ansi Terminal Emulation library. It reads a stream of Ansi characters and produces the appropriate function calls. The results of the function calls are platform dependent. + +For example the parser might receive "ESC, [, A" as a stream of three characters. This is the code for Cursor Up (http://www.vt100.net/docs/vt510-rm/CUU). The parser then calls the cursor up function (CUU()) on an event handler. The event handler determines what platform specific work must be done to cause the cursor to move up one position. + +The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go). + +See parser_test.go for examples exercising the state machine and generating appropriate function calls. + +----- +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/go-ansiterm/constants.go b/vendor/github.com/Azure/go-ansiterm/constants.go new file mode 100644 index 00000000..96504a33 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/constants.go @@ -0,0 +1,188 @@ +package ansiterm + +const LogEnv = "DEBUG_TERMINAL" + +// ANSI constants +// References: +// -- http://www.ecma-international.org/publications/standards/Ecma-048.htm +// -- http://man7.org/linux/man-pages/man4/console_codes.4.html +// -- http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html +// -- http://en.wikipedia.org/wiki/ANSI_escape_code +// -- http://vt100.net/emu/dec_ansi_parser +// -- http://vt100.net/emu/vt500_parser.svg +// -- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html +// -- http://www.inwap.com/pdp10/ansicode.txt +const ( + // ECMA-48 Set Graphics Rendition + // Note: + // -- Constants leading with an underscore (e.g., _ANSI_xxx) are unsupported or reserved + // -- Fonts could possibly be supported via SetCurrentConsoleFontEx + // -- Windows does not expose the per-window cursor (i.e., caret) blink times + ANSI_SGR_RESET = 0 + ANSI_SGR_BOLD = 1 + ANSI_SGR_DIM = 2 + _ANSI_SGR_ITALIC = 3 + ANSI_SGR_UNDERLINE = 4 + _ANSI_SGR_BLINKSLOW = 5 + _ANSI_SGR_BLINKFAST = 6 + ANSI_SGR_REVERSE = 7 + _ANSI_SGR_INVISIBLE = 8 + _ANSI_SGR_LINETHROUGH = 9 + _ANSI_SGR_FONT_00 = 10 + _ANSI_SGR_FONT_01 = 11 + _ANSI_SGR_FONT_02 = 12 + _ANSI_SGR_FONT_03 = 13 + _ANSI_SGR_FONT_04 = 14 + _ANSI_SGR_FONT_05 = 15 + _ANSI_SGR_FONT_06 = 16 + _ANSI_SGR_FONT_07 = 17 + _ANSI_SGR_FONT_08 = 18 + _ANSI_SGR_FONT_09 = 19 + _ANSI_SGR_FONT_10 = 20 + _ANSI_SGR_DOUBLEUNDERLINE = 21 + ANSI_SGR_BOLD_DIM_OFF = 22 + _ANSI_SGR_ITALIC_OFF = 23 + ANSI_SGR_UNDERLINE_OFF = 24 + _ANSI_SGR_BLINK_OFF = 25 + _ANSI_SGR_RESERVED_00 = 26 + ANSI_SGR_REVERSE_OFF = 27 + _ANSI_SGR_INVISIBLE_OFF = 28 + _ANSI_SGR_LINETHROUGH_OFF = 29 + ANSI_SGR_FOREGROUND_BLACK = 30 + ANSI_SGR_FOREGROUND_RED = 31 + ANSI_SGR_FOREGROUND_GREEN = 32 + ANSI_SGR_FOREGROUND_YELLOW = 33 + ANSI_SGR_FOREGROUND_BLUE = 34 + ANSI_SGR_FOREGROUND_MAGENTA = 35 + ANSI_SGR_FOREGROUND_CYAN = 36 + ANSI_SGR_FOREGROUND_WHITE = 37 + _ANSI_SGR_RESERVED_01 = 38 + ANSI_SGR_FOREGROUND_DEFAULT = 39 + ANSI_SGR_BACKGROUND_BLACK = 40 + ANSI_SGR_BACKGROUND_RED = 41 + ANSI_SGR_BACKGROUND_GREEN = 42 + ANSI_SGR_BACKGROUND_YELLOW = 43 + ANSI_SGR_BACKGROUND_BLUE = 44 + ANSI_SGR_BACKGROUND_MAGENTA = 45 + ANSI_SGR_BACKGROUND_CYAN = 46 + ANSI_SGR_BACKGROUND_WHITE = 47 + _ANSI_SGR_RESERVED_02 = 48 + ANSI_SGR_BACKGROUND_DEFAULT = 49 + // 50 - 65: Unsupported + + ANSI_MAX_CMD_LENGTH = 4096 + + MAX_INPUT_EVENTS = 128 + DEFAULT_WIDTH = 80 + DEFAULT_HEIGHT = 24 + + ANSI_BEL = 0x07 + ANSI_BACKSPACE = 0x08 + ANSI_TAB = 0x09 + ANSI_LINE_FEED = 0x0A + ANSI_VERTICAL_TAB = 0x0B + ANSI_FORM_FEED = 0x0C + ANSI_CARRIAGE_RETURN = 0x0D + ANSI_ESCAPE_PRIMARY = 0x1B + ANSI_ESCAPE_SECONDARY = 0x5B + ANSI_OSC_STRING_ENTRY = 0x5D + ANSI_COMMAND_FIRST = 0x40 + ANSI_COMMAND_LAST = 0x7E + DCS_ENTRY = 0x90 + CSI_ENTRY = 0x9B + OSC_STRING = 0x9D + ANSI_PARAMETER_SEP = ";" + ANSI_CMD_G0 = '(' + ANSI_CMD_G1 = ')' + ANSI_CMD_G2 = '*' + ANSI_CMD_G3 = '+' + ANSI_CMD_DECPNM = '>' + ANSI_CMD_DECPAM = '=' + ANSI_CMD_OSC = ']' + ANSI_CMD_STR_TERM = '\\' + + KEY_CONTROL_PARAM_2 = ";2" + KEY_CONTROL_PARAM_3 = ";3" + KEY_CONTROL_PARAM_4 = ";4" + KEY_CONTROL_PARAM_5 = ";5" + KEY_CONTROL_PARAM_6 = ";6" + KEY_CONTROL_PARAM_7 = ";7" + KEY_CONTROL_PARAM_8 = ";8" + KEY_ESC_CSI = "\x1B[" + KEY_ESC_N = "\x1BN" + KEY_ESC_O = "\x1BO" + + FILL_CHARACTER = ' ' +) + +func getByteRange(start byte, end byte) []byte { + bytes := make([]byte, 0, 32) + for i := start; i <= end; i++ { + bytes = append(bytes, byte(i)) + } + + return bytes +} + +var toGroundBytes = getToGroundBytes() +var executors = getExecuteBytes() + +// SPACE 20+A0 hex Always and everywhere a blank space +// Intermediate 20-2F hex !"#$%&'()*+,-./ +var intermeds = getByteRange(0x20, 0x2F) + +// Parameters 30-3F hex 0123456789:;<=>? +// CSI Parameters 30-39, 3B hex 0123456789; +var csiParams = getByteRange(0x30, 0x3F) + +var csiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...) + +// Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ +var upperCase = getByteRange(0x40, 0x5F) + +// Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~ +var lowerCase = getByteRange(0x60, 0x7E) + +// Alphabetics 40-7E hex (all of upper and lower case) +var alphabetics = append(upperCase, lowerCase...) + +var printables = getByteRange(0x20, 0x7F) + +var escapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E) +var escapeToGroundBytes = getEscapeToGroundBytes() + +// See http://www.vt100.net/emu/vt500_parser.png for description of the complex +// byte ranges below + +func getEscapeToGroundBytes() []byte { + escapeToGroundBytes := getByteRange(0x30, 0x4F) + escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x51, 0x57)...) + escapeToGroundBytes = append(escapeToGroundBytes, 0x59) + escapeToGroundBytes = append(escapeToGroundBytes, 0x5A) + escapeToGroundBytes = append(escapeToGroundBytes, 0x5C) + escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x60, 0x7E)...) + return escapeToGroundBytes +} + +func getExecuteBytes() []byte { + executeBytes := getByteRange(0x00, 0x17) + executeBytes = append(executeBytes, 0x19) + executeBytes = append(executeBytes, getByteRange(0x1C, 0x1F)...) + return executeBytes +} + +func getToGroundBytes() []byte { + groundBytes := []byte{0x18} + groundBytes = append(groundBytes, 0x1A) + groundBytes = append(groundBytes, getByteRange(0x80, 0x8F)...) + groundBytes = append(groundBytes, getByteRange(0x91, 0x97)...) + groundBytes = append(groundBytes, 0x99) + groundBytes = append(groundBytes, 0x9A) + groundBytes = append(groundBytes, 0x9C) + return groundBytes +} + +// Delete 7F hex Always and everywhere ignored +// C1 Control 80-9F hex 32 additional control characters +// G1 Displayable A1-FE hex 94 additional displayable characters +// Special A0+FF hex Same as SPACE and DELETE diff --git a/vendor/github.com/Azure/go-ansiterm/context.go b/vendor/github.com/Azure/go-ansiterm/context.go new file mode 100644 index 00000000..8d66e777 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/context.go @@ -0,0 +1,7 @@ +package ansiterm + +type ansiContext struct { + currentChar byte + paramBuffer []byte + interBuffer []byte +} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go new file mode 100644 index 00000000..1bd6057d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go @@ -0,0 +1,49 @@ +package ansiterm + +type csiEntryState struct { + baseState +} + +func (csiState csiEntryState) Handle(b byte) (s state, e error) { + logger.Infof("CsiEntry::Handle %#x", b) + + nextState, err := csiState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(alphabetics, b): + return csiState.parser.ground, nil + case sliceContains(csiCollectables, b): + return csiState.parser.csiParam, nil + case sliceContains(executors, b): + return csiState, csiState.parser.execute() + } + + return csiState, nil +} + +func (csiState csiEntryState) Transition(s state) error { + logger.Infof("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name()) + csiState.baseState.Transition(s) + + switch s { + case csiState.parser.ground: + return csiState.parser.csiDispatch() + case csiState.parser.csiParam: + switch { + case sliceContains(csiParams, csiState.parser.context.currentChar): + csiState.parser.collectParam() + case sliceContains(intermeds, csiState.parser.context.currentChar): + csiState.parser.collectInter() + } + } + + return nil +} + +func (csiState csiEntryState) Enter() error { + csiState.parser.clear() + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go new file mode 100644 index 00000000..4be35c5f --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go @@ -0,0 +1,38 @@ +package ansiterm + +type csiParamState struct { + baseState +} + +func (csiState csiParamState) Handle(b byte) (s state, e error) { + logger.Infof("CsiParam::Handle %#x", b) + + nextState, err := csiState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(alphabetics, b): + return csiState.parser.ground, nil + case sliceContains(csiCollectables, b): + csiState.parser.collectParam() + return csiState, nil + case sliceContains(executors, b): + return csiState, csiState.parser.execute() + } + + return csiState, nil +} + +func (csiState csiParamState) Transition(s state) error { + logger.Infof("CsiParam::Transition %s --> %s", csiState.Name(), s.Name()) + csiState.baseState.Transition(s) + + switch s { + case csiState.parser.ground: + return csiState.parser.csiDispatch() + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go new file mode 100644 index 00000000..2189eb6b --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go @@ -0,0 +1,36 @@ +package ansiterm + +type escapeIntermediateState struct { + baseState +} + +func (escState escapeIntermediateState) Handle(b byte) (s state, e error) { + logger.Infof("escapeIntermediateState::Handle %#x", b) + nextState, err := escState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(intermeds, b): + return escState, escState.parser.collectInter() + case sliceContains(executors, b): + return escState, escState.parser.execute() + case sliceContains(escapeIntermediateToGroundBytes, b): + return escState.parser.ground, nil + } + + return escState, nil +} + +func (escState escapeIntermediateState) Transition(s state) error { + logger.Infof("escapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) + escState.baseState.Transition(s) + + switch s { + case escState.parser.ground: + return escState.parser.escDispatch() + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_state.go b/vendor/github.com/Azure/go-ansiterm/escape_state.go new file mode 100644 index 00000000..7b1b9ad3 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/escape_state.go @@ -0,0 +1,47 @@ +package ansiterm + +type escapeState struct { + baseState +} + +func (escState escapeState) Handle(b byte) (s state, e error) { + logger.Infof("escapeState::Handle %#x", b) + nextState, err := escState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case b == ANSI_ESCAPE_SECONDARY: + return escState.parser.csiEntry, nil + case b == ANSI_OSC_STRING_ENTRY: + return escState.parser.oscString, nil + case sliceContains(executors, b): + return escState, escState.parser.execute() + case sliceContains(escapeToGroundBytes, b): + return escState.parser.ground, nil + case sliceContains(intermeds, b): + return escState.parser.escapeIntermediate, nil + } + + return escState, nil +} + +func (escState escapeState) Transition(s state) error { + logger.Infof("Escape::Transition %s --> %s", escState.Name(), s.Name()) + escState.baseState.Transition(s) + + switch s { + case escState.parser.ground: + return escState.parser.escDispatch() + case escState.parser.escapeIntermediate: + return escState.parser.collectInter() + } + + return nil +} + +func (escState escapeState) Enter() error { + escState.parser.clear() + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/event_handler.go b/vendor/github.com/Azure/go-ansiterm/event_handler.go new file mode 100644 index 00000000..98087b38 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/event_handler.go @@ -0,0 +1,90 @@ +package ansiterm + +type AnsiEventHandler interface { + // Print + Print(b byte) error + + // Execute C0 commands + Execute(b byte) error + + // CUrsor Up + CUU(int) error + + // CUrsor Down + CUD(int) error + + // CUrsor Forward + CUF(int) error + + // CUrsor Backward + CUB(int) error + + // Cursor to Next Line + CNL(int) error + + // Cursor to Previous Line + CPL(int) error + + // Cursor Horizontal position Absolute + CHA(int) error + + // Vertical line Position Absolute + VPA(int) error + + // CUrsor Position + CUP(int, int) error + + // Horizontal and Vertical Position (depends on PUM) + HVP(int, int) error + + // Text Cursor Enable Mode + DECTCEM(bool) error + + // Origin Mode + DECOM(bool) error + + // 132 Column Mode + DECCOLM(bool) error + + // Erase in Display + ED(int) error + + // Erase in Line + EL(int) error + + // Insert Line + IL(int) error + + // Delete Line + DL(int) error + + // Insert Character + ICH(int) error + + // Delete Character + DCH(int) error + + // Set Graphics Rendition + SGR([]int) error + + // Pan Down + SU(int) error + + // Pan Up + SD(int) error + + // Device Attributes + DA([]string) error + + // Set Top and Bottom Margins + DECSTBM(int, int) error + + // Index + IND() error + + // Reverse Index + RI() error + + // Flush updates from previous commands + Flush() error +} diff --git a/vendor/github.com/Azure/go-ansiterm/ground_state.go b/vendor/github.com/Azure/go-ansiterm/ground_state.go new file mode 100644 index 00000000..52451e94 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/ground_state.go @@ -0,0 +1,24 @@ +package ansiterm + +type groundState struct { + baseState +} + +func (gs groundState) Handle(b byte) (s state, e error) { + gs.parser.context.currentChar = b + + nextState, err := gs.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(printables, b): + return gs, gs.parser.print() + + case sliceContains(executors, b): + return gs, gs.parser.execute() + } + + return gs, nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go new file mode 100644 index 00000000..24062d42 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go @@ -0,0 +1,31 @@ +package ansiterm + +type oscStringState struct { + baseState +} + +func (oscState oscStringState) Handle(b byte) (s state, e error) { + logger.Infof("OscString::Handle %#x", b) + nextState, err := oscState.baseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case isOscStringTerminator(b): + return oscState.parser.ground, nil + } + + return oscState, nil +} + +// See below for OSC string terminators for linux +// http://man7.org/linux/man-pages/man4/console_codes.4.html +func isOscStringTerminator(b byte) bool { + + if b == ANSI_BEL || b == 0x5C { + return true + } + + return false +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser.go b/vendor/github.com/Azure/go-ansiterm/parser.go new file mode 100644 index 00000000..169f68db --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser.go @@ -0,0 +1,136 @@ +package ansiterm + +import ( + "errors" + "io/ioutil" + "os" + + "github.com/Sirupsen/logrus" +) + +var logger *logrus.Logger + +type AnsiParser struct { + currState state + eventHandler AnsiEventHandler + context *ansiContext + csiEntry state + csiParam state + dcsEntry state + escape state + escapeIntermediate state + error state + ground state + oscString state + stateMap []state +} + +func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser { + logFile := ioutil.Discard + + if isDebugEnv := os.Getenv(LogEnv); isDebugEnv == "1" { + logFile, _ = os.Create("ansiParser.log") + } + + logger = &logrus.Logger{ + Out: logFile, + Formatter: new(logrus.TextFormatter), + Level: logrus.InfoLevel, + } + + parser := &AnsiParser{ + eventHandler: evtHandler, + context: &ansiContext{}, + } + + parser.csiEntry = csiEntryState{baseState{name: "CsiEntry", parser: parser}} + parser.csiParam = csiParamState{baseState{name: "CsiParam", parser: parser}} + parser.dcsEntry = dcsEntryState{baseState{name: "DcsEntry", parser: parser}} + parser.escape = escapeState{baseState{name: "Escape", parser: parser}} + parser.escapeIntermediate = escapeIntermediateState{baseState{name: "EscapeIntermediate", parser: parser}} + parser.error = errorState{baseState{name: "Error", parser: parser}} + parser.ground = groundState{baseState{name: "Ground", parser: parser}} + parser.oscString = oscStringState{baseState{name: "OscString", parser: parser}} + + parser.stateMap = []state{ + parser.csiEntry, + parser.csiParam, + parser.dcsEntry, + parser.escape, + parser.escapeIntermediate, + parser.error, + parser.ground, + parser.oscString, + } + + parser.currState = getState(initialState, parser.stateMap) + + logger.Infof("CreateParser: parser %p", parser) + return parser +} + +func getState(name string, states []state) state { + for _, el := range states { + if el.Name() == name { + return el + } + } + + return nil +} + +func (ap *AnsiParser) Parse(bytes []byte) (int, error) { + for i, b := range bytes { + if err := ap.handle(b); err != nil { + return i, err + } + } + + return len(bytes), ap.eventHandler.Flush() +} + +func (ap *AnsiParser) handle(b byte) error { + ap.context.currentChar = b + newState, err := ap.currState.Handle(b) + if err != nil { + return err + } + + if newState == nil { + logger.Warning("newState is nil") + return errors.New("New state of 'nil' is invalid.") + } + + if newState != ap.currState { + if err := ap.changeState(newState); err != nil { + return err + } + } + + return nil +} + +func (ap *AnsiParser) changeState(newState state) error { + logger.Infof("ChangeState %s --> %s", ap.currState.Name(), newState.Name()) + + // Exit old state + if err := ap.currState.Exit(); err != nil { + logger.Infof("Exit state '%s' failed with : '%v'", ap.currState.Name(), err) + return err + } + + // Perform transition action + if err := ap.currState.Transition(newState); err != nil { + logger.Infof("Transition from '%s' to '%s' failed with: '%v'", ap.currState.Name(), newState.Name, err) + return err + } + + // Enter new state + if err := newState.Enter(); err != nil { + logger.Infof("Enter state '%s' failed with: '%v'", newState.Name(), err) + return err + } + + ap.currState = newState + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go new file mode 100644 index 00000000..8b69a67a --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go @@ -0,0 +1,103 @@ +package ansiterm + +import ( + "strconv" +) + +func parseParams(bytes []byte) ([]string, error) { + paramBuff := make([]byte, 0, 0) + params := []string{} + + for _, v := range bytes { + if v == ';' { + if len(paramBuff) > 0 { + // Completed parameter, append it to the list + s := string(paramBuff) + params = append(params, s) + paramBuff = make([]byte, 0, 0) + } + } else { + paramBuff = append(paramBuff, v) + } + } + + // Last parameter may not be terminated with ';' + if len(paramBuff) > 0 { + s := string(paramBuff) + params = append(params, s) + } + + logger.Infof("Parsed params: %v with length: %d", params, len(params)) + return params, nil +} + +func parseCmd(context ansiContext) (string, error) { + return string(context.currentChar), nil +} + +func getInt(params []string, dflt int) int { + i := getInts(params, 1, dflt)[0] + logger.Infof("getInt: %v", i) + return i +} + +func getInts(params []string, minCount int, dflt int) []int { + ints := []int{} + + for _, v := range params { + i, _ := strconv.Atoi(v) + // Zero is mapped to the default value in VT100. + if i == 0 { + i = dflt + } + ints = append(ints, i) + } + + if len(ints) < minCount { + remaining := minCount - len(ints) + for i := 0; i < remaining; i++ { + ints = append(ints, dflt) + } + } + + logger.Infof("getInts: %v", ints) + + return ints +} + +func (ap *AnsiParser) modeDispatch(param string, set bool) error { + switch param { + case "?3": + return ap.eventHandler.DECCOLM(set) + case "?6": + return ap.eventHandler.DECOM(set) + case "?25": + return ap.eventHandler.DECTCEM(set) + } + return nil +} + +func (ap *AnsiParser) hDispatch(params []string) error { + if len(params) == 1 { + return ap.modeDispatch(params[0], true) + } + + return nil +} + +func (ap *AnsiParser) lDispatch(params []string) error { + if len(params) == 1 { + return ap.modeDispatch(params[0], false) + } + + return nil +} + +func getEraseParam(params []string) int { + param := getInt(params, 0) + if param < 0 || 3 < param { + param = 0 + } + + return param +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_actions.go b/vendor/github.com/Azure/go-ansiterm/parser_actions.go new file mode 100644 index 00000000..58750a2d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_actions.go @@ -0,0 +1,122 @@ +package ansiterm + +import ( + "fmt" +) + +func (ap *AnsiParser) collectParam() error { + currChar := ap.context.currentChar + logger.Infof("collectParam %#x", currChar) + ap.context.paramBuffer = append(ap.context.paramBuffer, currChar) + return nil +} + +func (ap *AnsiParser) collectInter() error { + currChar := ap.context.currentChar + logger.Infof("collectInter %#x", currChar) + ap.context.paramBuffer = append(ap.context.interBuffer, currChar) + return nil +} + +func (ap *AnsiParser) escDispatch() error { + cmd, _ := parseCmd(*ap.context) + intermeds := ap.context.interBuffer + logger.Infof("escDispatch currentChar: %#x", ap.context.currentChar) + logger.Infof("escDispatch: %v(%v)", cmd, intermeds) + + switch cmd { + case "D": // IND + return ap.eventHandler.IND() + case "E": // NEL, equivalent to CRLF + err := ap.eventHandler.Execute(ANSI_CARRIAGE_RETURN) + if err == nil { + err = ap.eventHandler.Execute(ANSI_LINE_FEED) + } + return err + case "M": // RI + return ap.eventHandler.RI() + } + + return nil +} + +func (ap *AnsiParser) csiDispatch() error { + cmd, _ := parseCmd(*ap.context) + params, _ := parseParams(ap.context.paramBuffer) + + logger.Infof("csiDispatch: %v(%v)", cmd, params) + + switch cmd { + case "@": + return ap.eventHandler.ICH(getInt(params, 1)) + case "A": + return ap.eventHandler.CUU(getInt(params, 1)) + case "B": + return ap.eventHandler.CUD(getInt(params, 1)) + case "C": + return ap.eventHandler.CUF(getInt(params, 1)) + case "D": + return ap.eventHandler.CUB(getInt(params, 1)) + case "E": + return ap.eventHandler.CNL(getInt(params, 1)) + case "F": + return ap.eventHandler.CPL(getInt(params, 1)) + case "G": + return ap.eventHandler.CHA(getInt(params, 1)) + case "H": + ints := getInts(params, 2, 1) + x, y := ints[0], ints[1] + return ap.eventHandler.CUP(x, y) + case "J": + param := getEraseParam(params) + return ap.eventHandler.ED(param) + case "K": + param := getEraseParam(params) + return ap.eventHandler.EL(param) + case "L": + return ap.eventHandler.IL(getInt(params, 1)) + case "M": + return ap.eventHandler.DL(getInt(params, 1)) + case "P": + return ap.eventHandler.DCH(getInt(params, 1)) + case "S": + return ap.eventHandler.SU(getInt(params, 1)) + case "T": + return ap.eventHandler.SD(getInt(params, 1)) + case "c": + return ap.eventHandler.DA(params) + case "d": + return ap.eventHandler.VPA(getInt(params, 1)) + case "f": + ints := getInts(params, 2, 1) + x, y := ints[0], ints[1] + return ap.eventHandler.HVP(x, y) + case "h": + return ap.hDispatch(params) + case "l": + return ap.lDispatch(params) + case "m": + return ap.eventHandler.SGR(getInts(params, 1, 0)) + case "r": + ints := getInts(params, 2, 1) + top, bottom := ints[0], ints[1] + return ap.eventHandler.DECSTBM(top, bottom) + default: + logger.Errorf(fmt.Sprintf("Unsupported CSI command: '%s', with full context: %v", cmd, ap.context)) + return nil + } + +} + +func (ap *AnsiParser) print() error { + return ap.eventHandler.Print(ap.context.currentChar) +} + +func (ap *AnsiParser) clear() error { + ap.context = &ansiContext{} + return nil +} + +func (ap *AnsiParser) execute() error { + return ap.eventHandler.Execute(ap.context.currentChar) +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_test.go b/vendor/github.com/Azure/go-ansiterm/parser_test.go new file mode 100644 index 00000000..cd4888ff --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_test.go @@ -0,0 +1,141 @@ +package ansiterm + +import ( + "fmt" + "testing" +) + +func TestStateTransitions(t *testing.T) { + stateTransitionHelper(t, "CsiEntry", "Ground", alphabetics) + stateTransitionHelper(t, "CsiEntry", "CsiParam", csiCollectables) + stateTransitionHelper(t, "Escape", "CsiEntry", []byte{ANSI_ESCAPE_SECONDARY}) + stateTransitionHelper(t, "Escape", "OscString", []byte{0x5D}) + stateTransitionHelper(t, "Escape", "Ground", escapeToGroundBytes) + stateTransitionHelper(t, "Escape", "EscapeIntermediate", intermeds) + stateTransitionHelper(t, "EscapeIntermediate", "EscapeIntermediate", intermeds) + stateTransitionHelper(t, "EscapeIntermediate", "EscapeIntermediate", executors) + stateTransitionHelper(t, "EscapeIntermediate", "Ground", escapeIntermediateToGroundBytes) + stateTransitionHelper(t, "OscString", "Ground", []byte{ANSI_BEL}) + stateTransitionHelper(t, "OscString", "Ground", []byte{0x5C}) + stateTransitionHelper(t, "Ground", "Ground", executors) +} + +func TestAnyToX(t *testing.T) { + anyToXHelper(t, []byte{ANSI_ESCAPE_PRIMARY}, "Escape") + anyToXHelper(t, []byte{DCS_ENTRY}, "DcsEntry") + anyToXHelper(t, []byte{OSC_STRING}, "OscString") + anyToXHelper(t, []byte{CSI_ENTRY}, "CsiEntry") + anyToXHelper(t, toGroundBytes, "Ground") +} + +func TestCollectCsiParams(t *testing.T) { + parser, _ := createTestParser("CsiEntry") + parser.Parse(csiCollectables) + + buffer := parser.context.paramBuffer + bufferCount := len(buffer) + + if bufferCount != len(csiCollectables) { + t.Errorf("Buffer: %v", buffer) + t.Errorf("CsiParams: %v", csiCollectables) + t.Errorf("Buffer count failure: %d != %d", bufferCount, len(csiParams)) + return + } + + for i, v := range csiCollectables { + if v != buffer[i] { + t.Errorf("Buffer: %v", buffer) + t.Errorf("CsiParams: %v", csiParams) + t.Errorf("Mismatch at buffer[%d] = %d", i, buffer[i]) + } + } +} + +func TestParseParams(t *testing.T) { + parseParamsHelper(t, []byte{}, []string{}) + parseParamsHelper(t, []byte{';'}, []string{}) + parseParamsHelper(t, []byte{';', ';'}, []string{}) + parseParamsHelper(t, []byte{'7'}, []string{"7"}) + parseParamsHelper(t, []byte{'7', ';'}, []string{"7"}) + parseParamsHelper(t, []byte{'7', ';', ';'}, []string{"7"}) + parseParamsHelper(t, []byte{'7', ';', ';', '8'}, []string{"7", "8"}) + parseParamsHelper(t, []byte{'7', ';', '8', ';'}, []string{"7", "8"}) + parseParamsHelper(t, []byte{'7', ';', ';', '8', ';', ';'}, []string{"7", "8"}) + parseParamsHelper(t, []byte{'7', '8'}, []string{"78"}) + parseParamsHelper(t, []byte{'7', '8', ';'}, []string{"78"}) + parseParamsHelper(t, []byte{'7', '8', ';', '9', '0'}, []string{"78", "90"}) + parseParamsHelper(t, []byte{'7', '8', ';', ';', '9', '0'}, []string{"78", "90"}) + parseParamsHelper(t, []byte{'7', '8', ';', '9', '0', ';'}, []string{"78", "90"}) + parseParamsHelper(t, []byte{'7', '8', ';', '9', '0', ';', ';'}, []string{"78", "90"}) +} + +func TestCursor(t *testing.T) { + cursorSingleParamHelper(t, 'A', "CUU") + cursorSingleParamHelper(t, 'B', "CUD") + cursorSingleParamHelper(t, 'C', "CUF") + cursorSingleParamHelper(t, 'D', "CUB") + cursorSingleParamHelper(t, 'E', "CNL") + cursorSingleParamHelper(t, 'F', "CPL") + cursorSingleParamHelper(t, 'G', "CHA") + cursorTwoParamHelper(t, 'H', "CUP") + cursorTwoParamHelper(t, 'f', "HVP") + funcCallParamHelper(t, []byte{'?', '2', '5', 'h'}, "CsiEntry", "Ground", []string{"DECTCEM([true])"}) + funcCallParamHelper(t, []byte{'?', '2', '5', 'l'}, "CsiEntry", "Ground", []string{"DECTCEM([false])"}) +} + +func TestErase(t *testing.T) { + // Erase in Display + eraseHelper(t, 'J', "ED") + + // Erase in Line + eraseHelper(t, 'K', "EL") +} + +func TestSelectGraphicRendition(t *testing.T) { + funcCallParamHelper(t, []byte{'m'}, "CsiEntry", "Ground", []string{"SGR([0])"}) + funcCallParamHelper(t, []byte{'0', 'm'}, "CsiEntry", "Ground", []string{"SGR([0])"}) + funcCallParamHelper(t, []byte{'0', ';', '1', 'm'}, "CsiEntry", "Ground", []string{"SGR([0 1])"}) + funcCallParamHelper(t, []byte{'0', ';', '1', ';', '2', 'm'}, "CsiEntry", "Ground", []string{"SGR([0 1 2])"}) +} + +func TestScroll(t *testing.T) { + scrollHelper(t, 'S', "SU") + scrollHelper(t, 'T', "SD") +} + +func TestPrint(t *testing.T) { + parser, evtHandler := createTestParser("Ground") + parser.Parse(printables) + validateState(t, parser.currState, "Ground") + + for i, v := range printables { + expectedCall := fmt.Sprintf("Print([%s])", string(v)) + actualCall := evtHandler.FunctionCalls[i] + if actualCall != expectedCall { + t.Errorf("Actual != Expected: %v != %v at %d", actualCall, expectedCall, i) + } + } +} + +func TestClear(t *testing.T) { + p, _ := createTestParser("Ground") + fillContext(p.context) + p.clear() + validateEmptyContext(t, p.context) +} + +func TestClearOnStateChange(t *testing.T) { + clearOnStateChangeHelper(t, "Ground", "Escape", []byte{ANSI_ESCAPE_PRIMARY}) + clearOnStateChangeHelper(t, "Ground", "CsiEntry", []byte{CSI_ENTRY}) +} + +func TestC0(t *testing.T) { + expectedCall := "Execute([" + string(ANSI_LINE_FEED) + "])" + c0Helper(t, []byte{ANSI_LINE_FEED}, "Ground", []string{expectedCall}) + expectedCall = "Execute([" + string(ANSI_CARRIAGE_RETURN) + "])" + c0Helper(t, []byte{ANSI_CARRIAGE_RETURN}, "Ground", []string{expectedCall}) +} + +func TestEscDispatch(t *testing.T) { + funcCallParamHelper(t, []byte{'M'}, "Escape", "Ground", []string{"RI([])"}) +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_test_helpers_test.go b/vendor/github.com/Azure/go-ansiterm/parser_test_helpers_test.go new file mode 100644 index 00000000..562f215d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_test_helpers_test.go @@ -0,0 +1,114 @@ +package ansiterm + +import ( + "fmt" + "testing" +) + +func getStateNames() []string { + parser, _ := createTestParser("Ground") + + stateNames := []string{} + for _, state := range parser.stateMap { + stateNames = append(stateNames, state.Name()) + } + + return stateNames +} + +func stateTransitionHelper(t *testing.T, start string, end string, bytes []byte) { + for _, b := range bytes { + bytes := []byte{byte(b)} + parser, _ := createTestParser(start) + parser.Parse(bytes) + validateState(t, parser.currState, end) + } +} + +func anyToXHelper(t *testing.T, bytes []byte, expectedState string) { + for _, s := range getStateNames() { + stateTransitionHelper(t, s, expectedState, bytes) + } +} + +func funcCallParamHelper(t *testing.T, bytes []byte, start string, expected string, expectedCalls []string) { + parser, evtHandler := createTestParser(start) + parser.Parse(bytes) + validateState(t, parser.currState, expected) + validateFuncCalls(t, evtHandler.FunctionCalls, expectedCalls) +} + +func parseParamsHelper(t *testing.T, bytes []byte, expectedParams []string) { + params, err := parseParams(bytes) + + if err != nil { + t.Errorf("Parameter parse error: %v", err) + return + } + + if len(params) != len(expectedParams) { + t.Errorf("Parsed parameters: %v", params) + t.Errorf("Expected parameters: %v", expectedParams) + t.Errorf("Parameter length failure: %d != %d", len(params), len(expectedParams)) + return + } + + for i, v := range expectedParams { + if v != params[i] { + t.Errorf("Parsed parameters: %v", params) + t.Errorf("Expected parameters: %v", expectedParams) + t.Errorf("Parameter parse failure: %s != %s at position %d", v, params[i], i) + } + } +} + +func cursorSingleParamHelper(t *testing.T, command byte, funcName string) { + funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) + funcCallParamHelper(t, []byte{'2', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([23])", funcName)}) + funcCallParamHelper(t, []byte{'2', ';', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) + funcCallParamHelper(t, []byte{'2', ';', '3', ';', '4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) +} + +func cursorTwoParamHelper(t *testing.T, command byte, funcName string) { + funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1 1])", funcName)}) + funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1 1])", funcName)}) + funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 1])", funcName)}) + funcCallParamHelper(t, []byte{'2', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([23 1])", funcName)}) + funcCallParamHelper(t, []byte{'2', ';', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 3])", funcName)}) + funcCallParamHelper(t, []byte{'2', ';', '3', ';', '4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 3])", funcName)}) +} + +func eraseHelper(t *testing.T, command byte, funcName string) { + funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) + funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) + funcCallParamHelper(t, []byte{'1', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) + funcCallParamHelper(t, []byte{'3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([3])", funcName)}) + funcCallParamHelper(t, []byte{'4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) + funcCallParamHelper(t, []byte{'1', ';', '2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) +} + +func scrollHelper(t *testing.T, command byte, funcName string) { + funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'1', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'5', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([5])", funcName)}) + funcCallParamHelper(t, []byte{'4', ';', '6', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([4])", funcName)}) +} + +func clearOnStateChangeHelper(t *testing.T, start string, end string, bytes []byte) { + p, _ := createTestParser(start) + fillContext(p.context) + p.Parse(bytes) + validateState(t, p.currState, end) + validateEmptyContext(t, p.context) +} + +func c0Helper(t *testing.T, bytes []byte, expectedState string, expectedCalls []string) { + parser, evtHandler := createTestParser("Ground") + parser.Parse(bytes) + validateState(t, parser.currState, expectedState) + validateFuncCalls(t, evtHandler.FunctionCalls, expectedCalls) +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_test_utilities_test.go b/vendor/github.com/Azure/go-ansiterm/parser_test_utilities_test.go new file mode 100644 index 00000000..78b885ca --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_test_utilities_test.go @@ -0,0 +1,66 @@ +package ansiterm + +import ( + "testing" +) + +func createTestParser(s string) (*AnsiParser, *TestAnsiEventHandler) { + evtHandler := CreateTestAnsiEventHandler() + parser := CreateParser(s, evtHandler) + + return parser, evtHandler +} + +func validateState(t *testing.T, actualState state, expectedStateName string) { + actualName := "Nil" + + if actualState != nil { + actualName = actualState.Name() + } + + if actualName != expectedStateName { + t.Errorf("Invalid state: '%s' != '%s'", actualName, expectedStateName) + } +} + +func validateFuncCalls(t *testing.T, actualCalls []string, expectedCalls []string) { + actualCount := len(actualCalls) + expectedCount := len(expectedCalls) + + if actualCount != expectedCount { + t.Errorf("Actual calls: %v", actualCalls) + t.Errorf("Expected calls: %v", expectedCalls) + t.Errorf("Call count error: %d != %d", actualCount, expectedCount) + return + } + + for i, v := range actualCalls { + if v != expectedCalls[i] { + t.Errorf("Actual calls: %v", actualCalls) + t.Errorf("Expected calls: %v", expectedCalls) + t.Errorf("Mismatched calls: %s != %s with lengths %d and %d", v, expectedCalls[i], len(v), len(expectedCalls[i])) + } + } +} + +func fillContext(context *ansiContext) { + context.currentChar = 'A' + context.paramBuffer = []byte{'C', 'D', 'E'} + context.interBuffer = []byte{'F', 'G', 'H'} +} + +func validateEmptyContext(t *testing.T, context *ansiContext) { + var expectedCurrChar byte = 0x0 + if context.currentChar != expectedCurrChar { + t.Errorf("Currentchar mismatch '%#x' != '%#x'", context.currentChar, expectedCurrChar) + } + + if len(context.paramBuffer) != 0 { + t.Errorf("Non-empty parameter buffer: %v", context.paramBuffer) + } + + if len(context.paramBuffer) != 0 { + t.Errorf("Non-empty intermediate buffer: %v", context.interBuffer) + } + +} diff --git a/vendor/github.com/Azure/go-ansiterm/states.go b/vendor/github.com/Azure/go-ansiterm/states.go new file mode 100644 index 00000000..f2ea1fcd --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/states.go @@ -0,0 +1,71 @@ +package ansiterm + +type stateID int + +type state interface { + Enter() error + Exit() error + Handle(byte) (state, error) + Name() string + Transition(state) error +} + +type baseState struct { + name string + parser *AnsiParser +} + +func (base baseState) Enter() error { + return nil +} + +func (base baseState) Exit() error { + return nil +} + +func (base baseState) Handle(b byte) (s state, e error) { + + switch { + case b == CSI_ENTRY: + return base.parser.csiEntry, nil + case b == DCS_ENTRY: + return base.parser.dcsEntry, nil + case b == ANSI_ESCAPE_PRIMARY: + return base.parser.escape, nil + case b == OSC_STRING: + return base.parser.oscString, nil + case sliceContains(toGroundBytes, b): + return base.parser.ground, nil + } + + return nil, nil +} + +func (base baseState) Name() string { + return base.name +} + +func (base baseState) Transition(s state) error { + if s == base.parser.ground { + execBytes := []byte{0x18} + execBytes = append(execBytes, 0x1A) + execBytes = append(execBytes, getByteRange(0x80, 0x8F)...) + execBytes = append(execBytes, getByteRange(0x91, 0x97)...) + execBytes = append(execBytes, 0x99) + execBytes = append(execBytes, 0x9A) + + if sliceContains(execBytes, base.parser.context.currentChar) { + return base.parser.execute() + } + } + + return nil +} + +type dcsEntryState struct { + baseState +} + +type errorState struct { + baseState +} diff --git a/vendor/github.com/Azure/go-ansiterm/test_event_handler_test.go b/vendor/github.com/Azure/go-ansiterm/test_event_handler_test.go new file mode 100644 index 00000000..60f9f30b --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/test_event_handler_test.go @@ -0,0 +1,173 @@ +package ansiterm + +import ( + "fmt" + "strconv" +) + +type TestAnsiEventHandler struct { + FunctionCalls []string +} + +func CreateTestAnsiEventHandler() *TestAnsiEventHandler { + evtHandler := TestAnsiEventHandler{} + evtHandler.FunctionCalls = make([]string, 0) + return &evtHandler +} + +func (h *TestAnsiEventHandler) recordCall(call string, params []string) { + s := fmt.Sprintf("%s(%v)", call, params) + h.FunctionCalls = append(h.FunctionCalls, s) +} + +func (h *TestAnsiEventHandler) Print(b byte) error { + h.recordCall("Print", []string{string(b)}) + return nil +} + +func (h *TestAnsiEventHandler) Execute(b byte) error { + h.recordCall("Execute", []string{string(b)}) + return nil +} + +func (h *TestAnsiEventHandler) CUU(param int) error { + h.recordCall("CUU", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CUD(param int) error { + h.recordCall("CUD", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CUF(param int) error { + h.recordCall("CUF", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CUB(param int) error { + h.recordCall("CUB", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CNL(param int) error { + h.recordCall("CNL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CPL(param int) error { + h.recordCall("CPL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CHA(param int) error { + h.recordCall("CHA", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) VPA(param int) error { + h.recordCall("VPA", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CUP(x int, y int) error { + xS, yS := strconv.Itoa(x), strconv.Itoa(y) + h.recordCall("CUP", []string{xS, yS}) + return nil +} + +func (h *TestAnsiEventHandler) HVP(x int, y int) error { + xS, yS := strconv.Itoa(x), strconv.Itoa(y) + h.recordCall("HVP", []string{xS, yS}) + return nil +} + +func (h *TestAnsiEventHandler) DECTCEM(visible bool) error { + h.recordCall("DECTCEM", []string{strconv.FormatBool(visible)}) + return nil +} + +func (h *TestAnsiEventHandler) DECOM(visible bool) error { + h.recordCall("DECOM", []string{strconv.FormatBool(visible)}) + return nil +} + +func (h *TestAnsiEventHandler) DECCOLM(use132 bool) error { + h.recordCall("DECOLM", []string{strconv.FormatBool(use132)}) + return nil +} + +func (h *TestAnsiEventHandler) ED(param int) error { + h.recordCall("ED", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) EL(param int) error { + h.recordCall("EL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) IL(param int) error { + h.recordCall("IL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) DL(param int) error { + h.recordCall("DL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) ICH(param int) error { + h.recordCall("ICH", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) DCH(param int) error { + h.recordCall("DCH", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) SGR(params []int) error { + strings := []string{} + for _, v := range params { + strings = append(strings, strconv.Itoa(v)) + } + + h.recordCall("SGR", strings) + return nil +} + +func (h *TestAnsiEventHandler) SU(param int) error { + h.recordCall("SU", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) SD(param int) error { + h.recordCall("SD", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) DA(params []string) error { + h.recordCall("DA", params) + return nil +} + +func (h *TestAnsiEventHandler) DECSTBM(top int, bottom int) error { + topS, bottomS := strconv.Itoa(top), strconv.Itoa(bottom) + h.recordCall("DECSTBM", []string{topS, bottomS}) + return nil +} + +func (h *TestAnsiEventHandler) RI() error { + h.recordCall("RI", nil) + return nil +} + +func (h *TestAnsiEventHandler) IND() error { + h.recordCall("IND", nil) + return nil +} + +func (h *TestAnsiEventHandler) Flush() error { + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/utilities.go new file mode 100644 index 00000000..39211449 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/utilities.go @@ -0,0 +1,21 @@ +package ansiterm + +import ( + "strconv" +) + +func sliceContains(bytes []byte, b byte) bool { + for _, v := range bytes { + if v == b { + return true + } + } + + return false +} + +func convertBytesToInteger(bytes []byte) int { + s := string(bytes) + i, _ := strconv.Atoi(s) + return i +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go new file mode 100644 index 00000000..daf2f069 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go @@ -0,0 +1,182 @@ +// +build windows + +package winterm + +import ( + "fmt" + "os" + "strconv" + "strings" + "syscall" + + "github.com/Azure/go-ansiterm" +) + +// Windows keyboard constants +// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx. +const ( + VK_PRIOR = 0x21 // PAGE UP key + VK_NEXT = 0x22 // PAGE DOWN key + VK_END = 0x23 // END key + VK_HOME = 0x24 // HOME key + VK_LEFT = 0x25 // LEFT ARROW key + VK_UP = 0x26 // UP ARROW key + VK_RIGHT = 0x27 // RIGHT ARROW key + VK_DOWN = 0x28 // DOWN ARROW key + VK_SELECT = 0x29 // SELECT key + VK_PRINT = 0x2A // PRINT key + VK_EXECUTE = 0x2B // EXECUTE key + VK_SNAPSHOT = 0x2C // PRINT SCREEN key + VK_INSERT = 0x2D // INS key + VK_DELETE = 0x2E // DEL key + VK_HELP = 0x2F // HELP key + VK_F1 = 0x70 // F1 key + VK_F2 = 0x71 // F2 key + VK_F3 = 0x72 // F3 key + VK_F4 = 0x73 // F4 key + VK_F5 = 0x74 // F5 key + VK_F6 = 0x75 // F6 key + VK_F7 = 0x76 // F7 key + VK_F8 = 0x77 // F8 key + VK_F9 = 0x78 // F9 key + VK_F10 = 0x79 // F10 key + VK_F11 = 0x7A // F11 key + VK_F12 = 0x7B // F12 key + + RIGHT_ALT_PRESSED = 0x0001 + LEFT_ALT_PRESSED = 0x0002 + RIGHT_CTRL_PRESSED = 0x0004 + LEFT_CTRL_PRESSED = 0x0008 + SHIFT_PRESSED = 0x0010 + NUMLOCK_ON = 0x0020 + SCROLLLOCK_ON = 0x0040 + CAPSLOCK_ON = 0x0080 + ENHANCED_KEY = 0x0100 +) + +type ansiCommand struct { + CommandBytes []byte + Command string + Parameters []string + IsSpecial bool +} + +func newAnsiCommand(command []byte) *ansiCommand { + + if isCharacterSelectionCmdChar(command[1]) { + // Is Character Set Selection commands + return &ansiCommand{ + CommandBytes: command, + Command: string(command), + IsSpecial: true, + } + } + + // last char is command character + lastCharIndex := len(command) - 1 + + ac := &ansiCommand{ + CommandBytes: command, + Command: string(command[lastCharIndex]), + IsSpecial: false, + } + + // more than a single escape + if lastCharIndex != 0 { + start := 1 + // skip if double char escape sequence + if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY { + start++ + } + // convert this to GetNextParam method + ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP) + } + + return ac +} + +func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 { + if index < 0 || index >= len(ac.Parameters) { + return defaultValue + } + + param, err := strconv.ParseInt(ac.Parameters[index], 10, 16) + if err != nil { + return defaultValue + } + + return int16(param) +} + +func (ac *ansiCommand) String() string { + return fmt.Sprintf("0x%v \"%v\" (\"%v\")", + bytesToHex(ac.CommandBytes), + ac.Command, + strings.Join(ac.Parameters, "\",\"")) +} + +// isAnsiCommandChar returns true if the passed byte falls within the range of ANSI commands. +// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. +func isAnsiCommandChar(b byte) bool { + switch { + case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY: + return true + case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM: + // non-CSI escape sequence terminator + return true + case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL: + // String escape sequence terminator + return true + } + return false +} + +func isXtermOscSequence(command []byte, current byte) bool { + return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL) +} + +func isCharacterSelectionCmdChar(b byte) bool { + return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3) +} + +// bytesToHex converts a slice of bytes to a human-readable string. +func bytesToHex(b []byte) string { + hex := make([]string, len(b)) + for i, ch := range b { + hex[i] = fmt.Sprintf("%X", ch) + } + return strings.Join(hex, "") +} + +// ensureInRange adjusts the passed value, if necessary, to ensure it is within +// the passed min / max range. +func ensureInRange(n int16, min int16, max int16) int16 { + if n < min { + return min + } else if n > max { + return max + } else { + return n + } +} + +func GetStdFile(nFile int) (*os.File, uintptr) { + var file *os.File + switch nFile { + case syscall.STD_INPUT_HANDLE: + file = os.Stdin + case syscall.STD_OUTPUT_HANDLE: + file = os.Stdout + case syscall.STD_ERROR_HANDLE: + file = os.Stderr + default: + panic(fmt.Errorf("Invalid standard handle identifier: %v", nFile)) + } + + fd, err := syscall.GetStdHandle(nFile) + if err != nil { + panic(fmt.Errorf("Invalid standard handle indentifier: %v -- %v", nFile, err)) + } + + return file, uintptr(fd) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go new file mode 100644 index 00000000..462d92f8 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/api.go @@ -0,0 +1,322 @@ +// +build windows + +package winterm + +import ( + "fmt" + "syscall" + "unsafe" +) + +//=========================================================================================================== +// IMPORTANT NOTE: +// +// The methods below make extensive use of the "unsafe" package to obtain the required pointers. +// Beginning in Go 1.3, the garbage collector may release local variables (e.g., incoming arguments, stack +// variables) the pointers reference *before* the API completes. +// +// As a result, in those cases, the code must hint that the variables remain in active by invoking the +// dummy method "use" (see below). Newer versions of Go are planned to change the mechanism to no longer +// require unsafe pointers. +// +// If you add or modify methods, ENSURE protection of local variables through the "use" builtin to inform +// the garbage collector the variables remain in use if: +// +// -- The value is not a pointer (e.g., int32, struct) +// -- The value is not referenced by the method after passing the pointer to Windows +// +// See http://golang.org/doc/go1.3. +//=========================================================================================================== + +var ( + kernel32DLL = syscall.NewLazyDLL("kernel32.dll") + + getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo") + setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo") + setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition") + setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode") + getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo") + setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize") + scrollConsoleScreenBufferProc = kernel32DLL.NewProc("ScrollConsoleScreenBufferA") + setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") + setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo") + writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW") + readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW") + waitForSingleObjectProc = kernel32DLL.NewProc("WaitForSingleObject") +) + +// Windows Console constants +const ( + // Console modes + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. + ENABLE_PROCESSED_INPUT = 0x0001 + ENABLE_LINE_INPUT = 0x0002 + ENABLE_ECHO_INPUT = 0x0004 + ENABLE_WINDOW_INPUT = 0x0008 + ENABLE_MOUSE_INPUT = 0x0010 + ENABLE_INSERT_MODE = 0x0020 + ENABLE_QUICK_EDIT_MODE = 0x0040 + ENABLE_EXTENDED_FLAGS = 0x0080 + + ENABLE_PROCESSED_OUTPUT = 0x0001 + ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 + + // Character attributes + // Note: + // -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan). + // Clearing all foreground or background colors results in black; setting all creates white. + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes. + FOREGROUND_BLUE uint16 = 0x0001 + FOREGROUND_GREEN uint16 = 0x0002 + FOREGROUND_RED uint16 = 0x0004 + FOREGROUND_INTENSITY uint16 = 0x0008 + FOREGROUND_MASK uint16 = 0x000F + + BACKGROUND_BLUE uint16 = 0x0010 + BACKGROUND_GREEN uint16 = 0x0020 + BACKGROUND_RED uint16 = 0x0040 + BACKGROUND_INTENSITY uint16 = 0x0080 + BACKGROUND_MASK uint16 = 0x00F0 + + COMMON_LVB_MASK uint16 = 0xFF00 + COMMON_LVB_REVERSE_VIDEO uint16 = 0x4000 + COMMON_LVB_UNDERSCORE uint16 = 0x8000 + + // Input event types + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. + KEY_EVENT = 0x0001 + MOUSE_EVENT = 0x0002 + WINDOW_BUFFER_SIZE_EVENT = 0x0004 + MENU_EVENT = 0x0008 + FOCUS_EVENT = 0x0010 + + // WaitForSingleObject return codes + WAIT_ABANDONED = 0x00000080 + WAIT_FAILED = 0xFFFFFFFF + WAIT_SIGNALED = 0x0000000 + WAIT_TIMEOUT = 0x00000102 + + // WaitForSingleObject wait duration + WAIT_INFINITE = 0xFFFFFFFF + WAIT_ONE_SECOND = 1000 + WAIT_HALF_SECOND = 500 + WAIT_QUARTER_SECOND = 250 +) + +// Windows API Console types +// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD) +// -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment +type ( + CHAR_INFO struct { + UnicodeChar uint16 + Attributes uint16 + } + + CONSOLE_CURSOR_INFO struct { + Size uint32 + Visible int32 + } + + CONSOLE_SCREEN_BUFFER_INFO struct { + Size COORD + CursorPosition COORD + Attributes uint16 + Window SMALL_RECT + MaximumWindowSize COORD + } + + COORD struct { + X int16 + Y int16 + } + + SMALL_RECT struct { + Left int16 + Top int16 + Right int16 + Bottom int16 + } + + // INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. + INPUT_RECORD struct { + EventType uint16 + KeyEvent KEY_EVENT_RECORD + } + + KEY_EVENT_RECORD struct { + KeyDown int32 + RepeatCount uint16 + VirtualKeyCode uint16 + VirtualScanCode uint16 + UnicodeChar uint16 + ControlKeyState uint32 + } + + WINDOW_BUFFER_SIZE struct { + Size COORD + } +) + +// boolToBOOL converts a Go bool into a Windows int32. +func boolToBOOL(f bool) int32 { + if f { + return int32(1) + } else { + return int32(0) + } +} + +// GetConsoleCursorInfo retrieves information about the size and visiblity of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683163(v=vs.85).aspx. +func GetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { + r1, r2, err := getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) + return checkError(r1, r2, err) +} + +// SetConsoleCursorInfo sets the size and visiblity of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx. +func SetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { + r1, r2, err := setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) + return checkError(r1, r2, err) +} + +// SetConsoleCursorPosition location of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx. +func SetConsoleCursorPosition(handle uintptr, coord COORD) error { + r1, r2, err := setConsoleCursorPositionProc.Call(handle, coordToPointer(coord)) + use(coord) + return checkError(r1, r2, err) +} + +// GetConsoleMode gets the console mode for given file descriptor +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx. +func GetConsoleMode(handle uintptr) (mode uint32, err error) { + err = syscall.GetConsoleMode(syscall.Handle(handle), &mode) + return mode, err +} + +// SetConsoleMode sets the console mode for given file descriptor +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. +func SetConsoleMode(handle uintptr, mode uint32) error { + r1, r2, err := setConsoleModeProc.Call(handle, uintptr(mode), 0) + use(mode) + return checkError(r1, r2, err) +} + +// GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer. +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx. +func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) { + info := CONSOLE_SCREEN_BUFFER_INFO{} + err := checkError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)) + if err != nil { + return nil, err + } + return &info, nil +} + +func ScrollConsoleScreenBuffer(handle uintptr, scrollRect SMALL_RECT, clipRect SMALL_RECT, destOrigin COORD, char CHAR_INFO) error { + r1, r2, err := scrollConsoleScreenBufferProc.Call(handle, uintptr(unsafe.Pointer(&scrollRect)), uintptr(unsafe.Pointer(&clipRect)), coordToPointer(destOrigin), uintptr(unsafe.Pointer(&char))) + use(scrollRect) + use(clipRect) + use(destOrigin) + use(char) + return checkError(r1, r2, err) +} + +// SetConsoleScreenBufferSize sets the size of the console screen buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686044(v=vs.85).aspx. +func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error { + r1, r2, err := setConsoleScreenBufferSizeProc.Call(handle, coordToPointer(coord)) + use(coord) + return checkError(r1, r2, err) +} + +// SetConsoleTextAttribute sets the attributes of characters written to the +// console screen buffer by the WriteFile or WriteConsole function. +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. +func SetConsoleTextAttribute(handle uintptr, attribute uint16) error { + r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0) + use(attribute) + return checkError(r1, r2, err) +} + +// SetConsoleWindowInfo sets the size and position of the console screen buffer's window. +// Note that the size and location must be within and no larger than the backing console screen buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686125(v=vs.85).aspx. +func SetConsoleWindowInfo(handle uintptr, isAbsolute bool, rect SMALL_RECT) error { + r1, r2, err := setConsoleWindowInfoProc.Call(handle, uintptr(boolToBOOL(isAbsolute)), uintptr(unsafe.Pointer(&rect))) + use(isAbsolute) + use(rect) + return checkError(r1, r2, err) +} + +// WriteConsoleOutput writes the CHAR_INFOs from the provided buffer to the active console buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687404(v=vs.85).aspx. +func WriteConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) error { + r1, r2, err := writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), coordToPointer(bufferSize), coordToPointer(bufferCoord), uintptr(unsafe.Pointer(writeRegion))) + use(buffer) + use(bufferSize) + use(bufferCoord) + return checkError(r1, r2, err) +} + +// ReadConsoleInput reads (and removes) data from the console input buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx. +func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) error { + r1, r2, err := readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)), uintptr(unsafe.Pointer(count))) + use(buffer) + return checkError(r1, r2, err) +} + +// WaitForSingleObject waits for the passed handle to be signaled. +// It returns true if the handle was signaled; false otherwise. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx. +func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) { + r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(uint32(msWait))) + switch r1 { + case WAIT_ABANDONED, WAIT_TIMEOUT: + return false, nil + case WAIT_SIGNALED: + return true, nil + } + use(msWait) + return false, err +} + +// String helpers +func (info CONSOLE_SCREEN_BUFFER_INFO) String() string { + return fmt.Sprintf("Size(%v) Cursor(%v) Window(%v) Max(%v)", info.Size, info.CursorPosition, info.Window, info.MaximumWindowSize) +} + +func (coord COORD) String() string { + return fmt.Sprintf("%v,%v", coord.X, coord.Y) +} + +func (rect SMALL_RECT) String() string { + return fmt.Sprintf("(%v,%v),(%v,%v)", rect.Left, rect.Top, rect.Right, rect.Bottom) +} + +// checkError evaluates the results of a Windows API call and returns the error if it failed. +func checkError(r1, r2 uintptr, err error) error { + // Windows APIs return non-zero to indicate success + if r1 != 0 { + return nil + } + + // Return the error if provided, otherwise default to EINVAL + if err != nil { + return err + } + return syscall.EINVAL +} + +// coordToPointer converts a COORD into a uintptr (by fooling the type system). +func coordToPointer(c COORD) uintptr { + // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to uint32 is just to get a pointer to pass. + return uintptr(*((*uint32)(unsafe.Pointer(&c)))) +} + +// use is a no-op, but the compiler cannot see that it is. +// Calling use(p) ensures that p is kept live until that point. +func use(p interface{}) {} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go new file mode 100644 index 00000000..cbec8f72 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go @@ -0,0 +1,100 @@ +// +build windows + +package winterm + +import "github.com/Azure/go-ansiterm" + +const ( + FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + BACKGROUND_COLOR_MASK = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE +) + +// collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the +// request represented by the passed ANSI mode. +func collectAnsiIntoWindowsAttributes(windowsMode uint16, inverted bool, baseMode uint16, ansiMode int16) (uint16, bool) { + switch ansiMode { + + // Mode styles + case ansiterm.ANSI_SGR_BOLD: + windowsMode = windowsMode | FOREGROUND_INTENSITY + + case ansiterm.ANSI_SGR_DIM, ansiterm.ANSI_SGR_BOLD_DIM_OFF: + windowsMode &^= FOREGROUND_INTENSITY + + case ansiterm.ANSI_SGR_UNDERLINE: + windowsMode = windowsMode | COMMON_LVB_UNDERSCORE + + case ansiterm.ANSI_SGR_REVERSE: + inverted = true + + case ansiterm.ANSI_SGR_REVERSE_OFF: + inverted = false + + case ansiterm.ANSI_SGR_UNDERLINE_OFF: + windowsMode &^= COMMON_LVB_UNDERSCORE + + // Foreground colors + case ansiterm.ANSI_SGR_FOREGROUND_DEFAULT: + windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK) + + case ansiterm.ANSI_SGR_FOREGROUND_BLACK: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) + + case ansiterm.ANSI_SGR_FOREGROUND_RED: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED + + case ansiterm.ANSI_SGR_FOREGROUND_GREEN: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN + + case ansiterm.ANSI_SGR_FOREGROUND_YELLOW: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN + + case ansiterm.ANSI_SGR_FOREGROUND_BLUE: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE + + case ansiterm.ANSI_SGR_FOREGROUND_MAGENTA: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE + + case ansiterm.ANSI_SGR_FOREGROUND_CYAN: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE + + case ansiterm.ANSI_SGR_FOREGROUND_WHITE: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + + // Background colors + case ansiterm.ANSI_SGR_BACKGROUND_DEFAULT: + // Black with no intensity + windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK) + + case ansiterm.ANSI_SGR_BACKGROUND_BLACK: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) + + case ansiterm.ANSI_SGR_BACKGROUND_RED: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED + + case ansiterm.ANSI_SGR_BACKGROUND_GREEN: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN + + case ansiterm.ANSI_SGR_BACKGROUND_YELLOW: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN + + case ansiterm.ANSI_SGR_BACKGROUND_BLUE: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE + + case ansiterm.ANSI_SGR_BACKGROUND_MAGENTA: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE + + case ansiterm.ANSI_SGR_BACKGROUND_CYAN: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE + + case ansiterm.ANSI_SGR_BACKGROUND_WHITE: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE + } + + return windowsMode, inverted +} + +// invertAttributes inverts the foreground and background colors of a Windows attributes value +func invertAttributes(windowsMode uint16) uint16 { + return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go new file mode 100644 index 00000000..f015723a --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go @@ -0,0 +1,101 @@ +// +build windows + +package winterm + +const ( + horizontal = iota + vertical +) + +func (h *windowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT { + if h.originMode { + sr := h.effectiveSr(info.Window) + return SMALL_RECT{ + Top: sr.top, + Bottom: sr.bottom, + Left: 0, + Right: info.Size.X - 1, + } + } else { + return SMALL_RECT{ + Top: info.Window.Top, + Bottom: info.Window.Bottom, + Left: 0, + Right: info.Size.X - 1, + } + } +} + +// setCursorPosition sets the cursor to the specified position, bounded to the screen size +func (h *windowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error { + position.X = ensureInRange(position.X, window.Left, window.Right) + position.Y = ensureInRange(position.Y, window.Top, window.Bottom) + err := SetConsoleCursorPosition(h.fd, position) + if err != nil { + return err + } + logger.Infof("Cursor position set: (%d, %d)", position.X, position.Y) + return err +} + +func (h *windowsAnsiEventHandler) moveCursorVertical(param int) error { + return h.moveCursor(vertical, param) +} + +func (h *windowsAnsiEventHandler) moveCursorHorizontal(param int) error { + return h.moveCursor(horizontal, param) +} + +func (h *windowsAnsiEventHandler) moveCursor(moveMode int, param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + switch moveMode { + case horizontal: + position.X += int16(param) + case vertical: + position.Y += int16(param) + } + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) moveCursorLine(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + position.X = 0 + position.Y += int16(param) + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) moveCursorColumn(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + position.X = int16(param) - 1 + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go new file mode 100644 index 00000000..244b5fa2 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go @@ -0,0 +1,84 @@ +// +build windows + +package winterm + +import "github.com/Azure/go-ansiterm" + +func (h *windowsAnsiEventHandler) clearRange(attributes uint16, fromCoord COORD, toCoord COORD) error { + // Ignore an invalid (negative area) request + if toCoord.Y < fromCoord.Y { + return nil + } + + var err error + + var coordStart = COORD{} + var coordEnd = COORD{} + + xCurrent, yCurrent := fromCoord.X, fromCoord.Y + xEnd, yEnd := toCoord.X, toCoord.Y + + // Clear any partial initial line + if xCurrent > 0 { + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yCurrent + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + xCurrent = 0 + yCurrent += 1 + } + + // Clear intervening rectangular section + if yCurrent < yEnd { + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yEnd-1 + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + xCurrent = 0 + yCurrent = yEnd + } + + // Clear remaining partial ending line + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yEnd + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) clearRect(attributes uint16, fromCoord COORD, toCoord COORD) error { + region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X} + width := toCoord.X - fromCoord.X + 1 + height := toCoord.Y - fromCoord.Y + 1 + size := uint32(width) * uint32(height) + + if size <= 0 { + return nil + } + + buffer := make([]CHAR_INFO, size) + + char := CHAR_INFO{ansiterm.FILL_CHARACTER, attributes} + for i := 0; i < int(size); i++ { + buffer[i] = char + } + + err := WriteConsoleOutput(h.fd, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, ®ion) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go new file mode 100644 index 00000000..706d2705 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go @@ -0,0 +1,118 @@ +// +build windows + +package winterm + +// effectiveSr gets the current effective scroll region in buffer coordinates +func (h *windowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { + top := addInRange(window.Top, h.sr.top, window.Top, window.Bottom) + bottom := addInRange(window.Top, h.sr.bottom, window.Top, window.Bottom) + if top >= bottom { + top = window.Top + bottom = window.Bottom + } + return scrollRegion{top: top, bottom: bottom} +} + +func (h *windowsAnsiEventHandler) scrollUp(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + sr := h.effectiveSr(info.Window) + return h.scroll(param, sr, info) +} + +func (h *windowsAnsiEventHandler) scrollDown(param int) error { + return h.scrollUp(-param) +} + +func (h *windowsAnsiEventHandler) deleteLines(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + start := info.CursorPosition.Y + sr := h.effectiveSr(info.Window) + // Lines cannot be inserted or deleted outside the scrolling region. + if start >= sr.top && start <= sr.bottom { + sr.top = start + return h.scroll(param, sr, info) + } else { + return nil + } +} + +func (h *windowsAnsiEventHandler) insertLines(param int) error { + return h.deleteLines(-param) +} + +// scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates. +func (h *windowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error { + logger.Infof("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom) + logger.Infof("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom) + + // Copy from and clip to the scroll region (full buffer width) + scrollRect := SMALL_RECT{ + Top: sr.top, + Bottom: sr.bottom, + Left: 0, + Right: info.Size.X - 1, + } + + // Origin to which area should be copied + destOrigin := COORD{ + X: 0, + Y: sr.top - int16(param), + } + + char := CHAR_INFO{ + UnicodeChar: ' ', + Attributes: h.attributes, + } + + if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { + return err + } + return nil +} + +func (h *windowsAnsiEventHandler) deleteCharacters(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + return h.scrollLine(param, info.CursorPosition, info) +} + +func (h *windowsAnsiEventHandler) insertCharacters(param int) error { + return h.deleteCharacters(-param) +} + +// scrollLine scrolls a line horizontally starting at the provided position by a number of columns. +func (h *windowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error { + // Copy from and clip to the scroll region (full buffer width) + scrollRect := SMALL_RECT{ + Top: position.Y, + Bottom: position.Y, + Left: position.X, + Right: info.Size.X - 1, + } + + // Origin to which area should be copied + destOrigin := COORD{ + X: position.X - int16(columns), + Y: position.Y, + } + + char := CHAR_INFO{ + UnicodeChar: ' ', + Attributes: h.attributes, + } + + if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go new file mode 100644 index 00000000..afa7635d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go @@ -0,0 +1,9 @@ +// +build windows + +package winterm + +// AddInRange increments a value by the passed quantity while ensuring the values +// always remain within the supplied min / max range. +func addInRange(n int16, increment int16, min int16, max int16) int16 { + return ensureInRange(n+increment, min, max) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go new file mode 100644 index 00000000..4d858ed6 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go @@ -0,0 +1,726 @@ +// +build windows + +package winterm + +import ( + "bytes" + "io/ioutil" + "os" + "strconv" + + "github.com/Azure/go-ansiterm" + "github.com/Sirupsen/logrus" +) + +var logger *logrus.Logger + +type windowsAnsiEventHandler struct { + fd uintptr + file *os.File + infoReset *CONSOLE_SCREEN_BUFFER_INFO + sr scrollRegion + buffer bytes.Buffer + attributes uint16 + inverted bool + wrapNext bool + drewMarginByte bool + originMode bool + marginByte byte + curInfo *CONSOLE_SCREEN_BUFFER_INFO + curPos COORD +} + +func CreateWinEventHandler(fd uintptr, file *os.File) ansiterm.AnsiEventHandler { + logFile := ioutil.Discard + + if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { + logFile, _ = os.Create("winEventHandler.log") + } + + logger = &logrus.Logger{ + Out: logFile, + Formatter: new(logrus.TextFormatter), + Level: logrus.DebugLevel, + } + + infoReset, err := GetConsoleScreenBufferInfo(fd) + if err != nil { + return nil + } + + return &windowsAnsiEventHandler{ + fd: fd, + file: file, + infoReset: infoReset, + attributes: infoReset.Attributes, + } +} + +type scrollRegion struct { + top int16 + bottom int16 +} + +// simulateLF simulates a LF or CR+LF by scrolling if necessary to handle the +// current cursor position and scroll region settings, in which case it returns +// true. If no special handling is necessary, then it does nothing and returns +// false. +// +// In the false case, the caller should ensure that a carriage return +// and line feed are inserted or that the text is otherwise wrapped. +func (h *windowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { + if h.wrapNext { + if err := h.Flush(); err != nil { + return false, err + } + h.clearWrap() + } + pos, info, err := h.getCurrentInfo() + if err != nil { + return false, err + } + sr := h.effectiveSr(info.Window) + if pos.Y == sr.bottom { + // Scrolling is necessary. Let Windows automatically scroll if the scrolling region + // is the full window. + if sr.top == info.Window.Top && sr.bottom == info.Window.Bottom { + if includeCR { + pos.X = 0 + h.updatePos(pos) + } + return false, nil + } + + // A custom scroll region is active. Scroll the window manually to simulate + // the LF. + if err := h.Flush(); err != nil { + return false, err + } + logger.Info("Simulating LF inside scroll region") + if err := h.scrollUp(1); err != nil { + return false, err + } + if includeCR { + pos.X = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return false, err + } + } + return true, nil + + } else if pos.Y < info.Window.Bottom { + // Let Windows handle the LF. + pos.Y++ + if includeCR { + pos.X = 0 + } + h.updatePos(pos) + return false, nil + } else { + // The cursor is at the bottom of the screen but outside the scroll + // region. Skip the LF. + logger.Info("Simulating LF outside scroll region") + if includeCR { + if err := h.Flush(); err != nil { + return false, err + } + pos.X = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return false, err + } + } + return true, nil + } +} + +// executeLF executes a LF without a CR. +func (h *windowsAnsiEventHandler) executeLF() error { + handled, err := h.simulateLF(false) + if err != nil { + return err + } + if !handled { + // Windows LF will reset the cursor column position. Write the LF + // and restore the cursor position. + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) + if pos.X != 0 { + if err := h.Flush(); err != nil { + return err + } + logger.Info("Resetting cursor position for LF without CR") + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + } + } + return nil +} + +func (h *windowsAnsiEventHandler) Print(b byte) error { + if h.wrapNext { + h.buffer.WriteByte(h.marginByte) + h.clearWrap() + if _, err := h.simulateLF(true); err != nil { + return err + } + } + pos, info, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X == info.Size.X-1 { + h.wrapNext = true + h.marginByte = b + } else { + pos.X++ + h.updatePos(pos) + h.buffer.WriteByte(b) + } + return nil +} + +func (h *windowsAnsiEventHandler) Execute(b byte) error { + switch b { + case ansiterm.ANSI_TAB: + logger.Info("Execute(TAB)") + // Move to the next tab stop, but preserve auto-wrap if already set. + if !h.wrapNext { + pos, info, err := h.getCurrentInfo() + if err != nil { + return err + } + pos.X = (pos.X + 8) - pos.X%8 + if pos.X >= info.Size.X { + pos.X = info.Size.X - 1 + } + if err := h.Flush(); err != nil { + return err + } + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + } + return nil + + case ansiterm.ANSI_BEL: + h.buffer.WriteByte(ansiterm.ANSI_BEL) + return nil + + case ansiterm.ANSI_BACKSPACE: + if h.wrapNext { + if err := h.Flush(); err != nil { + return err + } + h.clearWrap() + } + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X > 0 { + pos.X-- + h.updatePos(pos) + h.buffer.WriteByte(ansiterm.ANSI_BACKSPACE) + } + return nil + + case ansiterm.ANSI_VERTICAL_TAB, ansiterm.ANSI_FORM_FEED: + // Treat as true LF. + return h.executeLF() + + case ansiterm.ANSI_LINE_FEED: + // Simulate a CR and LF for now since there is no way in go-ansiterm + // to tell if the LF should include CR (and more things break when it's + // missing than when it's incorrectly added). + handled, err := h.simulateLF(true) + if handled || err != nil { + return err + } + return h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) + + case ansiterm.ANSI_CARRIAGE_RETURN: + if h.wrapNext { + if err := h.Flush(); err != nil { + return err + } + h.clearWrap() + } + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X != 0 { + pos.X = 0 + h.updatePos(pos) + h.buffer.WriteByte(ansiterm.ANSI_CARRIAGE_RETURN) + } + return nil + + default: + return nil + } +} + +func (h *windowsAnsiEventHandler) CUU(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUU: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorVertical(-param) +} + +func (h *windowsAnsiEventHandler) CUD(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUD: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorVertical(param) +} + +func (h *windowsAnsiEventHandler) CUF(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUF: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorHorizontal(param) +} + +func (h *windowsAnsiEventHandler) CUB(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUB: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorHorizontal(-param) +} + +func (h *windowsAnsiEventHandler) CNL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CNL: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorLine(param) +} + +func (h *windowsAnsiEventHandler) CPL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CPL: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorLine(-param) +} + +func (h *windowsAnsiEventHandler) CHA(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CHA: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorColumn(param) +} + +func (h *windowsAnsiEventHandler) VPA(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("VPA: [[%d]]", param) + h.clearWrap() + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + window := h.getCursorWindow(info) + position := info.CursorPosition + position.Y = window.Top + int16(param) - 1 + return h.setCursorPosition(position, window) +} + +func (h *windowsAnsiEventHandler) CUP(row int, col int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUP: [[%d %d]]", row, col) + h.clearWrap() + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + window := h.getCursorWindow(info) + position := COORD{window.Left + int16(col) - 1, window.Top + int16(row) - 1} + return h.setCursorPosition(position, window) +} + +func (h *windowsAnsiEventHandler) HVP(row int, col int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("HVP: [[%d %d]]", row, col) + h.clearWrap() + return h.CUP(row, col) +} + +func (h *windowsAnsiEventHandler) DECTCEM(visible bool) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DECTCEM: [%v]", []string{strconv.FormatBool(visible)}) + h.clearWrap() + return nil +} + +func (h *windowsAnsiEventHandler) DECOM(enable bool) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DECOM: [%v]", []string{strconv.FormatBool(enable)}) + h.clearWrap() + h.originMode = enable + return h.CUP(1, 1) +} + +func (h *windowsAnsiEventHandler) DECCOLM(use132 bool) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DECCOLM: [%v]", []string{strconv.FormatBool(use132)}) + h.clearWrap() + if err := h.ED(2); err != nil { + return err + } + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + targetWidth := int16(80) + if use132 { + targetWidth = 132 + } + if info.Size.X < targetWidth { + if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { + logger.Info("set buffer failed:", err) + return err + } + } + window := info.Window + window.Left = 0 + window.Right = targetWidth - 1 + if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { + logger.Info("set window failed:", err) + return err + } + if info.Size.X > targetWidth { + if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { + logger.Info("set buffer failed:", err) + return err + } + } + return SetConsoleCursorPosition(h.fd, COORD{0, 0}) +} + +func (h *windowsAnsiEventHandler) ED(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("ED: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + + // [J -- Erases from the cursor to the end of the screen, including the cursor position. + // [1J -- Erases from the beginning of the screen to the cursor, including the cursor position. + // [2J -- Erases the complete display. The cursor does not move. + // Notes: + // -- Clearing the entire buffer, versus just the Window, works best for Windows Consoles + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + var start COORD + var end COORD + + switch param { + case 0: + start = info.CursorPosition + end = COORD{info.Size.X - 1, info.Size.Y - 1} + + case 1: + start = COORD{0, 0} + end = info.CursorPosition + + case 2: + start = COORD{0, 0} + end = COORD{info.Size.X - 1, info.Size.Y - 1} + } + + err = h.clearRange(h.attributes, start, end) + if err != nil { + return err + } + + // If the whole buffer was cleared, move the window to the top while preserving + // the window-relative cursor position. + if param == 2 { + pos := info.CursorPosition + window := info.Window + pos.Y -= window.Top + window.Bottom -= window.Top + window.Top = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { + return err + } + } + + return nil +} + +func (h *windowsAnsiEventHandler) EL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("EL: [%v]", strconv.Itoa(param)) + h.clearWrap() + + // [K -- Erases from the cursor to the end of the line, including the cursor position. + // [1K -- Erases from the beginning of the line to the cursor, including the cursor position. + // [2K -- Erases the complete line. + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + var start COORD + var end COORD + + switch param { + case 0: + start = info.CursorPosition + end = COORD{info.Size.X, info.CursorPosition.Y} + + case 1: + start = COORD{0, info.CursorPosition.Y} + end = info.CursorPosition + + case 2: + start = COORD{0, info.CursorPosition.Y} + end = COORD{info.Size.X, info.CursorPosition.Y} + } + + err = h.clearRange(h.attributes, start, end) + if err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) IL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("IL: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.insertLines(param) +} + +func (h *windowsAnsiEventHandler) DL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DL: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.deleteLines(param) +} + +func (h *windowsAnsiEventHandler) ICH(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("ICH: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.insertCharacters(param) +} + +func (h *windowsAnsiEventHandler) DCH(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DCH: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.deleteCharacters(param) +} + +func (h *windowsAnsiEventHandler) SGR(params []int) error { + if err := h.Flush(); err != nil { + return err + } + strings := []string{} + for _, v := range params { + strings = append(strings, strconv.Itoa(v)) + } + + logger.Infof("SGR: [%v]", strings) + + if len(params) <= 0 { + h.attributes = h.infoReset.Attributes + h.inverted = false + } else { + for _, attr := range params { + + if attr == ansiterm.ANSI_SGR_RESET { + h.attributes = h.infoReset.Attributes + h.inverted = false + continue + } + + h.attributes, h.inverted = collectAnsiIntoWindowsAttributes(h.attributes, h.inverted, h.infoReset.Attributes, int16(attr)) + } + } + + attributes := h.attributes + if h.inverted { + attributes = invertAttributes(attributes) + } + err := SetConsoleTextAttribute(h.fd, attributes) + if err != nil { + return err + } + + return nil +} + +func (h *windowsAnsiEventHandler) SU(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("SU: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.scrollUp(param) +} + +func (h *windowsAnsiEventHandler) SD(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("SD: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.scrollDown(param) +} + +func (h *windowsAnsiEventHandler) DA(params []string) error { + logger.Infof("DA: [%v]", params) + // DA cannot be implemented because it must send data on the VT100 input stream, + // which is not available to go-ansiterm. + return nil +} + +func (h *windowsAnsiEventHandler) DECSTBM(top int, bottom int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DECSTBM: [%d, %d]", top, bottom) + + // Windows is 0 indexed, Linux is 1 indexed + h.sr.top = int16(top - 1) + h.sr.bottom = int16(bottom - 1) + + // This command also moves the cursor to the origin. + h.clearWrap() + return h.CUP(1, 1) +} + +func (h *windowsAnsiEventHandler) RI() error { + if err := h.Flush(); err != nil { + return err + } + logger.Info("RI: []") + h.clearWrap() + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + sr := h.effectiveSr(info.Window) + if info.CursorPosition.Y == sr.top { + return h.scrollDown(1) + } + + return h.moveCursorVertical(-1) +} + +func (h *windowsAnsiEventHandler) IND() error { + logger.Info("IND: []") + return h.executeLF() +} + +func (h *windowsAnsiEventHandler) Flush() error { + h.curInfo = nil + if h.buffer.Len() > 0 { + logger.Infof("Flush: [%s]", h.buffer.Bytes()) + if _, err := h.buffer.WriteTo(h.file); err != nil { + return err + } + } + + if h.wrapNext && !h.drewMarginByte { + logger.Infof("Flush: drawing margin byte '%c'", h.marginByte) + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + charInfo := []CHAR_INFO{{UnicodeChar: uint16(h.marginByte), Attributes: info.Attributes}} + size := COORD{1, 1} + position := COORD{0, 0} + region := SMALL_RECT{Left: info.CursorPosition.X, Top: info.CursorPosition.Y, Right: info.CursorPosition.X, Bottom: info.CursorPosition.Y} + if err := WriteConsoleOutput(h.fd, charInfo, size, position, ®ion); err != nil { + return err + } + h.drewMarginByte = true + } + return nil +} + +// cacheConsoleInfo ensures that the current console screen information has been queried +// since the last call to Flush(). It must be called before accessing h.curInfo or h.curPos. +func (h *windowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFER_INFO, error) { + if h.curInfo == nil { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return COORD{}, nil, err + } + h.curInfo = info + h.curPos = info.CursorPosition + } + return h.curPos, h.curInfo, nil +} + +func (h *windowsAnsiEventHandler) updatePos(pos COORD) { + if h.curInfo == nil { + panic("failed to call getCurrentInfo before calling updatePos") + } + h.curPos = pos +} + +// clearWrap clears the state where the cursor is in the margin +// waiting for the next character before wrapping the line. This must +// be done before most operations that act on the cursor. +func (h *windowsAnsiEventHandler) clearWrap() { + h.wrapNext = false + h.drewMarginByte = false +} diff --git a/vendor/github.com/PuerkitoBio/purell/.gitignore b/vendor/github.com/PuerkitoBio/purell/.gitignore new file mode 100644 index 00000000..748e4c80 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/.gitignore @@ -0,0 +1,5 @@ +*.sublime-* +.DS_Store +*.swp +*.swo +tags diff --git a/vendor/github.com/PuerkitoBio/purell/.travis.yml b/vendor/github.com/PuerkitoBio/purell/.travis.yml new file mode 100644 index 00000000..facfc91c --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/.travis.yml @@ -0,0 +1,7 @@ +language: go + +go: + - 1.4 + - 1.5 + - 1.6 + - tip diff --git a/vendor/github.com/PuerkitoBio/purell/LICENSE b/vendor/github.com/PuerkitoBio/purell/LICENSE new file mode 100644 index 00000000..4b9986de --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/LICENSE @@ -0,0 +1,12 @@ +Copyright (c) 2012, Martin Angers +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/PuerkitoBio/purell/README.md b/vendor/github.com/PuerkitoBio/purell/README.md new file mode 100644 index 00000000..09e8a32c --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/README.md @@ -0,0 +1,187 @@ +# Purell + +Purell is a tiny Go library to normalize URLs. It returns a pure URL. Pure-ell. Sanitizer and all. Yeah, I know... + +Based on the [wikipedia paper][wiki] and the [RFC 3986 document][rfc]. + +[![build status](https://secure.travis-ci.org/PuerkitoBio/purell.png)](http://travis-ci.org/PuerkitoBio/purell) + +## Install + +`go get github.com/PuerkitoBio/purell` + +## Changelog + +* **2016-11-14 (v1.1.0)** : IDN: Conform to RFC 5895: Fold character width (thanks to @beeker1121). +* **2016-07-27 (v1.0.0)** : Normalize IDN to ASCII (thanks to @zenovich). +* **2015-02-08** : Add fix for relative paths issue ([PR #5][pr5]) and add fix for unnecessary encoding of reserved characters ([see issue #7][iss7]). +* **v0.2.0** : Add benchmarks, Attempt IDN support. +* **v0.1.0** : Initial release. + +## Examples + +From `example_test.go` (note that in your code, you would import "github.com/PuerkitoBio/purell", and would prefix references to its methods and constants with "purell."): + +```go +package purell + +import ( + "fmt" + "net/url" +) + +func ExampleNormalizeURLString() { + if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", + FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { + panic(err) + } else { + fmt.Print(normalized) + } + // Output: http://somewebsite.com:80/Amazing%3F/url/ +} + +func ExampleMustNormalizeURLString() { + normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", + FlagsUnsafeGreedy) + fmt.Print(normalized) + + // Output: http://somewebsite.com/Amazing%FA/url +} + +func ExampleNormalizeURL() { + if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { + panic(err) + } else { + normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) + fmt.Print(normalized) + } + + // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 +} +``` + +## API + +As seen in the examples above, purell offers three methods, `NormalizeURLString(string, NormalizationFlags) (string, error)`, `MustNormalizeURLString(string, NormalizationFlags) (string)` and `NormalizeURL(*url.URL, NormalizationFlags) (string)`. They all normalize the provided URL based on the specified flags. Here are the available flags: + +```go +const ( + // Safe normalizations + FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 + FlagLowercaseHost // http://HOST -> http://host + FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF + FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA + FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ + FlagRemoveDefaultPort // http://host:80 -> http://host + FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path + + // Usually safe normalizations + FlagRemoveTrailingSlash // http://host/path/ -> http://host/path + FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) + FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c + + // Unsafe normalizations + FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ + FlagRemoveFragment // http://host/path#fragment -> http://host/path + FlagForceHTTP // https://host -> http://host + FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b + FlagRemoveWWW // http://www.host/ -> http://host/ + FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) + FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 + + // Normalizations not in the wikipedia article, required to cover tests cases + // submitted by jehiah + FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 + FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 + FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 + FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path + FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path + + // Convenience set of safe normalizations + FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator + + // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, + // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". + + // Convenience set of usually safe normalizations (includes FlagsSafe) + FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments + FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments + + // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) + FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery + FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery + + // Convenience set of all available flags + FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator + FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator +) +``` + +For convenience, the set of flags `FlagsSafe`, `FlagsUsuallySafe[Greedy|NonGreedy]`, `FlagsUnsafe[Greedy|NonGreedy]` and `FlagsAll[Greedy|NonGreedy]` are provided for the similarly grouped normalizations on [wikipedia's URL normalization page][wiki]. You can add (using the bitwise OR `|` operator) or remove (using the bitwise AND NOT `&^` operator) individual flags from the sets if required, to build your own custom set. + +The [full godoc reference is available on gopkgdoc][godoc]. + +Some things to note: + +* `FlagDecodeUnnecessaryEscapes`, `FlagEncodeNecessaryEscapes`, `FlagUppercaseEscapes` and `FlagRemoveEmptyQuerySeparator` are always implicitly set, because internally, the URL string is parsed as an URL object, which automatically decodes unnecessary escapes, uppercases and encodes necessary ones, and removes empty query separators (an unnecessary `?` at the end of the url). So this operation cannot **not** be done. For this reason, `FlagRemoveEmptyQuerySeparator` (as well as the other three) has been included in the `FlagsSafe` convenience set, instead of `FlagsUnsafe`, where Wikipedia puts it. + +* The `FlagDecodeUnnecessaryEscapes` decodes the following escapes (*from -> to*): + - %24 -> $ + - %26 -> & + - %2B-%3B -> +,-./0123456789:; + - %3D -> = + - %40-%5A -> @ABCDEFGHIJKLMNOPQRSTUVWXYZ + - %5F -> _ + - %61-%7A -> abcdefghijklmnopqrstuvwxyz + - %7E -> ~ + + +* When the `NormalizeURL` function is used (passing an URL object), this source URL object is modified (that is, after the call, the URL object will be modified to reflect the normalization). + +* The *replace IP with domain name* normalization (`http://208.77.188.166/ → http://www.example.com/`) is obviously not possible for a library without making some network requests. This is not implemented in purell. + +* The *remove unused query string parameters* and *remove default query parameters* are also not implemented, since this is a very case-specific normalization, and it is quite trivial to do with an URL object. + +### Safe vs Usually Safe vs Unsafe + +Purell allows you to control the level of risk you take while normalizing an URL. You can aggressively normalize, play it totally safe, or anything in between. + +Consider the following URL: + +`HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` + +Normalizing with the `FlagsSafe` gives: + +`https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` + +With the `FlagsUsuallySafeGreedy`: + +`https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid` + +And with `FlagsUnsafeGreedy`: + +`http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3` + +## TODOs + +* Add a class/default instance to allow specifying custom directory index names? At the moment, removing directory index removes `(^|/)((?:default|index)\.\w{1,4})$`. + +## Thanks / Contributions + +@rogpeppe +@jehiah +@opennota +@pchristopher1275 +@zenovich +@beeker1121 + +## License + +The [BSD 3-Clause license][bsd]. + +[bsd]: http://opensource.org/licenses/BSD-3-Clause +[wiki]: http://en.wikipedia.org/wiki/URL_normalization +[rfc]: http://tools.ietf.org/html/rfc3986#section-6 +[godoc]: http://go.pkgdoc.org/github.com/PuerkitoBio/purell +[pr5]: https://github.com/PuerkitoBio/purell/pull/5 +[iss7]: https://github.com/PuerkitoBio/purell/issues/7 diff --git a/vendor/github.com/PuerkitoBio/purell/bench_test.go b/vendor/github.com/PuerkitoBio/purell/bench_test.go new file mode 100644 index 00000000..7549731f --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/bench_test.go @@ -0,0 +1,57 @@ +package purell + +import ( + "testing" +) + +var ( + safeUrl = "HttPS://..iaMHost..Test:443/paTh^A%ef//./%41PaTH/..//?" + usuallySafeUrl = "HttPS://..iaMHost..Test:443/paTh^A%ef//./%41PaTH/../final/" + unsafeUrl = "HttPS://..www.iaMHost..Test:443/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" + allDWORDUrl = "HttPS://1113982867:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" + allOctalUrl = "HttPS://0102.0146.07.0223:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" + allHexUrl = "HttPS://0x42660793:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" + allCombinedUrl = "HttPS://..0x42660793.:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" +) + +func BenchmarkSafe(b *testing.B) { + for i := 0; i < b.N; i++ { + NormalizeURLString(safeUrl, FlagsSafe) + } +} + +func BenchmarkUsuallySafe(b *testing.B) { + for i := 0; i < b.N; i++ { + NormalizeURLString(usuallySafeUrl, FlagsUsuallySafeGreedy) + } +} + +func BenchmarkUnsafe(b *testing.B) { + for i := 0; i < b.N; i++ { + NormalizeURLString(unsafeUrl, FlagsUnsafeGreedy) + } +} + +func BenchmarkAllDWORD(b *testing.B) { + for i := 0; i < b.N; i++ { + NormalizeURLString(allDWORDUrl, FlagsAllGreedy) + } +} + +func BenchmarkAllOctal(b *testing.B) { + for i := 0; i < b.N; i++ { + NormalizeURLString(allOctalUrl, FlagsAllGreedy) + } +} + +func BenchmarkAllHex(b *testing.B) { + for i := 0; i < b.N; i++ { + NormalizeURLString(allHexUrl, FlagsAllGreedy) + } +} + +func BenchmarkAllCombined(b *testing.B) { + for i := 0; i < b.N; i++ { + NormalizeURLString(allCombinedUrl, FlagsAllGreedy) + } +} diff --git a/vendor/github.com/PuerkitoBio/purell/benchmarks/v0.1.0 b/vendor/github.com/PuerkitoBio/purell/benchmarks/v0.1.0 new file mode 100644 index 00000000..3bbe7113 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/benchmarks/v0.1.0 @@ -0,0 +1,9 @@ +PASS +BenchmarkSafe 500000 6131 ns/op +BenchmarkUsuallySafe 200000 7864 ns/op +BenchmarkUnsafe 100000 28560 ns/op +BenchmarkAllDWORD 50000 38722 ns/op +BenchmarkAllOctal 50000 40941 ns/op +BenchmarkAllHex 50000 44063 ns/op +BenchmarkAllCombined 50000 33613 ns/op +ok github.com/PuerkitoBio/purell 17.404s diff --git a/vendor/github.com/PuerkitoBio/purell/example_test.go b/vendor/github.com/PuerkitoBio/purell/example_test.go new file mode 100644 index 00000000..997b9536 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/example_test.go @@ -0,0 +1,35 @@ +package purell + +import ( + "fmt" + "net/url" +) + +func ExampleNormalizeURLString() { + if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", + FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { + panic(err) + } else { + fmt.Print(normalized) + } + // Output: http://somewebsite.com:80/Amazing%3F/url/ +} + +func ExampleMustNormalizeURLString() { + normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", + FlagsUnsafeGreedy) + fmt.Print(normalized) + + // Output: http://somewebsite.com/Amazing%FA/url +} + +func ExampleNormalizeURL() { + if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { + panic(err) + } else { + normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) + fmt.Print(normalized) + } + + // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 +} diff --git a/vendor/github.com/PuerkitoBio/purell/purell.go b/vendor/github.com/PuerkitoBio/purell/purell.go new file mode 100644 index 00000000..645e1b76 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/purell.go @@ -0,0 +1,379 @@ +/* +Package purell offers URL normalization as described on the wikipedia page: +http://en.wikipedia.org/wiki/URL_normalization +*/ +package purell + +import ( + "bytes" + "fmt" + "net/url" + "regexp" + "sort" + "strconv" + "strings" + + "github.com/PuerkitoBio/urlesc" + "golang.org/x/net/idna" + "golang.org/x/text/unicode/norm" + "golang.org/x/text/width" +) + +// A set of normalization flags determines how a URL will +// be normalized. +type NormalizationFlags uint + +const ( + // Safe normalizations + FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 + FlagLowercaseHost // http://HOST -> http://host + FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF + FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA + FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ + FlagRemoveDefaultPort // http://host:80 -> http://host + FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path + + // Usually safe normalizations + FlagRemoveTrailingSlash // http://host/path/ -> http://host/path + FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) + FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c + + // Unsafe normalizations + FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ + FlagRemoveFragment // http://host/path#fragment -> http://host/path + FlagForceHTTP // https://host -> http://host + FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b + FlagRemoveWWW // http://www.host/ -> http://host/ + FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) + FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 + + // Normalizations not in the wikipedia article, required to cover tests cases + // submitted by jehiah + FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 + FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 + FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 + FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path + FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path + + // Convenience set of safe normalizations + FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator + + // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, + // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". + + // Convenience set of usually safe normalizations (includes FlagsSafe) + FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments + FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments + + // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) + FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery + FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery + + // Convenience set of all available flags + FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator + FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator +) + +const ( + defaultHttpPort = ":80" + defaultHttpsPort = ":443" +) + +// Regular expressions used by the normalizations +var rxPort = regexp.MustCompile(`(:\d+)/?$`) +var rxDirIndex = regexp.MustCompile(`(^|/)((?:default|index)\.\w{1,4})$`) +var rxDupSlashes = regexp.MustCompile(`/{2,}`) +var rxDWORDHost = regexp.MustCompile(`^(\d+)((?:\.+)?(?:\:\d*)?)$`) +var rxOctalHost = regexp.MustCompile(`^(0\d*)\.(0\d*)\.(0\d*)\.(0\d*)((?:\.+)?(?:\:\d*)?)$`) +var rxHexHost = regexp.MustCompile(`^0x([0-9A-Fa-f]+)((?:\.+)?(?:\:\d*)?)$`) +var rxHostDots = regexp.MustCompile(`^(.+?)(:\d+)?$`) +var rxEmptyPort = regexp.MustCompile(`:+$`) + +// Map of flags to implementation function. +// FlagDecodeUnnecessaryEscapes has no action, since it is done automatically +// by parsing the string as an URL. Same for FlagUppercaseEscapes and FlagRemoveEmptyQuerySeparator. + +// Since maps have undefined traversing order, make a slice of ordered keys +var flagsOrder = []NormalizationFlags{ + FlagLowercaseScheme, + FlagLowercaseHost, + FlagRemoveDefaultPort, + FlagRemoveDirectoryIndex, + FlagRemoveDotSegments, + FlagRemoveFragment, + FlagForceHTTP, // Must be after remove default port (because https=443/http=80) + FlagRemoveDuplicateSlashes, + FlagRemoveWWW, + FlagAddWWW, + FlagSortQuery, + FlagDecodeDWORDHost, + FlagDecodeOctalHost, + FlagDecodeHexHost, + FlagRemoveUnnecessaryHostDots, + FlagRemoveEmptyPortSeparator, + FlagRemoveTrailingSlash, // These two (add/remove trailing slash) must be last + FlagAddTrailingSlash, +} + +// ... and then the map, where order is unimportant +var flags = map[NormalizationFlags]func(*url.URL){ + FlagLowercaseScheme: lowercaseScheme, + FlagLowercaseHost: lowercaseHost, + FlagRemoveDefaultPort: removeDefaultPort, + FlagRemoveDirectoryIndex: removeDirectoryIndex, + FlagRemoveDotSegments: removeDotSegments, + FlagRemoveFragment: removeFragment, + FlagForceHTTP: forceHTTP, + FlagRemoveDuplicateSlashes: removeDuplicateSlashes, + FlagRemoveWWW: removeWWW, + FlagAddWWW: addWWW, + FlagSortQuery: sortQuery, + FlagDecodeDWORDHost: decodeDWORDHost, + FlagDecodeOctalHost: decodeOctalHost, + FlagDecodeHexHost: decodeHexHost, + FlagRemoveUnnecessaryHostDots: removeUnncessaryHostDots, + FlagRemoveEmptyPortSeparator: removeEmptyPortSeparator, + FlagRemoveTrailingSlash: removeTrailingSlash, + FlagAddTrailingSlash: addTrailingSlash, +} + +// MustNormalizeURLString returns the normalized string, and panics if an error occurs. +// It takes an URL string as input, as well as the normalization flags. +func MustNormalizeURLString(u string, f NormalizationFlags) string { + result, e := NormalizeURLString(u, f) + if e != nil { + panic(e) + } + return result +} + +// NormalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object. +// It takes an URL string as input, as well as the normalization flags. +func NormalizeURLString(u string, f NormalizationFlags) (string, error) { + parsed, err := url.Parse(u) + if err != nil { + return "", err + } + + if f&FlagLowercaseHost == FlagLowercaseHost { + parsed.Host = strings.ToLower(parsed.Host) + } + + // The idna package doesn't fully conform to RFC 5895 + // (https://tools.ietf.org/html/rfc5895), so we do it here. + // Taken from Go 1.8 cycle source, courtesy of bradfitz. + // TODO: Remove when (if?) idna package conforms to RFC 5895. + parsed.Host = width.Fold.String(parsed.Host) + parsed.Host = norm.NFC.String(parsed.Host) + if parsed.Host, err = idna.ToASCII(parsed.Host); err != nil { + return "", err + } + + return NormalizeURL(parsed, f), nil +} + +// NormalizeURL returns the normalized string. +// It takes a parsed URL object as input, as well as the normalization flags. +func NormalizeURL(u *url.URL, f NormalizationFlags) string { + for _, k := range flagsOrder { + if f&k == k { + flags[k](u) + } + } + return urlesc.Escape(u) +} + +func lowercaseScheme(u *url.URL) { + if len(u.Scheme) > 0 { + u.Scheme = strings.ToLower(u.Scheme) + } +} + +func lowercaseHost(u *url.URL) { + if len(u.Host) > 0 { + u.Host = strings.ToLower(u.Host) + } +} + +func removeDefaultPort(u *url.URL) { + if len(u.Host) > 0 { + scheme := strings.ToLower(u.Scheme) + u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string { + if (scheme == "http" && val == defaultHttpPort) || (scheme == "https" && val == defaultHttpsPort) { + return "" + } + return val + }) + } +} + +func removeTrailingSlash(u *url.URL) { + if l := len(u.Path); l > 0 { + if strings.HasSuffix(u.Path, "/") { + u.Path = u.Path[:l-1] + } + } else if l = len(u.Host); l > 0 { + if strings.HasSuffix(u.Host, "/") { + u.Host = u.Host[:l-1] + } + } +} + +func addTrailingSlash(u *url.URL) { + if l := len(u.Path); l > 0 { + if !strings.HasSuffix(u.Path, "/") { + u.Path += "/" + } + } else if l = len(u.Host); l > 0 { + if !strings.HasSuffix(u.Host, "/") { + u.Host += "/" + } + } +} + +func removeDotSegments(u *url.URL) { + if len(u.Path) > 0 { + var dotFree []string + var lastIsDot bool + + sections := strings.Split(u.Path, "/") + for _, s := range sections { + if s == ".." { + if len(dotFree) > 0 { + dotFree = dotFree[:len(dotFree)-1] + } + } else if s != "." { + dotFree = append(dotFree, s) + } + lastIsDot = (s == "." || s == "..") + } + // Special case if host does not end with / and new path does not begin with / + u.Path = strings.Join(dotFree, "/") + if u.Host != "" && !strings.HasSuffix(u.Host, "/") && !strings.HasPrefix(u.Path, "/") { + u.Path = "/" + u.Path + } + // Special case if the last segment was a dot, make sure the path ends with a slash + if lastIsDot && !strings.HasSuffix(u.Path, "/") { + u.Path += "/" + } + } +} + +func removeDirectoryIndex(u *url.URL) { + if len(u.Path) > 0 { + u.Path = rxDirIndex.ReplaceAllString(u.Path, "$1") + } +} + +func removeFragment(u *url.URL) { + u.Fragment = "" +} + +func forceHTTP(u *url.URL) { + if strings.ToLower(u.Scheme) == "https" { + u.Scheme = "http" + } +} + +func removeDuplicateSlashes(u *url.URL) { + if len(u.Path) > 0 { + u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/") + } +} + +func removeWWW(u *url.URL) { + if len(u.Host) > 0 && strings.HasPrefix(strings.ToLower(u.Host), "www.") { + u.Host = u.Host[4:] + } +} + +func addWWW(u *url.URL) { + if len(u.Host) > 0 && !strings.HasPrefix(strings.ToLower(u.Host), "www.") { + u.Host = "www." + u.Host + } +} + +func sortQuery(u *url.URL) { + q := u.Query() + + if len(q) > 0 { + arKeys := make([]string, len(q)) + i := 0 + for k, _ := range q { + arKeys[i] = k + i++ + } + sort.Strings(arKeys) + buf := new(bytes.Buffer) + for _, k := range arKeys { + sort.Strings(q[k]) + for _, v := range q[k] { + if buf.Len() > 0 { + buf.WriteRune('&') + } + buf.WriteString(fmt.Sprintf("%s=%s", k, urlesc.QueryEscape(v))) + } + } + + // Rebuild the raw query string + u.RawQuery = buf.String() + } +} + +func decodeDWORDHost(u *url.URL) { + if len(u.Host) > 0 { + if matches := rxDWORDHost.FindStringSubmatch(u.Host); len(matches) > 2 { + var parts [4]int64 + + dword, _ := strconv.ParseInt(matches[1], 10, 0) + for i, shift := range []uint{24, 16, 8, 0} { + parts[i] = dword >> shift & 0xFF + } + u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[2]) + } + } +} + +func decodeOctalHost(u *url.URL) { + if len(u.Host) > 0 { + if matches := rxOctalHost.FindStringSubmatch(u.Host); len(matches) > 5 { + var parts [4]int64 + + for i := 1; i <= 4; i++ { + parts[i-1], _ = strconv.ParseInt(matches[i], 8, 0) + } + u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[5]) + } + } +} + +func decodeHexHost(u *url.URL) { + if len(u.Host) > 0 { + if matches := rxHexHost.FindStringSubmatch(u.Host); len(matches) > 2 { + // Conversion is safe because of regex validation + parsed, _ := strconv.ParseInt(matches[1], 16, 0) + // Set host as DWORD (base 10) encoded host + u.Host = fmt.Sprintf("%d%s", parsed, matches[2]) + // The rest is the same as decoding a DWORD host + decodeDWORDHost(u) + } + } +} + +func removeUnncessaryHostDots(u *url.URL) { + if len(u.Host) > 0 { + if matches := rxHostDots.FindStringSubmatch(u.Host); len(matches) > 1 { + // Trim the leading and trailing dots + u.Host = strings.Trim(matches[1], ".") + if len(matches) > 2 { + u.Host += matches[2] + } + } + } +} + +func removeEmptyPortSeparator(u *url.URL) { + if len(u.Host) > 0 { + u.Host = rxEmptyPort.ReplaceAllString(u.Host, "") + } +} diff --git a/vendor/github.com/PuerkitoBio/purell/purell_test.go b/vendor/github.com/PuerkitoBio/purell/purell_test.go new file mode 100644 index 00000000..a3732e5a --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/purell_test.go @@ -0,0 +1,768 @@ +package purell + +import ( + "fmt" + "net/url" + "testing" +) + +type testCase struct { + nm string + src string + flgs NormalizationFlags + res string + parsed bool +} + +var ( + cases = [...]*testCase{ + &testCase{ + "LowerScheme", + "HTTP://www.SRC.ca", + FlagLowercaseScheme, + "http://www.SRC.ca", + false, + }, + &testCase{ + "LowerScheme2", + "http://www.SRC.ca", + FlagLowercaseScheme, + "http://www.SRC.ca", + false, + }, + &testCase{ + "LowerHost", + "HTTP://www.SRC.ca/", + FlagLowercaseHost, + "http://www.src.ca/", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "UpperEscapes", + `http://www.whatever.com/Some%aa%20Special%8Ecases/`, + FlagUppercaseEscapes, + "http://www.whatever.com/Some%AA%20Special%8Ecases/", + false, + }, + &testCase{ + "UnnecessaryEscapes", + `http://www.toto.com/%41%42%2E%44/%32%33%52%2D/%5f%7E`, + FlagDecodeUnnecessaryEscapes, + "http://www.toto.com/AB.D/23R-/_~", + false, + }, + &testCase{ + "RemoveDefaultPort", + "HTTP://www.SRC.ca:80/", + FlagRemoveDefaultPort, + "http://www.SRC.ca/", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "RemoveDefaultPort2", + "HTTP://www.SRC.ca:80", + FlagRemoveDefaultPort, + "http://www.SRC.ca", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "RemoveDefaultPort3", + "HTTP://www.SRC.ca:8080", + FlagRemoveDefaultPort, + "http://www.SRC.ca:8080", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "Safe", + "HTTP://www.SRC.ca:80/to%1ato%8b%ee/OKnow%41%42%43%7e", + FlagsSafe, + "http://www.src.ca/to%1Ato%8B%EE/OKnowABC~", + false, + }, + &testCase{ + "BothLower", + "HTTP://www.SRC.ca:80/to%1ato%8b%ee/OKnow%41%42%43%7e", + FlagLowercaseHost | FlagLowercaseScheme, + "http://www.src.ca:80/to%1Ato%8B%EE/OKnowABC~", + false, + }, + &testCase{ + "RemoveTrailingSlash", + "HTTP://www.SRC.ca:80/", + FlagRemoveTrailingSlash, + "http://www.SRC.ca:80", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "RemoveTrailingSlash2", + "HTTP://www.SRC.ca:80/toto/titi/", + FlagRemoveTrailingSlash, + "http://www.SRC.ca:80/toto/titi", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "RemoveTrailingSlash3", + "HTTP://www.SRC.ca:80/toto/titi/fin/?a=1", + FlagRemoveTrailingSlash, + "http://www.SRC.ca:80/toto/titi/fin?a=1", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "AddTrailingSlash", + "HTTP://www.SRC.ca:80", + FlagAddTrailingSlash, + "http://www.SRC.ca:80/", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "AddTrailingSlash2", + "HTTP://www.SRC.ca:80/toto/titi.html", + FlagAddTrailingSlash, + "http://www.SRC.ca:80/toto/titi.html/", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "AddTrailingSlash3", + "HTTP://www.SRC.ca:80/toto/titi/fin?a=1", + FlagAddTrailingSlash, + "http://www.SRC.ca:80/toto/titi/fin/?a=1", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "RemoveDotSegments", + "HTTP://root/a/b/./../../c/", + FlagRemoveDotSegments, + "http://root/c/", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "RemoveDotSegments2", + "HTTP://root/../a/b/./../c/../d", + FlagRemoveDotSegments, + "http://root/a/d", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "UsuallySafe", + "HTTP://www.SRC.ca:80/to%1ato%8b%ee/./c/d/../OKnow%41%42%43%7e/?a=b#test", + FlagsUsuallySafeGreedy, + "http://www.src.ca/to%1Ato%8B%EE/c/OKnowABC~?a=b#test", + false, + }, + &testCase{ + "RemoveDirectoryIndex", + "HTTP://root/a/b/c/default.aspx", + FlagRemoveDirectoryIndex, + "http://root/a/b/c/", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "RemoveDirectoryIndex2", + "HTTP://root/a/b/c/default#a=b", + FlagRemoveDirectoryIndex, + "http://root/a/b/c/default#a=b", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "RemoveFragment", + "HTTP://root/a/b/c/default#toto=tata", + FlagRemoveFragment, + "http://root/a/b/c/default", // Since Go1.1, scheme is automatically lowercased + false, + }, + &testCase{ + "ForceHTTP", + "https://root/a/b/c/default#toto=tata", + FlagForceHTTP, + "http://root/a/b/c/default#toto=tata", + false, + }, + &testCase{ + "RemoveDuplicateSlashes", + "https://root/a//b///c////default#toto=tata", + FlagRemoveDuplicateSlashes, + "https://root/a/b/c/default#toto=tata", + false, + }, + &testCase{ + "RemoveDuplicateSlashes2", + "https://root//a//b///c////default#toto=tata", + FlagRemoveDuplicateSlashes, + "https://root/a/b/c/default#toto=tata", + false, + }, + &testCase{ + "RemoveWWW", + "https://www.root/a/b/c/", + FlagRemoveWWW, + "https://root/a/b/c/", + false, + }, + &testCase{ + "RemoveWWW2", + "https://WwW.Root/a/b/c/", + FlagRemoveWWW, + "https://Root/a/b/c/", + false, + }, + &testCase{ + "AddWWW", + "https://Root/a/b/c/", + FlagAddWWW, + "https://www.Root/a/b/c/", + false, + }, + &testCase{ + "SortQuery", + "http://root/toto/?b=4&a=1&c=3&b=2&a=5", + FlagSortQuery, + "http://root/toto/?a=1&a=5&b=2&b=4&c=3", + false, + }, + &testCase{ + "RemoveEmptyQuerySeparator", + "http://root/toto/?", + FlagRemoveEmptyQuerySeparator, + "http://root/toto/", + false, + }, + &testCase{ + "Unsafe", + "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", + FlagsUnsafeGreedy, + "http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3", + false, + }, + &testCase{ + "Safe2", + "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", + FlagsSafe, + "https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", + false, + }, + &testCase{ + "UsuallySafe2", + "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", + FlagsUsuallySafeGreedy, + "https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid", + false, + }, + &testCase{ + "AddTrailingSlashBug", + "http://src.ca/", + FlagsAllNonGreedy, + "http://www.src.ca/", + false, + }, + &testCase{ + "SourceModified", + "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", + FlagsUnsafeGreedy, + "http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3", + true, + }, + &testCase{ + "IPv6-1", + "http://[2001:db8:1f70::999:de8:7648:6e8]/test", + FlagsSafe | FlagRemoveDotSegments, + "http://[2001:db8:1f70::999:de8:7648:6e8]/test", + false, + }, + &testCase{ + "IPv6-2", + "http://[::ffff:192.168.1.1]/test", + FlagsSafe | FlagRemoveDotSegments, + "http://[::ffff:192.168.1.1]/test", + false, + }, + &testCase{ + "IPv6-3", + "http://[::ffff:192.168.1.1]:80/test", + FlagsSafe | FlagRemoveDotSegments, + "http://[::ffff:192.168.1.1]/test", + false, + }, + &testCase{ + "IPv6-4", + "htTps://[::fFff:192.168.1.1]:443/test", + FlagsSafe | FlagRemoveDotSegments, + "https://[::ffff:192.168.1.1]/test", + false, + }, + &testCase{ + "FTP", + "ftp://user:pass@ftp.foo.net/foo/bar", + FlagsSafe | FlagRemoveDotSegments, + "ftp://user:pass@ftp.foo.net/foo/bar", + false, + }, + &testCase{ + "Standard-1", + "http://www.foo.com:80/foo", + FlagsSafe | FlagRemoveDotSegments, + "http://www.foo.com/foo", + false, + }, + &testCase{ + "Standard-2", + "http://www.foo.com:8000/foo", + FlagsSafe | FlagRemoveDotSegments, + "http://www.foo.com:8000/foo", + false, + }, + &testCase{ + "Standard-3", + "http://www.foo.com/%7ebar", + FlagsSafe | FlagRemoveDotSegments, + "http://www.foo.com/~bar", + false, + }, + &testCase{ + "Standard-4", + "http://www.foo.com/%7Ebar", + FlagsSafe | FlagRemoveDotSegments, + "http://www.foo.com/~bar", + false, + }, + &testCase{ + "Standard-5", + "http://USER:pass@www.Example.COM/foo/bar", + FlagsSafe | FlagRemoveDotSegments, + "http://USER:pass@www.example.com/foo/bar", + false, + }, + &testCase{ + "Standard-6", + "http://test.example/?a=%26&b=1", + FlagsSafe | FlagRemoveDotSegments, + "http://test.example/?a=%26&b=1", + false, + }, + &testCase{ + "Standard-7", + "http://test.example/%25/?p=%20val%20%25", + FlagsSafe | FlagRemoveDotSegments, + "http://test.example/%25/?p=%20val%20%25", + false, + }, + &testCase{ + "Standard-8", + "http://test.example/path/with a%20space+/", + FlagsSafe | FlagRemoveDotSegments, + "http://test.example/path/with%20a%20space+/", + false, + }, + &testCase{ + "Standard-9", + "http://test.example/?", + FlagsSafe | FlagRemoveDotSegments, + "http://test.example/", + false, + }, + &testCase{ + "Standard-10", + "http://a.COM/path/?b&a", + FlagsSafe | FlagRemoveDotSegments, + "http://a.com/path/?b&a", + false, + }, + &testCase{ + "StandardCasesAddTrailingSlash", + "http://test.example?", + FlagsSafe | FlagAddTrailingSlash, + "http://test.example/", + false, + }, + &testCase{ + "OctalIP-1", + "http://0123.011.0.4/", + FlagsSafe | FlagDecodeOctalHost, + "http://0123.011.0.4/", + false, + }, + &testCase{ + "OctalIP-2", + "http://0102.0146.07.0223/", + FlagsSafe | FlagDecodeOctalHost, + "http://66.102.7.147/", + false, + }, + &testCase{ + "OctalIP-3", + "http://0102.0146.07.0223.:23/", + FlagsSafe | FlagDecodeOctalHost, + "http://66.102.7.147.:23/", + false, + }, + &testCase{ + "OctalIP-4", + "http://USER:pass@0102.0146.07.0223../", + FlagsSafe | FlagDecodeOctalHost, + "http://USER:pass@66.102.7.147../", + false, + }, + &testCase{ + "DWORDIP-1", + "http://123.1113982867/", + FlagsSafe | FlagDecodeDWORDHost, + "http://123.1113982867/", + false, + }, + &testCase{ + "DWORDIP-2", + "http://1113982867/", + FlagsSafe | FlagDecodeDWORDHost, + "http://66.102.7.147/", + false, + }, + &testCase{ + "DWORDIP-3", + "http://1113982867.:23/", + FlagsSafe | FlagDecodeDWORDHost, + "http://66.102.7.147.:23/", + false, + }, + &testCase{ + "DWORDIP-4", + "http://USER:pass@1113982867../", + FlagsSafe | FlagDecodeDWORDHost, + "http://USER:pass@66.102.7.147../", + false, + }, + &testCase{ + "HexIP-1", + "http://0x123.1113982867/", + FlagsSafe | FlagDecodeHexHost, + "http://0x123.1113982867/", + false, + }, + &testCase{ + "HexIP-2", + "http://0x42660793/", + FlagsSafe | FlagDecodeHexHost, + "http://66.102.7.147/", + false, + }, + &testCase{ + "HexIP-3", + "http://0x42660793.:23/", + FlagsSafe | FlagDecodeHexHost, + "http://66.102.7.147.:23/", + false, + }, + &testCase{ + "HexIP-4", + "http://USER:pass@0x42660793../", + FlagsSafe | FlagDecodeHexHost, + "http://USER:pass@66.102.7.147../", + false, + }, + &testCase{ + "UnnecessaryHostDots-1", + "http://.www.foo.com../foo/bar.html", + FlagsSafe | FlagRemoveUnnecessaryHostDots, + "http://www.foo.com/foo/bar.html", + false, + }, + &testCase{ + "UnnecessaryHostDots-2", + "http://www.foo.com./foo/bar.html", + FlagsSafe | FlagRemoveUnnecessaryHostDots, + "http://www.foo.com/foo/bar.html", + false, + }, + &testCase{ + "UnnecessaryHostDots-3", + "http://www.foo.com.:81/foo", + FlagsSafe | FlagRemoveUnnecessaryHostDots, + "http://www.foo.com:81/foo", + false, + }, + &testCase{ + "UnnecessaryHostDots-4", + "http://www.example.com./", + FlagsSafe | FlagRemoveUnnecessaryHostDots, + "http://www.example.com/", + false, + }, + &testCase{ + "EmptyPort-1", + "http://www.thedraymin.co.uk:/main/?p=308", + FlagsSafe | FlagRemoveEmptyPortSeparator, + "http://www.thedraymin.co.uk/main/?p=308", + false, + }, + &testCase{ + "EmptyPort-2", + "http://www.src.ca:", + FlagsSafe | FlagRemoveEmptyPortSeparator, + "http://www.src.ca", + false, + }, + &testCase{ + "Slashes-1", + "http://test.example/foo/bar/.", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/bar/", + false, + }, + &testCase{ + "Slashes-2", + "http://test.example/foo/bar/./", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/bar/", + false, + }, + &testCase{ + "Slashes-3", + "http://test.example/foo/bar/..", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/", + false, + }, + &testCase{ + "Slashes-4", + "http://test.example/foo/bar/../", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/", + false, + }, + &testCase{ + "Slashes-5", + "http://test.example/foo/bar/../baz", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/baz", + false, + }, + &testCase{ + "Slashes-6", + "http://test.example/foo/bar/../..", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/", + false, + }, + &testCase{ + "Slashes-7", + "http://test.example/foo/bar/../../", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/", + false, + }, + &testCase{ + "Slashes-8", + "http://test.example/foo/bar/../../baz", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/baz", + false, + }, + &testCase{ + "Slashes-9", + "http://test.example/foo/bar/../../../baz", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/baz", + false, + }, + &testCase{ + "Slashes-10", + "http://test.example/foo/bar/../../../../baz", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/baz", + false, + }, + &testCase{ + "Slashes-11", + "http://test.example/./foo", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo", + false, + }, + &testCase{ + "Slashes-12", + "http://test.example/../foo", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo", + false, + }, + &testCase{ + "Slashes-13", + "http://test.example/foo.", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo.", + false, + }, + &testCase{ + "Slashes-14", + "http://test.example/.foo", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/.foo", + false, + }, + &testCase{ + "Slashes-15", + "http://test.example/foo..", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo..", + false, + }, + &testCase{ + "Slashes-16", + "http://test.example/..foo", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/..foo", + false, + }, + &testCase{ + "Slashes-17", + "http://test.example/./../foo", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo", + false, + }, + &testCase{ + "Slashes-18", + "http://test.example/./foo/.", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/", + false, + }, + &testCase{ + "Slashes-19", + "http://test.example/foo/./bar", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/bar", + false, + }, + &testCase{ + "Slashes-20", + "http://test.example/foo/../bar", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/bar", + false, + }, + &testCase{ + "Slashes-21", + "http://test.example/foo//", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/", + false, + }, + &testCase{ + "Slashes-22", + "http://test.example/foo///bar//", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "http://test.example/foo/bar/", + false, + }, + &testCase{ + "Relative", + "foo/bar", + FlagsAllGreedy, + "foo/bar", + false, + }, + &testCase{ + "Relative-1", + "./../foo", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "foo", + false, + }, + &testCase{ + "Relative-2", + "./foo/bar/../baz/../bang/..", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "foo/", + false, + }, + &testCase{ + "Relative-3", + "foo///bar//", + FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, + "foo/bar/", + false, + }, + &testCase{ + "Relative-4", + "www.youtube.com", + FlagsUsuallySafeGreedy, + "www.youtube.com", + false, + }, + /*&testCase{ + "UrlNorm-5", + "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3", + FlagsSafe | FlagRemoveDotSegments, + "http://ja.wikipedia.org/wiki/\xe3\x82\xad\xe3\x83\xa3\xe3\x82\xbf\xe3\x83\x94\xe3\x83\xa9\xe3\x83\xbc\xe3\x82\xb8\xe3\x83\xa3\xe3\x83\x91\xe3\x83\xb3", + false, + }, + &testCase{ + "UrlNorm-1", + "http://test.example/?a=%e3%82%82%26", + FlagsAllGreedy, + "http://test.example/?a=\xe3\x82\x82%26", + false, + },*/ + } +) + +func TestRunner(t *testing.T) { + for _, tc := range cases { + runCase(tc, t) + } +} + +func runCase(tc *testCase, t *testing.T) { + t.Logf("running %s...", tc.nm) + if tc.parsed { + u, e := url.Parse(tc.src) + if e != nil { + t.Errorf("%s - FAIL : %s", tc.nm, e) + return + } else { + NormalizeURL(u, tc.flgs) + if s := u.String(); s != tc.res { + t.Errorf("%s - FAIL expected '%s', got '%s'", tc.nm, tc.res, s) + } + } + } else { + if s, e := NormalizeURLString(tc.src, tc.flgs); e != nil { + t.Errorf("%s - FAIL : %s", tc.nm, e) + } else if s != tc.res { + t.Errorf("%s - FAIL expected '%s', got '%s'", tc.nm, tc.res, s) + } + } +} + +func TestDecodeUnnecessaryEscapesAll(t *testing.T) { + var url = "http://host/" + + for i := 0; i < 256; i++ { + url += fmt.Sprintf("%%%02x", i) + } + if s, e := NormalizeURLString(url, FlagDecodeUnnecessaryEscapes); e != nil { + t.Fatalf("Got error %s", e.Error()) + } else { + const want = "http://host/%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22%23$%25&'()*+,-./0123456789:;%3C=%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF" + if s != want { + t.Errorf("DecodeUnnecessaryEscapesAll:\nwant\n%s\ngot\n%s", want, s) + } + } +} + +func TestEncodeNecessaryEscapesAll(t *testing.T) { + var url = "http://host/" + + for i := 0; i < 256; i++ { + if i != 0x25 { + url += string(i) + } + } + if s, e := NormalizeURLString(url, FlagEncodeNecessaryEscapes); e != nil { + t.Fatalf("Got error %s", e.Error()) + } else { + const want = "http://host/%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22#$&'()*+,-./0123456789:;%3C=%3E?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%C2%80%C2%81%C2%82%C2%83%C2%84%C2%85%C2%86%C2%87%C2%88%C2%89%C2%8A%C2%8B%C2%8C%C2%8D%C2%8E%C2%8F%C2%90%C2%91%C2%92%C2%93%C2%94%C2%95%C2%96%C2%97%C2%98%C2%99%C2%9A%C2%9B%C2%9C%C2%9D%C2%9E%C2%9F%C2%A0%C2%A1%C2%A2%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%C3%86%C3%87%C3%88%C3%89%C3%8A%C3%8B%C3%8C%C3%8D%C3%8E%C3%8F%C3%90%C3%91%C3%92%C3%93%C3%94%C3%95%C3%96%C3%97%C3%98%C3%99%C3%9A%C3%9B%C3%9C%C3%9D%C3%9E%C3%9F%C3%A0%C3%A1%C3%A2%C3%A3%C3%A4%C3%A5%C3%A6%C3%A7%C3%A8%C3%A9%C3%AA%C3%AB%C3%AC%C3%AD%C3%AE%C3%AF%C3%B0%C3%B1%C3%B2%C3%B3%C3%B4%C3%B5%C3%B6%C3%B7%C3%B8%C3%B9%C3%BA%C3%BB%C3%BC%C3%BD%C3%BE%C3%BF" + if s != want { + t.Errorf("EncodeNecessaryEscapesAll:\nwant\n%s\ngot\n%s", want, s) + } + } +} diff --git a/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go b/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go new file mode 100644 index 00000000..d1b2ca6c --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go @@ -0,0 +1,53 @@ +package purell + +import ( + "testing" +) + +// Test cases merged from PR #1 +// Originally from https://github.com/jehiah/urlnorm/blob/master/test_urlnorm.py + +func assertMap(t *testing.T, cases map[string]string, f NormalizationFlags) { + for bad, good := range cases { + s, e := NormalizeURLString(bad, f) + if e != nil { + t.Errorf("%s normalizing %v to %v", e.Error(), bad, good) + } else { + if s != good { + t.Errorf("source: %v expected: %v got: %v", bad, good, s) + } + } + } +} + +// This tests normalization to a unicode representation +// precent escapes for unreserved values are unescaped to their unicode value +// tests normalization to idna domains +// test ip word handling, ipv6 address handling, and trailing domain periods +// in general, this matches google chromes unescaping for things in the address bar. +// spaces are converted to '+' (perhaphs controversial) +// http://code.google.com/p/google-url/ probably is another good reference for this approach +func TestUrlnorm(t *testing.T) { + testcases := map[string]string{ + "http://test.example/?a=%e3%82%82%26": "http://test.example/?a=%e3%82%82%26", + //"http://test.example/?a=%e3%82%82%26": "http://test.example/?a=\xe3\x82\x82%26", //should return a unicode character + "http://s.xn--q-bga.DE/": "http://s.xn--q-bga.de/", //should be in idna format + "http://XBLA\u306eXbox.com": "http://xn--xblaxbox-jf4g.com", //test utf8 and unicode + "http://президент.рф": "http://xn--d1abbgf6aiiy.xn--p1ai", + "http://ПРЕЗИДЕНТ.РФ": "http://xn--d1abbgf6aiiy.xn--p1ai", + "http://ab¥ヲ₩○.com": "http://xn--ab-ida8983azmfnvs.com", //test width folding + "http://\u00e9.com": "http://xn--9ca.com", + "http://e\u0301.com": "http://xn--9ca.com", + "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3": "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3", + //"http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3": "http://ja.wikipedia.org/wiki/\xe3\x82\xad\xe3\x83\xa3\xe3\x82\xbf\xe3\x83\x94\xe3\x83\xa9\xe3\x83\xbc\xe3\x82\xb8\xe3\x83\xa3\xe3\x83\x91\xe3\x83\xb3", + + "http://test.example/\xe3\x82\xad": "http://test.example/%E3%82%AD", + //"http://test.example/\xe3\x82\xad": "http://test.example/\xe3\x82\xad", + "http://test.example/?p=%23val#test-%23-val%25": "http://test.example/?p=%23val#test-%23-val%25", //check that %23 (#) is not escaped where it shouldn't be + + "http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n": "http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n", + //"http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n": "http://test.domain/I\xc3\xb1t\xc3\xabrn\xc3\xa2ti\xc3\xb4n\xef\xbf\xbdliz\xc3\xa6ti\xc3\xb8n", + } + + assertMap(t, testcases, FlagsSafe|FlagRemoveDotSegments) +} diff --git a/vendor/github.com/PuerkitoBio/urlesc/.travis.yml b/vendor/github.com/PuerkitoBio/urlesc/.travis.yml new file mode 100644 index 00000000..478630e5 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/.travis.yml @@ -0,0 +1,11 @@ +language: go + +go: + - 1.4 + - tip + +install: + - go build . + +script: + - go test -v diff --git a/vendor/github.com/PuerkitoBio/urlesc/LICENSE b/vendor/github.com/PuerkitoBio/urlesc/LICENSE new file mode 100644 index 00000000..74487567 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/PuerkitoBio/urlesc/README.md b/vendor/github.com/PuerkitoBio/urlesc/README.md new file mode 100644 index 00000000..bebe305e --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/README.md @@ -0,0 +1,16 @@ +urlesc [![Build Status](https://travis-ci.org/PuerkitoBio/urlesc.png?branch=master)](https://travis-ci.org/PuerkitoBio/urlesc) [![GoDoc](http://godoc.org/github.com/PuerkitoBio/urlesc?status.svg)](http://godoc.org/github.com/PuerkitoBio/urlesc) +====== + +Package urlesc implements query escaping as per RFC 3986. + +It contains some parts of the net/url package, modified so as to allow +some reserved characters incorrectly escaped by net/url (see [issue 5684](https://github.com/golang/go/issues/5684)). + +## Install + + go get github.com/PuerkitoBio/urlesc + +## License + +Go license (BSD-3-Clause) + diff --git a/vendor/github.com/PuerkitoBio/urlesc/urlesc.go b/vendor/github.com/PuerkitoBio/urlesc/urlesc.go new file mode 100644 index 00000000..1b846245 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/urlesc.go @@ -0,0 +1,180 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package urlesc implements query escaping as per RFC 3986. +// It contains some parts of the net/url package, modified so as to allow +// some reserved characters incorrectly escaped by net/url. +// See https://github.com/golang/go/issues/5684 +package urlesc + +import ( + "bytes" + "net/url" + "strings" +) + +type encoding int + +const ( + encodePath encoding = 1 + iota + encodeUserPassword + encodeQueryComponent + encodeFragment +) + +// Return true if the specified character should be escaped when +// appearing in a URL string, according to RFC 3986. +func shouldEscape(c byte, mode encoding) bool { + // §2.3 Unreserved characters (alphanum) + if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { + return false + } + + switch c { + case '-', '.', '_', '~': // §2.3 Unreserved characters (mark) + return false + + // §2.2 Reserved characters (reserved) + case ':', '/', '?', '#', '[', ']', '@', // gen-delims + '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': // sub-delims + // Different sections of the URL allow a few of + // the reserved characters to appear unescaped. + switch mode { + case encodePath: // §3.3 + // The RFC allows sub-delims and : @. + // '/', '[' and ']' can be used to assign meaning to individual path + // segments. This package only manipulates the path as a whole, + // so we allow those as well. That leaves only ? and # to escape. + return c == '?' || c == '#' + + case encodeUserPassword: // §3.2.1 + // The RFC allows : and sub-delims in + // userinfo. The parsing of userinfo treats ':' as special so we must escape + // all the gen-delims. + return c == ':' || c == '/' || c == '?' || c == '#' || c == '[' || c == ']' || c == '@' + + case encodeQueryComponent: // §3.4 + // The RFC allows / and ?. + return c != '/' && c != '?' + + case encodeFragment: // §4.1 + // The RFC text is silent but the grammar allows + // everything, so escape nothing but # + return c == '#' + } + } + + // Everything else must be escaped. + return true +} + +// QueryEscape escapes the string so it can be safely placed +// inside a URL query. +func QueryEscape(s string) string { + return escape(s, encodeQueryComponent) +} + +func escape(s string, mode encoding) string { + spaceCount, hexCount := 0, 0 + for i := 0; i < len(s); i++ { + c := s[i] + if shouldEscape(c, mode) { + if c == ' ' && mode == encodeQueryComponent { + spaceCount++ + } else { + hexCount++ + } + } + } + + if spaceCount == 0 && hexCount == 0 { + return s + } + + t := make([]byte, len(s)+2*hexCount) + j := 0 + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == ' ' && mode == encodeQueryComponent: + t[j] = '+' + j++ + case shouldEscape(c, mode): + t[j] = '%' + t[j+1] = "0123456789ABCDEF"[c>>4] + t[j+2] = "0123456789ABCDEF"[c&15] + j += 3 + default: + t[j] = s[i] + j++ + } + } + return string(t) +} + +var uiReplacer = strings.NewReplacer( + "%21", "!", + "%27", "'", + "%28", "(", + "%29", ")", + "%2A", "*", +) + +// unescapeUserinfo unescapes some characters that need not to be escaped as per RFC3986. +func unescapeUserinfo(s string) string { + return uiReplacer.Replace(s) +} + +// Escape reassembles the URL into a valid URL string. +// The general form of the result is one of: +// +// scheme:opaque +// scheme://userinfo@host/path?query#fragment +// +// If u.Opaque is non-empty, String uses the first form; +// otherwise it uses the second form. +// +// In the second form, the following rules apply: +// - if u.Scheme is empty, scheme: is omitted. +// - if u.User is nil, userinfo@ is omitted. +// - if u.Host is empty, host/ is omitted. +// - if u.Scheme and u.Host are empty and u.User is nil, +// the entire scheme://userinfo@host/ is omitted. +// - if u.Host is non-empty and u.Path begins with a /, +// the form host/path does not add its own /. +// - if u.RawQuery is empty, ?query is omitted. +// - if u.Fragment is empty, #fragment is omitted. +func Escape(u *url.URL) string { + var buf bytes.Buffer + if u.Scheme != "" { + buf.WriteString(u.Scheme) + buf.WriteByte(':') + } + if u.Opaque != "" { + buf.WriteString(u.Opaque) + } else { + if u.Scheme != "" || u.Host != "" || u.User != nil { + buf.WriteString("//") + if ui := u.User; ui != nil { + buf.WriteString(unescapeUserinfo(ui.String())) + buf.WriteByte('@') + } + if h := u.Host; h != "" { + buf.WriteString(h) + } + } + if u.Path != "" && u.Path[0] != '/' && u.Host != "" { + buf.WriteByte('/') + } + buf.WriteString(escape(u.Path, encodePath)) + } + if u.RawQuery != "" { + buf.WriteByte('?') + buf.WriteString(u.RawQuery) + } + if u.Fragment != "" { + buf.WriteByte('#') + buf.WriteString(escape(u.Fragment, encodeFragment)) + } + return buf.String() +} diff --git a/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go b/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go new file mode 100644 index 00000000..45202e1d --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go @@ -0,0 +1,641 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package urlesc + +import ( + "net/url" + "testing" +) + +type URLTest struct { + in string + out *url.URL + roundtrip string // expected result of reserializing the URL; empty means same as "in". +} + +var urltests = []URLTest{ + // no path + { + "http://www.google.com", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + }, + "", + }, + // path + { + "http://www.google.com/", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + Path: "/", + }, + "", + }, + // path with hex escaping + { + "http://www.google.com/file%20one%26two", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + Path: "/file one&two", + }, + "http://www.google.com/file%20one&two", + }, + // user + { + "ftp://webmaster@www.google.com/", + &url.URL{ + Scheme: "ftp", + User: url.User("webmaster"), + Host: "www.google.com", + Path: "/", + }, + "", + }, + // escape sequence in username + { + "ftp://john%20doe@www.google.com/", + &url.URL{ + Scheme: "ftp", + User: url.User("john doe"), + Host: "www.google.com", + Path: "/", + }, + "ftp://john%20doe@www.google.com/", + }, + // query + { + "http://www.google.com/?q=go+language", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + Path: "/", + RawQuery: "q=go+language", + }, + "", + }, + // query with hex escaping: NOT parsed + { + "http://www.google.com/?q=go%20language", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + Path: "/", + RawQuery: "q=go%20language", + }, + "", + }, + // %20 outside query + { + "http://www.google.com/a%20b?q=c+d", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + Path: "/a b", + RawQuery: "q=c+d", + }, + "", + }, + // path without leading /, so no parsing + { + "http:www.google.com/?q=go+language", + &url.URL{ + Scheme: "http", + Opaque: "www.google.com/", + RawQuery: "q=go+language", + }, + "http:www.google.com/?q=go+language", + }, + // path without leading /, so no parsing + { + "http:%2f%2fwww.google.com/?q=go+language", + &url.URL{ + Scheme: "http", + Opaque: "%2f%2fwww.google.com/", + RawQuery: "q=go+language", + }, + "http:%2f%2fwww.google.com/?q=go+language", + }, + // non-authority with path + { + "mailto:/webmaster@golang.org", + &url.URL{ + Scheme: "mailto", + Path: "/webmaster@golang.org", + }, + "mailto:///webmaster@golang.org", // unfortunate compromise + }, + // non-authority + { + "mailto:webmaster@golang.org", + &url.URL{ + Scheme: "mailto", + Opaque: "webmaster@golang.org", + }, + "", + }, + // unescaped :// in query should not create a scheme + { + "/foo?query=http://bad", + &url.URL{ + Path: "/foo", + RawQuery: "query=http://bad", + }, + "", + }, + // leading // without scheme should create an authority + { + "//foo", + &url.URL{ + Host: "foo", + }, + "", + }, + // leading // without scheme, with userinfo, path, and query + { + "//user@foo/path?a=b", + &url.URL{ + User: url.User("user"), + Host: "foo", + Path: "/path", + RawQuery: "a=b", + }, + "", + }, + // Three leading slashes isn't an authority, but doesn't return an error. + // (We can't return an error, as this code is also used via + // ServeHTTP -> ReadRequest -> Parse, which is arguably a + // different URL parsing context, but currently shares the + // same codepath) + { + "///threeslashes", + &url.URL{ + Path: "///threeslashes", + }, + "", + }, + { + "http://user:password@google.com", + &url.URL{ + Scheme: "http", + User: url.UserPassword("user", "password"), + Host: "google.com", + }, + "http://user:password@google.com", + }, + // unescaped @ in username should not confuse host + { + "http://j@ne:password@google.com", + &url.URL{ + Scheme: "http", + User: url.UserPassword("j@ne", "password"), + Host: "google.com", + }, + "http://j%40ne:password@google.com", + }, + // unescaped @ in password should not confuse host + { + "http://jane:p@ssword@google.com", + &url.URL{ + Scheme: "http", + User: url.UserPassword("jane", "p@ssword"), + Host: "google.com", + }, + "http://jane:p%40ssword@google.com", + }, + { + "http://j@ne:password@google.com/p@th?q=@go", + &url.URL{ + Scheme: "http", + User: url.UserPassword("j@ne", "password"), + Host: "google.com", + Path: "/p@th", + RawQuery: "q=@go", + }, + "http://j%40ne:password@google.com/p@th?q=@go", + }, + { + "http://www.google.com/?q=go+language#foo", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + Path: "/", + RawQuery: "q=go+language", + Fragment: "foo", + }, + "", + }, + { + "http://www.google.com/?q=go+language#foo%26bar", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + Path: "/", + RawQuery: "q=go+language", + Fragment: "foo&bar", + }, + "http://www.google.com/?q=go+language#foo&bar", + }, + { + "file:///home/adg/rabbits", + &url.URL{ + Scheme: "file", + Host: "", + Path: "/home/adg/rabbits", + }, + "file:///home/adg/rabbits", + }, + // "Windows" paths are no exception to the rule. + // See golang.org/issue/6027, especially comment #9. + { + "file:///C:/FooBar/Baz.txt", + &url.URL{ + Scheme: "file", + Host: "", + Path: "/C:/FooBar/Baz.txt", + }, + "file:///C:/FooBar/Baz.txt", + }, + // case-insensitive scheme + { + "MaIlTo:webmaster@golang.org", + &url.URL{ + Scheme: "mailto", + Opaque: "webmaster@golang.org", + }, + "mailto:webmaster@golang.org", + }, + // Relative path + { + "a/b/c", + &url.URL{ + Path: "a/b/c", + }, + "a/b/c", + }, + // escaped '?' in username and password + { + "http://%3Fam:pa%3Fsword@google.com", + &url.URL{ + Scheme: "http", + User: url.UserPassword("?am", "pa?sword"), + Host: "google.com", + }, + "", + }, + // escaped '?' and '#' in path + { + "http://example.com/%3F%23", + &url.URL{ + Scheme: "http", + Host: "example.com", + Path: "?#", + }, + "", + }, + // unescaped [ ] ! ' ( ) * in path + { + "http://example.com/[]!'()*", + &url.URL{ + Scheme: "http", + Host: "example.com", + Path: "[]!'()*", + }, + "http://example.com/[]!'()*", + }, + // escaped : / ? # [ ] @ in username and password + { + "http://%3A%2F%3F:%23%5B%5D%40@example.com", + &url.URL{ + Scheme: "http", + User: url.UserPassword(":/?", "#[]@"), + Host: "example.com", + }, + "", + }, + // unescaped ! $ & ' ( ) * + , ; = in username and password + { + "http://!$&'():*+,;=@example.com", + &url.URL{ + Scheme: "http", + User: url.UserPassword("!$&'()", "*+,;="), + Host: "example.com", + }, + "", + }, + // unescaped = : / . ? = in query component + { + "http://example.com/?q=http://google.com/?q=", + &url.URL{ + Scheme: "http", + Host: "example.com", + Path: "/", + RawQuery: "q=http://google.com/?q=", + }, + "", + }, + // unescaped : / ? [ ] @ ! $ & ' ( ) * + , ; = in fragment + { + "http://example.com/#:/?%23[]@!$&'()*+,;=", + &url.URL{ + Scheme: "http", + Host: "example.com", + Path: "/", + Fragment: ":/?#[]@!$&'()*+,;=", + }, + "", + }, +} + +func DoTestString(t *testing.T, parse func(string) (*url.URL, error), name string, tests []URLTest) { + for _, tt := range tests { + u, err := parse(tt.in) + if err != nil { + t.Errorf("%s(%q) returned error %s", name, tt.in, err) + continue + } + expected := tt.in + if len(tt.roundtrip) > 0 { + expected = tt.roundtrip + } + s := Escape(u) + if s != expected { + t.Errorf("Escape(%s(%q)) == %q (expected %q)", name, tt.in, s, expected) + } + } +} + +func TestURLString(t *testing.T) { + DoTestString(t, url.Parse, "Parse", urltests) + + // no leading slash on path should prepend + // slash on String() call + noslash := URLTest{ + "http://www.google.com/search", + &url.URL{ + Scheme: "http", + Host: "www.google.com", + Path: "search", + }, + "", + } + s := Escape(noslash.out) + if s != noslash.in { + t.Errorf("Expected %s; go %s", noslash.in, s) + } +} + +type EscapeTest struct { + in string + out string + err error +} + +var escapeTests = []EscapeTest{ + { + "", + "", + nil, + }, + { + "abc", + "abc", + nil, + }, + { + "one two", + "one+two", + nil, + }, + { + "10%", + "10%25", + nil, + }, + { + " ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;", + "+?%26%3D%23%2B%25%21%3C%3E%23%22%7B%7D%7C%5C%5E%5B%5D%60%E2%98%BA%09%3A/%40%24%27%28%29%2A%2C%3B", + nil, + }, +} + +func TestEscape(t *testing.T) { + for _, tt := range escapeTests { + actual := QueryEscape(tt.in) + if tt.out != actual { + t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out) + } + + // for bonus points, verify that escape:unescape is an identity. + roundtrip, err := url.QueryUnescape(actual) + if roundtrip != tt.in || err != nil { + t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]") + } + } +} + +var resolveReferenceTests = []struct { + base, rel, expected string +}{ + // Absolute URL references + {"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"}, + {"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"}, + {"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"}, + + // Path-absolute references + {"http://foo.com/bar", "/baz", "http://foo.com/baz"}, + {"http://foo.com/bar?a=b#f", "/baz", "http://foo.com/baz"}, + {"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"}, + + // Scheme-relative + {"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"}, + + // Path-relative references: + + // ... current directory + {"http://foo.com", ".", "http://foo.com/"}, + {"http://foo.com/bar", ".", "http://foo.com/"}, + {"http://foo.com/bar/", ".", "http://foo.com/bar/"}, + + // ... going down + {"http://foo.com", "bar", "http://foo.com/bar"}, + {"http://foo.com/", "bar", "http://foo.com/bar"}, + {"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"}, + + // ... going up + {"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"}, + {"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"}, + {"http://foo.com/bar", "..", "http://foo.com/"}, + {"http://foo.com/bar/baz", "./..", "http://foo.com/"}, + // ".." in the middle (issue 3560) + {"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"}, + {"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"}, + {"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"}, + {"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"}, + {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"}, + {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"}, + {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"}, + {"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot/"}, + + // Remove any dot-segments prior to forming the target URI. + // http://tools.ietf.org/html/rfc3986#section-5.2.4 + {"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"}, + + // Triple dot isn't special + {"http://foo.com/bar", "...", "http://foo.com/..."}, + + // Fragment + {"http://foo.com/bar", ".#frag", "http://foo.com/#frag"}, + + // RFC 3986: Normal Examples + // http://tools.ietf.org/html/rfc3986#section-5.4.1 + {"http://a/b/c/d;p?q", "g:h", "g:h"}, + {"http://a/b/c/d;p?q", "g", "http://a/b/c/g"}, + {"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"}, + {"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"}, + {"http://a/b/c/d;p?q", "/g", "http://a/g"}, + {"http://a/b/c/d;p?q", "//g", "http://g"}, + {"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"}, + {"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"}, + {"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"}, + {"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"}, + {"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"}, + {"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"}, + {"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"}, + {"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"}, + {"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"}, + {"http://a/b/c/d;p?q", ".", "http://a/b/c/"}, + {"http://a/b/c/d;p?q", "./", "http://a/b/c/"}, + {"http://a/b/c/d;p?q", "..", "http://a/b/"}, + {"http://a/b/c/d;p?q", "../", "http://a/b/"}, + {"http://a/b/c/d;p?q", "../g", "http://a/b/g"}, + {"http://a/b/c/d;p?q", "../..", "http://a/"}, + {"http://a/b/c/d;p?q", "../../", "http://a/"}, + {"http://a/b/c/d;p?q", "../../g", "http://a/g"}, + + // RFC 3986: Abnormal Examples + // http://tools.ietf.org/html/rfc3986#section-5.4.2 + {"http://a/b/c/d;p?q", "../../../g", "http://a/g"}, + {"http://a/b/c/d;p?q", "../../../../g", "http://a/g"}, + {"http://a/b/c/d;p?q", "/./g", "http://a/g"}, + {"http://a/b/c/d;p?q", "/../g", "http://a/g"}, + {"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."}, + {"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"}, + {"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."}, + {"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"}, + {"http://a/b/c/d;p?q", "./../g", "http://a/b/g"}, + {"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"}, + {"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"}, + {"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"}, + {"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"}, + {"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"}, + {"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"}, + {"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"}, + {"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"}, + {"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"}, + + // Extras. + {"https://a/b/c/d;p?q", "//g?q", "https://g?q"}, + {"https://a/b/c/d;p?q", "//g#s", "https://g#s"}, + {"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"}, + {"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"}, + {"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"}, +} + +func TestResolveReference(t *testing.T) { + mustParse := func(url_ string) *url.URL { + u, err := url.Parse(url_) + if err != nil { + t.Fatalf("Expected URL to parse: %q, got error: %v", url_, err) + } + return u + } + opaque := &url.URL{Scheme: "scheme", Opaque: "opaque"} + for _, test := range resolveReferenceTests { + base := mustParse(test.base) + rel := mustParse(test.rel) + url := base.ResolveReference(rel) + if Escape(url) != test.expected { + t.Errorf("URL(%q).ResolveReference(%q) == %q, got %q", test.base, test.rel, test.expected, Escape(url)) + } + // Ensure that new instances are returned. + if base == url { + t.Errorf("Expected URL.ResolveReference to return new URL instance.") + } + // Test the convenience wrapper too. + url, err := base.Parse(test.rel) + if err != nil { + t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err) + } else if Escape(url) != test.expected { + t.Errorf("URL(%q).Parse(%q) == %q, got %q", test.base, test.rel, test.expected, Escape(url)) + } else if base == url { + // Ensure that new instances are returned for the wrapper too. + t.Errorf("Expected URL.Parse to return new URL instance.") + } + // Ensure Opaque resets the URL. + url = base.ResolveReference(opaque) + if *url != *opaque { + t.Errorf("ResolveReference failed to resolve opaque URL: want %#v, got %#v", url, opaque) + } + // Test the convenience wrapper with an opaque URL too. + url, err = base.Parse("scheme:opaque") + if err != nil { + t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err) + } else if *url != *opaque { + t.Errorf("Parse failed to resolve opaque URL: want %#v, got %#v", url, opaque) + } else if base == url { + // Ensure that new instances are returned, again. + t.Errorf("Expected URL.Parse to return new URL instance.") + } + } +} + +type shouldEscapeTest struct { + in byte + mode encoding + escape bool +} + +var shouldEscapeTests = []shouldEscapeTest{ + // Unreserved characters (§2.3) + {'a', encodePath, false}, + {'a', encodeUserPassword, false}, + {'a', encodeQueryComponent, false}, + {'a', encodeFragment, false}, + {'z', encodePath, false}, + {'A', encodePath, false}, + {'Z', encodePath, false}, + {'0', encodePath, false}, + {'9', encodePath, false}, + {'-', encodePath, false}, + {'-', encodeUserPassword, false}, + {'-', encodeQueryComponent, false}, + {'-', encodeFragment, false}, + {'.', encodePath, false}, + {'_', encodePath, false}, + {'~', encodePath, false}, + + // User information (§3.2.1) + {':', encodeUserPassword, true}, + {'/', encodeUserPassword, true}, + {'?', encodeUserPassword, true}, + {'@', encodeUserPassword, true}, + {'$', encodeUserPassword, false}, + {'&', encodeUserPassword, false}, + {'+', encodeUserPassword, false}, + {',', encodeUserPassword, false}, + {';', encodeUserPassword, false}, + {'=', encodeUserPassword, false}, +} + +func TestShouldEscape(t *testing.T) { + for _, tt := range shouldEscapeTests { + if shouldEscape(tt.in, tt.mode) != tt.escape { + t.Errorf("shouldEscape(%q, %v) returned %v; expected %v", tt.in, tt.mode, !tt.escape, tt.escape) + } + } +} diff --git a/vendor/github.com/davecgh/go-spew/.gitignore b/vendor/github.com/davecgh/go-spew/.gitignore new file mode 100644 index 00000000..00268614 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/.gitignore @@ -0,0 +1,22 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe diff --git a/vendor/github.com/davecgh/go-spew/.travis.yml b/vendor/github.com/davecgh/go-spew/.travis.yml new file mode 100644 index 00000000..984e0736 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/.travis.yml @@ -0,0 +1,14 @@ +language: go +go: + - 1.5.4 + - 1.6.3 + - 1.7 +install: + - go get -v golang.org/x/tools/cmd/cover +script: + - go test -v -tags=safe ./spew + - go test -v -tags=testcgo ./spew -covermode=count -coverprofile=profile.cov +after_success: + - go get -v github.com/mattn/goveralls + - export PATH=$PATH:$HOME/gopath/bin + - goveralls -coverprofile=profile.cov -service=travis-ci diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE new file mode 100644 index 00000000..c8364161 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2012-2016 Dave Collins + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/README.md b/vendor/github.com/davecgh/go-spew/README.md new file mode 100644 index 00000000..26243044 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/README.md @@ -0,0 +1,205 @@ +go-spew +======= + +[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)] +(https://travis-ci.org/davecgh/go-spew) [![ISC License] +(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) [![Coverage Status] +(https://img.shields.io/coveralls/davecgh/go-spew.svg)] +(https://coveralls.io/r/davecgh/go-spew?branch=master) + + +Go-spew implements a deep pretty printer for Go data structures to aid in +debugging. A comprehensive suite of tests with 100% test coverage is provided +to ensure proper functionality. See `test_coverage.txt` for the gocov coverage +report. Go-spew is licensed under the liberal ISC license, so it may be used in +open source or commercial projects. + +If you're interested in reading about how this package came to life and some +of the challenges involved in providing a deep pretty printer, there is a blog +post about it +[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/). + +## Documentation + +[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)] +(http://godoc.org/github.com/davecgh/go-spew/spew) + +Full `go doc` style documentation for the project can be viewed online without +installing this package by using the excellent GoDoc site here: +http://godoc.org/github.com/davecgh/go-spew/spew + +You can also view the documentation locally once the package is installed with +the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to +http://localhost:6060/pkg/github.com/davecgh/go-spew/spew + +## Installation + +```bash +$ go get -u github.com/davecgh/go-spew/spew +``` + +## Quick Start + +Add this import line to the file you're working in: + +```Go +import "github.com/davecgh/go-spew/spew" +``` + +To dump a variable with full newlines, indentation, type, and pointer +information use Dump, Fdump, or Sdump: + +```Go +spew.Dump(myVar1, myVar2, ...) +spew.Fdump(someWriter, myVar1, myVar2, ...) +str := spew.Sdump(myVar1, myVar2, ...) +``` + +Alternatively, if you would prefer to use format strings with a compacted inline +printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most +compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types +and pointer addresses): + +```Go +spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) +spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) +spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) +spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) +``` + +## Debugging a Web Application Example + +Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production. + +```Go +package main + +import ( + "fmt" + "html" + "net/http" + + "github.com/davecgh/go-spew/spew" +) + +func handler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:]) + fmt.Fprintf(w, "") +} + +func main() { + http.HandleFunc("/", handler) + http.ListenAndServe(":8080", nil) +} +``` + +## Sample Dump Output + +``` +(main.Foo) { + unexportedField: (*main.Bar)(0xf84002e210)({ + flag: (main.Flag) flagTwo, + data: (uintptr) + }), + ExportedField: (map[interface {}]interface {}) { + (string) "one": (bool) true + } +} +([]uint8) { + 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | + 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| + 00000020 31 32 |12| +} +``` + +## Sample Formatter Output + +Double pointer to a uint8: +``` + %v: <**>5 + %+v: <**>(0xf8400420d0->0xf8400420c8)5 + %#v: (**uint8)5 + %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 +``` + +Pointer to circular struct with a uint8 field and a pointer to itself: +``` + %v: <*>{1 <*>} + %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} + %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} + %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} +``` + +## Configuration Options + +Configuration of spew is handled by fields in the ConfigState type. For +convenience, all of the top-level functions use a global state available via the +spew.Config global. + +It is also possible to create a ConfigState instance that provides methods +equivalent to the top-level functions. This allows concurrent configuration +options. See the ConfigState documentation for more details. + +``` +* Indent + String to use for each indentation level for Dump functions. + It is a single space by default. A popular alternative is "\t". + +* MaxDepth + Maximum number of levels to descend into nested data structures. + There is no limit by default. + +* DisableMethods + Disables invocation of error and Stringer interface methods. + Method invocation is enabled by default. + +* DisablePointerMethods + Disables invocation of error and Stringer interface methods on types + which only accept pointer receivers from non-pointer variables. This option + relies on access to the unsafe package, so it will not have any effect when + running in environments without access to the unsafe package such as Google + App Engine or with the "safe" build tag specified. + Pointer method invocation is enabled by default. + +* DisablePointerAddresses + DisablePointerAddresses specifies whether to disable the printing of + pointer addresses. This is useful when diffing data structures in tests. + +* DisableCapacities + DisableCapacities specifies whether to disable the printing of capacities + for arrays, slices, maps and channels. This is useful when diffing data + structures in tests. + +* ContinueOnMethod + Enables recursion into types after invoking error and Stringer interface + methods. Recursion after method invocation is disabled by default. + +* SortKeys + Specifies map keys should be sorted before being printed. Use + this to have a more deterministic, diffable output. Note that + only native types (bool, int, uint, floats, uintptr and string) + and types which implement error or Stringer interfaces are supported, + with other types sorted according to the reflect.Value.String() output + which guarantees display stability. Natural map order is used by + default. + +* SpewKeys + SpewKeys specifies that, as a last resort attempt, map keys should be + spewed to strings and sorted by those strings. This is only considered + if SortKeys is true. + +``` + +## Unsafe Package Dependency + +This package relies on the unsafe package to perform some of the more advanced +features, however it also supports a "limited" mode which allows it to work in +environments where the unsafe package is not available. By default, it will +operate in this mode on Google App Engine and when compiled with GopherJS. The +"safe" build tag may also be specified to force the package to build without +using the unsafe package. + +## License + +Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License. diff --git a/vendor/github.com/davecgh/go-spew/cov_report.sh b/vendor/github.com/davecgh/go-spew/cov_report.sh new file mode 100644 index 00000000..9579497e --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/cov_report.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +# This script uses gocov to generate a test coverage report. +# The gocov tool my be obtained with the following command: +# go get github.com/axw/gocov/gocov +# +# It will be installed to $GOPATH/bin, so ensure that location is in your $PATH. + +# Check for gocov. +if ! type gocov >/dev/null 2>&1; then + echo >&2 "This script requires the gocov tool." + echo >&2 "You may obtain it with the following command:" + echo >&2 "go get github.com/axw/gocov/gocov" + exit 1 +fi + +# Only run the cgo tests if gcc is installed. +if type gcc >/dev/null 2>&1; then + (cd spew && gocov test -tags testcgo | gocov report) +else + (cd spew && gocov test | gocov report) +fi diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go new file mode 100644 index 00000000..8a4a6589 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -0,0 +1,152 @@ +// Copyright (c) 2015-2016 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when the code is not running on Google App Engine, compiled by GopherJS, and +// "-tags safe" is not added to the go build command line. The "disableunsafe" +// tag is deprecated and thus should not be used. +// +build !js,!appengine,!safe,!disableunsafe + +package spew + +import ( + "reflect" + "unsafe" +) + +const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = false + + // ptrSize is the size of a pointer on the current arch. + ptrSize = unsafe.Sizeof((*byte)(nil)) +) + +var ( + // offsetPtr, offsetScalar, and offsetFlag are the offsets for the + // internal reflect.Value fields. These values are valid before golang + // commit ecccf07e7f9d which changed the format. The are also valid + // after commit 82f48826c6c7 which changed the format again to mirror + // the original format. Code in the init function updates these offsets + // as necessary. + offsetPtr = uintptr(ptrSize) + offsetScalar = uintptr(0) + offsetFlag = uintptr(ptrSize * 2) + + // flagKindWidth and flagKindShift indicate various bits that the + // reflect package uses internally to track kind information. + // + // flagRO indicates whether or not the value field of a reflect.Value is + // read-only. + // + // flagIndir indicates whether the value field of a reflect.Value is + // the actual data or a pointer to the data. + // + // These values are valid before golang commit 90a7c3c86944 which + // changed their positions. Code in the init function updates these + // flags as necessary. + flagKindWidth = uintptr(5) + flagKindShift = uintptr(flagKindWidth - 1) + flagRO = uintptr(1 << 0) + flagIndir = uintptr(1 << 1) +) + +func init() { + // Older versions of reflect.Value stored small integers directly in the + // ptr field (which is named val in the older versions). Versions + // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named + // scalar for this purpose which unfortunately came before the flag + // field, so the offset of the flag field is different for those + // versions. + // + // This code constructs a new reflect.Value from a known small integer + // and checks if the size of the reflect.Value struct indicates it has + // the scalar field. When it does, the offsets are updated accordingly. + vv := reflect.ValueOf(0xf00) + if unsafe.Sizeof(vv) == (ptrSize * 4) { + offsetScalar = ptrSize * 2 + offsetFlag = ptrSize * 3 + } + + // Commit 90a7c3c86944 changed the flag positions such that the low + // order bits are the kind. This code extracts the kind from the flags + // field and ensures it's the correct type. When it's not, the flag + // order has been changed to the newer format, so the flags are updated + // accordingly. + upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag) + upfv := *(*uintptr)(upf) + flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) { + flagKindShift = 0 + flagRO = 1 << 5 + flagIndir = 1 << 6 + + // Commit adf9b30e5594 modified the flags to separate the + // flagRO flag into two bits which specifies whether or not the + // field is embedded. This causes flagIndir to move over a bit + // and means that flagRO is the combination of either of the + // original flagRO bit and the new bit. + // + // This code detects the change by extracting what used to be + // the indirect bit to ensure it's set. When it's not, the flag + // order has been changed to the newer format, so the flags are + // updated accordingly. + if upfv&flagIndir == 0 { + flagRO = 3 << 5 + flagIndir = 1 << 7 + } + } +} + +// unsafeReflectValue converts the passed reflect.Value into a one that bypasses +// the typical safety restrictions preventing access to unaddressable and +// unexported data. It works by digging the raw pointer to the underlying +// value out of the protected value and generating a new unprotected (unsafe) +// reflect.Value to it. +// +// This allows us to check for implementations of the Stringer and error +// interfaces to be used for pretty printing ordinarily unaddressable and +// inaccessible values such as unexported struct fields. +func unsafeReflectValue(v reflect.Value) (rv reflect.Value) { + indirects := 1 + vt := v.Type() + upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) + rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) + if rvf&flagIndir != 0 { + vt = reflect.PtrTo(v.Type()) + indirects++ + } else if offsetScalar != 0 { + // The value is in the scalar field when it's not one of the + // reference types. + switch vt.Kind() { + case reflect.Uintptr: + case reflect.Chan: + case reflect.Func: + case reflect.Map: + case reflect.Ptr: + case reflect.UnsafePointer: + default: + upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + + offsetScalar) + } + } + + pv := reflect.NewAt(vt, upv) + rv = pv + for i := 0; i < indirects; i++ { + rv = rv.Elem() + } + return rv +} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go new file mode 100644 index 00000000..1fe3cf3d --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go @@ -0,0 +1,38 @@ +// Copyright (c) 2015-2016 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when the code is running on Google App Engine, compiled by GopherJS, or +// "-tags safe" is added to the go build command line. The "disableunsafe" +// tag is deprecated and thus should not be used. +// +build js appengine safe disableunsafe + +package spew + +import "reflect" + +const ( + // UnsafeDisabled is a build-time constant which specifies whether or + // not access to the unsafe package is available. + UnsafeDisabled = true +) + +// unsafeReflectValue typically converts the passed reflect.Value into a one +// that bypasses the typical safety restrictions preventing access to +// unaddressable and unexported data. However, doing this relies on access to +// the unsafe package. This is a stub version which simply returns the passed +// reflect.Value when the unsafe package is not available. +func unsafeReflectValue(v reflect.Value) reflect.Value { + return v +} diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go new file mode 100644 index 00000000..7c519ff4 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/common.go @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "io" + "reflect" + "sort" + "strconv" +) + +// Some constants in the form of bytes to avoid string overhead. This mirrors +// the technique used in the fmt package. +var ( + panicBytes = []byte("(PANIC=") + plusBytes = []byte("+") + iBytes = []byte("i") + trueBytes = []byte("true") + falseBytes = []byte("false") + interfaceBytes = []byte("(interface {})") + commaNewlineBytes = []byte(",\n") + newlineBytes = []byte("\n") + openBraceBytes = []byte("{") + openBraceNewlineBytes = []byte("{\n") + closeBraceBytes = []byte("}") + asteriskBytes = []byte("*") + colonBytes = []byte(":") + colonSpaceBytes = []byte(": ") + openParenBytes = []byte("(") + closeParenBytes = []byte(")") + spaceBytes = []byte(" ") + pointerChainBytes = []byte("->") + nilAngleBytes = []byte("") + maxNewlineBytes = []byte("\n") + maxShortBytes = []byte("") + circularBytes = []byte("") + circularShortBytes = []byte("") + invalidAngleBytes = []byte("") + openBracketBytes = []byte("[") + closeBracketBytes = []byte("]") + percentBytes = []byte("%") + precisionBytes = []byte(".") + openAngleBytes = []byte("<") + closeAngleBytes = []byte(">") + openMapBytes = []byte("map[") + closeMapBytes = []byte("]") + lenEqualsBytes = []byte("len=") + capEqualsBytes = []byte("cap=") +) + +// hexDigits is used to map a decimal value to a hex digit. +var hexDigits = "0123456789abcdef" + +// catchPanic handles any panics that might occur during the handleMethods +// calls. +func catchPanic(w io.Writer, v reflect.Value) { + if err := recover(); err != nil { + w.Write(panicBytes) + fmt.Fprintf(w, "%v", err) + w.Write(closeParenBytes) + } +} + +// handleMethods attempts to call the Error and String methods on the underlying +// type the passed reflect.Value represents and outputes the result to Writer w. +// +// It handles panics in any called methods by catching and displaying the error +// as the formatted value. +func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { + // We need an interface to check if the type implements the error or + // Stringer interface. However, the reflect package won't give us an + // interface on certain things like unexported struct fields in order + // to enforce visibility rules. We use unsafe, when it's available, + // to bypass these restrictions since this package does not mutate the + // values. + if !v.CanInterface() { + if UnsafeDisabled { + return false + } + + v = unsafeReflectValue(v) + } + + // Choose whether or not to do error and Stringer interface lookups against + // the base type or a pointer to the base type depending on settings. + // Technically calling one of these methods with a pointer receiver can + // mutate the value, however, types which choose to satisify an error or + // Stringer interface with a pointer receiver should not be mutating their + // state inside these interface methods. + if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { + v = unsafeReflectValue(v) + } + if v.CanAddr() { + v = v.Addr() + } + + // Is it an error or Stringer? + switch iface := v.Interface().(type) { + case error: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.Error())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + + w.Write([]byte(iface.Error())) + return true + + case fmt.Stringer: + defer catchPanic(w, v) + if cs.ContinueOnMethod { + w.Write(openParenBytes) + w.Write([]byte(iface.String())) + w.Write(closeParenBytes) + w.Write(spaceBytes) + return false + } + w.Write([]byte(iface.String())) + return true + } + return false +} + +// printBool outputs a boolean value as true or false to Writer w. +func printBool(w io.Writer, val bool) { + if val { + w.Write(trueBytes) + } else { + w.Write(falseBytes) + } +} + +// printInt outputs a signed integer value to Writer w. +func printInt(w io.Writer, val int64, base int) { + w.Write([]byte(strconv.FormatInt(val, base))) +} + +// printUint outputs an unsigned integer value to Writer w. +func printUint(w io.Writer, val uint64, base int) { + w.Write([]byte(strconv.FormatUint(val, base))) +} + +// printFloat outputs a floating point value using the specified precision, +// which is expected to be 32 or 64bit, to Writer w. +func printFloat(w io.Writer, val float64, precision int) { + w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) +} + +// printComplex outputs a complex value using the specified float precision +// for the real and imaginary parts to Writer w. +func printComplex(w io.Writer, c complex128, floatPrecision int) { + r := real(c) + w.Write(openParenBytes) + w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) + i := imag(c) + if i >= 0 { + w.Write(plusBytes) + } + w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) + w.Write(iBytes) + w.Write(closeParenBytes) +} + +// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' +// prefix to Writer w. +func printHexPtr(w io.Writer, p uintptr) { + // Null pointer. + num := uint64(p) + if num == 0 { + w.Write(nilAngleBytes) + return + } + + // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix + buf := make([]byte, 18) + + // It's simpler to construct the hex string right to left. + base := uint64(16) + i := len(buf) - 1 + for num >= base { + buf[i] = hexDigits[num%base] + num /= base + i-- + } + buf[i] = hexDigits[num] + + // Add '0x' prefix. + i-- + buf[i] = 'x' + i-- + buf[i] = '0' + + // Strip unused leading bytes. + buf = buf[i:] + w.Write(buf) +} + +// valuesSorter implements sort.Interface to allow a slice of reflect.Value +// elements to be sorted. +type valuesSorter struct { + values []reflect.Value + strings []string // either nil or same len and values + cs *ConfigState +} + +// newValuesSorter initializes a valuesSorter instance, which holds a set of +// surrogate keys on which the data should be sorted. It uses flags in +// ConfigState to decide if and how to populate those surrogate keys. +func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { + vs := &valuesSorter{values: values, cs: cs} + if canSortSimply(vs.values[0].Kind()) { + return vs + } + if !cs.DisableMethods { + vs.strings = make([]string, len(values)) + for i := range vs.values { + b := bytes.Buffer{} + if !handleMethods(cs, &b, vs.values[i]) { + vs.strings = nil + break + } + vs.strings[i] = b.String() + } + } + if vs.strings == nil && cs.SpewKeys { + vs.strings = make([]string, len(values)) + for i := range vs.values { + vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) + } + } + return vs +} + +// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted +// directly, or whether it should be considered for sorting by surrogate keys +// (if the ConfigState allows it). +func canSortSimply(kind reflect.Kind) bool { + // This switch parallels valueSortLess, except for the default case. + switch kind { + case reflect.Bool: + return true + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return true + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return true + case reflect.Float32, reflect.Float64: + return true + case reflect.String: + return true + case reflect.Uintptr: + return true + case reflect.Array: + return true + } + return false +} + +// Len returns the number of values in the slice. It is part of the +// sort.Interface implementation. +func (s *valuesSorter) Len() int { + return len(s.values) +} + +// Swap swaps the values at the passed indices. It is part of the +// sort.Interface implementation. +func (s *valuesSorter) Swap(i, j int) { + s.values[i], s.values[j] = s.values[j], s.values[i] + if s.strings != nil { + s.strings[i], s.strings[j] = s.strings[j], s.strings[i] + } +} + +// valueSortLess returns whether the first value should sort before the second +// value. It is used by valueSorter.Less as part of the sort.Interface +// implementation. +func valueSortLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Bool: + return !a.Bool() && b.Bool() + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + return a.Int() < b.Int() + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + return a.Uint() < b.Uint() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.String: + return a.String() < b.String() + case reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Array: + // Compare the contents of both arrays. + l := a.Len() + for i := 0; i < l; i++ { + av := a.Index(i) + bv := b.Index(i) + if av.Interface() == bv.Interface() { + continue + } + return valueSortLess(av, bv) + } + } + return a.String() < b.String() +} + +// Less returns whether the value at index i should sort before the +// value at index j. It is part of the sort.Interface implementation. +func (s *valuesSorter) Less(i, j int) bool { + if s.strings == nil { + return valueSortLess(s.values[i], s.values[j]) + } + return s.strings[i] < s.strings[j] +} + +// sortValues is a sort function that handles both native types and any type that +// can be converted to error or Stringer. Other inputs are sorted according to +// their Value.String() value to ensure display stability. +func sortValues(values []reflect.Value, cs *ConfigState) { + if len(values) == 0 { + return + } + sort.Sort(newValuesSorter(values, cs)) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/common_test.go b/vendor/github.com/davecgh/go-spew/spew/common_test.go new file mode 100644 index 00000000..0f5ce47d --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/common_test.go @@ -0,0 +1,298 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew_test + +import ( + "fmt" + "reflect" + "testing" + + "github.com/davecgh/go-spew/spew" +) + +// custom type to test Stinger interface on non-pointer receiver. +type stringer string + +// String implements the Stringer interface for testing invocation of custom +// stringers on types with non-pointer receivers. +func (s stringer) String() string { + return "stringer " + string(s) +} + +// custom type to test Stinger interface on pointer receiver. +type pstringer string + +// String implements the Stringer interface for testing invocation of custom +// stringers on types with only pointer receivers. +func (s *pstringer) String() string { + return "stringer " + string(*s) +} + +// xref1 and xref2 are cross referencing structs for testing circular reference +// detection. +type xref1 struct { + ps2 *xref2 +} +type xref2 struct { + ps1 *xref1 +} + +// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular +// reference for testing detection. +type indirCir1 struct { + ps2 *indirCir2 +} +type indirCir2 struct { + ps3 *indirCir3 +} +type indirCir3 struct { + ps1 *indirCir1 +} + +// embed is used to test embedded structures. +type embed struct { + a string +} + +// embedwrap is used to test embedded structures. +type embedwrap struct { + *embed + e *embed +} + +// panicer is used to intentionally cause a panic for testing spew properly +// handles them +type panicer int + +func (p panicer) String() string { + panic("test panic") +} + +// customError is used to test custom error interface invocation. +type customError int + +func (e customError) Error() string { + return fmt.Sprintf("error: %d", int(e)) +} + +// stringizeWants converts a slice of wanted test output into a format suitable +// for a test error message. +func stringizeWants(wants []string) string { + s := "" + for i, want := range wants { + if i > 0 { + s += fmt.Sprintf("want%d: %s", i+1, want) + } else { + s += "want: " + want + } + } + return s +} + +// testFailed returns whether or not a test failed by checking if the result +// of the test is in the slice of wanted strings. +func testFailed(result string, wants []string) bool { + for _, want := range wants { + if result == want { + return false + } + } + return true +} + +type sortableStruct struct { + x int +} + +func (ss sortableStruct) String() string { + return fmt.Sprintf("ss.%d", ss.x) +} + +type unsortableStruct struct { + x int +} + +type sortTestCase struct { + input []reflect.Value + expected []reflect.Value +} + +func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) { + getInterfaces := func(values []reflect.Value) []interface{} { + interfaces := []interface{}{} + for _, v := range values { + interfaces = append(interfaces, v.Interface()) + } + return interfaces + } + + for _, test := range tests { + spew.SortValues(test.input, cs) + // reflect.DeepEqual cannot really make sense of reflect.Value, + // probably because of all the pointer tricks. For instance, + // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{} + // instead. + input := getInterfaces(test.input) + expected := getInterfaces(test.expected) + if !reflect.DeepEqual(input, expected) { + t.Errorf("Sort mismatch:\n %v != %v", input, expected) + } + } +} + +// TestSortValues ensures the sort functionality for relect.Value based sorting +// works as intended. +func TestSortValues(t *testing.T) { + v := reflect.ValueOf + + a := v("a") + b := v("b") + c := v("c") + embedA := v(embed{"a"}) + embedB := v(embed{"b"}) + embedC := v(embed{"c"}) + tests := []sortTestCase{ + // No values. + { + []reflect.Value{}, + []reflect.Value{}, + }, + // Bools. + { + []reflect.Value{v(false), v(true), v(false)}, + []reflect.Value{v(false), v(false), v(true)}, + }, + // Ints. + { + []reflect.Value{v(2), v(1), v(3)}, + []reflect.Value{v(1), v(2), v(3)}, + }, + // Uints. + { + []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))}, + []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))}, + }, + // Floats. + { + []reflect.Value{v(2.0), v(1.0), v(3.0)}, + []reflect.Value{v(1.0), v(2.0), v(3.0)}, + }, + // Strings. + { + []reflect.Value{b, a, c}, + []reflect.Value{a, b, c}, + }, + // Array + { + []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})}, + []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})}, + }, + // Uintptrs. + { + []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))}, + []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))}, + }, + // SortableStructs. + { + // Note: not sorted - DisableMethods is set. + []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, + []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, + }, + // UnsortableStructs. + { + // Note: not sorted - SpewKeys is false. + []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, + []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, + }, + // Invalid. + { + []reflect.Value{embedB, embedA, embedC}, + []reflect.Value{embedB, embedA, embedC}, + }, + } + cs := spew.ConfigState{DisableMethods: true, SpewKeys: false} + helpTestSortValues(tests, &cs, t) +} + +// TestSortValuesWithMethods ensures the sort functionality for relect.Value +// based sorting works as intended when using string methods. +func TestSortValuesWithMethods(t *testing.T) { + v := reflect.ValueOf + + a := v("a") + b := v("b") + c := v("c") + tests := []sortTestCase{ + // Ints. + { + []reflect.Value{v(2), v(1), v(3)}, + []reflect.Value{v(1), v(2), v(3)}, + }, + // Strings. + { + []reflect.Value{b, a, c}, + []reflect.Value{a, b, c}, + }, + // SortableStructs. + { + []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, + []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, + }, + // UnsortableStructs. + { + // Note: not sorted - SpewKeys is false. + []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, + []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, + }, + } + cs := spew.ConfigState{DisableMethods: false, SpewKeys: false} + helpTestSortValues(tests, &cs, t) +} + +// TestSortValuesWithSpew ensures the sort functionality for relect.Value +// based sorting works as intended when using spew to stringify keys. +func TestSortValuesWithSpew(t *testing.T) { + v := reflect.ValueOf + + a := v("a") + b := v("b") + c := v("c") + tests := []sortTestCase{ + // Ints. + { + []reflect.Value{v(2), v(1), v(3)}, + []reflect.Value{v(1), v(2), v(3)}, + }, + // Strings. + { + []reflect.Value{b, a, c}, + []reflect.Value{a, b, c}, + }, + // SortableStructs. + { + []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, + []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, + }, + // UnsortableStructs. + { + []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, + []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})}, + }, + } + cs := spew.ConfigState{DisableMethods: true, SpewKeys: true} + helpTestSortValues(tests, &cs, t) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go new file mode 100644 index 00000000..2e3d22f3 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/config.go @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "io" + "os" +) + +// ConfigState houses the configuration options used by spew to format and +// display values. There is a global instance, Config, that is used to control +// all top-level Formatter and Dump functionality. Each ConfigState instance +// provides methods equivalent to the top-level functions. +// +// The zero value for ConfigState provides no indentation. You would typically +// want to set it to a space or a tab. +// +// Alternatively, you can use NewDefaultConfig to get a ConfigState instance +// with default settings. See the documentation of NewDefaultConfig for default +// values. +type ConfigState struct { + // Indent specifies the string to use for each indentation level. The + // global config instance that all top-level functions use set this to a + // single space by default. If you would like more indentation, you might + // set this to a tab with "\t" or perhaps two spaces with " ". + Indent string + + // MaxDepth controls the maximum number of levels to descend into nested + // data structures. The default, 0, means there is no limit. + // + // NOTE: Circular data structures are properly detected, so it is not + // necessary to set this value unless you specifically want to limit deeply + // nested data structures. + MaxDepth int + + // DisableMethods specifies whether or not error and Stringer interfaces are + // invoked for types that implement them. + DisableMethods bool + + // DisablePointerMethods specifies whether or not to check for and invoke + // error and Stringer interfaces on types which only accept a pointer + // receiver when the current type is not a pointer. + // + // NOTE: This might be an unsafe action since calling one of these methods + // with a pointer receiver could technically mutate the value, however, + // in practice, types which choose to satisify an error or Stringer + // interface with a pointer receiver should not be mutating their state + // inside these interface methods. As a result, this option relies on + // access to the unsafe package, so it will not have any effect when + // running in environments without access to the unsafe package such as + // Google App Engine or with the "safe" build tag specified. + DisablePointerMethods bool + + // DisablePointerAddresses specifies whether to disable the printing of + // pointer addresses. This is useful when diffing data structures in tests. + DisablePointerAddresses bool + + // DisableCapacities specifies whether to disable the printing of capacities + // for arrays, slices, maps and channels. This is useful when diffing + // data structures in tests. + DisableCapacities bool + + // ContinueOnMethod specifies whether or not recursion should continue once + // a custom error or Stringer interface is invoked. The default, false, + // means it will print the results of invoking the custom error or Stringer + // interface and return immediately instead of continuing to recurse into + // the internals of the data type. + // + // NOTE: This flag does not have any effect if method invocation is disabled + // via the DisableMethods or DisablePointerMethods options. + ContinueOnMethod bool + + // SortKeys specifies map keys should be sorted before being printed. Use + // this to have a more deterministic, diffable output. Note that only + // native types (bool, int, uint, floats, uintptr and string) and types + // that support the error or Stringer interfaces (if methods are + // enabled) are supported, with other types sorted according to the + // reflect.Value.String() output which guarantees display stability. + SortKeys bool + + // SpewKeys specifies that, as a last resort attempt, map keys should + // be spewed to strings and sorted by those strings. This is only + // considered if SortKeys is true. + SpewKeys bool +} + +// Config is the active configuration of the top-level functions. +// The configuration can be changed by modifying the contents of spew.Config. +var Config = ConfigState{Indent: " "} + +// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the formatted string as a value that satisfies error. See NewFormatter +// for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, c.convertArgs(a)...) +} + +// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, c.convertArgs(a)...) +} + +// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, c.convertArgs(a)...) +} + +// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it +// passed with a Formatter interface returned by c.NewFormatter. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, c.convertArgs(a)...) +} + +// Print is a wrapper for fmt.Print that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Print(a ...interface{}) (n int, err error) { + return fmt.Print(c.convertArgs(a)...) +} + +// Printf is a wrapper for fmt.Printf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, c.convertArgs(a)...) +} + +// Println is a wrapper for fmt.Println that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Println(a ...interface{}) (n int, err error) { + return fmt.Println(c.convertArgs(a)...) +} + +// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprint(a ...interface{}) string { + return fmt.Sprint(c.convertArgs(a)...) +} + +// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were +// passed with a Formatter interface returned by c.NewFormatter. It returns +// the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, c.convertArgs(a)...) +} + +// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it +// were passed with a Formatter interface returned by c.NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) +func (c *ConfigState) Sprintln(a ...interface{}) string { + return fmt.Sprintln(c.convertArgs(a)...) +} + +/* +NewFormatter returns a custom formatter that satisfies the fmt.Formatter +interface. As a result, it integrates cleanly with standard fmt package +printing functions. The formatter is useful for inline printing of smaller data +types similar to the standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Typically this function shouldn't be called directly. It is much easier to make +use of the custom formatter by calling one of the convenience functions such as +c.Printf, c.Println, or c.Printf. +*/ +func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(c, v) +} + +// Fdump formats and displays the passed arguments to io.Writer w. It formats +// exactly the same as Dump. +func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { + fdump(c, w, a...) +} + +/* +Dump displays the passed parameters to standard out with newlines, customizable +indentation, and additional debug information such as complete types and all +pointer addresses used to indirect to the final value. It provides the +following features over the built-in printing facilities provided by the fmt +package: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + +The configuration options are controlled by modifying the public members +of c. See ConfigState for options documentation. + +See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to +get the formatted result as a string. +*/ +func (c *ConfigState) Dump(a ...interface{}) { + fdump(c, os.Stdout, a...) +} + +// Sdump returns a string with the passed arguments formatted exactly the same +// as Dump. +func (c *ConfigState) Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(c, &buf, a...) + return buf.String() +} + +// convertArgs accepts a slice of arguments and returns a slice of the same +// length with each argument converted to a spew Formatter interface using +// the ConfigState associated with s. +func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = newFormatter(c, arg) + } + return formatters +} + +// NewDefaultConfig returns a ConfigState with the following default settings. +// +// Indent: " " +// MaxDepth: 0 +// DisableMethods: false +// DisablePointerMethods: false +// ContinueOnMethod: false +// SortKeys: false +func NewDefaultConfig() *ConfigState { + return &ConfigState{Indent: " "} +} diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go new file mode 100644 index 00000000..aacaac6f --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/doc.go @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* +Package spew implements a deep pretty printer for Go data structures to aid in +debugging. + +A quick overview of the additional features spew provides over the built-in +printing facilities for Go data types are as follows: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output (only when using + Dump style) + +There are two different approaches spew allows for dumping Go data structures: + + * Dump style which prints with newlines, customizable indentation, + and additional debug information such as types and all pointer addresses + used to indirect to the final value + * A custom Formatter interface that integrates cleanly with the standard fmt + package and replaces %v, %+v, %#v, and %#+v to provide inline printing + similar to the default %v while providing the additional functionality + outlined above and passing unsupported format verbs such as %x and %q + along to fmt + +Quick Start + +This section demonstrates how to quickly get started with spew. See the +sections below for further details on formatting and configuration options. + +To dump a variable with full newlines, indentation, type, and pointer +information use Dump, Fdump, or Sdump: + spew.Dump(myVar1, myVar2, ...) + spew.Fdump(someWriter, myVar1, myVar2, ...) + str := spew.Sdump(myVar1, myVar2, ...) + +Alternatively, if you would prefer to use format strings with a compacted inline +printing style, use the convenience wrappers Printf, Fprintf, etc with +%v (most compact), %+v (adds pointer addresses), %#v (adds types), or +%#+v (adds types and pointer addresses): + spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + +Configuration Options + +Configuration of spew is handled by fields in the ConfigState type. For +convenience, all of the top-level functions use a global state available +via the spew.Config global. + +It is also possible to create a ConfigState instance that provides methods +equivalent to the top-level functions. This allows concurrent configuration +options. See the ConfigState documentation for more details. + +The following configuration options are available: + * Indent + String to use for each indentation level for Dump functions. + It is a single space by default. A popular alternative is "\t". + + * MaxDepth + Maximum number of levels to descend into nested data structures. + There is no limit by default. + + * DisableMethods + Disables invocation of error and Stringer interface methods. + Method invocation is enabled by default. + + * DisablePointerMethods + Disables invocation of error and Stringer interface methods on types + which only accept pointer receivers from non-pointer variables. + Pointer method invocation is enabled by default. + + * DisablePointerAddresses + DisablePointerAddresses specifies whether to disable the printing of + pointer addresses. This is useful when diffing data structures in tests. + + * DisableCapacities + DisableCapacities specifies whether to disable the printing of + capacities for arrays, slices, maps and channels. This is useful when + diffing data structures in tests. + + * ContinueOnMethod + Enables recursion into types after invoking error and Stringer interface + methods. Recursion after method invocation is disabled by default. + + * SortKeys + Specifies map keys should be sorted before being printed. Use + this to have a more deterministic, diffable output. Note that + only native types (bool, int, uint, floats, uintptr and string) + and types which implement error or Stringer interfaces are + supported with other types sorted according to the + reflect.Value.String() output which guarantees display + stability. Natural map order is used by default. + + * SpewKeys + Specifies that, as a last resort attempt, map keys should be + spewed to strings and sorted by those strings. This is only + considered if SortKeys is true. + +Dump Usage + +Simply call spew.Dump with a list of variables you want to dump: + + spew.Dump(myVar1, myVar2, ...) + +You may also call spew.Fdump if you would prefer to output to an arbitrary +io.Writer. For example, to dump to standard error: + + spew.Fdump(os.Stderr, myVar1, myVar2, ...) + +A third option is to call spew.Sdump to get the formatted output as a string: + + str := spew.Sdump(myVar1, myVar2, ...) + +Sample Dump Output + +See the Dump example for details on the setup of the types and variables being +shown here. + + (main.Foo) { + unexportedField: (*main.Bar)(0xf84002e210)({ + flag: (main.Flag) flagTwo, + data: (uintptr) + }), + ExportedField: (map[interface {}]interface {}) (len=1) { + (string) (len=3) "one": (bool) true + } + } + +Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C +command as shown. + ([]uint8) (len=32 cap=32) { + 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | + 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| + 00000020 31 32 |12| + } + +Custom Formatter + +Spew provides a custom formatter that implements the fmt.Formatter interface +so that it integrates cleanly with standard fmt package printing functions. The +formatter is useful for inline printing of smaller data types similar to the +standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Custom Formatter Usage + +The simplest way to make use of the spew custom formatter is to call one of the +convenience functions such as spew.Printf, spew.Println, or spew.Printf. The +functions have syntax you are most likely already familiar with: + + spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + spew.Println(myVar, myVar2) + spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) + spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) + +See the Index for the full list convenience functions. + +Sample Formatter Output + +Double pointer to a uint8: + %v: <**>5 + %+v: <**>(0xf8400420d0->0xf8400420c8)5 + %#v: (**uint8)5 + %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 + +Pointer to circular struct with a uint8 field and a pointer to itself: + %v: <*>{1 <*>} + %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} + %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} + %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} + +See the Printf example for details on the setup of variables being shown +here. + +Errors + +Since it is possible for custom Stringer/error interfaces to panic, spew +detects them and handles them internally by printing the panic information +inline with the output. Since spew is intended to provide deep pretty printing +capabilities on structures, it intentionally does not return any errors. +*/ +package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go new file mode 100644 index 00000000..df1d582a --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/dump.go @@ -0,0 +1,509 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "encoding/hex" + "fmt" + "io" + "os" + "reflect" + "regexp" + "strconv" + "strings" +) + +var ( + // uint8Type is a reflect.Type representing a uint8. It is used to + // convert cgo types to uint8 slices for hexdumping. + uint8Type = reflect.TypeOf(uint8(0)) + + // cCharRE is a regular expression that matches a cgo char. + // It is used to detect character arrays to hexdump them. + cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") + + // cUnsignedCharRE is a regular expression that matches a cgo unsigned + // char. It is used to detect unsigned character arrays to hexdump + // them. + cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") + + // cUint8tCharRE is a regular expression that matches a cgo uint8_t. + // It is used to detect uint8_t arrays to hexdump them. + cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") +) + +// dumpState contains information about the state of a dump operation. +type dumpState struct { + w io.Writer + depth int + pointers map[uintptr]int + ignoreNextType bool + ignoreNextIndent bool + cs *ConfigState +} + +// indent performs indentation according to the depth level and cs.Indent +// option. +func (d *dumpState) indent() { + if d.ignoreNextIndent { + d.ignoreNextIndent = false + return + } + d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) +} + +// unpackValue returns values inside of non-nil interfaces when possible. +// This is useful for data types like structs, arrays, slices, and maps which +// can contain varying types packed inside an interface. +func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface && !v.IsNil() { + v = v.Elem() + } + return v +} + +// dumpPtr handles formatting of pointers by indirecting them as necessary. +func (d *dumpState) dumpPtr(v reflect.Value) { + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range d.pointers { + if depth >= d.depth { + delete(d.pointers, k) + } + } + + // Keep list of all dereferenced pointers to show later. + pointerChain := make([]uintptr, 0) + + // Figure out how many levels of indirection there are by dereferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := d.pointers[addr]; ok && pd < d.depth { + cycleFound = true + indirects-- + break + } + d.pointers[addr] = d.depth + + ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } + + // Display type information. + d.w.Write(openParenBytes) + d.w.Write(bytes.Repeat(asteriskBytes, indirects)) + d.w.Write([]byte(ve.Type().String())) + d.w.Write(closeParenBytes) + + // Display pointer information. + if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { + d.w.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + d.w.Write(pointerChainBytes) + } + printHexPtr(d.w, addr) + } + d.w.Write(closeParenBytes) + } + + // Display dereferenced value. + d.w.Write(openParenBytes) + switch { + case nilFound == true: + d.w.Write(nilAngleBytes) + + case cycleFound == true: + d.w.Write(circularBytes) + + default: + d.ignoreNextType = true + d.dump(ve) + } + d.w.Write(closeParenBytes) +} + +// dumpSlice handles formatting of arrays and slices. Byte (uint8 under +// reflection) arrays and slices are dumped in hexdump -C fashion. +func (d *dumpState) dumpSlice(v reflect.Value) { + // Determine whether this type should be hex dumped or not. Also, + // for types which should be hexdumped, try to use the underlying data + // first, then fall back to trying to convert them to a uint8 slice. + var buf []uint8 + doConvert := false + doHexDump := false + numEntries := v.Len() + if numEntries > 0 { + vt := v.Index(0).Type() + vts := vt.String() + switch { + // C types that need to be converted. + case cCharRE.MatchString(vts): + fallthrough + case cUnsignedCharRE.MatchString(vts): + fallthrough + case cUint8tCharRE.MatchString(vts): + doConvert = true + + // Try to use existing uint8 slices and fall back to converting + // and copying if that fails. + case vt.Kind() == reflect.Uint8: + // We need an addressable interface to convert the type + // to a byte slice. However, the reflect package won't + // give us an interface on certain things like + // unexported struct fields in order to enforce + // visibility rules. We use unsafe, when available, to + // bypass these restrictions since this package does not + // mutate the values. + vs := v + if !vs.CanInterface() || !vs.CanAddr() { + vs = unsafeReflectValue(vs) + } + if !UnsafeDisabled { + vs = vs.Slice(0, numEntries) + + // Use the existing uint8 slice if it can be + // type asserted. + iface := vs.Interface() + if slice, ok := iface.([]uint8); ok { + buf = slice + doHexDump = true + break + } + } + + // The underlying data needs to be converted if it can't + // be type asserted to a uint8 slice. + doConvert = true + } + + // Copy and convert the underlying type if needed. + if doConvert && vt.ConvertibleTo(uint8Type) { + // Convert and copy each element into a uint8 byte + // slice. + buf = make([]uint8, numEntries) + for i := 0; i < numEntries; i++ { + vv := v.Index(i) + buf[i] = uint8(vv.Convert(uint8Type).Uint()) + } + doHexDump = true + } + } + + // Hexdump the entire slice as needed. + if doHexDump { + indent := strings.Repeat(d.cs.Indent, d.depth) + str := indent + hex.Dump(buf) + str = strings.Replace(str, "\n", "\n"+indent, -1) + str = strings.TrimRight(str, d.cs.Indent) + d.w.Write([]byte(str)) + return + } + + // Recursively call dump for each item. + for i := 0; i < numEntries; i++ { + d.dump(d.unpackValue(v.Index(i))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } +} + +// dump is the main workhorse for dumping a value. It uses the passed reflect +// value to figure out what kind of object we are dealing with and formats it +// appropriately. It is a recursive function, however circular data structures +// are detected and handled properly. +func (d *dumpState) dump(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + d.w.Write(invalidAngleBytes) + return + } + + // Handle pointers specially. + if kind == reflect.Ptr { + d.indent() + d.dumpPtr(v) + return + } + + // Print type information unless already handled elsewhere. + if !d.ignoreNextType { + d.indent() + d.w.Write(openParenBytes) + d.w.Write([]byte(v.Type().String())) + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + d.ignoreNextType = false + + // Display length and capacity if the built-in len and cap functions + // work with the value's kind and the len/cap itself is non-zero. + valueLen, valueCap := 0, 0 + switch v.Kind() { + case reflect.Array, reflect.Slice, reflect.Chan: + valueLen, valueCap = v.Len(), v.Cap() + case reflect.Map, reflect.String: + valueLen = v.Len() + } + if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { + d.w.Write(openParenBytes) + if valueLen != 0 { + d.w.Write(lenEqualsBytes) + printInt(d.w, int64(valueLen), 10) + } + if !d.cs.DisableCapacities && valueCap != 0 { + if valueLen != 0 { + d.w.Write(spaceBytes) + } + d.w.Write(capEqualsBytes) + printInt(d.w, int64(valueCap), 10) + } + d.w.Write(closeParenBytes) + d.w.Write(spaceBytes) + } + + // Call Stringer/error interfaces if they exist and the handle methods flag + // is enabled + if !d.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(d.cs, d.w, v); handled { + return + } + } + } + + switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. + + case reflect.Bool: + printBool(d.w, v.Bool()) + + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(d.w, v.Int(), 10) + + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(d.w, v.Uint(), 10) + + case reflect.Float32: + printFloat(d.w, v.Float(), 32) + + case reflect.Float64: + printFloat(d.w, v.Float(), 64) + + case reflect.Complex64: + printComplex(d.w, v.Complex(), 32) + + case reflect.Complex128: + printComplex(d.w, v.Complex(), 64) + + case reflect.Slice: + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + fallthrough + + case reflect.Array: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + d.dumpSlice(v) + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.String: + d.w.Write([]byte(strconv.Quote(v.String()))) + + case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + d.w.Write(nilAngleBytes) + } + + case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. + + case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + d.w.Write(nilAngleBytes) + break + } + + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + numEntries := v.Len() + keys := v.MapKeys() + if d.cs.SortKeys { + sortValues(keys, d.cs) + } + for i, key := range keys { + d.dump(d.unpackValue(key)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.MapIndex(key))) + if i < (numEntries - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.Struct: + d.w.Write(openBraceNewlineBytes) + d.depth++ + if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { + d.indent() + d.w.Write(maxNewlineBytes) + } else { + vt := v.Type() + numFields := v.NumField() + for i := 0; i < numFields; i++ { + d.indent() + vtf := vt.Field(i) + d.w.Write([]byte(vtf.Name)) + d.w.Write(colonSpaceBytes) + d.ignoreNextIndent = true + d.dump(d.unpackValue(v.Field(i))) + if i < (numFields - 1) { + d.w.Write(commaNewlineBytes) + } else { + d.w.Write(newlineBytes) + } + } + } + d.depth-- + d.indent() + d.w.Write(closeBraceBytes) + + case reflect.Uintptr: + printHexPtr(d.w, uintptr(v.Uint())) + + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(d.w, v.Pointer()) + + // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it in case any new + // types are added. + default: + if v.CanInterface() { + fmt.Fprintf(d.w, "%v", v.Interface()) + } else { + fmt.Fprintf(d.w, "%v", v.String()) + } + } +} + +// fdump is a helper function to consolidate the logic from the various public +// methods which take varying writers and config states. +func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { + for _, arg := range a { + if arg == nil { + w.Write(interfaceBytes) + w.Write(spaceBytes) + w.Write(nilAngleBytes) + w.Write(newlineBytes) + continue + } + + d := dumpState{w: w, cs: cs} + d.pointers = make(map[uintptr]int) + d.dump(reflect.ValueOf(arg)) + d.w.Write(newlineBytes) + } +} + +// Fdump formats and displays the passed arguments to io.Writer w. It formats +// exactly the same as Dump. +func Fdump(w io.Writer, a ...interface{}) { + fdump(&Config, w, a...) +} + +// Sdump returns a string with the passed arguments formatted exactly the same +// as Dump. +func Sdump(a ...interface{}) string { + var buf bytes.Buffer + fdump(&Config, &buf, a...) + return buf.String() +} + +/* +Dump displays the passed parameters to standard out with newlines, customizable +indentation, and additional debug information such as complete types and all +pointer addresses used to indirect to the final value. It provides the +following features over the built-in printing facilities provided by the fmt +package: + + * Pointers are dereferenced and followed + * Circular data structures are detected and handled properly + * Custom Stringer/error interfaces are optionally invoked, including + on unexported types + * Custom types which only implement the Stringer/error interfaces via + a pointer receiver are optionally invoked when passing non-pointer + variables + * Byte arrays and slices are dumped like the hexdump -C command which + includes offsets, byte values in hex, and ASCII output + +The configuration options are controlled by an exported package global, +spew.Config. See ConfigState for options documentation. + +See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to +get the formatted result as a string. +*/ +func Dump(a ...interface{}) { + fdump(&Config, os.Stdout, a...) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/dump_test.go b/vendor/github.com/davecgh/go-spew/spew/dump_test.go new file mode 100644 index 00000000..5aad9c7a --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/dump_test.go @@ -0,0 +1,1042 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* +Test Summary: +NOTE: For each test, a nil pointer, a single pointer and double pointer to the +base test element are also tested to ensure proper indirection across all types. + +- Max int8, int16, int32, int64, int +- Max uint8, uint16, uint32, uint64, uint +- Boolean true and false +- Standard complex64 and complex128 +- Array containing standard ints +- Array containing type with custom formatter on pointer receiver only +- Array containing interfaces +- Array containing bytes +- Slice containing standard float32 values +- Slice containing type with custom formatter on pointer receiver only +- Slice containing interfaces +- Slice containing bytes +- Nil slice +- Standard string +- Nil interface +- Sub-interface +- Map with string keys and int vals +- Map with custom formatter type on pointer receiver only keys and vals +- Map with interface keys and values +- Map with nil interface value +- Struct with primitives +- Struct that contains another struct +- Struct that contains custom type with Stringer pointer interface via both + exported and unexported fields +- Struct that contains embedded struct and field to same struct +- Uintptr to 0 (null pointer) +- Uintptr address of real variable +- Unsafe.Pointer to 0 (null pointer) +- Unsafe.Pointer to address of real variable +- Nil channel +- Standard int channel +- Function with no params and no returns +- Function with param and no returns +- Function with multiple params and multiple returns +- Struct that is circular through self referencing +- Structs that are circular through cross referencing +- Structs that are indirectly circular +- Type that panics in its Stringer interface +*/ + +package spew_test + +import ( + "bytes" + "fmt" + "testing" + "unsafe" + + "github.com/davecgh/go-spew/spew" +) + +// dumpTest is used to describe a test to be performed against the Dump method. +type dumpTest struct { + in interface{} + wants []string +} + +// dumpTests houses all of the tests to be performed against the Dump method. +var dumpTests = make([]dumpTest, 0) + +// addDumpTest is a helper method to append the passed input and desired result +// to dumpTests +func addDumpTest(in interface{}, wants ...string) { + test := dumpTest{in, wants} + dumpTests = append(dumpTests, test) +} + +func addIntDumpTests() { + // Max int8. + v := int8(127) + nv := (*int8)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "int8" + vs := "127" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Max int16. + v2 := int16(32767) + nv2 := (*int16)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "int16" + v2s := "32767" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv2, "(*"+v2t+")()\n") + + // Max int32. + v3 := int32(2147483647) + nv3 := (*int32)(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "int32" + v3s := "2147483647" + addDumpTest(v3, "("+v3t+") "+v3s+"\n") + addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") + addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") + addDumpTest(nv3, "(*"+v3t+")()\n") + + // Max int64. + v4 := int64(9223372036854775807) + nv4 := (*int64)(nil) + pv4 := &v4 + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "int64" + v4s := "9223372036854775807" + addDumpTest(v4, "("+v4t+") "+v4s+"\n") + addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") + addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") + addDumpTest(nv4, "(*"+v4t+")()\n") + + // Max int. + v5 := int(2147483647) + nv5 := (*int)(nil) + pv5 := &v5 + v5Addr := fmt.Sprintf("%p", pv5) + pv5Addr := fmt.Sprintf("%p", &pv5) + v5t := "int" + v5s := "2147483647" + addDumpTest(v5, "("+v5t+") "+v5s+"\n") + addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") + addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") + addDumpTest(nv5, "(*"+v5t+")()\n") +} + +func addUintDumpTests() { + // Max uint8. + v := uint8(255) + nv := (*uint8)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "uint8" + vs := "255" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Max uint16. + v2 := uint16(65535) + nv2 := (*uint16)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "uint16" + v2s := "65535" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv2, "(*"+v2t+")()\n") + + // Max uint32. + v3 := uint32(4294967295) + nv3 := (*uint32)(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "uint32" + v3s := "4294967295" + addDumpTest(v3, "("+v3t+") "+v3s+"\n") + addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") + addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") + addDumpTest(nv3, "(*"+v3t+")()\n") + + // Max uint64. + v4 := uint64(18446744073709551615) + nv4 := (*uint64)(nil) + pv4 := &v4 + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "uint64" + v4s := "18446744073709551615" + addDumpTest(v4, "("+v4t+") "+v4s+"\n") + addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") + addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") + addDumpTest(nv4, "(*"+v4t+")()\n") + + // Max uint. + v5 := uint(4294967295) + nv5 := (*uint)(nil) + pv5 := &v5 + v5Addr := fmt.Sprintf("%p", pv5) + pv5Addr := fmt.Sprintf("%p", &pv5) + v5t := "uint" + v5s := "4294967295" + addDumpTest(v5, "("+v5t+") "+v5s+"\n") + addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") + addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") + addDumpTest(nv5, "(*"+v5t+")()\n") +} + +func addBoolDumpTests() { + // Boolean true. + v := bool(true) + nv := (*bool)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "bool" + vs := "true" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Boolean false. + v2 := bool(false) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "bool" + v2s := "false" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") +} + +func addFloatDumpTests() { + // Standard float32. + v := float32(3.1415) + nv := (*float32)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "float32" + vs := "3.1415" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Standard float64. + v2 := float64(3.1415926) + nv2 := (*float64)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "float64" + v2s := "3.1415926" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv2, "(*"+v2t+")()\n") +} + +func addComplexDumpTests() { + // Standard complex64. + v := complex(float32(6), -2) + nv := (*complex64)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "complex64" + vs := "(6-2i)" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Standard complex128. + v2 := complex(float64(-6), 2) + nv2 := (*complex128)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "complex128" + v2s := "(-6+2i)" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv2, "(*"+v2t+")()\n") +} + +func addArrayDumpTests() { + // Array containing standard ints. + v := [3]int{1, 2, 3} + vLen := fmt.Sprintf("%d", len(v)) + vCap := fmt.Sprintf("%d", cap(v)) + nv := (*[3]int)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "int" + vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" + + vt + ") 2,\n (" + vt + ") 3\n}" + addDumpTest(v, "([3]"+vt+") "+vs+"\n") + addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*[3]"+vt+")()\n") + + // Array containing type with custom formatter on pointer receiver only. + v2i0 := pstringer("1") + v2i1 := pstringer("2") + v2i2 := pstringer("3") + v2 := [3]pstringer{v2i0, v2i1, v2i2} + v2i0Len := fmt.Sprintf("%d", len(v2i0)) + v2i1Len := fmt.Sprintf("%d", len(v2i1)) + v2i2Len := fmt.Sprintf("%d", len(v2i2)) + v2Len := fmt.Sprintf("%d", len(v2)) + v2Cap := fmt.Sprintf("%d", cap(v2)) + nv2 := (*[3]pstringer)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "spew_test.pstringer" + v2sp := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + + ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t + + ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t + + ") (len=" + v2i2Len + ") " + "stringer 3\n}" + v2s := v2sp + if spew.UnsafeDisabled { + v2s = "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + + ") (len=" + v2i0Len + ") \"1\",\n (" + v2t + ") (len=" + + v2i1Len + ") \"2\",\n (" + v2t + ") (len=" + v2i2Len + + ") " + "\"3\"\n}" + } + addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2sp+")\n") + addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2sp+")\n") + addDumpTest(nv2, "(*[3]"+v2t+")()\n") + + // Array containing interfaces. + v3i0 := "one" + v3 := [3]interface{}{v3i0, int(2), uint(3)} + v3i0Len := fmt.Sprintf("%d", len(v3i0)) + v3Len := fmt.Sprintf("%d", len(v3)) + v3Cap := fmt.Sprintf("%d", cap(v3)) + nv3 := (*[3]interface{})(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "[3]interface {}" + v3t2 := "string" + v3t3 := "int" + v3t4 := "uint" + v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + + "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + + v3t4 + ") 3\n}" + addDumpTest(v3, "("+v3t+") "+v3s+"\n") + addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") + addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") + addDumpTest(nv3, "(*"+v3t+")()\n") + + // Array containing bytes. + v4 := [34]byte{ + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, + 0x31, 0x32, + } + v4Len := fmt.Sprintf("%d", len(v4)) + v4Cap := fmt.Sprintf("%d", cap(v4)) + nv4 := (*[34]byte)(nil) + pv4 := &v4 + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "[34]uint8" + v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + + "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + + " |............... |\n" + + " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + + " |!\"#$%&'()*+,-./0|\n" + + " 00000020 31 32 " + + " |12|\n}" + addDumpTest(v4, "("+v4t+") "+v4s+"\n") + addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") + addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") + addDumpTest(nv4, "(*"+v4t+")()\n") +} + +func addSliceDumpTests() { + // Slice containing standard float32 values. + v := []float32{3.14, 6.28, 12.56} + vLen := fmt.Sprintf("%d", len(v)) + vCap := fmt.Sprintf("%d", cap(v)) + nv := (*[]float32)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "float32" + vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" + + vt + ") 6.28,\n (" + vt + ") 12.56\n}" + addDumpTest(v, "([]"+vt+") "+vs+"\n") + addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*[]"+vt+")()\n") + + // Slice containing type with custom formatter on pointer receiver only. + v2i0 := pstringer("1") + v2i1 := pstringer("2") + v2i2 := pstringer("3") + v2 := []pstringer{v2i0, v2i1, v2i2} + v2i0Len := fmt.Sprintf("%d", len(v2i0)) + v2i1Len := fmt.Sprintf("%d", len(v2i1)) + v2i2Len := fmt.Sprintf("%d", len(v2i2)) + v2Len := fmt.Sprintf("%d", len(v2)) + v2Cap := fmt.Sprintf("%d", cap(v2)) + nv2 := (*[]pstringer)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "spew_test.pstringer" + v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + + v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + + ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + + "stringer 3\n}" + addDumpTest(v2, "([]"+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv2, "(*[]"+v2t+")()\n") + + // Slice containing interfaces. + v3i0 := "one" + v3 := []interface{}{v3i0, int(2), uint(3), nil} + v3i0Len := fmt.Sprintf("%d", len(v3i0)) + v3Len := fmt.Sprintf("%d", len(v3)) + v3Cap := fmt.Sprintf("%d", cap(v3)) + nv3 := (*[]interface{})(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "[]interface {}" + v3t2 := "string" + v3t3 := "int" + v3t4 := "uint" + v3t5 := "interface {}" + v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + + "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + + v3t4 + ") 3,\n (" + v3t5 + ") \n}" + addDumpTest(v3, "("+v3t+") "+v3s+"\n") + addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") + addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") + addDumpTest(nv3, "(*"+v3t+")()\n") + + // Slice containing bytes. + v4 := []byte{ + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, + 0x31, 0x32, + } + v4Len := fmt.Sprintf("%d", len(v4)) + v4Cap := fmt.Sprintf("%d", cap(v4)) + nv4 := (*[]byte)(nil) + pv4 := &v4 + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "[]uint8" + v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + + "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + + " |............... |\n" + + " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + + " |!\"#$%&'()*+,-./0|\n" + + " 00000020 31 32 " + + " |12|\n}" + addDumpTest(v4, "("+v4t+") "+v4s+"\n") + addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") + addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") + addDumpTest(nv4, "(*"+v4t+")()\n") + + // Nil slice. + v5 := []int(nil) + nv5 := (*[]int)(nil) + pv5 := &v5 + v5Addr := fmt.Sprintf("%p", pv5) + pv5Addr := fmt.Sprintf("%p", &pv5) + v5t := "[]int" + v5s := "" + addDumpTest(v5, "("+v5t+") "+v5s+"\n") + addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") + addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") + addDumpTest(nv5, "(*"+v5t+")()\n") +} + +func addStringDumpTests() { + // Standard string. + v := "test" + vLen := fmt.Sprintf("%d", len(v)) + nv := (*string)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "string" + vs := "(len=" + vLen + ") \"test\"" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") +} + +func addInterfaceDumpTests() { + // Nil interface. + var v interface{} + nv := (*interface{})(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "interface {}" + vs := "" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Sub-interface. + v2 := interface{}(uint16(65535)) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "uint16" + v2s := "65535" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") +} + +func addMapDumpTests() { + // Map with string keys and int vals. + k := "one" + kk := "two" + m := map[string]int{k: 1, kk: 2} + klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up + kkLen := fmt.Sprintf("%d", len(kk)) + mLen := fmt.Sprintf("%d", len(m)) + nilMap := map[string]int(nil) + nm := (*map[string]int)(nil) + pm := &m + mAddr := fmt.Sprintf("%p", pm) + pmAddr := fmt.Sprintf("%p", &pm) + mt := "map[string]int" + mt1 := "string" + mt2 := "int" + ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " + + "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen + + ") \"two\": (" + mt2 + ") 2\n}" + ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " + + "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen + + ") \"one\": (" + mt2 + ") 1\n}" + addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n") + addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n", + "(*"+mt+")("+mAddr+")("+ms2+")\n") + addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n", + "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n") + addDumpTest(nm, "(*"+mt+")()\n") + addDumpTest(nilMap, "("+mt+") \n") + + // Map with custom formatter type on pointer receiver only keys and vals. + k2 := pstringer("one") + v2 := pstringer("1") + m2 := map[pstringer]pstringer{k2: v2} + k2Len := fmt.Sprintf("%d", len(k2)) + v2Len := fmt.Sprintf("%d", len(v2)) + m2Len := fmt.Sprintf("%d", len(m2)) + nilMap2 := map[pstringer]pstringer(nil) + nm2 := (*map[pstringer]pstringer)(nil) + pm2 := &m2 + m2Addr := fmt.Sprintf("%p", pm2) + pm2Addr := fmt.Sprintf("%p", &pm2) + m2t := "map[spew_test.pstringer]spew_test.pstringer" + m2t1 := "spew_test.pstringer" + m2t2 := "spew_test.pstringer" + m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " + + "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}" + if spew.UnsafeDisabled { + m2s = "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + + ") " + "\"one\": (" + m2t2 + ") (len=" + v2Len + + ") \"1\"\n}" + } + addDumpTest(m2, "("+m2t+") "+m2s+"\n") + addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n") + addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n") + addDumpTest(nm2, "(*"+m2t+")()\n") + addDumpTest(nilMap2, "("+m2t+") \n") + + // Map with interface keys and values. + k3 := "one" + k3Len := fmt.Sprintf("%d", len(k3)) + m3 := map[interface{}]interface{}{k3: 1} + m3Len := fmt.Sprintf("%d", len(m3)) + nilMap3 := map[interface{}]interface{}(nil) + nm3 := (*map[interface{}]interface{})(nil) + pm3 := &m3 + m3Addr := fmt.Sprintf("%p", pm3) + pm3Addr := fmt.Sprintf("%p", &pm3) + m3t := "map[interface {}]interface {}" + m3t1 := "string" + m3t2 := "int" + m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " + + "\"one\": (" + m3t2 + ") 1\n}" + addDumpTest(m3, "("+m3t+") "+m3s+"\n") + addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n") + addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n") + addDumpTest(nm3, "(*"+m3t+")()\n") + addDumpTest(nilMap3, "("+m3t+") \n") + + // Map with nil interface value. + k4 := "nil" + k4Len := fmt.Sprintf("%d", len(k4)) + m4 := map[string]interface{}{k4: nil} + m4Len := fmt.Sprintf("%d", len(m4)) + nilMap4 := map[string]interface{}(nil) + nm4 := (*map[string]interface{})(nil) + pm4 := &m4 + m4Addr := fmt.Sprintf("%p", pm4) + pm4Addr := fmt.Sprintf("%p", &pm4) + m4t := "map[string]interface {}" + m4t1 := "string" + m4t2 := "interface {}" + m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" + + " \"nil\": (" + m4t2 + ") \n}" + addDumpTest(m4, "("+m4t+") "+m4s+"\n") + addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n") + addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n") + addDumpTest(nm4, "(*"+m4t+")()\n") + addDumpTest(nilMap4, "("+m4t+") \n") +} + +func addStructDumpTests() { + // Struct with primitives. + type s1 struct { + a int8 + b uint8 + } + v := s1{127, 255} + nv := (*s1)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "spew_test.s1" + vt2 := "int8" + vt3 := "uint8" + vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Struct that contains another struct. + type s2 struct { + s1 s1 + b bool + } + v2 := s2{s1{127, 255}, true} + nv2 := (*s2)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "spew_test.s2" + v2t2 := "spew_test.s1" + v2t3 := "int8" + v2t4 := "uint8" + v2t5 := "bool" + v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" + + v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv2, "(*"+v2t+")()\n") + + // Struct that contains custom type with Stringer pointer interface via both + // exported and unexported fields. + type s3 struct { + s pstringer + S pstringer + } + v3 := s3{"test", "test2"} + nv3 := (*s3)(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "spew_test.s3" + v3t2 := "spew_test.pstringer" + v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 + + ") (len=5) stringer test2\n}" + v3sp := v3s + if spew.UnsafeDisabled { + v3s = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + + v3t2 + ") (len=5) \"test2\"\n}" + v3sp = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + + v3t2 + ") (len=5) stringer test2\n}" + } + addDumpTest(v3, "("+v3t+") "+v3s+"\n") + addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3sp+")\n") + addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3sp+")\n") + addDumpTest(nv3, "(*"+v3t+")()\n") + + // Struct that contains embedded struct and field to same struct. + e := embed{"embedstr"} + eLen := fmt.Sprintf("%d", len("embedstr")) + v4 := embedwrap{embed: &e, e: &e} + nv4 := (*embedwrap)(nil) + pv4 := &v4 + eAddr := fmt.Sprintf("%p", &e) + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "spew_test.embedwrap" + v4t2 := "spew_test.embed" + v4t3 := "string" + v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + + ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 + + ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" + + " \"embedstr\"\n })\n}" + addDumpTest(v4, "("+v4t+") "+v4s+"\n") + addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") + addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") + addDumpTest(nv4, "(*"+v4t+")()\n") +} + +func addUintptrDumpTests() { + // Null pointer. + v := uintptr(0) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "uintptr" + vs := "" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + + // Address of real variable. + i := 1 + v2 := uintptr(unsafe.Pointer(&i)) + nv2 := (*uintptr)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "uintptr" + v2s := fmt.Sprintf("%p", &i) + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv2, "(*"+v2t+")()\n") +} + +func addUnsafePointerDumpTests() { + // Null pointer. + v := unsafe.Pointer(uintptr(0)) + nv := (*unsafe.Pointer)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "unsafe.Pointer" + vs := "" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Address of real variable. + i := 1 + v2 := unsafe.Pointer(&i) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "unsafe.Pointer" + v2s := fmt.Sprintf("%p", &i) + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv, "(*"+vt+")()\n") +} + +func addChanDumpTests() { + // Nil channel. + var v chan int + pv := &v + nv := (*chan int)(nil) + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "chan int" + vs := "" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Real channel. + v2 := make(chan int) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "chan int" + v2s := fmt.Sprintf("%p", v2) + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") +} + +func addFuncDumpTests() { + // Function with no params and no returns. + v := addIntDumpTests + nv := (*func())(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "func()" + vs := fmt.Sprintf("%p", v) + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") + + // Function with param and no returns. + v2 := TestDump + nv2 := (*func(*testing.T))(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "func(*testing.T)" + v2s := fmt.Sprintf("%p", v2) + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") + addDumpTest(nv2, "(*"+v2t+")()\n") + + // Function with multiple params and multiple returns. + var v3 = func(i int, s string) (b bool, err error) { + return true, nil + } + nv3 := (*func(int, string) (bool, error))(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "func(int, string) (bool, error)" + v3s := fmt.Sprintf("%p", v3) + addDumpTest(v3, "("+v3t+") "+v3s+"\n") + addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") + addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") + addDumpTest(nv3, "(*"+v3t+")()\n") +} + +func addCircularDumpTests() { + // Struct that is circular through self referencing. + type circular struct { + c *circular + } + v := circular{nil} + v.c = &v + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "spew_test.circular" + vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" + + vAddr + ")()\n })\n}" + vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n") + + // Structs that are circular through cross referencing. + v2 := xref1{nil} + ts2 := xref2{&v2} + v2.ps2 = &ts2 + pv2 := &v2 + ts2Addr := fmt.Sprintf("%p", &ts2) + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "spew_test.xref1" + v2t2 := "spew_test.xref2" + v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + + ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr + + ")()\n })\n })\n}" + v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + + ")(" + v2Addr + ")()\n })\n}" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n") + addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n") + + // Structs that are indirectly circular. + v3 := indirCir1{nil} + tic2 := indirCir2{nil} + tic3 := indirCir3{&v3} + tic2.ps3 = &tic3 + v3.ps2 = &tic2 + pv3 := &v3 + tic2Addr := fmt.Sprintf("%p", &tic2) + tic3Addr := fmt.Sprintf("%p", &tic3) + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "spew_test.indirCir1" + v3t2 := "spew_test.indirCir2" + v3t3 := "spew_test.indirCir3" + v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + + ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + + ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr + + ")()\n })\n })\n })\n}" + v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + + ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + + ")()\n })\n })\n}" + addDumpTest(v3, "("+v3t+") "+v3s+"\n") + addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n") + addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n") +} + +func addPanicDumpTests() { + // Type that panics in its Stringer interface. + v := panicer(127) + nv := (*panicer)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "spew_test.panicer" + vs := "(PANIC=test panic)127" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") +} + +func addErrorDumpTests() { + // Type that has a custom Error interface. + v := customError(127) + nv := (*customError)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "spew_test.customError" + vs := "error: 127" + addDumpTest(v, "("+vt+") "+vs+"\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") + addDumpTest(nv, "(*"+vt+")()\n") +} + +// TestDump executes all of the tests described by dumpTests. +func TestDump(t *testing.T) { + // Setup tests. + addIntDumpTests() + addUintDumpTests() + addBoolDumpTests() + addFloatDumpTests() + addComplexDumpTests() + addArrayDumpTests() + addSliceDumpTests() + addStringDumpTests() + addInterfaceDumpTests() + addMapDumpTests() + addStructDumpTests() + addUintptrDumpTests() + addUnsafePointerDumpTests() + addChanDumpTests() + addFuncDumpTests() + addCircularDumpTests() + addPanicDumpTests() + addErrorDumpTests() + addCgoDumpTests() + + t.Logf("Running %d tests", len(dumpTests)) + for i, test := range dumpTests { + buf := new(bytes.Buffer) + spew.Fdump(buf, test.in) + s := buf.String() + if testFailed(s, test.wants) { + t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants)) + continue + } + } +} + +func TestDumpSortedKeys(t *testing.T) { + cfg := spew.ConfigState{SortKeys: true} + s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"}) + expected := "(map[int]string) (len=3) {\n(int) 1: (string) (len=1) " + + "\"1\",\n(int) 2: (string) (len=1) \"2\",\n(int) 3: (string) " + + "(len=1) \"3\"\n" + + "}\n" + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } + + s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2}) + expected = "(map[spew_test.stringer]int) (len=3) {\n" + + "(spew_test.stringer) (len=1) stringer 1: (int) 1,\n" + + "(spew_test.stringer) (len=1) stringer 2: (int) 2,\n" + + "(spew_test.stringer) (len=1) stringer 3: (int) 3\n" + + "}\n" + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } + + s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) + expected = "(map[spew_test.pstringer]int) (len=3) {\n" + + "(spew_test.pstringer) (len=1) stringer 1: (int) 1,\n" + + "(spew_test.pstringer) (len=1) stringer 2: (int) 2,\n" + + "(spew_test.pstringer) (len=1) stringer 3: (int) 3\n" + + "}\n" + if spew.UnsafeDisabled { + expected = "(map[spew_test.pstringer]int) (len=3) {\n" + + "(spew_test.pstringer) (len=1) \"1\": (int) 1,\n" + + "(spew_test.pstringer) (len=1) \"2\": (int) 2,\n" + + "(spew_test.pstringer) (len=1) \"3\": (int) 3\n" + + "}\n" + } + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } + + s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) + expected = "(map[spew_test.customError]int) (len=3) {\n" + + "(spew_test.customError) error: 1: (int) 1,\n" + + "(spew_test.customError) error: 2: (int) 2,\n" + + "(spew_test.customError) error: 3: (int) 3\n" + + "}\n" + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } + +} diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go new file mode 100644 index 00000000..6ab18080 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go @@ -0,0 +1,99 @@ +// Copyright (c) 2013-2016 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when both cgo is supported and "-tags testcgo" is added to the go test +// command line. This means the cgo tests are only added (and hence run) when +// specifially requested. This configuration is used because spew itself +// does not require cgo to run even though it does handle certain cgo types +// specially. Rather than forcing all clients to require cgo and an external +// C compiler just to run the tests, this scheme makes them optional. +// +build cgo,testcgo + +package spew_test + +import ( + "fmt" + + "github.com/davecgh/go-spew/spew/testdata" +) + +func addCgoDumpTests() { + // C char pointer. + v := testdata.GetCgoCharPointer() + nv := testdata.GetCgoNullCharPointer() + pv := &v + vcAddr := fmt.Sprintf("%p", v) + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "*testdata._Ctype_char" + vs := "116" + addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n") + addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n") + addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n") + addDumpTest(nv, "("+vt+")()\n") + + // C char array. + v2, v2l, v2c := testdata.GetCgoCharArray() + v2Len := fmt.Sprintf("%d", v2l) + v2Cap := fmt.Sprintf("%d", v2c) + v2t := "[6]testdata._Ctype_char" + v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " + + "{\n 00000000 74 65 73 74 32 00 " + + " |test2.|\n}" + addDumpTest(v2, "("+v2t+") "+v2s+"\n") + + // C unsigned char array. + v3, v3l, v3c := testdata.GetCgoUnsignedCharArray() + v3Len := fmt.Sprintf("%d", v3l) + v3Cap := fmt.Sprintf("%d", v3c) + v3t := "[6]testdata._Ctype_unsignedchar" + v3t2 := "[6]testdata._Ctype_uchar" + v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " + + "{\n 00000000 74 65 73 74 33 00 " + + " |test3.|\n}" + addDumpTest(v3, "("+v3t+") "+v3s+"\n", "("+v3t2+") "+v3s+"\n") + + // C signed char array. + v4, v4l, v4c := testdata.GetCgoSignedCharArray() + v4Len := fmt.Sprintf("%d", v4l) + v4Cap := fmt.Sprintf("%d", v4c) + v4t := "[6]testdata._Ctype_schar" + v4t2 := "testdata._Ctype_schar" + v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + + "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 + + ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 + + ") 0\n}" + addDumpTest(v4, "("+v4t+") "+v4s+"\n") + + // C uint8_t array. + v5, v5l, v5c := testdata.GetCgoUint8tArray() + v5Len := fmt.Sprintf("%d", v5l) + v5Cap := fmt.Sprintf("%d", v5c) + v5t := "[6]testdata._Ctype_uint8_t" + v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + + "{\n 00000000 74 65 73 74 35 00 " + + " |test5.|\n}" + addDumpTest(v5, "("+v5t+") "+v5s+"\n") + + // C typedefed unsigned char array. + v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray() + v6Len := fmt.Sprintf("%d", v6l) + v6Cap := fmt.Sprintf("%d", v6c) + v6t := "[6]testdata._Ctype_custom_uchar_t" + v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + + "{\n 00000000 74 65 73 74 36 00 " + + " |test6.|\n}" + addDumpTest(v6, "("+v6t+") "+v6s+"\n") +} diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go new file mode 100644 index 00000000..52a0971f --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go @@ -0,0 +1,26 @@ +// Copyright (c) 2013 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when either cgo is not supported or "-tags testcgo" is not added to the go +// test command line. This file intentionally does not setup any cgo tests in +// this scenario. +// +build !cgo !testcgo + +package spew_test + +func addCgoDumpTests() { + // Don't add any tests for cgo since this file is only compiled when + // there should not be any cgo tests. +} diff --git a/vendor/github.com/davecgh/go-spew/spew/example_test.go b/vendor/github.com/davecgh/go-spew/spew/example_test.go new file mode 100644 index 00000000..c6ec8c6d --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/example_test.go @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew_test + +import ( + "fmt" + + "github.com/davecgh/go-spew/spew" +) + +type Flag int + +const ( + flagOne Flag = iota + flagTwo +) + +var flagStrings = map[Flag]string{ + flagOne: "flagOne", + flagTwo: "flagTwo", +} + +func (f Flag) String() string { + if s, ok := flagStrings[f]; ok { + return s + } + return fmt.Sprintf("Unknown flag (%d)", int(f)) +} + +type Bar struct { + data uintptr +} + +type Foo struct { + unexportedField Bar + ExportedField map[interface{}]interface{} +} + +// This example demonstrates how to use Dump to dump variables to stdout. +func ExampleDump() { + // The following package level declarations are assumed for this example: + /* + type Flag int + + const ( + flagOne Flag = iota + flagTwo + ) + + var flagStrings = map[Flag]string{ + flagOne: "flagOne", + flagTwo: "flagTwo", + } + + func (f Flag) String() string { + if s, ok := flagStrings[f]; ok { + return s + } + return fmt.Sprintf("Unknown flag (%d)", int(f)) + } + + type Bar struct { + data uintptr + } + + type Foo struct { + unexportedField Bar + ExportedField map[interface{}]interface{} + } + */ + + // Setup some sample data structures for the example. + bar := Bar{uintptr(0)} + s1 := Foo{bar, map[interface{}]interface{}{"one": true}} + f := Flag(5) + b := []byte{ + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, + 0x31, 0x32, + } + + // Dump! + spew.Dump(s1, f, b) + + // Output: + // (spew_test.Foo) { + // unexportedField: (spew_test.Bar) { + // data: (uintptr) + // }, + // ExportedField: (map[interface {}]interface {}) (len=1) { + // (string) (len=3) "one": (bool) true + // } + // } + // (spew_test.Flag) Unknown flag (5) + // ([]uint8) (len=34 cap=34) { + // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | + // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| + // 00000020 31 32 |12| + // } + // +} + +// This example demonstrates how to use Printf to display a variable with a +// format string and inline formatting. +func ExamplePrintf() { + // Create a double pointer to a uint 8. + ui8 := uint8(5) + pui8 := &ui8 + ppui8 := &pui8 + + // Create a circular data type. + type circular struct { + ui8 uint8 + c *circular + } + c := circular{ui8: 1} + c.c = &c + + // Print! + spew.Printf("ppui8: %v\n", ppui8) + spew.Printf("circular: %v\n", c) + + // Output: + // ppui8: <**>5 + // circular: {1 <*>{1 <*>}} +} + +// This example demonstrates how to use a ConfigState. +func ExampleConfigState() { + // Modify the indent level of the ConfigState only. The global + // configuration is not modified. + scs := spew.ConfigState{Indent: "\t"} + + // Output using the ConfigState instance. + v := map[string]int{"one": 1} + scs.Printf("v: %v\n", v) + scs.Dump(v) + + // Output: + // v: map[one:1] + // (map[string]int) (len=1) { + // (string) (len=3) "one": (int) 1 + // } +} + +// This example demonstrates how to use ConfigState.Dump to dump variables to +// stdout +func ExampleConfigState_Dump() { + // See the top-level Dump example for details on the types used in this + // example. + + // Create two ConfigState instances with different indentation. + scs := spew.ConfigState{Indent: "\t"} + scs2 := spew.ConfigState{Indent: " "} + + // Setup some sample data structures for the example. + bar := Bar{uintptr(0)} + s1 := Foo{bar, map[interface{}]interface{}{"one": true}} + + // Dump using the ConfigState instances. + scs.Dump(s1) + scs2.Dump(s1) + + // Output: + // (spew_test.Foo) { + // unexportedField: (spew_test.Bar) { + // data: (uintptr) + // }, + // ExportedField: (map[interface {}]interface {}) (len=1) { + // (string) (len=3) "one": (bool) true + // } + // } + // (spew_test.Foo) { + // unexportedField: (spew_test.Bar) { + // data: (uintptr) + // }, + // ExportedField: (map[interface {}]interface {}) (len=1) { + // (string) (len=3) "one": (bool) true + // } + // } + // +} + +// This example demonstrates how to use ConfigState.Printf to display a variable +// with a format string and inline formatting. +func ExampleConfigState_Printf() { + // See the top-level Dump example for details on the types used in this + // example. + + // Create two ConfigState instances and modify the method handling of the + // first ConfigState only. + scs := spew.NewDefaultConfig() + scs2 := spew.NewDefaultConfig() + scs.DisableMethods = true + + // Alternatively + // scs := spew.ConfigState{Indent: " ", DisableMethods: true} + // scs2 := spew.ConfigState{Indent: " "} + + // This is of type Flag which implements a Stringer and has raw value 1. + f := flagTwo + + // Dump using the ConfigState instances. + scs.Printf("f: %v\n", f) + scs2.Printf("f: %v\n", f) + + // Output: + // f: 1 + // f: flagTwo +} diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go new file mode 100644 index 00000000..c49875ba --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/format.go @@ -0,0 +1,419 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "bytes" + "fmt" + "reflect" + "strconv" + "strings" +) + +// supportedFlags is a list of all the character flags supported by fmt package. +const supportedFlags = "0-+# " + +// formatState implements the fmt.Formatter interface and contains information +// about the state of a formatting operation. The NewFormatter function can +// be used to get a new Formatter which can be used directly as arguments +// in standard fmt package printing calls. +type formatState struct { + value interface{} + fs fmt.State + depth int + pointers map[uintptr]int + ignoreNextType bool + cs *ConfigState +} + +// buildDefaultFormat recreates the original format string without precision +// and width information to pass in to fmt.Sprintf in the case of an +// unrecognized type. Unless new types are added to the language, this +// function won't ever be called. +func (f *formatState) buildDefaultFormat() (format string) { + buf := bytes.NewBuffer(percentBytes) + + for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } + + buf.WriteRune('v') + + format = buf.String() + return format +} + +// constructOrigFormat recreates the original format string including precision +// and width information to pass along to the standard fmt package. This allows +// automatic deferral of all format strings this package doesn't support. +func (f *formatState) constructOrigFormat(verb rune) (format string) { + buf := bytes.NewBuffer(percentBytes) + + for _, flag := range supportedFlags { + if f.fs.Flag(int(flag)) { + buf.WriteRune(flag) + } + } + + if width, ok := f.fs.Width(); ok { + buf.WriteString(strconv.Itoa(width)) + } + + if precision, ok := f.fs.Precision(); ok { + buf.Write(precisionBytes) + buf.WriteString(strconv.Itoa(precision)) + } + + buf.WriteRune(verb) + + format = buf.String() + return format +} + +// unpackValue returns values inside of non-nil interfaces when possible and +// ensures that types for values which have been unpacked from an interface +// are displayed when the show types flag is also set. +// This is useful for data types like structs, arrays, slices, and maps which +// can contain varying types packed inside an interface. +func (f *formatState) unpackValue(v reflect.Value) reflect.Value { + if v.Kind() == reflect.Interface { + f.ignoreNextType = false + if !v.IsNil() { + v = v.Elem() + } + } + return v +} + +// formatPtr handles formatting of pointers by indirecting them as necessary. +func (f *formatState) formatPtr(v reflect.Value) { + // Display nil if top level pointer is nil. + showTypes := f.fs.Flag('#') + if v.IsNil() && (!showTypes || f.ignoreNextType) { + f.fs.Write(nilAngleBytes) + return + } + + // Remove pointers at or below the current depth from map used to detect + // circular refs. + for k, depth := range f.pointers { + if depth >= f.depth { + delete(f.pointers, k) + } + } + + // Keep list of all dereferenced pointers to possibly show later. + pointerChain := make([]uintptr, 0) + + // Figure out how many levels of indirection there are by derferencing + // pointers and unpacking interfaces down the chain while detecting circular + // references. + nilFound := false + cycleFound := false + indirects := 0 + ve := v + for ve.Kind() == reflect.Ptr { + if ve.IsNil() { + nilFound = true + break + } + indirects++ + addr := ve.Pointer() + pointerChain = append(pointerChain, addr) + if pd, ok := f.pointers[addr]; ok && pd < f.depth { + cycleFound = true + indirects-- + break + } + f.pointers[addr] = f.depth + + ve = ve.Elem() + if ve.Kind() == reflect.Interface { + if ve.IsNil() { + nilFound = true + break + } + ve = ve.Elem() + } + } + + // Display type or indirection level depending on flags. + if showTypes && !f.ignoreNextType { + f.fs.Write(openParenBytes) + f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) + f.fs.Write([]byte(ve.Type().String())) + f.fs.Write(closeParenBytes) + } else { + if nilFound || cycleFound { + indirects += strings.Count(ve.Type().String(), "*") + } + f.fs.Write(openAngleBytes) + f.fs.Write([]byte(strings.Repeat("*", indirects))) + f.fs.Write(closeAngleBytes) + } + + // Display pointer information depending on flags. + if f.fs.Flag('+') && (len(pointerChain) > 0) { + f.fs.Write(openParenBytes) + for i, addr := range pointerChain { + if i > 0 { + f.fs.Write(pointerChainBytes) + } + printHexPtr(f.fs, addr) + } + f.fs.Write(closeParenBytes) + } + + // Display dereferenced value. + switch { + case nilFound == true: + f.fs.Write(nilAngleBytes) + + case cycleFound == true: + f.fs.Write(circularShortBytes) + + default: + f.ignoreNextType = true + f.format(ve) + } +} + +// format is the main workhorse for providing the Formatter interface. It +// uses the passed reflect value to figure out what kind of object we are +// dealing with and formats it appropriately. It is a recursive function, +// however circular data structures are detected and handled properly. +func (f *formatState) format(v reflect.Value) { + // Handle invalid reflect values immediately. + kind := v.Kind() + if kind == reflect.Invalid { + f.fs.Write(invalidAngleBytes) + return + } + + // Handle pointers specially. + if kind == reflect.Ptr { + f.formatPtr(v) + return + } + + // Print type information unless already handled elsewhere. + if !f.ignoreNextType && f.fs.Flag('#') { + f.fs.Write(openParenBytes) + f.fs.Write([]byte(v.Type().String())) + f.fs.Write(closeParenBytes) + } + f.ignoreNextType = false + + // Call Stringer/error interfaces if they exist and the handle methods + // flag is enabled. + if !f.cs.DisableMethods { + if (kind != reflect.Invalid) && (kind != reflect.Interface) { + if handled := handleMethods(f.cs, f.fs, v); handled { + return + } + } + } + + switch kind { + case reflect.Invalid: + // Do nothing. We should never get here since invalid has already + // been handled above. + + case reflect.Bool: + printBool(f.fs, v.Bool()) + + case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: + printInt(f.fs, v.Int(), 10) + + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + printUint(f.fs, v.Uint(), 10) + + case reflect.Float32: + printFloat(f.fs, v.Float(), 32) + + case reflect.Float64: + printFloat(f.fs, v.Float(), 64) + + case reflect.Complex64: + printComplex(f.fs, v.Complex(), 32) + + case reflect.Complex128: + printComplex(f.fs, v.Complex(), 64) + + case reflect.Slice: + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + fallthrough + + case reflect.Array: + f.fs.Write(openBracketBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + numEntries := v.Len() + for i := 0; i < numEntries; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(v.Index(i))) + } + } + f.depth-- + f.fs.Write(closeBracketBytes) + + case reflect.String: + f.fs.Write([]byte(v.String())) + + case reflect.Interface: + // The only time we should get here is for nil interfaces due to + // unpackValue calls. + if v.IsNil() { + f.fs.Write(nilAngleBytes) + } + + case reflect.Ptr: + // Do nothing. We should never get here since pointers have already + // been handled above. + + case reflect.Map: + // nil maps should be indicated as different than empty maps + if v.IsNil() { + f.fs.Write(nilAngleBytes) + break + } + + f.fs.Write(openMapBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + keys := v.MapKeys() + if f.cs.SortKeys { + sortValues(keys, f.cs) + } + for i, key := range keys { + if i > 0 { + f.fs.Write(spaceBytes) + } + f.ignoreNextType = true + f.format(f.unpackValue(key)) + f.fs.Write(colonBytes) + f.ignoreNextType = true + f.format(f.unpackValue(v.MapIndex(key))) + } + } + f.depth-- + f.fs.Write(closeMapBytes) + + case reflect.Struct: + numFields := v.NumField() + f.fs.Write(openBraceBytes) + f.depth++ + if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { + f.fs.Write(maxShortBytes) + } else { + vt := v.Type() + for i := 0; i < numFields; i++ { + if i > 0 { + f.fs.Write(spaceBytes) + } + vtf := vt.Field(i) + if f.fs.Flag('+') || f.fs.Flag('#') { + f.fs.Write([]byte(vtf.Name)) + f.fs.Write(colonBytes) + } + f.format(f.unpackValue(v.Field(i))) + } + } + f.depth-- + f.fs.Write(closeBraceBytes) + + case reflect.Uintptr: + printHexPtr(f.fs, uintptr(v.Uint())) + + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + printHexPtr(f.fs, v.Pointer()) + + // There were not any other types at the time this code was written, but + // fall back to letting the default fmt package handle it if any get added. + default: + format := f.buildDefaultFormat() + if v.CanInterface() { + fmt.Fprintf(f.fs, format, v.Interface()) + } else { + fmt.Fprintf(f.fs, format, v.String()) + } + } +} + +// Format satisfies the fmt.Formatter interface. See NewFormatter for usage +// details. +func (f *formatState) Format(fs fmt.State, verb rune) { + f.fs = fs + + // Use standard formatting for verbs that are not v. + if verb != 'v' { + format := f.constructOrigFormat(verb) + fmt.Fprintf(fs, format, f.value) + return + } + + if f.value == nil { + if fs.Flag('#') { + fs.Write(interfaceBytes) + } + fs.Write(nilAngleBytes) + return + } + + f.format(reflect.ValueOf(f.value)) +} + +// newFormatter is a helper function to consolidate the logic from the various +// public methods which take varying config states. +func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { + fs := &formatState{value: v, cs: cs} + fs.pointers = make(map[uintptr]int) + return fs +} + +/* +NewFormatter returns a custom formatter that satisfies the fmt.Formatter +interface. As a result, it integrates cleanly with standard fmt package +printing functions. The formatter is useful for inline printing of smaller data +types similar to the standard %v format specifier. + +The custom formatter only responds to the %v (most compact), %+v (adds pointer +addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb +combinations. Any other verbs such as %x and %q will be sent to the the +standard fmt package for formatting. In addition, the custom formatter ignores +the width and precision arguments (however they will still work on the format +specifiers not handled by the custom formatter). + +Typically this function shouldn't be called directly. It is much easier to make +use of the custom formatter by calling one of the convenience functions such as +Printf, Println, or Fprintf. +*/ +func NewFormatter(v interface{}) fmt.Formatter { + return newFormatter(&Config, v) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/format_test.go b/vendor/github.com/davecgh/go-spew/spew/format_test.go new file mode 100644 index 00000000..f9b93abe --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/format_test.go @@ -0,0 +1,1558 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* +Test Summary: +NOTE: For each test, a nil pointer, a single pointer and double pointer to the +base test element are also tested to ensure proper indirection across all types. + +- Max int8, int16, int32, int64, int +- Max uint8, uint16, uint32, uint64, uint +- Boolean true and false +- Standard complex64 and complex128 +- Array containing standard ints +- Array containing type with custom formatter on pointer receiver only +- Array containing interfaces +- Slice containing standard float32 values +- Slice containing type with custom formatter on pointer receiver only +- Slice containing interfaces +- Nil slice +- Standard string +- Nil interface +- Sub-interface +- Map with string keys and int vals +- Map with custom formatter type on pointer receiver only keys and vals +- Map with interface keys and values +- Map with nil interface value +- Struct with primitives +- Struct that contains another struct +- Struct that contains custom type with Stringer pointer interface via both + exported and unexported fields +- Struct that contains embedded struct and field to same struct +- Uintptr to 0 (null pointer) +- Uintptr address of real variable +- Unsafe.Pointer to 0 (null pointer) +- Unsafe.Pointer to address of real variable +- Nil channel +- Standard int channel +- Function with no params and no returns +- Function with param and no returns +- Function with multiple params and multiple returns +- Struct that is circular through self referencing +- Structs that are circular through cross referencing +- Structs that are indirectly circular +- Type that panics in its Stringer interface +- Type that has a custom Error interface +- %x passthrough with uint +- %#x passthrough with uint +- %f passthrough with precision +- %f passthrough with width and precision +- %d passthrough with width +- %q passthrough with string +*/ + +package spew_test + +import ( + "bytes" + "fmt" + "testing" + "unsafe" + + "github.com/davecgh/go-spew/spew" +) + +// formatterTest is used to describe a test to be performed against NewFormatter. +type formatterTest struct { + format string + in interface{} + wants []string +} + +// formatterTests houses all of the tests to be performed against NewFormatter. +var formatterTests = make([]formatterTest, 0) + +// addFormatterTest is a helper method to append the passed input and desired +// result to formatterTests. +func addFormatterTest(format string, in interface{}, wants ...string) { + test := formatterTest{format, in, wants} + formatterTests = append(formatterTests, test) +} + +func addIntFormatterTests() { + // Max int8. + v := int8(127) + nv := (*int8)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "int8" + vs := "127" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Max int16. + v2 := int16(32767) + nv2 := (*int16)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "int16" + v2s := "32767" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%v", nv2, "") + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") + + // Max int32. + v3 := int32(2147483647) + nv3 := (*int32)(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "int32" + v3s := "2147483647" + addFormatterTest("%v", v3, v3s) + addFormatterTest("%v", pv3, "<*>"+v3s) + addFormatterTest("%v", &pv3, "<**>"+v3s) + addFormatterTest("%v", nv3, "") + addFormatterTest("%+v", v3, v3s) + addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) + addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%#v", v3, "("+v3t+")"+v3s) + addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) + addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) + addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) + addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + + // Max int64. + v4 := int64(9223372036854775807) + nv4 := (*int64)(nil) + pv4 := &v4 + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "int64" + v4s := "9223372036854775807" + addFormatterTest("%v", v4, v4s) + addFormatterTest("%v", pv4, "<*>"+v4s) + addFormatterTest("%v", &pv4, "<**>"+v4s) + addFormatterTest("%v", nv4, "") + addFormatterTest("%+v", v4, v4s) + addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) + addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) + addFormatterTest("%+v", nv4, "") + addFormatterTest("%#v", v4, "("+v4t+")"+v4s) + addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) + addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) + addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") + addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) + addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) + addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) + addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") + + // Max int. + v5 := int(2147483647) + nv5 := (*int)(nil) + pv5 := &v5 + v5Addr := fmt.Sprintf("%p", pv5) + pv5Addr := fmt.Sprintf("%p", &pv5) + v5t := "int" + v5s := "2147483647" + addFormatterTest("%v", v5, v5s) + addFormatterTest("%v", pv5, "<*>"+v5s) + addFormatterTest("%v", &pv5, "<**>"+v5s) + addFormatterTest("%v", nv5, "") + addFormatterTest("%+v", v5, v5s) + addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) + addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) + addFormatterTest("%+v", nv5, "") + addFormatterTest("%#v", v5, "("+v5t+")"+v5s) + addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) + addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) + addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") + addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) + addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) + addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) + addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"") +} + +func addUintFormatterTests() { + // Max uint8. + v := uint8(255) + nv := (*uint8)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "uint8" + vs := "255" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Max uint16. + v2 := uint16(65535) + nv2 := (*uint16)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "uint16" + v2s := "65535" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%v", nv2, "") + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") + + // Max uint32. + v3 := uint32(4294967295) + nv3 := (*uint32)(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "uint32" + v3s := "4294967295" + addFormatterTest("%v", v3, v3s) + addFormatterTest("%v", pv3, "<*>"+v3s) + addFormatterTest("%v", &pv3, "<**>"+v3s) + addFormatterTest("%v", nv3, "") + addFormatterTest("%+v", v3, v3s) + addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) + addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%#v", v3, "("+v3t+")"+v3s) + addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) + addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) + addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) + addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + + // Max uint64. + v4 := uint64(18446744073709551615) + nv4 := (*uint64)(nil) + pv4 := &v4 + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "uint64" + v4s := "18446744073709551615" + addFormatterTest("%v", v4, v4s) + addFormatterTest("%v", pv4, "<*>"+v4s) + addFormatterTest("%v", &pv4, "<**>"+v4s) + addFormatterTest("%v", nv4, "") + addFormatterTest("%+v", v4, v4s) + addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) + addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) + addFormatterTest("%+v", nv4, "") + addFormatterTest("%#v", v4, "("+v4t+")"+v4s) + addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) + addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) + addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") + addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) + addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) + addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) + addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") + + // Max uint. + v5 := uint(4294967295) + nv5 := (*uint)(nil) + pv5 := &v5 + v5Addr := fmt.Sprintf("%p", pv5) + pv5Addr := fmt.Sprintf("%p", &pv5) + v5t := "uint" + v5s := "4294967295" + addFormatterTest("%v", v5, v5s) + addFormatterTest("%v", pv5, "<*>"+v5s) + addFormatterTest("%v", &pv5, "<**>"+v5s) + addFormatterTest("%v", nv5, "") + addFormatterTest("%+v", v5, v5s) + addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) + addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) + addFormatterTest("%+v", nv5, "") + addFormatterTest("%#v", v5, "("+v5t+")"+v5s) + addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) + addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) + addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") + addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) + addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) + addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) + addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") +} + +func addBoolFormatterTests() { + // Boolean true. + v := bool(true) + nv := (*bool)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "bool" + vs := "true" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Boolean false. + v2 := bool(false) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "bool" + v2s := "false" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) +} + +func addFloatFormatterTests() { + // Standard float32. + v := float32(3.1415) + nv := (*float32)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "float32" + vs := "3.1415" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Standard float64. + v2 := float64(3.1415926) + nv2 := (*float64)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "float64" + v2s := "3.1415926" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") +} + +func addComplexFormatterTests() { + // Standard complex64. + v := complex(float32(6), -2) + nv := (*complex64)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "complex64" + vs := "(6-2i)" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Standard complex128. + v2 := complex(float64(-6), 2) + nv2 := (*complex128)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "complex128" + v2s := "(-6+2i)" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") +} + +func addArrayFormatterTests() { + // Array containing standard ints. + v := [3]int{1, 2, 3} + nv := (*[3]int)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "[3]int" + vs := "[1 2 3]" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Array containing type with custom formatter on pointer receiver only. + v2 := [3]pstringer{"1", "2", "3"} + nv2 := (*[3]pstringer)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "[3]spew_test.pstringer" + v2sp := "[stringer 1 stringer 2 stringer 3]" + v2s := v2sp + if spew.UnsafeDisabled { + v2s = "[1 2 3]" + } + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2sp) + addFormatterTest("%v", &pv2, "<**>"+v2sp) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") + + // Array containing interfaces. + v3 := [3]interface{}{"one", int(2), uint(3)} + nv3 := (*[3]interface{})(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "[3]interface {}" + v3t2 := "string" + v3t3 := "int" + v3t4 := "uint" + v3s := "[one 2 3]" + v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]" + addFormatterTest("%v", v3, v3s) + addFormatterTest("%v", pv3, "<*>"+v3s) + addFormatterTest("%v", &pv3, "<**>"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%+v", v3, v3s) + addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) + addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) + addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) + addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) + addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) + addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) + addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") +} + +func addSliceFormatterTests() { + // Slice containing standard float32 values. + v := []float32{3.14, 6.28, 12.56} + nv := (*[]float32)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "[]float32" + vs := "[3.14 6.28 12.56]" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Slice containing type with custom formatter on pointer receiver only. + v2 := []pstringer{"1", "2", "3"} + nv2 := (*[]pstringer)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "[]spew_test.pstringer" + v2s := "[stringer 1 stringer 2 stringer 3]" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") + + // Slice containing interfaces. + v3 := []interface{}{"one", int(2), uint(3), nil} + nv3 := (*[]interface{})(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "[]interface {}" + v3t2 := "string" + v3t3 := "int" + v3t4 := "uint" + v3t5 := "interface {}" + v3s := "[one 2 3 ]" + v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 + + ")]" + addFormatterTest("%v", v3, v3s) + addFormatterTest("%v", pv3, "<*>"+v3s) + addFormatterTest("%v", &pv3, "<**>"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%+v", v3, v3s) + addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) + addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) + addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) + addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) + addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) + addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) + addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") + + // Nil slice. + var v4 []int + nv4 := (*[]int)(nil) + pv4 := &v4 + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "[]int" + v4s := "" + addFormatterTest("%v", v4, v4s) + addFormatterTest("%v", pv4, "<*>"+v4s) + addFormatterTest("%v", &pv4, "<**>"+v4s) + addFormatterTest("%+v", nv4, "") + addFormatterTest("%+v", v4, v4s) + addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) + addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) + addFormatterTest("%+v", nv4, "") + addFormatterTest("%#v", v4, "("+v4t+")"+v4s) + addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) + addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) + addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") + addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) + addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) + addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) + addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") +} + +func addStringFormatterTests() { + // Standard string. + v := "test" + nv := (*string)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "string" + vs := "test" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") +} + +func addInterfaceFormatterTests() { + // Nil interface. + var v interface{} + nv := (*interface{})(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "interface {}" + vs := "" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Sub-interface. + v2 := interface{}(uint16(65535)) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "uint16" + v2s := "65535" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) +} + +func addMapFormatterTests() { + // Map with string keys and int vals. + v := map[string]int{"one": 1, "two": 2} + nilMap := map[string]int(nil) + nv := (*map[string]int)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "map[string]int" + vs := "map[one:1 two:2]" + vs2 := "map[two:2 one:1]" + addFormatterTest("%v", v, vs, vs2) + addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2) + addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2) + addFormatterTest("%+v", nilMap, "") + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs, vs2) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs, + "<**>("+pvAddr+"->"+vAddr+")"+vs2) + addFormatterTest("%+v", nilMap, "") + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2) + addFormatterTest("%#v", nilMap, "("+vt+")"+"") + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs, + "(*"+vt+")("+vAddr+")"+vs2) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs, + "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2) + addFormatterTest("%#+v", nilMap, "("+vt+")"+"") + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Map with custom formatter type on pointer receiver only keys and vals. + v2 := map[pstringer]pstringer{"one": "1"} + nv2 := (*map[pstringer]pstringer)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "map[spew_test.pstringer]spew_test.pstringer" + v2s := "map[stringer one:stringer 1]" + if spew.UnsafeDisabled { + v2s = "map[one:1]" + } + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") + + // Map with interface keys and values. + v3 := map[interface{}]interface{}{"one": 1} + nv3 := (*map[interface{}]interface{})(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "map[interface {}]interface {}" + v3t1 := "string" + v3t2 := "int" + v3s := "map[one:1]" + v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]" + addFormatterTest("%v", v3, v3s) + addFormatterTest("%v", pv3, "<*>"+v3s) + addFormatterTest("%v", &pv3, "<**>"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%+v", v3, v3s) + addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) + addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) + addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) + addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) + addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) + addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) + addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") + + // Map with nil interface value + v4 := map[string]interface{}{"nil": nil} + nv4 := (*map[string]interface{})(nil) + pv4 := &v4 + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "map[string]interface {}" + v4t1 := "interface {}" + v4s := "map[nil:]" + v4s2 := "map[nil:(" + v4t1 + ")]" + addFormatterTest("%v", v4, v4s) + addFormatterTest("%v", pv4, "<*>"+v4s) + addFormatterTest("%v", &pv4, "<**>"+v4s) + addFormatterTest("%+v", nv4, "") + addFormatterTest("%+v", v4, v4s) + addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) + addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) + addFormatterTest("%+v", nv4, "") + addFormatterTest("%#v", v4, "("+v4t+")"+v4s2) + addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2) + addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2) + addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") + addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2) + addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2) + addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2) + addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") +} + +func addStructFormatterTests() { + // Struct with primitives. + type s1 struct { + a int8 + b uint8 + } + v := s1{127, 255} + nv := (*s1)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "spew_test.s1" + vt2 := "int8" + vt3 := "uint8" + vs := "{127 255}" + vs2 := "{a:127 b:255}" + vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs2) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs3) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs3) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs3) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Struct that contains another struct. + type s2 struct { + s1 s1 + b bool + } + v2 := s2{s1{127, 255}, true} + nv2 := (*s2)(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "spew_test.s2" + v2t2 := "spew_test.s1" + v2t3 := "int8" + v2t4 := "uint8" + v2t5 := "bool" + v2s := "{{127 255} true}" + v2s2 := "{s1:{a:127 b:255} b:true}" + v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" + + v2t5 + ")true}" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%+v", v2, v2s2) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s3) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") + + // Struct that contains custom type with Stringer pointer interface via both + // exported and unexported fields. + type s3 struct { + s pstringer + S pstringer + } + v3 := s3{"test", "test2"} + nv3 := (*s3)(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "spew_test.s3" + v3t2 := "spew_test.pstringer" + v3s := "{stringer test stringer test2}" + v3sp := v3s + v3s2 := "{s:stringer test S:stringer test2}" + v3s2p := v3s2 + v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}" + v3s3p := v3s3 + if spew.UnsafeDisabled { + v3s = "{test test2}" + v3sp = "{test stringer test2}" + v3s2 = "{s:test S:test2}" + v3s2p = "{s:test S:stringer test2}" + v3s3 = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")test2}" + v3s3p = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")stringer test2}" + } + addFormatterTest("%v", v3, v3s) + addFormatterTest("%v", pv3, "<*>"+v3sp) + addFormatterTest("%v", &pv3, "<**>"+v3sp) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%+v", v3, v3s2) + addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p) + addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%#v", v3, "("+v3t+")"+v3s3) + addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p) + addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3) + addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p) + addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p) + addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") + + // Struct that contains embedded struct and field to same struct. + e := embed{"embedstr"} + v4 := embedwrap{embed: &e, e: &e} + nv4 := (*embedwrap)(nil) + pv4 := &v4 + eAddr := fmt.Sprintf("%p", &e) + v4Addr := fmt.Sprintf("%p", pv4) + pv4Addr := fmt.Sprintf("%p", &pv4) + v4t := "spew_test.embedwrap" + v4t2 := "spew_test.embed" + v4t3 := "string" + v4s := "{<*>{embedstr} <*>{embedstr}}" + v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr + + "){a:embedstr}}" + v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + + "){a:(" + v4t3 + ")embedstr}}" + v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + + ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}" + addFormatterTest("%v", v4, v4s) + addFormatterTest("%v", pv4, "<*>"+v4s) + addFormatterTest("%v", &pv4, "<**>"+v4s) + addFormatterTest("%+v", nv4, "") + addFormatterTest("%+v", v4, v4s2) + addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2) + addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2) + addFormatterTest("%+v", nv4, "") + addFormatterTest("%#v", v4, "("+v4t+")"+v4s3) + addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3) + addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3) + addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") + addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4) + addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4) + addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4) + addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") +} + +func addUintptrFormatterTests() { + // Null pointer. + v := uintptr(0) + nv := (*uintptr)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "uintptr" + vs := "" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Address of real variable. + i := 1 + v2 := uintptr(unsafe.Pointer(&i)) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "uintptr" + v2s := fmt.Sprintf("%p", &i) + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) +} + +func addUnsafePointerFormatterTests() { + // Null pointer. + v := unsafe.Pointer(uintptr(0)) + nv := (*unsafe.Pointer)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "unsafe.Pointer" + vs := "" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Address of real variable. + i := 1 + v2 := unsafe.Pointer(&i) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "unsafe.Pointer" + v2s := fmt.Sprintf("%p", &i) + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) +} + +func addChanFormatterTests() { + // Nil channel. + var v chan int + pv := &v + nv := (*chan int)(nil) + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "chan int" + vs := "" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Real channel. + v2 := make(chan int) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "chan int" + v2s := fmt.Sprintf("%p", v2) + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) +} + +func addFuncFormatterTests() { + // Function with no params and no returns. + v := addIntFormatterTests + nv := (*func())(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "func()" + vs := fmt.Sprintf("%p", v) + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") + + // Function with param and no returns. + v2 := TestFormatter + nv2 := (*func(*testing.T))(nil) + pv2 := &v2 + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "func(*testing.T)" + v2s := fmt.Sprintf("%p", v2) + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s) + addFormatterTest("%v", &pv2, "<**>"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%+v", v2, v2s) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%+v", nv2, "") + addFormatterTest("%#v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) + addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) + addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") + + // Function with multiple params and multiple returns. + var v3 = func(i int, s string) (b bool, err error) { + return true, nil + } + nv3 := (*func(int, string) (bool, error))(nil) + pv3 := &v3 + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "func(int, string) (bool, error)" + v3s := fmt.Sprintf("%p", v3) + addFormatterTest("%v", v3, v3s) + addFormatterTest("%v", pv3, "<*>"+v3s) + addFormatterTest("%v", &pv3, "<**>"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%+v", v3, v3s) + addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) + addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%+v", nv3, "") + addFormatterTest("%#v", v3, "("+v3t+")"+v3s) + addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) + addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) + addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") + addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) + addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) + addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) + addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") +} + +func addCircularFormatterTests() { + // Struct that is circular through self referencing. + type circular struct { + c *circular + } + v := circular{nil} + v.c = &v + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "spew_test.circular" + vs := "{<*>{<*>}}" + vs2 := "{<*>}" + vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}" + vs4 := "{c:<*>(" + vAddr + ")}" + vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}" + vs6 := "{c:(*" + vt + ")}" + vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr + + ")}}" + vs8 := "{c:(*" + vt + ")(" + vAddr + ")}" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs2) + addFormatterTest("%v", &pv, "<**>"+vs2) + addFormatterTest("%+v", v, vs3) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4) + addFormatterTest("%#v", v, "("+vt+")"+vs5) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs6) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6) + addFormatterTest("%#+v", v, "("+vt+")"+vs7) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8) + + // Structs that are circular through cross referencing. + v2 := xref1{nil} + ts2 := xref2{&v2} + v2.ps2 = &ts2 + pv2 := &v2 + ts2Addr := fmt.Sprintf("%p", &ts2) + v2Addr := fmt.Sprintf("%p", pv2) + pv2Addr := fmt.Sprintf("%p", &pv2) + v2t := "spew_test.xref1" + v2t2 := "spew_test.xref2" + v2s := "{<*>{<*>{<*>}}}" + v2s2 := "{<*>{<*>}}" + v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" + + ts2Addr + ")}}}" + v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")}}" + v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 + + ")}}}" + v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")}}" + v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + + ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr + + ")}}}" + v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + + ")(" + v2Addr + ")}}" + addFormatterTest("%v", v2, v2s) + addFormatterTest("%v", pv2, "<*>"+v2s2) + addFormatterTest("%v", &pv2, "<**>"+v2s2) + addFormatterTest("%+v", v2, v2s3) + addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4) + addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4) + addFormatterTest("%#v", v2, "("+v2t+")"+v2s5) + addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6) + addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6) + addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7) + addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8) + addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8) + + // Structs that are indirectly circular. + v3 := indirCir1{nil} + tic2 := indirCir2{nil} + tic3 := indirCir3{&v3} + tic2.ps3 = &tic3 + v3.ps2 = &tic2 + pv3 := &v3 + tic2Addr := fmt.Sprintf("%p", &tic2) + tic3Addr := fmt.Sprintf("%p", &tic3) + v3Addr := fmt.Sprintf("%p", pv3) + pv3Addr := fmt.Sprintf("%p", &pv3) + v3t := "spew_test.indirCir1" + v3t2 := "spew_test.indirCir2" + v3t3 := "spew_test.indirCir3" + v3s := "{<*>{<*>{<*>{<*>}}}}" + v3s2 := "{<*>{<*>{<*>}}}" + v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + + v3Addr + "){ps2:<*>(" + tic2Addr + ")}}}}" + v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + + v3Addr + ")}}}" + v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + + "){ps2:(*" + v3t2 + ")}}}}" + v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + + ")}}}" + v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + + tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 + + ")(" + tic2Addr + ")}}}}" + v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + + tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")}}}" + addFormatterTest("%v", v3, v3s) + addFormatterTest("%v", pv3, "<*>"+v3s2) + addFormatterTest("%v", &pv3, "<**>"+v3s2) + addFormatterTest("%+v", v3, v3s3) + addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4) + addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4) + addFormatterTest("%#v", v3, "("+v3t+")"+v3s5) + addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6) + addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6) + addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7) + addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8) + addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8) +} + +func addPanicFormatterTests() { + // Type that panics in its Stringer interface. + v := panicer(127) + nv := (*panicer)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "spew_test.panicer" + vs := "(PANIC=test panic)127" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") +} + +func addErrorFormatterTests() { + // Type that has a custom Error interface. + v := customError(127) + nv := (*customError)(nil) + pv := &v + vAddr := fmt.Sprintf("%p", pv) + pvAddr := fmt.Sprintf("%p", &pv) + vt := "spew_test.customError" + vs := "error: 127" + addFormatterTest("%v", v, vs) + addFormatterTest("%v", pv, "<*>"+vs) + addFormatterTest("%v", &pv, "<**>"+vs) + addFormatterTest("%v", nv, "") + addFormatterTest("%+v", v, vs) + addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) + addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%+v", nv, "") + addFormatterTest("%#v", v, "("+vt+")"+vs) + addFormatterTest("%#v", pv, "(*"+vt+")"+vs) + addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) + addFormatterTest("%#v", nv, "(*"+vt+")"+"") + addFormatterTest("%#+v", v, "("+vt+")"+vs) + addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) + addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) + addFormatterTest("%#+v", nv, "(*"+vt+")"+"") +} + +func addPassthroughFormatterTests() { + // %x passthrough with uint. + v := uint(4294967295) + pv := &v + vAddr := fmt.Sprintf("%x", pv) + pvAddr := fmt.Sprintf("%x", &pv) + vs := "ffffffff" + addFormatterTest("%x", v, vs) + addFormatterTest("%x", pv, vAddr) + addFormatterTest("%x", &pv, pvAddr) + + // %#x passthrough with uint. + v2 := int(2147483647) + pv2 := &v2 + v2Addr := fmt.Sprintf("%#x", pv2) + pv2Addr := fmt.Sprintf("%#x", &pv2) + v2s := "0x7fffffff" + addFormatterTest("%#x", v2, v2s) + addFormatterTest("%#x", pv2, v2Addr) + addFormatterTest("%#x", &pv2, pv2Addr) + + // %f passthrough with precision. + addFormatterTest("%.2f", 3.1415, "3.14") + addFormatterTest("%.3f", 3.1415, "3.142") + addFormatterTest("%.4f", 3.1415, "3.1415") + + // %f passthrough with width and precision. + addFormatterTest("%5.2f", 3.1415, " 3.14") + addFormatterTest("%6.3f", 3.1415, " 3.142") + addFormatterTest("%7.4f", 3.1415, " 3.1415") + + // %d passthrough with width. + addFormatterTest("%3d", 127, "127") + addFormatterTest("%4d", 127, " 127") + addFormatterTest("%5d", 127, " 127") + + // %q passthrough with string. + addFormatterTest("%q", "test", "\"test\"") +} + +// TestFormatter executes all of the tests described by formatterTests. +func TestFormatter(t *testing.T) { + // Setup tests. + addIntFormatterTests() + addUintFormatterTests() + addBoolFormatterTests() + addFloatFormatterTests() + addComplexFormatterTests() + addArrayFormatterTests() + addSliceFormatterTests() + addStringFormatterTests() + addInterfaceFormatterTests() + addMapFormatterTests() + addStructFormatterTests() + addUintptrFormatterTests() + addUnsafePointerFormatterTests() + addChanFormatterTests() + addFuncFormatterTests() + addCircularFormatterTests() + addPanicFormatterTests() + addErrorFormatterTests() + addPassthroughFormatterTests() + + t.Logf("Running %d tests", len(formatterTests)) + for i, test := range formatterTests { + buf := new(bytes.Buffer) + spew.Fprintf(buf, test.format, test.in) + s := buf.String() + if testFailed(s, test.wants) { + t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s, + stringizeWants(test.wants)) + continue + } + } +} + +type testStruct struct { + x int +} + +func (ts testStruct) String() string { + return fmt.Sprintf("ts.%d", ts.x) +} + +type testStructP struct { + x int +} + +func (ts *testStructP) String() string { + return fmt.Sprintf("ts.%d", ts.x) +} + +func TestPrintSortedKeys(t *testing.T) { + cfg := spew.ConfigState{SortKeys: true} + s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) + expected := "map[1:1 2:2 3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch 1:\n %v %v", s, expected) + } + + s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) + expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch 2:\n %v %v", s, expected) + } + + s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) + expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" + if spew.UnsafeDisabled { + expected = "map[1:1 2:2 3:3]" + } + if s != expected { + t.Errorf("Sorted keys mismatch 3:\n %v %v", s, expected) + } + + s = cfg.Sprint(map[testStruct]int{testStruct{1}: 1, testStruct{3}: 3, testStruct{2}: 2}) + expected = "map[ts.1:1 ts.2:2 ts.3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch 4:\n %v %v", s, expected) + } + + if !spew.UnsafeDisabled { + s = cfg.Sprint(map[testStructP]int{testStructP{1}: 1, testStructP{3}: 3, testStructP{2}: 2}) + expected = "map[ts.1:1 ts.2:2 ts.3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch 5:\n %v %v", s, expected) + } + } + + s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) + expected = "map[error: 1:1 error: 2:2 error: 3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch 6:\n %v %v", s, expected) + } +} diff --git a/vendor/github.com/davecgh/go-spew/spew/internal_test.go b/vendor/github.com/davecgh/go-spew/spew/internal_test.go new file mode 100644 index 00000000..20a9cfef --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/internal_test.go @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* +This test file is part of the spew package rather than than the spew_test +package because it needs access to internals to properly test certain cases +which are not possible via the public interface since they should never happen. +*/ + +package spew + +import ( + "bytes" + "reflect" + "testing" +) + +// dummyFmtState implements a fake fmt.State to use for testing invalid +// reflect.Value handling. This is necessary because the fmt package catches +// invalid values before invoking the formatter on them. +type dummyFmtState struct { + bytes.Buffer +} + +func (dfs *dummyFmtState) Flag(f int) bool { + if f == int('+') { + return true + } + return false +} + +func (dfs *dummyFmtState) Precision() (int, bool) { + return 0, false +} + +func (dfs *dummyFmtState) Width() (int, bool) { + return 0, false +} + +// TestInvalidReflectValue ensures the dump and formatter code handles an +// invalid reflect value properly. This needs access to internal state since it +// should never happen in real code and therefore can't be tested via the public +// API. +func TestInvalidReflectValue(t *testing.T) { + i := 1 + + // Dump invalid reflect value. + v := new(reflect.Value) + buf := new(bytes.Buffer) + d := dumpState{w: buf, cs: &Config} + d.dump(*v) + s := buf.String() + want := "" + if s != want { + t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want) + } + i++ + + // Formatter invalid reflect value. + buf2 := new(dummyFmtState) + f := formatState{value: *v, cs: &Config, fs: buf2} + f.format(*v) + s = buf2.String() + want = "" + if s != want { + t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want) + } +} + +// SortValues makes the internal sortValues function available to the test +// package. +func SortValues(values []reflect.Value, cs *ConfigState) { + sortValues(values, cs) +} diff --git a/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go b/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go new file mode 100644 index 00000000..a0c612ec --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go @@ -0,0 +1,102 @@ +// Copyright (c) 2013-2016 Dave Collins + +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. + +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when the code is not running on Google App Engine, compiled by GopherJS, and +// "-tags safe" is not added to the go build command line. The "disableunsafe" +// tag is deprecated and thus should not be used. +// +build !js,!appengine,!safe,!disableunsafe + +/* +This test file is part of the spew package rather than than the spew_test +package because it needs access to internals to properly test certain cases +which are not possible via the public interface since they should never happen. +*/ + +package spew + +import ( + "bytes" + "reflect" + "testing" + "unsafe" +) + +// changeKind uses unsafe to intentionally change the kind of a reflect.Value to +// the maximum kind value which does not exist. This is needed to test the +// fallback code which punts to the standard fmt library for new types that +// might get added to the language. +func changeKind(v *reflect.Value, readOnly bool) { + rvf := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + offsetFlag)) + *rvf = *rvf | ((1< + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew + +import ( + "fmt" + "io" +) + +// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the formatted string as a value that satisfies error. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Errorf(format string, a ...interface{}) (err error) { + return fmt.Errorf(format, convertArgs(a)...) +} + +// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprint(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprint(w, convertArgs(a)...) +} + +// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { + return fmt.Fprintf(w, format, convertArgs(a)...) +} + +// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it +// passed with a default Formatter interface returned by NewFormatter. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) +func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { + return fmt.Fprintln(w, convertArgs(a)...) +} + +// Print is a wrapper for fmt.Print that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) +func Print(a ...interface{}) (n int, err error) { + return fmt.Print(convertArgs(a)...) +} + +// Printf is a wrapper for fmt.Printf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Printf(format string, a ...interface{}) (n int, err error) { + return fmt.Printf(format, convertArgs(a)...) +} + +// Println is a wrapper for fmt.Println that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the number of bytes written and any write error encountered. See +// NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) +func Println(a ...interface{}) (n int, err error) { + return fmt.Println(convertArgs(a)...) +} + +// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprint(a ...interface{}) string { + return fmt.Sprint(convertArgs(a)...) +} + +// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were +// passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprintf(format string, a ...interface{}) string { + return fmt.Sprintf(format, convertArgs(a)...) +} + +// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it +// were passed with a default Formatter interface returned by NewFormatter. It +// returns the resulting string. See NewFormatter for formatting details. +// +// This function is shorthand for the following syntax: +// +// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) +func Sprintln(a ...interface{}) string { + return fmt.Sprintln(convertArgs(a)...) +} + +// convertArgs accepts a slice of arguments and returns a slice of the same +// length with each argument converted to a default spew Formatter interface. +func convertArgs(args []interface{}) (formatters []interface{}) { + formatters = make([]interface{}, len(args)) + for index, arg := range args { + formatters[index] = NewFormatter(arg) + } + return formatters +} diff --git a/vendor/github.com/davecgh/go-spew/spew/spew_test.go b/vendor/github.com/davecgh/go-spew/spew/spew_test.go new file mode 100644 index 00000000..b70466c6 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/spew_test.go @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2013-2016 Dave Collins + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +package spew_test + +import ( + "bytes" + "fmt" + "io/ioutil" + "os" + "testing" + + "github.com/davecgh/go-spew/spew" +) + +// spewFunc is used to identify which public function of the spew package or +// ConfigState a test applies to. +type spewFunc int + +const ( + fCSFdump spewFunc = iota + fCSFprint + fCSFprintf + fCSFprintln + fCSPrint + fCSPrintln + fCSSdump + fCSSprint + fCSSprintf + fCSSprintln + fCSErrorf + fCSNewFormatter + fErrorf + fFprint + fFprintln + fPrint + fPrintln + fSdump + fSprint + fSprintf + fSprintln +) + +// Map of spewFunc values to names for pretty printing. +var spewFuncStrings = map[spewFunc]string{ + fCSFdump: "ConfigState.Fdump", + fCSFprint: "ConfigState.Fprint", + fCSFprintf: "ConfigState.Fprintf", + fCSFprintln: "ConfigState.Fprintln", + fCSSdump: "ConfigState.Sdump", + fCSPrint: "ConfigState.Print", + fCSPrintln: "ConfigState.Println", + fCSSprint: "ConfigState.Sprint", + fCSSprintf: "ConfigState.Sprintf", + fCSSprintln: "ConfigState.Sprintln", + fCSErrorf: "ConfigState.Errorf", + fCSNewFormatter: "ConfigState.NewFormatter", + fErrorf: "spew.Errorf", + fFprint: "spew.Fprint", + fFprintln: "spew.Fprintln", + fPrint: "spew.Print", + fPrintln: "spew.Println", + fSdump: "spew.Sdump", + fSprint: "spew.Sprint", + fSprintf: "spew.Sprintf", + fSprintln: "spew.Sprintln", +} + +func (f spewFunc) String() string { + if s, ok := spewFuncStrings[f]; ok { + return s + } + return fmt.Sprintf("Unknown spewFunc (%d)", int(f)) +} + +// spewTest is used to describe a test to be performed against the public +// functions of the spew package or ConfigState. +type spewTest struct { + cs *spew.ConfigState + f spewFunc + format string + in interface{} + want string +} + +// spewTests houses the tests to be performed against the public functions of +// the spew package and ConfigState. +// +// These tests are only intended to ensure the public functions are exercised +// and are intentionally not exhaustive of types. The exhaustive type +// tests are handled in the dump and format tests. +var spewTests []spewTest + +// redirStdout is a helper function to return the standard output from f as a +// byte slice. +func redirStdout(f func()) ([]byte, error) { + tempFile, err := ioutil.TempFile("", "ss-test") + if err != nil { + return nil, err + } + fileName := tempFile.Name() + defer os.Remove(fileName) // Ignore error + + origStdout := os.Stdout + os.Stdout = tempFile + f() + os.Stdout = origStdout + tempFile.Close() + + return ioutil.ReadFile(fileName) +} + +func initSpewTests() { + // Config states with various settings. + scsDefault := spew.NewDefaultConfig() + scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true} + scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true} + scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1} + scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true} + scsNoPtrAddr := &spew.ConfigState{DisablePointerAddresses: true} + scsNoCap := &spew.ConfigState{DisableCapacities: true} + + // Variables for tests on types which implement Stringer interface with and + // without a pointer receiver. + ts := stringer("test") + tps := pstringer("test") + + type ptrTester struct { + s *struct{} + } + tptr := &ptrTester{s: &struct{}{}} + + // depthTester is used to test max depth handling for structs, array, slices + // and maps. + type depthTester struct { + ic indirCir1 + arr [1]string + slice []string + m map[string]int + } + dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"}, + map[string]int{"one": 1}} + + // Variable for tests on types which implement error interface. + te := customError(10) + + spewTests = []spewTest{ + {scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"}, + {scsDefault, fCSFprint, "", int16(32767), "32767"}, + {scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"}, + {scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"}, + {scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"}, + {scsDefault, fCSPrintln, "", uint8(255), "255\n"}, + {scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"}, + {scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"}, + {scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"}, + {scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"}, + {scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"}, + {scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"}, + {scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"}, + {scsDefault, fFprint, "", float32(3.14), "3.14"}, + {scsDefault, fFprintln, "", float64(6.28), "6.28\n"}, + {scsDefault, fPrint, "", true, "true"}, + {scsDefault, fPrintln, "", false, "false\n"}, + {scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"}, + {scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"}, + {scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"}, + {scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"}, + {scsNoMethods, fCSFprint, "", ts, "test"}, + {scsNoMethods, fCSFprint, "", &ts, "<*>test"}, + {scsNoMethods, fCSFprint, "", tps, "test"}, + {scsNoMethods, fCSFprint, "", &tps, "<*>test"}, + {scsNoPmethods, fCSFprint, "", ts, "stringer test"}, + {scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"}, + {scsNoPmethods, fCSFprint, "", tps, "test"}, + {scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"}, + {scsMaxDepth, fCSFprint, "", dt, "{{} [] [] map[]}"}, + {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" + + " ic: (spew_test.indirCir1) {\n \n },\n" + + " arr: ([1]string) (len=1 cap=1) {\n \n },\n" + + " slice: ([]string) (len=1 cap=1) {\n \n },\n" + + " m: (map[string]int) (len=1) {\n \n }\n}\n"}, + {scsContinue, fCSFprint, "", ts, "(stringer test) test"}, + {scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " + + "(len=4) (stringer test) \"test\"\n"}, + {scsContinue, fCSFprint, "", te, "(error: 10) 10"}, + {scsContinue, fCSFdump, "", te, "(spew_test.customError) " + + "(error: 10) 10\n"}, + {scsNoPtrAddr, fCSFprint, "", tptr, "<*>{<*>{}}"}, + {scsNoPtrAddr, fCSSdump, "", tptr, "(*spew_test.ptrTester)({\ns: (*struct {})({\n})\n})\n"}, + {scsNoCap, fCSSdump, "", make([]string, 0, 10), "([]string) {\n}\n"}, + {scsNoCap, fCSSdump, "", make([]string, 1, 10), "([]string) (len=1) {\n(string) \"\"\n}\n"}, + } +} + +// TestSpew executes all of the tests described by spewTests. +func TestSpew(t *testing.T) { + initSpewTests() + + t.Logf("Running %d tests", len(spewTests)) + for i, test := range spewTests { + buf := new(bytes.Buffer) + switch test.f { + case fCSFdump: + test.cs.Fdump(buf, test.in) + + case fCSFprint: + test.cs.Fprint(buf, test.in) + + case fCSFprintf: + test.cs.Fprintf(buf, test.format, test.in) + + case fCSFprintln: + test.cs.Fprintln(buf, test.in) + + case fCSPrint: + b, err := redirStdout(func() { test.cs.Print(test.in) }) + if err != nil { + t.Errorf("%v #%d %v", test.f, i, err) + continue + } + buf.Write(b) + + case fCSPrintln: + b, err := redirStdout(func() { test.cs.Println(test.in) }) + if err != nil { + t.Errorf("%v #%d %v", test.f, i, err) + continue + } + buf.Write(b) + + case fCSSdump: + str := test.cs.Sdump(test.in) + buf.WriteString(str) + + case fCSSprint: + str := test.cs.Sprint(test.in) + buf.WriteString(str) + + case fCSSprintf: + str := test.cs.Sprintf(test.format, test.in) + buf.WriteString(str) + + case fCSSprintln: + str := test.cs.Sprintln(test.in) + buf.WriteString(str) + + case fCSErrorf: + err := test.cs.Errorf(test.format, test.in) + buf.WriteString(err.Error()) + + case fCSNewFormatter: + fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in)) + + case fErrorf: + err := spew.Errorf(test.format, test.in) + buf.WriteString(err.Error()) + + case fFprint: + spew.Fprint(buf, test.in) + + case fFprintln: + spew.Fprintln(buf, test.in) + + case fPrint: + b, err := redirStdout(func() { spew.Print(test.in) }) + if err != nil { + t.Errorf("%v #%d %v", test.f, i, err) + continue + } + buf.Write(b) + + case fPrintln: + b, err := redirStdout(func() { spew.Println(test.in) }) + if err != nil { + t.Errorf("%v #%d %v", test.f, i, err) + continue + } + buf.Write(b) + + case fSdump: + str := spew.Sdump(test.in) + buf.WriteString(str) + + case fSprint: + str := spew.Sprint(test.in) + buf.WriteString(str) + + case fSprintf: + str := spew.Sprintf(test.format, test.in) + buf.WriteString(str) + + case fSprintln: + str := spew.Sprintln(test.in) + buf.WriteString(str) + + default: + t.Errorf("%v #%d unrecognized function", test.f, i) + continue + } + s := buf.String() + if test.want != s { + t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want) + continue + } + } +} diff --git a/vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go b/vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go new file mode 100644 index 00000000..5c87dd45 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go @@ -0,0 +1,82 @@ +// Copyright (c) 2013 Dave Collins +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// NOTE: Due to the following build constraints, this file will only be compiled +// when both cgo is supported and "-tags testcgo" is added to the go test +// command line. This code should really only be in the dumpcgo_test.go file, +// but unfortunately Go will not allow cgo in test files, so this is a +// workaround to allow cgo types to be tested. This configuration is used +// because spew itself does not require cgo to run even though it does handle +// certain cgo types specially. Rather than forcing all clients to require cgo +// and an external C compiler just to run the tests, this scheme makes them +// optional. +// +build cgo,testcgo + +package testdata + +/* +#include +typedef unsigned char custom_uchar_t; + +char *ncp = 0; +char *cp = "test"; +char ca[6] = {'t', 'e', 's', 't', '2', '\0'}; +unsigned char uca[6] = {'t', 'e', 's', 't', '3', '\0'}; +signed char sca[6] = {'t', 'e', 's', 't', '4', '\0'}; +uint8_t ui8ta[6] = {'t', 'e', 's', 't', '5', '\0'}; +custom_uchar_t tuca[6] = {'t', 'e', 's', 't', '6', '\0'}; +*/ +import "C" + +// GetCgoNullCharPointer returns a null char pointer via cgo. This is only +// used for tests. +func GetCgoNullCharPointer() interface{} { + return C.ncp +} + +// GetCgoCharPointer returns a char pointer via cgo. This is only used for +// tests. +func GetCgoCharPointer() interface{} { + return C.cp +} + +// GetCgoCharArray returns a char array via cgo and the array's len and cap. +// This is only used for tests. +func GetCgoCharArray() (interface{}, int, int) { + return C.ca, len(C.ca), cap(C.ca) +} + +// GetCgoUnsignedCharArray returns an unsigned char array via cgo and the +// array's len and cap. This is only used for tests. +func GetCgoUnsignedCharArray() (interface{}, int, int) { + return C.uca, len(C.uca), cap(C.uca) +} + +// GetCgoSignedCharArray returns a signed char array via cgo and the array's len +// and cap. This is only used for tests. +func GetCgoSignedCharArray() (interface{}, int, int) { + return C.sca, len(C.sca), cap(C.sca) +} + +// GetCgoUint8tArray returns a uint8_t array via cgo and the array's len and +// cap. This is only used for tests. +func GetCgoUint8tArray() (interface{}, int, int) { + return C.ui8ta, len(C.ui8ta), cap(C.ui8ta) +} + +// GetCgoTypdefedUnsignedCharArray returns a typedefed unsigned char array via +// cgo and the array's len and cap. This is only used for tests. +func GetCgoTypdefedUnsignedCharArray() (interface{}, int, int) { + return C.tuca, len(C.tuca), cap(C.tuca) +} diff --git a/vendor/github.com/davecgh/go-spew/test_coverage.txt b/vendor/github.com/davecgh/go-spew/test_coverage.txt new file mode 100644 index 00000000..2cd087a2 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/test_coverage.txt @@ -0,0 +1,61 @@ + +github.com/davecgh/go-spew/spew/dump.go dumpState.dump 100.00% (88/88) +github.com/davecgh/go-spew/spew/format.go formatState.format 100.00% (82/82) +github.com/davecgh/go-spew/spew/format.go formatState.formatPtr 100.00% (52/52) +github.com/davecgh/go-spew/spew/dump.go dumpState.dumpPtr 100.00% (44/44) +github.com/davecgh/go-spew/spew/dump.go dumpState.dumpSlice 100.00% (39/39) +github.com/davecgh/go-spew/spew/common.go handleMethods 100.00% (30/30) +github.com/davecgh/go-spew/spew/common.go printHexPtr 100.00% (18/18) +github.com/davecgh/go-spew/spew/common.go unsafeReflectValue 100.00% (13/13) +github.com/davecgh/go-spew/spew/format.go formatState.constructOrigFormat 100.00% (12/12) +github.com/davecgh/go-spew/spew/dump.go fdump 100.00% (11/11) +github.com/davecgh/go-spew/spew/format.go formatState.Format 100.00% (11/11) +github.com/davecgh/go-spew/spew/common.go init 100.00% (10/10) +github.com/davecgh/go-spew/spew/common.go printComplex 100.00% (9/9) +github.com/davecgh/go-spew/spew/common.go valuesSorter.Less 100.00% (8/8) +github.com/davecgh/go-spew/spew/format.go formatState.buildDefaultFormat 100.00% (7/7) +github.com/davecgh/go-spew/spew/format.go formatState.unpackValue 100.00% (5/5) +github.com/davecgh/go-spew/spew/dump.go dumpState.indent 100.00% (4/4) +github.com/davecgh/go-spew/spew/common.go catchPanic 100.00% (4/4) +github.com/davecgh/go-spew/spew/config.go ConfigState.convertArgs 100.00% (4/4) +github.com/davecgh/go-spew/spew/spew.go convertArgs 100.00% (4/4) +github.com/davecgh/go-spew/spew/format.go newFormatter 100.00% (3/3) +github.com/davecgh/go-spew/spew/dump.go Sdump 100.00% (3/3) +github.com/davecgh/go-spew/spew/common.go printBool 100.00% (3/3) +github.com/davecgh/go-spew/spew/common.go sortValues 100.00% (3/3) +github.com/davecgh/go-spew/spew/config.go ConfigState.Sdump 100.00% (3/3) +github.com/davecgh/go-spew/spew/dump.go dumpState.unpackValue 100.00% (3/3) +github.com/davecgh/go-spew/spew/spew.go Printf 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Println 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Sprint 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Sprintf 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Sprintln 100.00% (1/1) +github.com/davecgh/go-spew/spew/common.go printFloat 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go NewDefaultConfig 100.00% (1/1) +github.com/davecgh/go-spew/spew/common.go printInt 100.00% (1/1) +github.com/davecgh/go-spew/spew/common.go printUint 100.00% (1/1) +github.com/davecgh/go-spew/spew/common.go valuesSorter.Len 100.00% (1/1) +github.com/davecgh/go-spew/spew/common.go valuesSorter.Swap 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Errorf 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Fprint 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintf 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintln 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Print 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Printf 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Println 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Sprint 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintf 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintln 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.NewFormatter 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Fdump 100.00% (1/1) +github.com/davecgh/go-spew/spew/config.go ConfigState.Dump 100.00% (1/1) +github.com/davecgh/go-spew/spew/dump.go Fdump 100.00% (1/1) +github.com/davecgh/go-spew/spew/dump.go Dump 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Fprintln 100.00% (1/1) +github.com/davecgh/go-spew/spew/format.go NewFormatter 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Errorf 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Fprint 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Fprintf 100.00% (1/1) +github.com/davecgh/go-spew/spew/spew.go Print 100.00% (1/1) +github.com/davecgh/go-spew/spew ------------------------------- 100.00% (505/505) + diff --git a/vendor/github.com/docker/spdystream/CONTRIBUTING.md b/vendor/github.com/docker/spdystream/CONTRIBUTING.md new file mode 100644 index 00000000..d4eddcc5 --- /dev/null +++ b/vendor/github.com/docker/spdystream/CONTRIBUTING.md @@ -0,0 +1,13 @@ +# Contributing to SpdyStream + +Want to hack on spdystream? Awesome! Here are instructions to get you +started. + +SpdyStream is a part of the [Docker](https://docker.io) project, and follows +the same rules and principles. If you're already familiar with the way +Docker does things, you'll feel right at home. + +Otherwise, go read +[Docker's contributions guidelines](https://github.com/dotcloud/docker/blob/master/CONTRIBUTING.md). + +Happy hacking! diff --git a/vendor/github.com/docker/spdystream/LICENSE b/vendor/github.com/docker/spdystream/LICENSE new file mode 100644 index 00000000..9e4bd4db --- /dev/null +++ b/vendor/github.com/docker/spdystream/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2014-2015 Docker, 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. diff --git a/vendor/github.com/docker/spdystream/LICENSE.docs b/vendor/github.com/docker/spdystream/LICENSE.docs new file mode 100644 index 00000000..e26cd4fc --- /dev/null +++ b/vendor/github.com/docker/spdystream/LICENSE.docs @@ -0,0 +1,425 @@ +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + + including for purposes of Section 3(b); and + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the "Licensor." Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/vendor/github.com/docker/spdystream/MAINTAINERS b/vendor/github.com/docker/spdystream/MAINTAINERS new file mode 100644 index 00000000..14e26332 --- /dev/null +++ b/vendor/github.com/docker/spdystream/MAINTAINERS @@ -0,0 +1,28 @@ +# Spdystream maintainers file +# +# This file describes who runs the docker/spdystream project and how. +# This is a living document - if you see something out of date or missing, speak up! +# +# It is structured to be consumable by both humans and programs. +# To extract its contents programmatically, use any TOML-compliant parser. +# +# This file is compiled into the MAINTAINERS file in docker/opensource. +# +[Org] + [Org."Core maintainers"] + people = [ + "dmcgowan", + ] + +[people] + +# A reference list of all people associated with the project. +# All other sections should refer to people by their canonical key +# in the people section. + + # ADD YOURSELF HERE IN ALPHABETICAL ORDER + + [people.dmcgowan] + Name = "Derek McGowan" + Email = "derek@docker.com" + GitHub = "dmcgowan" diff --git a/vendor/github.com/docker/spdystream/README.md b/vendor/github.com/docker/spdystream/README.md new file mode 100644 index 00000000..11cccd0a --- /dev/null +++ b/vendor/github.com/docker/spdystream/README.md @@ -0,0 +1,77 @@ +# SpdyStream + +A multiplexed stream library using spdy + +## Usage + +Client example (connecting to mirroring server without auth) + +```go +package main + +import ( + "fmt" + "github.com/docker/spdystream" + "net" + "net/http" +) + +func main() { + conn, err := net.Dial("tcp", "localhost:8080") + if err != nil { + panic(err) + } + spdyConn, err := spdystream.NewConnection(conn, false) + if err != nil { + panic(err) + } + go spdyConn.Serve(spdystream.NoOpStreamHandler) + stream, err := spdyConn.CreateStream(http.Header{}, nil, false) + if err != nil { + panic(err) + } + + stream.Wait() + + fmt.Fprint(stream, "Writing to stream") + + buf := make([]byte, 25) + stream.Read(buf) + fmt.Println(string(buf)) + + stream.Close() +} +``` + +Server example (mirroring server without auth) + +```go +package main + +import ( + "github.com/docker/spdystream" + "net" +) + +func main() { + listener, err := net.Listen("tcp", "localhost:8080") + if err != nil { + panic(err) + } + for { + conn, err := listener.Accept() + if err != nil { + panic(err) + } + spdyConn, err := spdystream.NewConnection(conn, true) + if err != nil { + panic(err) + } + go spdyConn.Serve(spdystream.MirrorStreamHandler) + } +} +``` + +## Copyright and license + +Copyright © 2014-2015 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. The README.md file, and files in the "docs" folder are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file "LICENSE.docs". You may obtain a duplicate copy of the same license, titled CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/. diff --git a/vendor/github.com/docker/spdystream/connection.go b/vendor/github.com/docker/spdystream/connection.go new file mode 100644 index 00000000..df27d1dd --- /dev/null +++ b/vendor/github.com/docker/spdystream/connection.go @@ -0,0 +1,959 @@ +package spdystream + +import ( + "errors" + "fmt" + "io" + "net" + "net/http" + "sync" + "time" + + "github.com/docker/spdystream/spdy" +) + +var ( + ErrInvalidStreamId = errors.New("Invalid stream id") + ErrTimeout = errors.New("Timeout occured") + ErrReset = errors.New("Stream reset") + ErrWriteClosedStream = errors.New("Write on closed stream") +) + +const ( + FRAME_WORKERS = 5 + QUEUE_SIZE = 50 +) + +type StreamHandler func(stream *Stream) + +type AuthHandler func(header http.Header, slot uint8, parent uint32) bool + +type idleAwareFramer struct { + f *spdy.Framer + conn *Connection + writeLock sync.Mutex + resetChan chan struct{} + setTimeoutLock sync.Mutex + setTimeoutChan chan time.Duration + timeout time.Duration +} + +func newIdleAwareFramer(framer *spdy.Framer) *idleAwareFramer { + iaf := &idleAwareFramer{ + f: framer, + resetChan: make(chan struct{}, 2), + // setTimeoutChan needs to be buffered to avoid deadlocks when calling setIdleTimeout at about + // the same time the connection is being closed + setTimeoutChan: make(chan time.Duration, 1), + } + return iaf +} + +func (i *idleAwareFramer) monitor() { + var ( + timer *time.Timer + expired <-chan time.Time + resetChan = i.resetChan + setTimeoutChan = i.setTimeoutChan + ) +Loop: + for { + select { + case timeout := <-i.setTimeoutChan: + i.timeout = timeout + if timeout == 0 { + if timer != nil { + timer.Stop() + } + } else { + if timer == nil { + timer = time.NewTimer(timeout) + expired = timer.C + } else { + timer.Reset(timeout) + } + } + case <-resetChan: + if timer != nil && i.timeout > 0 { + timer.Reset(i.timeout) + } + case <-expired: + i.conn.streamCond.L.Lock() + streams := i.conn.streams + i.conn.streams = make(map[spdy.StreamId]*Stream) + i.conn.streamCond.Broadcast() + i.conn.streamCond.L.Unlock() + go func() { + for _, stream := range streams { + stream.resetStream() + } + i.conn.Close() + }() + case <-i.conn.closeChan: + if timer != nil { + timer.Stop() + } + + // Start a goroutine to drain resetChan. This is needed because we've seen + // some unit tests with large numbers of goroutines get into a situation + // where resetChan fills up, at least 1 call to Write() is still trying to + // send to resetChan, the connection gets closed, and this case statement + // attempts to grab the write lock that Write() already has, causing a + // deadlock. + // + // See https://github.com/docker/spdystream/issues/49 for more details. + go func() { + for _ = range resetChan { + } + }() + + go func() { + for _ = range setTimeoutChan { + } + }() + + i.writeLock.Lock() + close(resetChan) + i.resetChan = nil + i.writeLock.Unlock() + + i.setTimeoutLock.Lock() + close(i.setTimeoutChan) + i.setTimeoutChan = nil + i.setTimeoutLock.Unlock() + + break Loop + } + } + + // Drain resetChan + for _ = range resetChan { + } +} + +func (i *idleAwareFramer) WriteFrame(frame spdy.Frame) error { + i.writeLock.Lock() + defer i.writeLock.Unlock() + if i.resetChan == nil { + return io.EOF + } + err := i.f.WriteFrame(frame) + if err != nil { + return err + } + + i.resetChan <- struct{}{} + + return nil +} + +func (i *idleAwareFramer) ReadFrame() (spdy.Frame, error) { + frame, err := i.f.ReadFrame() + if err != nil { + return nil, err + } + + // resetChan should never be closed since it is only closed + // when the connection has closed its closeChan. This closure + // only occurs after all Reads have finished + // TODO (dmcgowan): refactor relationship into connection + i.resetChan <- struct{}{} + + return frame, nil +} + +func (i *idleAwareFramer) setIdleTimeout(timeout time.Duration) { + i.setTimeoutLock.Lock() + defer i.setTimeoutLock.Unlock() + + if i.setTimeoutChan == nil { + return + } + + i.setTimeoutChan <- timeout +} + +type Connection struct { + conn net.Conn + framer *idleAwareFramer + + closeChan chan bool + goneAway bool + lastStreamChan chan<- *Stream + goAwayTimeout time.Duration + closeTimeout time.Duration + + streamLock *sync.RWMutex + streamCond *sync.Cond + streams map[spdy.StreamId]*Stream + + nextIdLock sync.Mutex + receiveIdLock sync.Mutex + nextStreamId spdy.StreamId + receivedStreamId spdy.StreamId + + pingIdLock sync.Mutex + pingId uint32 + pingChans map[uint32]chan error + + shutdownLock sync.Mutex + shutdownChan chan error + hasShutdown bool + + // for testing https://github.com/docker/spdystream/pull/56 + dataFrameHandler func(*spdy.DataFrame) error +} + +// NewConnection creates a new spdy connection from an existing +// network connection. +func NewConnection(conn net.Conn, server bool) (*Connection, error) { + framer, framerErr := spdy.NewFramer(conn, conn) + if framerErr != nil { + return nil, framerErr + } + idleAwareFramer := newIdleAwareFramer(framer) + var sid spdy.StreamId + var rid spdy.StreamId + var pid uint32 + if server { + sid = 2 + rid = 1 + pid = 2 + } else { + sid = 1 + rid = 2 + pid = 1 + } + + streamLock := new(sync.RWMutex) + streamCond := sync.NewCond(streamLock) + + session := &Connection{ + conn: conn, + framer: idleAwareFramer, + + closeChan: make(chan bool), + goAwayTimeout: time.Duration(0), + closeTimeout: time.Duration(0), + + streamLock: streamLock, + streamCond: streamCond, + streams: make(map[spdy.StreamId]*Stream), + nextStreamId: sid, + receivedStreamId: rid, + + pingId: pid, + pingChans: make(map[uint32]chan error), + + shutdownChan: make(chan error), + } + session.dataFrameHandler = session.handleDataFrame + idleAwareFramer.conn = session + go idleAwareFramer.monitor() + + return session, nil +} + +// Ping sends a ping frame across the connection and +// returns the response time +func (s *Connection) Ping() (time.Duration, error) { + pid := s.pingId + s.pingIdLock.Lock() + if s.pingId > 0x7ffffffe { + s.pingId = s.pingId - 0x7ffffffe + } else { + s.pingId = s.pingId + 2 + } + s.pingIdLock.Unlock() + pingChan := make(chan error) + s.pingChans[pid] = pingChan + defer delete(s.pingChans, pid) + + frame := &spdy.PingFrame{Id: pid} + startTime := time.Now() + writeErr := s.framer.WriteFrame(frame) + if writeErr != nil { + return time.Duration(0), writeErr + } + select { + case <-s.closeChan: + return time.Duration(0), errors.New("connection closed") + case err, ok := <-pingChan: + if ok && err != nil { + return time.Duration(0), err + } + break + } + return time.Now().Sub(startTime), nil +} + +// Serve handles frames sent from the server, including reply frames +// which are needed to fully initiate connections. Both clients and servers +// should call Serve in a separate goroutine before creating streams. +func (s *Connection) Serve(newHandler StreamHandler) { + // use a WaitGroup to wait for all frames to be drained after receiving + // go-away. + var wg sync.WaitGroup + + // Parition queues to ensure stream frames are handled + // by the same worker, ensuring order is maintained + frameQueues := make([]*PriorityFrameQueue, FRAME_WORKERS) + for i := 0; i < FRAME_WORKERS; i++ { + frameQueues[i] = NewPriorityFrameQueue(QUEUE_SIZE) + + // Ensure frame queue is drained when connection is closed + go func(frameQueue *PriorityFrameQueue) { + <-s.closeChan + frameQueue.Drain() + }(frameQueues[i]) + + wg.Add(1) + go func(frameQueue *PriorityFrameQueue) { + // let the WaitGroup know this worker is done + defer wg.Done() + + s.frameHandler(frameQueue, newHandler) + }(frameQueues[i]) + } + + var ( + partitionRoundRobin int + goAwayFrame *spdy.GoAwayFrame + ) +Loop: + for { + readFrame, err := s.framer.ReadFrame() + if err != nil { + if err != io.EOF { + debugMessage("frame read error: %s", err) + } else { + debugMessage("(%p) EOF received", s) + } + break + } + var priority uint8 + var partition int + switch frame := readFrame.(type) { + case *spdy.SynStreamFrame: + if s.checkStreamFrame(frame) { + priority = frame.Priority + partition = int(frame.StreamId % FRAME_WORKERS) + debugMessage("(%p) Add stream frame: %d ", s, frame.StreamId) + s.addStreamFrame(frame) + } else { + debugMessage("(%p) Rejected stream frame: %d ", s, frame.StreamId) + continue + } + case *spdy.SynReplyFrame: + priority = s.getStreamPriority(frame.StreamId) + partition = int(frame.StreamId % FRAME_WORKERS) + case *spdy.DataFrame: + priority = s.getStreamPriority(frame.StreamId) + partition = int(frame.StreamId % FRAME_WORKERS) + case *spdy.RstStreamFrame: + priority = s.getStreamPriority(frame.StreamId) + partition = int(frame.StreamId % FRAME_WORKERS) + case *spdy.HeadersFrame: + priority = s.getStreamPriority(frame.StreamId) + partition = int(frame.StreamId % FRAME_WORKERS) + case *spdy.PingFrame: + priority = 0 + partition = partitionRoundRobin + partitionRoundRobin = (partitionRoundRobin + 1) % FRAME_WORKERS + case *spdy.GoAwayFrame: + // hold on to the go away frame and exit the loop + goAwayFrame = frame + break Loop + default: + priority = 7 + partition = partitionRoundRobin + partitionRoundRobin = (partitionRoundRobin + 1) % FRAME_WORKERS + } + frameQueues[partition].Push(readFrame, priority) + } + close(s.closeChan) + + // wait for all frame handler workers to indicate they've drained their queues + // before handling the go away frame + wg.Wait() + + if goAwayFrame != nil { + s.handleGoAwayFrame(goAwayFrame) + } + + // now it's safe to close remote channels and empty s.streams + s.streamCond.L.Lock() + // notify streams that they're now closed, which will + // unblock any stream Read() calls + for _, stream := range s.streams { + stream.closeRemoteChannels() + } + s.streams = make(map[spdy.StreamId]*Stream) + s.streamCond.Broadcast() + s.streamCond.L.Unlock() +} + +func (s *Connection) frameHandler(frameQueue *PriorityFrameQueue, newHandler StreamHandler) { + for { + popFrame := frameQueue.Pop() + if popFrame == nil { + return + } + + var frameErr error + switch frame := popFrame.(type) { + case *spdy.SynStreamFrame: + frameErr = s.handleStreamFrame(frame, newHandler) + case *spdy.SynReplyFrame: + frameErr = s.handleReplyFrame(frame) + case *spdy.DataFrame: + frameErr = s.dataFrameHandler(frame) + case *spdy.RstStreamFrame: + frameErr = s.handleResetFrame(frame) + case *spdy.HeadersFrame: + frameErr = s.handleHeaderFrame(frame) + case *spdy.PingFrame: + frameErr = s.handlePingFrame(frame) + case *spdy.GoAwayFrame: + frameErr = s.handleGoAwayFrame(frame) + default: + frameErr = fmt.Errorf("unhandled frame type: %T", frame) + } + + if frameErr != nil { + debugMessage("frame handling error: %s", frameErr) + } + } +} + +func (s *Connection) getStreamPriority(streamId spdy.StreamId) uint8 { + stream, streamOk := s.getStream(streamId) + if !streamOk { + return 7 + } + return stream.priority +} + +func (s *Connection) addStreamFrame(frame *spdy.SynStreamFrame) { + var parent *Stream + if frame.AssociatedToStreamId != spdy.StreamId(0) { + parent, _ = s.getStream(frame.AssociatedToStreamId) + } + + stream := &Stream{ + streamId: frame.StreamId, + parent: parent, + conn: s, + startChan: make(chan error), + headers: frame.Headers, + finished: (frame.CFHeader.Flags & spdy.ControlFlagUnidirectional) != 0x00, + replyCond: sync.NewCond(new(sync.Mutex)), + dataChan: make(chan []byte), + headerChan: make(chan http.Header), + closeChan: make(chan bool), + priority: frame.Priority, + } + if frame.CFHeader.Flags&spdy.ControlFlagFin != 0x00 { + stream.closeRemoteChannels() + } + + s.addStream(stream) +} + +// checkStreamFrame checks to see if a stream frame is allowed. +// If the stream is invalid, then a reset frame with protocol error +// will be returned. +func (s *Connection) checkStreamFrame(frame *spdy.SynStreamFrame) bool { + s.receiveIdLock.Lock() + defer s.receiveIdLock.Unlock() + if s.goneAway { + return false + } + validationErr := s.validateStreamId(frame.StreamId) + if validationErr != nil { + go func() { + resetErr := s.sendResetFrame(spdy.ProtocolError, frame.StreamId) + if resetErr != nil { + debugMessage("reset error: %s", resetErr) + } + }() + return false + } + return true +} + +func (s *Connection) handleStreamFrame(frame *spdy.SynStreamFrame, newHandler StreamHandler) error { + stream, ok := s.getStream(frame.StreamId) + if !ok { + return fmt.Errorf("Missing stream: %d", frame.StreamId) + } + + newHandler(stream) + + return nil +} + +func (s *Connection) handleReplyFrame(frame *spdy.SynReplyFrame) error { + debugMessage("(%p) Reply frame received for %d", s, frame.StreamId) + stream, streamOk := s.getStream(frame.StreamId) + if !streamOk { + debugMessage("Reply frame gone away for %d", frame.StreamId) + // Stream has already gone away + return nil + } + if stream.replied { + // Stream has already received reply + return nil + } + stream.replied = true + + // TODO Check for error + if (frame.CFHeader.Flags & spdy.ControlFlagFin) != 0x00 { + s.remoteStreamFinish(stream) + } + + close(stream.startChan) + + return nil +} + +func (s *Connection) handleResetFrame(frame *spdy.RstStreamFrame) error { + stream, streamOk := s.getStream(frame.StreamId) + if !streamOk { + // Stream has already been removed + return nil + } + s.removeStream(stream) + stream.closeRemoteChannels() + + if !stream.replied { + stream.replied = true + stream.startChan <- ErrReset + close(stream.startChan) + } + + stream.finishLock.Lock() + stream.finished = true + stream.finishLock.Unlock() + + return nil +} + +func (s *Connection) handleHeaderFrame(frame *spdy.HeadersFrame) error { + stream, streamOk := s.getStream(frame.StreamId) + if !streamOk { + // Stream has already gone away + return nil + } + if !stream.replied { + // No reply received...Protocol error? + return nil + } + + // TODO limit headers while not blocking (use buffered chan or goroutine?) + select { + case <-stream.closeChan: + return nil + case stream.headerChan <- frame.Headers: + } + + if (frame.CFHeader.Flags & spdy.ControlFlagFin) != 0x00 { + s.remoteStreamFinish(stream) + } + + return nil +} + +func (s *Connection) handleDataFrame(frame *spdy.DataFrame) error { + debugMessage("(%p) Data frame received for %d", s, frame.StreamId) + stream, streamOk := s.getStream(frame.StreamId) + if !streamOk { + debugMessage("(%p) Data frame gone away for %d", s, frame.StreamId) + // Stream has already gone away + return nil + } + if !stream.replied { + debugMessage("(%p) Data frame not replied %d", s, frame.StreamId) + // No reply received...Protocol error? + return nil + } + + debugMessage("(%p) (%d) Data frame handling", stream, stream.streamId) + if len(frame.Data) > 0 { + stream.dataLock.RLock() + select { + case <-stream.closeChan: + debugMessage("(%p) (%d) Data frame not sent (stream shut down)", stream, stream.streamId) + case stream.dataChan <- frame.Data: + debugMessage("(%p) (%d) Data frame sent", stream, stream.streamId) + } + stream.dataLock.RUnlock() + } + if (frame.Flags & spdy.DataFlagFin) != 0x00 { + s.remoteStreamFinish(stream) + } + return nil +} + +func (s *Connection) handlePingFrame(frame *spdy.PingFrame) error { + if s.pingId&0x01 != frame.Id&0x01 { + return s.framer.WriteFrame(frame) + } + pingChan, pingOk := s.pingChans[frame.Id] + if pingOk { + close(pingChan) + } + return nil +} + +func (s *Connection) handleGoAwayFrame(frame *spdy.GoAwayFrame) error { + debugMessage("(%p) Go away received", s) + s.receiveIdLock.Lock() + if s.goneAway { + s.receiveIdLock.Unlock() + return nil + } + s.goneAway = true + s.receiveIdLock.Unlock() + + if s.lastStreamChan != nil { + stream, _ := s.getStream(frame.LastGoodStreamId) + go func() { + s.lastStreamChan <- stream + }() + } + + // Do not block frame handler waiting for closure + go s.shutdown(s.goAwayTimeout) + + return nil +} + +func (s *Connection) remoteStreamFinish(stream *Stream) { + stream.closeRemoteChannels() + + stream.finishLock.Lock() + if stream.finished { + // Stream is fully closed, cleanup + s.removeStream(stream) + } + stream.finishLock.Unlock() +} + +// CreateStream creates a new spdy stream using the parameters for +// creating the stream frame. The stream frame will be sent upon +// calling this function, however this function does not wait for +// the reply frame. If waiting for the reply is desired, use +// the stream Wait or WaitTimeout function on the stream returned +// by this function. +func (s *Connection) CreateStream(headers http.Header, parent *Stream, fin bool) (*Stream, error) { + // MUST synchronize stream creation (all the way to writing the frame) + // as stream IDs **MUST** increase monotonically. + s.nextIdLock.Lock() + defer s.nextIdLock.Unlock() + + streamId := s.getNextStreamId() + if streamId == 0 { + return nil, fmt.Errorf("Unable to get new stream id") + } + + stream := &Stream{ + streamId: streamId, + parent: parent, + conn: s, + startChan: make(chan error), + headers: headers, + dataChan: make(chan []byte), + headerChan: make(chan http.Header), + closeChan: make(chan bool), + } + + debugMessage("(%p) (%p) Create stream", s, stream) + + s.addStream(stream) + + return stream, s.sendStream(stream, fin) +} + +func (s *Connection) shutdown(closeTimeout time.Duration) { + // TODO Ensure this isn't called multiple times + s.shutdownLock.Lock() + if s.hasShutdown { + s.shutdownLock.Unlock() + return + } + s.hasShutdown = true + s.shutdownLock.Unlock() + + var timeout <-chan time.Time + if closeTimeout > time.Duration(0) { + timeout = time.After(closeTimeout) + } + streamsClosed := make(chan bool) + + go func() { + s.streamCond.L.Lock() + for len(s.streams) > 0 { + debugMessage("Streams opened: %d, %#v", len(s.streams), s.streams) + s.streamCond.Wait() + } + s.streamCond.L.Unlock() + close(streamsClosed) + }() + + var err error + select { + case <-streamsClosed: + // No active streams, close should be safe + err = s.conn.Close() + case <-timeout: + // Force ungraceful close + err = s.conn.Close() + // Wait for cleanup to clear active streams + <-streamsClosed + } + + if err != nil { + duration := 10 * time.Minute + time.AfterFunc(duration, func() { + select { + case err, ok := <-s.shutdownChan: + if ok { + debugMessage("Unhandled close error after %s: %s", duration, err) + } + default: + } + }) + s.shutdownChan <- err + } + close(s.shutdownChan) + + return +} + +// Closes spdy connection by sending GoAway frame and initiating shutdown +func (s *Connection) Close() error { + s.receiveIdLock.Lock() + if s.goneAway { + s.receiveIdLock.Unlock() + return nil + } + s.goneAway = true + s.receiveIdLock.Unlock() + + var lastStreamId spdy.StreamId + if s.receivedStreamId > 2 { + lastStreamId = s.receivedStreamId - 2 + } + + goAwayFrame := &spdy.GoAwayFrame{ + LastGoodStreamId: lastStreamId, + Status: spdy.GoAwayOK, + } + + err := s.framer.WriteFrame(goAwayFrame) + if err != nil { + return err + } + + go s.shutdown(s.closeTimeout) + + return nil +} + +// CloseWait closes the connection and waits for shutdown +// to finish. Note the underlying network Connection +// is not closed until the end of shutdown. +func (s *Connection) CloseWait() error { + closeErr := s.Close() + if closeErr != nil { + return closeErr + } + shutdownErr, ok := <-s.shutdownChan + if ok { + return shutdownErr + } + return nil +} + +// Wait waits for the connection to finish shutdown or for +// the wait timeout duration to expire. This needs to be +// called either after Close has been called or the GOAWAYFRAME +// has been received. If the wait timeout is 0, this function +// will block until shutdown finishes. If wait is never called +// and a shutdown error occurs, that error will be logged as an +// unhandled error. +func (s *Connection) Wait(waitTimeout time.Duration) error { + var timeout <-chan time.Time + if waitTimeout > time.Duration(0) { + timeout = time.After(waitTimeout) + } + + select { + case err, ok := <-s.shutdownChan: + if ok { + return err + } + case <-timeout: + return ErrTimeout + } + return nil +} + +// NotifyClose registers a channel to be called when the remote +// peer inidicates connection closure. The last stream to be +// received by the remote will be sent on the channel. The notify +// timeout will determine the duration between go away received +// and the connection being closed. +func (s *Connection) NotifyClose(c chan<- *Stream, timeout time.Duration) { + s.goAwayTimeout = timeout + s.lastStreamChan = c +} + +// SetCloseTimeout sets the amount of time close will wait for +// streams to finish before terminating the underlying network +// connection. Setting the timeout to 0 will cause close to +// wait forever, which is the default. +func (s *Connection) SetCloseTimeout(timeout time.Duration) { + s.closeTimeout = timeout +} + +// SetIdleTimeout sets the amount of time the connection may sit idle before +// it is forcefully terminated. +func (s *Connection) SetIdleTimeout(timeout time.Duration) { + s.framer.setIdleTimeout(timeout) +} + +func (s *Connection) sendHeaders(headers http.Header, stream *Stream, fin bool) error { + var flags spdy.ControlFlags + if fin { + flags = spdy.ControlFlagFin + } + + headerFrame := &spdy.HeadersFrame{ + StreamId: stream.streamId, + Headers: headers, + CFHeader: spdy.ControlFrameHeader{Flags: flags}, + } + + return s.framer.WriteFrame(headerFrame) +} + +func (s *Connection) sendReply(headers http.Header, stream *Stream, fin bool) error { + var flags spdy.ControlFlags + if fin { + flags = spdy.ControlFlagFin + } + + replyFrame := &spdy.SynReplyFrame{ + StreamId: stream.streamId, + Headers: headers, + CFHeader: spdy.ControlFrameHeader{Flags: flags}, + } + + return s.framer.WriteFrame(replyFrame) +} + +func (s *Connection) sendResetFrame(status spdy.RstStreamStatus, streamId spdy.StreamId) error { + resetFrame := &spdy.RstStreamFrame{ + StreamId: streamId, + Status: status, + } + + return s.framer.WriteFrame(resetFrame) +} + +func (s *Connection) sendReset(status spdy.RstStreamStatus, stream *Stream) error { + return s.sendResetFrame(status, stream.streamId) +} + +func (s *Connection) sendStream(stream *Stream, fin bool) error { + var flags spdy.ControlFlags + if fin { + flags = spdy.ControlFlagFin + stream.finished = true + } + + var parentId spdy.StreamId + if stream.parent != nil { + parentId = stream.parent.streamId + } + + streamFrame := &spdy.SynStreamFrame{ + StreamId: spdy.StreamId(stream.streamId), + AssociatedToStreamId: spdy.StreamId(parentId), + Headers: stream.headers, + CFHeader: spdy.ControlFrameHeader{Flags: flags}, + } + + return s.framer.WriteFrame(streamFrame) +} + +// getNextStreamId returns the next sequential id +// every call should produce a unique value or an error +func (s *Connection) getNextStreamId() spdy.StreamId { + sid := s.nextStreamId + if sid > 0x7fffffff { + return 0 + } + s.nextStreamId = s.nextStreamId + 2 + return sid +} + +// PeekNextStreamId returns the next sequential id and keeps the next id untouched +func (s *Connection) PeekNextStreamId() spdy.StreamId { + sid := s.nextStreamId + return sid +} + +func (s *Connection) validateStreamId(rid spdy.StreamId) error { + if rid > 0x7fffffff || rid < s.receivedStreamId { + return ErrInvalidStreamId + } + s.receivedStreamId = rid + 2 + return nil +} + +func (s *Connection) addStream(stream *Stream) { + s.streamCond.L.Lock() + s.streams[stream.streamId] = stream + debugMessage("(%p) (%p) Stream added, broadcasting: %d", s, stream, stream.streamId) + s.streamCond.Broadcast() + s.streamCond.L.Unlock() +} + +func (s *Connection) removeStream(stream *Stream) { + s.streamCond.L.Lock() + delete(s.streams, stream.streamId) + debugMessage("(%p) (%p) Stream removed, broadcasting: %d", s, stream, stream.streamId) + s.streamCond.Broadcast() + s.streamCond.L.Unlock() +} + +func (s *Connection) getStream(streamId spdy.StreamId) (stream *Stream, ok bool) { + s.streamLock.RLock() + stream, ok = s.streams[streamId] + s.streamLock.RUnlock() + return +} + +// FindStream looks up the given stream id and either waits for the +// stream to be found or returns nil if the stream id is no longer +// valid. +func (s *Connection) FindStream(streamId uint32) *Stream { + var stream *Stream + var ok bool + s.streamCond.L.Lock() + stream, ok = s.streams[spdy.StreamId(streamId)] + debugMessage("(%p) Found stream %d? %t", s, spdy.StreamId(streamId), ok) + for !ok && streamId >= uint32(s.receivedStreamId) { + s.streamCond.Wait() + stream, ok = s.streams[spdy.StreamId(streamId)] + } + s.streamCond.L.Unlock() + return stream +} + +func (s *Connection) CloseChan() <-chan bool { + return s.closeChan +} diff --git a/vendor/github.com/docker/spdystream/handlers.go b/vendor/github.com/docker/spdystream/handlers.go new file mode 100644 index 00000000..b59fa5fd --- /dev/null +++ b/vendor/github.com/docker/spdystream/handlers.go @@ -0,0 +1,38 @@ +package spdystream + +import ( + "io" + "net/http" +) + +// MirrorStreamHandler mirrors all streams. +func MirrorStreamHandler(stream *Stream) { + replyErr := stream.SendReply(http.Header{}, false) + if replyErr != nil { + return + } + + go func() { + io.Copy(stream, stream) + stream.Close() + }() + go func() { + for { + header, receiveErr := stream.ReceiveHeader() + if receiveErr != nil { + return + } + sendErr := stream.SendHeader(header, false) + if sendErr != nil { + return + } + } + }() +} + +// NoopStreamHandler does nothing when stream connects, most +// likely used with RejectAuthHandler which will not allow any +// streams to make it to the stream handler. +func NoOpStreamHandler(stream *Stream) { + stream.SendReply(http.Header{}, false) +} diff --git a/vendor/github.com/docker/spdystream/priority.go b/vendor/github.com/docker/spdystream/priority.go new file mode 100644 index 00000000..fc8582b5 --- /dev/null +++ b/vendor/github.com/docker/spdystream/priority.go @@ -0,0 +1,98 @@ +package spdystream + +import ( + "container/heap" + "sync" + + "github.com/docker/spdystream/spdy" +) + +type prioritizedFrame struct { + frame spdy.Frame + priority uint8 + insertId uint64 +} + +type frameQueue []*prioritizedFrame + +func (fq frameQueue) Len() int { + return len(fq) +} + +func (fq frameQueue) Less(i, j int) bool { + if fq[i].priority == fq[j].priority { + return fq[i].insertId < fq[j].insertId + } + return fq[i].priority < fq[j].priority +} + +func (fq frameQueue) Swap(i, j int) { + fq[i], fq[j] = fq[j], fq[i] +} + +func (fq *frameQueue) Push(x interface{}) { + *fq = append(*fq, x.(*prioritizedFrame)) +} + +func (fq *frameQueue) Pop() interface{} { + old := *fq + n := len(old) + *fq = old[0 : n-1] + return old[n-1] +} + +type PriorityFrameQueue struct { + queue *frameQueue + c *sync.Cond + size int + nextInsertId uint64 + drain bool +} + +func NewPriorityFrameQueue(size int) *PriorityFrameQueue { + queue := make(frameQueue, 0, size) + heap.Init(&queue) + + return &PriorityFrameQueue{ + queue: &queue, + size: size, + c: sync.NewCond(&sync.Mutex{}), + } +} + +func (q *PriorityFrameQueue) Push(frame spdy.Frame, priority uint8) { + q.c.L.Lock() + defer q.c.L.Unlock() + for q.queue.Len() >= q.size { + q.c.Wait() + } + pFrame := &prioritizedFrame{ + frame: frame, + priority: priority, + insertId: q.nextInsertId, + } + q.nextInsertId = q.nextInsertId + 1 + heap.Push(q.queue, pFrame) + q.c.Signal() +} + +func (q *PriorityFrameQueue) Pop() spdy.Frame { + q.c.L.Lock() + defer q.c.L.Unlock() + for q.queue.Len() == 0 { + if q.drain { + return nil + } + q.c.Wait() + } + frame := heap.Pop(q.queue).(*prioritizedFrame).frame + q.c.Signal() + return frame +} + +func (q *PriorityFrameQueue) Drain() { + q.c.L.Lock() + defer q.c.L.Unlock() + q.drain = true + q.c.Broadcast() +} diff --git a/vendor/github.com/docker/spdystream/priority_test.go b/vendor/github.com/docker/spdystream/priority_test.go new file mode 100644 index 00000000..0746be2a --- /dev/null +++ b/vendor/github.com/docker/spdystream/priority_test.go @@ -0,0 +1,108 @@ +package spdystream + +import ( + "sync" + "testing" + "time" + + "github.com/docker/spdystream/spdy" +) + +func TestPriorityQueueOrdering(t *testing.T) { + queue := NewPriorityFrameQueue(150) + data1 := &spdy.DataFrame{} + data2 := &spdy.DataFrame{} + data3 := &spdy.DataFrame{} + data4 := &spdy.DataFrame{} + queue.Push(data1, 2) + queue.Push(data2, 1) + queue.Push(data3, 1) + queue.Push(data4, 0) + + if queue.Pop() != data4 { + t.Fatalf("Wrong order, expected data4 first") + } + if queue.Pop() != data2 { + t.Fatalf("Wrong order, expected data2 second") + } + if queue.Pop() != data3 { + t.Fatalf("Wrong order, expected data3 third") + } + if queue.Pop() != data1 { + t.Fatalf("Wrong order, expected data1 fourth") + } + + // Insert 50 Medium priority frames + for i := spdy.StreamId(50); i < 100; i++ { + queue.Push(&spdy.DataFrame{StreamId: i}, 1) + } + // Insert 50 low priority frames + for i := spdy.StreamId(100); i < 150; i++ { + queue.Push(&spdy.DataFrame{StreamId: i}, 2) + } + // Insert 50 high priority frames + for i := spdy.StreamId(0); i < 50; i++ { + queue.Push(&spdy.DataFrame{StreamId: i}, 0) + } + + for i := spdy.StreamId(0); i < 150; i++ { + frame := queue.Pop() + if frame.(*spdy.DataFrame).StreamId != i { + t.Fatalf("Wrong frame\nActual: %d\nExpecting: %d", frame.(*spdy.DataFrame).StreamId, i) + } + } +} + +func TestPriorityQueueSync(t *testing.T) { + queue := NewPriorityFrameQueue(150) + var wg sync.WaitGroup + insertRange := func(start, stop spdy.StreamId, priority uint8) { + for i := start; i < stop; i++ { + queue.Push(&spdy.DataFrame{StreamId: i}, priority) + } + wg.Done() + } + wg.Add(3) + go insertRange(spdy.StreamId(100), spdy.StreamId(150), 2) + go insertRange(spdy.StreamId(0), spdy.StreamId(50), 0) + go insertRange(spdy.StreamId(50), spdy.StreamId(100), 1) + + wg.Wait() + for i := spdy.StreamId(0); i < 150; i++ { + frame := queue.Pop() + if frame.(*spdy.DataFrame).StreamId != i { + t.Fatalf("Wrong frame\nActual: %d\nExpecting: %d", frame.(*spdy.DataFrame).StreamId, i) + } + } +} + +func TestPriorityQueueBlocking(t *testing.T) { + queue := NewPriorityFrameQueue(15) + for i := 0; i < 15; i++ { + queue.Push(&spdy.DataFrame{}, 2) + } + doneChan := make(chan bool) + go func() { + queue.Push(&spdy.DataFrame{}, 2) + close(doneChan) + }() + select { + case <-doneChan: + t.Fatalf("Push succeeded, expected to block") + case <-time.After(time.Millisecond): + break + } + + queue.Pop() + + select { + case <-doneChan: + break + case <-time.After(time.Millisecond): + t.Fatalf("Push should have succeeded, but timeout reached") + } + + for i := 0; i < 15; i++ { + queue.Pop() + } +} diff --git a/vendor/github.com/docker/spdystream/spdy/dictionary.go b/vendor/github.com/docker/spdystream/spdy/dictionary.go new file mode 100644 index 00000000..5a5ff0e1 --- /dev/null +++ b/vendor/github.com/docker/spdystream/spdy/dictionary.go @@ -0,0 +1,187 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package spdy + +// headerDictionary is the dictionary sent to the zlib compressor/decompressor. +var headerDictionary = []byte{ + 0x00, 0x00, 0x00, 0x07, 0x6f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x00, 0x00, 0x00, 0x04, 0x68, + 0x65, 0x61, 0x64, 0x00, 0x00, 0x00, 0x04, 0x70, + 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x70, + 0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x64, 0x65, + 0x6c, 0x65, 0x74, 0x65, 0x00, 0x00, 0x00, 0x05, + 0x74, 0x72, 0x61, 0x63, 0x65, 0x00, 0x00, 0x00, + 0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00, + 0x00, 0x00, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70, + 0x74, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, + 0x74, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, + 0x65, 0x70, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, + 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x0f, + 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x6c, + 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, + 0x00, 0x00, 0x0d, 0x61, 0x63, 0x63, 0x65, 0x70, + 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73, + 0x00, 0x00, 0x00, 0x03, 0x61, 0x67, 0x65, 0x00, + 0x00, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x77, + 0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x68, + 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x61, 0x63, + 0x68, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, + 0x65, 0x6e, 0x74, 0x2d, 0x62, 0x61, 0x73, 0x65, + 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, + 0x65, 0x6e, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, + 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, + 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, + 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, + 0x00, 0x00, 0x00, 0x0e, 0x63, 0x6f, 0x6e, 0x74, + 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, + 0x74, 0x68, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, + 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x6f, + 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, + 0x00, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, + 0x74, 0x2d, 0x6d, 0x64, 0x35, 0x00, 0x00, 0x00, + 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, + 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, + 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, + 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x00, 0x00, + 0x00, 0x04, 0x64, 0x61, 0x74, 0x65, 0x00, 0x00, + 0x00, 0x04, 0x65, 0x74, 0x61, 0x67, 0x00, 0x00, + 0x00, 0x06, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, + 0x00, 0x00, 0x00, 0x07, 0x65, 0x78, 0x70, 0x69, + 0x72, 0x65, 0x73, 0x00, 0x00, 0x00, 0x04, 0x66, + 0x72, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x68, + 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x08, 0x69, + 0x66, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, + 0x00, 0x00, 0x11, 0x69, 0x66, 0x2d, 0x6d, 0x6f, + 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, + 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, + 0x69, 0x66, 0x2d, 0x6e, 0x6f, 0x6e, 0x65, 0x2d, + 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, + 0x08, 0x69, 0x66, 0x2d, 0x72, 0x61, 0x6e, 0x67, + 0x65, 0x00, 0x00, 0x00, 0x13, 0x69, 0x66, 0x2d, + 0x75, 0x6e, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, + 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, + 0x00, 0x00, 0x00, 0x0d, 0x6c, 0x61, 0x73, 0x74, + 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, + 0x64, 0x00, 0x00, 0x00, 0x08, 0x6c, 0x6f, 0x63, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, + 0x0c, 0x6d, 0x61, 0x78, 0x2d, 0x66, 0x6f, 0x72, + 0x77, 0x61, 0x72, 0x64, 0x73, 0x00, 0x00, 0x00, + 0x06, 0x70, 0x72, 0x61, 0x67, 0x6d, 0x61, 0x00, + 0x00, 0x00, 0x12, 0x70, 0x72, 0x6f, 0x78, 0x79, + 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, + 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, + 0x13, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, + 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05, + 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, + 0x07, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72, + 0x00, 0x00, 0x00, 0x0b, 0x72, 0x65, 0x74, 0x72, + 0x79, 0x2d, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, + 0x00, 0x00, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, + 0x72, 0x00, 0x00, 0x00, 0x02, 0x74, 0x65, 0x00, + 0x00, 0x00, 0x07, 0x74, 0x72, 0x61, 0x69, 0x6c, + 0x65, 0x72, 0x00, 0x00, 0x00, 0x11, 0x74, 0x72, + 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2d, 0x65, + 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, + 0x00, 0x00, 0x07, 0x75, 0x70, 0x67, 0x72, 0x61, + 0x64, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x75, 0x73, + 0x65, 0x72, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, + 0x00, 0x00, 0x00, 0x04, 0x76, 0x61, 0x72, 0x79, + 0x00, 0x00, 0x00, 0x03, 0x76, 0x69, 0x61, 0x00, + 0x00, 0x00, 0x07, 0x77, 0x61, 0x72, 0x6e, 0x69, + 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x77, 0x77, + 0x77, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, + 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, + 0x00, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, + 0x00, 0x00, 0x00, 0x03, 0x67, 0x65, 0x74, 0x00, + 0x00, 0x00, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, + 0x73, 0x00, 0x00, 0x00, 0x06, 0x32, 0x30, 0x30, + 0x20, 0x4f, 0x4b, 0x00, 0x00, 0x00, 0x07, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00, + 0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, + 0x2e, 0x31, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72, + 0x6c, 0x00, 0x00, 0x00, 0x06, 0x70, 0x75, 0x62, + 0x6c, 0x69, 0x63, 0x00, 0x00, 0x00, 0x0a, 0x73, + 0x65, 0x74, 0x2d, 0x63, 0x6f, 0x6f, 0x6b, 0x69, + 0x65, 0x00, 0x00, 0x00, 0x0a, 0x6b, 0x65, 0x65, + 0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x00, + 0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69, + 0x6e, 0x31, 0x30, 0x30, 0x31, 0x30, 0x31, 0x32, + 0x30, 0x31, 0x32, 0x30, 0x32, 0x32, 0x30, 0x35, + 0x32, 0x30, 0x36, 0x33, 0x30, 0x30, 0x33, 0x30, + 0x32, 0x33, 0x30, 0x33, 0x33, 0x30, 0x34, 0x33, + 0x30, 0x35, 0x33, 0x30, 0x36, 0x33, 0x30, 0x37, + 0x34, 0x30, 0x32, 0x34, 0x30, 0x35, 0x34, 0x30, + 0x36, 0x34, 0x30, 0x37, 0x34, 0x30, 0x38, 0x34, + 0x30, 0x39, 0x34, 0x31, 0x30, 0x34, 0x31, 0x31, + 0x34, 0x31, 0x32, 0x34, 0x31, 0x33, 0x34, 0x31, + 0x34, 0x34, 0x31, 0x35, 0x34, 0x31, 0x36, 0x34, + 0x31, 0x37, 0x35, 0x30, 0x32, 0x35, 0x30, 0x34, + 0x35, 0x30, 0x35, 0x32, 0x30, 0x33, 0x20, 0x4e, + 0x6f, 0x6e, 0x2d, 0x41, 0x75, 0x74, 0x68, 0x6f, + 0x72, 0x69, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65, + 0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x32, 0x30, 0x34, 0x20, + 0x4e, 0x6f, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65, + 0x6e, 0x74, 0x33, 0x30, 0x31, 0x20, 0x4d, 0x6f, + 0x76, 0x65, 0x64, 0x20, 0x50, 0x65, 0x72, 0x6d, + 0x61, 0x6e, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x34, + 0x30, 0x30, 0x20, 0x42, 0x61, 0x64, 0x20, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x34, 0x30, + 0x31, 0x20, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68, + 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x34, 0x30, + 0x33, 0x20, 0x46, 0x6f, 0x72, 0x62, 0x69, 0x64, + 0x64, 0x65, 0x6e, 0x34, 0x30, 0x34, 0x20, 0x4e, + 0x6f, 0x74, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64, + 0x35, 0x30, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65, + 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x53, 0x65, 0x72, + 0x76, 0x65, 0x72, 0x20, 0x45, 0x72, 0x72, 0x6f, + 0x72, 0x35, 0x30, 0x31, 0x20, 0x4e, 0x6f, 0x74, + 0x20, 0x49, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65, + 0x6e, 0x74, 0x65, 0x64, 0x35, 0x30, 0x33, 0x20, + 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, + 0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, + 0x62, 0x6c, 0x65, 0x4a, 0x61, 0x6e, 0x20, 0x46, + 0x65, 0x62, 0x20, 0x4d, 0x61, 0x72, 0x20, 0x41, + 0x70, 0x72, 0x20, 0x4d, 0x61, 0x79, 0x20, 0x4a, + 0x75, 0x6e, 0x20, 0x4a, 0x75, 0x6c, 0x20, 0x41, + 0x75, 0x67, 0x20, 0x53, 0x65, 0x70, 0x74, 0x20, + 0x4f, 0x63, 0x74, 0x20, 0x4e, 0x6f, 0x76, 0x20, + 0x44, 0x65, 0x63, 0x20, 0x30, 0x30, 0x3a, 0x30, + 0x30, 0x3a, 0x30, 0x30, 0x20, 0x4d, 0x6f, 0x6e, + 0x2c, 0x20, 0x54, 0x75, 0x65, 0x2c, 0x20, 0x57, + 0x65, 0x64, 0x2c, 0x20, 0x54, 0x68, 0x75, 0x2c, + 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x53, 0x61, + 0x74, 0x2c, 0x20, 0x53, 0x75, 0x6e, 0x2c, 0x20, + 0x47, 0x4d, 0x54, 0x63, 0x68, 0x75, 0x6e, 0x6b, + 0x65, 0x64, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, + 0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x69, 0x6d, 0x61, + 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x2c, 0x69, + 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x67, + 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67, + 0x69, 0x66, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, + 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, + 0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, + 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, + 0x68, 0x74, 0x6d, 0x6c, 0x2b, 0x78, 0x6d, 0x6c, + 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c, + 0x61, 0x69, 0x6e, 0x2c, 0x74, 0x65, 0x78, 0x74, + 0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x2c, 0x70, 0x75, 0x62, 0x6c, + 0x69, 0x63, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, + 0x65, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65, + 0x3d, 0x67, 0x7a, 0x69, 0x70, 0x2c, 0x64, 0x65, + 0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64, + 0x63, 0x68, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, + 0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x63, + 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x69, + 0x73, 0x6f, 0x2d, 0x38, 0x38, 0x35, 0x39, 0x2d, + 0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x2c, 0x2a, + 0x2c, 0x65, 0x6e, 0x71, 0x3d, 0x30, 0x2e, +} diff --git a/vendor/github.com/docker/spdystream/spdy/read.go b/vendor/github.com/docker/spdystream/spdy/read.go new file mode 100644 index 00000000..9359a950 --- /dev/null +++ b/vendor/github.com/docker/spdystream/spdy/read.go @@ -0,0 +1,348 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package spdy + +import ( + "compress/zlib" + "encoding/binary" + "io" + "net/http" + "strings" +) + +func (frame *SynStreamFrame) read(h ControlFrameHeader, f *Framer) error { + return f.readSynStreamFrame(h, frame) +} + +func (frame *SynReplyFrame) read(h ControlFrameHeader, f *Framer) error { + return f.readSynReplyFrame(h, frame) +} + +func (frame *RstStreamFrame) read(h ControlFrameHeader, f *Framer) error { + frame.CFHeader = h + if err := binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { + return err + } + if err := binary.Read(f.r, binary.BigEndian, &frame.Status); err != nil { + return err + } + if frame.Status == 0 { + return &Error{InvalidControlFrame, frame.StreamId} + } + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + return nil +} + +func (frame *SettingsFrame) read(h ControlFrameHeader, f *Framer) error { + frame.CFHeader = h + var numSettings uint32 + if err := binary.Read(f.r, binary.BigEndian, &numSettings); err != nil { + return err + } + frame.FlagIdValues = make([]SettingsFlagIdValue, numSettings) + for i := uint32(0); i < numSettings; i++ { + if err := binary.Read(f.r, binary.BigEndian, &frame.FlagIdValues[i].Id); err != nil { + return err + } + frame.FlagIdValues[i].Flag = SettingsFlag((frame.FlagIdValues[i].Id & 0xff000000) >> 24) + frame.FlagIdValues[i].Id &= 0xffffff + if err := binary.Read(f.r, binary.BigEndian, &frame.FlagIdValues[i].Value); err != nil { + return err + } + } + return nil +} + +func (frame *PingFrame) read(h ControlFrameHeader, f *Framer) error { + frame.CFHeader = h + if err := binary.Read(f.r, binary.BigEndian, &frame.Id); err != nil { + return err + } + if frame.Id == 0 { + return &Error{ZeroStreamId, 0} + } + if frame.CFHeader.Flags != 0 { + return &Error{InvalidControlFrame, StreamId(frame.Id)} + } + return nil +} + +func (frame *GoAwayFrame) read(h ControlFrameHeader, f *Framer) error { + frame.CFHeader = h + if err := binary.Read(f.r, binary.BigEndian, &frame.LastGoodStreamId); err != nil { + return err + } + if frame.CFHeader.Flags != 0 { + return &Error{InvalidControlFrame, frame.LastGoodStreamId} + } + if frame.CFHeader.length != 8 { + return &Error{InvalidControlFrame, frame.LastGoodStreamId} + } + if err := binary.Read(f.r, binary.BigEndian, &frame.Status); err != nil { + return err + } + return nil +} + +func (frame *HeadersFrame) read(h ControlFrameHeader, f *Framer) error { + return f.readHeadersFrame(h, frame) +} + +func (frame *WindowUpdateFrame) read(h ControlFrameHeader, f *Framer) error { + frame.CFHeader = h + if err := binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { + return err + } + if frame.CFHeader.Flags != 0 { + return &Error{InvalidControlFrame, frame.StreamId} + } + if frame.CFHeader.length != 8 { + return &Error{InvalidControlFrame, frame.StreamId} + } + if err := binary.Read(f.r, binary.BigEndian, &frame.DeltaWindowSize); err != nil { + return err + } + return nil +} + +func newControlFrame(frameType ControlFrameType) (controlFrame, error) { + ctor, ok := cframeCtor[frameType] + if !ok { + return nil, &Error{Err: InvalidControlFrame} + } + return ctor(), nil +} + +var cframeCtor = map[ControlFrameType]func() controlFrame{ + TypeSynStream: func() controlFrame { return new(SynStreamFrame) }, + TypeSynReply: func() controlFrame { return new(SynReplyFrame) }, + TypeRstStream: func() controlFrame { return new(RstStreamFrame) }, + TypeSettings: func() controlFrame { return new(SettingsFrame) }, + TypePing: func() controlFrame { return new(PingFrame) }, + TypeGoAway: func() controlFrame { return new(GoAwayFrame) }, + TypeHeaders: func() controlFrame { return new(HeadersFrame) }, + TypeWindowUpdate: func() controlFrame { return new(WindowUpdateFrame) }, +} + +func (f *Framer) uncorkHeaderDecompressor(payloadSize int64) error { + if f.headerDecompressor != nil { + f.headerReader.N = payloadSize + return nil + } + f.headerReader = io.LimitedReader{R: f.r, N: payloadSize} + decompressor, err := zlib.NewReaderDict(&f.headerReader, []byte(headerDictionary)) + if err != nil { + return err + } + f.headerDecompressor = decompressor + return nil +} + +// ReadFrame reads SPDY encoded data and returns a decompressed Frame. +func (f *Framer) ReadFrame() (Frame, error) { + var firstWord uint32 + if err := binary.Read(f.r, binary.BigEndian, &firstWord); err != nil { + return nil, err + } + if firstWord&0x80000000 != 0 { + frameType := ControlFrameType(firstWord & 0xffff) + version := uint16(firstWord >> 16 & 0x7fff) + return f.parseControlFrame(version, frameType) + } + return f.parseDataFrame(StreamId(firstWord & 0x7fffffff)) +} + +func (f *Framer) parseControlFrame(version uint16, frameType ControlFrameType) (Frame, error) { + var length uint32 + if err := binary.Read(f.r, binary.BigEndian, &length); err != nil { + return nil, err + } + flags := ControlFlags((length & 0xff000000) >> 24) + length &= 0xffffff + header := ControlFrameHeader{version, frameType, flags, length} + cframe, err := newControlFrame(frameType) + if err != nil { + return nil, err + } + if err = cframe.read(header, f); err != nil { + return nil, err + } + return cframe, nil +} + +func parseHeaderValueBlock(r io.Reader, streamId StreamId) (http.Header, error) { + var numHeaders uint32 + if err := binary.Read(r, binary.BigEndian, &numHeaders); err != nil { + return nil, err + } + var e error + h := make(http.Header, int(numHeaders)) + for i := 0; i < int(numHeaders); i++ { + var length uint32 + if err := binary.Read(r, binary.BigEndian, &length); err != nil { + return nil, err + } + nameBytes := make([]byte, length) + if _, err := io.ReadFull(r, nameBytes); err != nil { + return nil, err + } + name := string(nameBytes) + if name != strings.ToLower(name) { + e = &Error{UnlowercasedHeaderName, streamId} + name = strings.ToLower(name) + } + if h[name] != nil { + e = &Error{DuplicateHeaders, streamId} + } + if err := binary.Read(r, binary.BigEndian, &length); err != nil { + return nil, err + } + value := make([]byte, length) + if _, err := io.ReadFull(r, value); err != nil { + return nil, err + } + valueList := strings.Split(string(value), headerValueSeparator) + for _, v := range valueList { + h.Add(name, v) + } + } + if e != nil { + return h, e + } + return h, nil +} + +func (f *Framer) readSynStreamFrame(h ControlFrameHeader, frame *SynStreamFrame) error { + frame.CFHeader = h + var err error + if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { + return err + } + if err = binary.Read(f.r, binary.BigEndian, &frame.AssociatedToStreamId); err != nil { + return err + } + if err = binary.Read(f.r, binary.BigEndian, &frame.Priority); err != nil { + return err + } + frame.Priority >>= 5 + if err = binary.Read(f.r, binary.BigEndian, &frame.Slot); err != nil { + return err + } + reader := f.r + if !f.headerCompressionDisabled { + err := f.uncorkHeaderDecompressor(int64(h.length - 10)) + if err != nil { + return err + } + reader = f.headerDecompressor + } + frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) + if !f.headerCompressionDisabled && (err == io.EOF && f.headerReader.N == 0 || f.headerReader.N != 0) { + err = &Error{WrongCompressedPayloadSize, 0} + } + if err != nil { + return err + } + for h := range frame.Headers { + if invalidReqHeaders[h] { + return &Error{InvalidHeaderPresent, frame.StreamId} + } + } + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + return nil +} + +func (f *Framer) readSynReplyFrame(h ControlFrameHeader, frame *SynReplyFrame) error { + frame.CFHeader = h + var err error + if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { + return err + } + reader := f.r + if !f.headerCompressionDisabled { + err := f.uncorkHeaderDecompressor(int64(h.length - 4)) + if err != nil { + return err + } + reader = f.headerDecompressor + } + frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) + if !f.headerCompressionDisabled && (err == io.EOF && f.headerReader.N == 0 || f.headerReader.N != 0) { + err = &Error{WrongCompressedPayloadSize, 0} + } + if err != nil { + return err + } + for h := range frame.Headers { + if invalidRespHeaders[h] { + return &Error{InvalidHeaderPresent, frame.StreamId} + } + } + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + return nil +} + +func (f *Framer) readHeadersFrame(h ControlFrameHeader, frame *HeadersFrame) error { + frame.CFHeader = h + var err error + if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { + return err + } + reader := f.r + if !f.headerCompressionDisabled { + err := f.uncorkHeaderDecompressor(int64(h.length - 4)) + if err != nil { + return err + } + reader = f.headerDecompressor + } + frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) + if !f.headerCompressionDisabled && (err == io.EOF && f.headerReader.N == 0 || f.headerReader.N != 0) { + err = &Error{WrongCompressedPayloadSize, 0} + } + if err != nil { + return err + } + var invalidHeaders map[string]bool + if frame.StreamId%2 == 0 { + invalidHeaders = invalidReqHeaders + } else { + invalidHeaders = invalidRespHeaders + } + for h := range frame.Headers { + if invalidHeaders[h] { + return &Error{InvalidHeaderPresent, frame.StreamId} + } + } + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + return nil +} + +func (f *Framer) parseDataFrame(streamId StreamId) (*DataFrame, error) { + var length uint32 + if err := binary.Read(f.r, binary.BigEndian, &length); err != nil { + return nil, err + } + var frame DataFrame + frame.StreamId = streamId + frame.Flags = DataFlags(length >> 24) + length &= 0xffffff + frame.Data = make([]byte, length) + if _, err := io.ReadFull(f.r, frame.Data); err != nil { + return nil, err + } + if frame.StreamId == 0 { + return nil, &Error{ZeroStreamId, 0} + } + return &frame, nil +} diff --git a/vendor/github.com/docker/spdystream/spdy/spdy_test.go b/vendor/github.com/docker/spdystream/spdy/spdy_test.go new file mode 100644 index 00000000..ce581f1d --- /dev/null +++ b/vendor/github.com/docker/spdystream/spdy/spdy_test.go @@ -0,0 +1,644 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package spdy + +import ( + "bytes" + "compress/zlib" + "encoding/base64" + "io" + "io/ioutil" + "net/http" + "reflect" + "testing" +) + +var HeadersFixture = http.Header{ + "Url": []string{"http://www.google.com/"}, + "Method": []string{"get"}, + "Version": []string{"http/1.1"}, +} + +func TestHeaderParsing(t *testing.T) { + var headerValueBlockBuf bytes.Buffer + writeHeaderValueBlock(&headerValueBlockBuf, HeadersFixture) + const bogusStreamId = 1 + newHeaders, err := parseHeaderValueBlock(&headerValueBlockBuf, bogusStreamId) + if err != nil { + t.Fatal("parseHeaderValueBlock:", err) + } + if !reflect.DeepEqual(HeadersFixture, newHeaders) { + t.Fatal("got: ", newHeaders, "\nwant: ", HeadersFixture) + } +} + +func TestCreateParseSynStreamFrameCompressionDisable(t *testing.T) { + buffer := new(bytes.Buffer) + // Fixture framer for no compression test. + framer := &Framer{ + headerCompressionDisabled: true, + w: buffer, + headerBuf: new(bytes.Buffer), + r: buffer, + } + synStreamFrame := SynStreamFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeSynStream, + }, + StreamId: 2, + Headers: HeadersFixture, + } + if err := framer.WriteFrame(&synStreamFrame); err != nil { + t.Fatal("WriteFrame without compression:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame without compression:", err) + } + parsedSynStreamFrame, ok := frame.(*SynStreamFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { + t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) + } +} + +func TestCreateParseSynStreamFrameCompressionEnable(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + synStreamFrame := SynStreamFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeSynStream, + }, + StreamId: 2, + Headers: HeadersFixture, + } + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + if err := framer.WriteFrame(&synStreamFrame); err != nil { + t.Fatal("WriteFrame with compression:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame with compression:", err) + } + parsedSynStreamFrame, ok := frame.(*SynStreamFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { + t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) + } +} + +func TestCreateParseSynReplyFrameCompressionDisable(t *testing.T) { + buffer := new(bytes.Buffer) + framer := &Framer{ + headerCompressionDisabled: true, + w: buffer, + headerBuf: new(bytes.Buffer), + r: buffer, + } + synReplyFrame := SynReplyFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeSynReply, + }, + StreamId: 2, + Headers: HeadersFixture, + } + if err := framer.WriteFrame(&synReplyFrame); err != nil { + t.Fatal("WriteFrame without compression:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame without compression:", err) + } + parsedSynReplyFrame, ok := frame.(*SynReplyFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(synReplyFrame, *parsedSynReplyFrame) { + t.Fatal("got: ", *parsedSynReplyFrame, "\nwant: ", synReplyFrame) + } +} + +func TestCreateParseSynReplyFrameCompressionEnable(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + synReplyFrame := SynReplyFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeSynReply, + }, + StreamId: 2, + Headers: HeadersFixture, + } + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + if err := framer.WriteFrame(&synReplyFrame); err != nil { + t.Fatal("WriteFrame with compression:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame with compression:", err) + } + parsedSynReplyFrame, ok := frame.(*SynReplyFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(synReplyFrame, *parsedSynReplyFrame) { + t.Fatal("got: ", *parsedSynReplyFrame, "\nwant: ", synReplyFrame) + } +} + +func TestCreateParseRstStream(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + rstStreamFrame := RstStreamFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeRstStream, + }, + StreamId: 1, + Status: InvalidStream, + } + if err := framer.WriteFrame(&rstStreamFrame); err != nil { + t.Fatal("WriteFrame:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame:", err) + } + parsedRstStreamFrame, ok := frame.(*RstStreamFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(rstStreamFrame, *parsedRstStreamFrame) { + t.Fatal("got: ", *parsedRstStreamFrame, "\nwant: ", rstStreamFrame) + } +} + +func TestCreateParseSettings(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + settingsFrame := SettingsFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeSettings, + }, + FlagIdValues: []SettingsFlagIdValue{ + {FlagSettingsPersistValue, SettingsCurrentCwnd, 10}, + {FlagSettingsPersisted, SettingsUploadBandwidth, 1}, + }, + } + if err := framer.WriteFrame(&settingsFrame); err != nil { + t.Fatal("WriteFrame:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame:", err) + } + parsedSettingsFrame, ok := frame.(*SettingsFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(settingsFrame, *parsedSettingsFrame) { + t.Fatal("got: ", *parsedSettingsFrame, "\nwant: ", settingsFrame) + } +} + +func TestCreateParsePing(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + pingFrame := PingFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypePing, + }, + Id: 31337, + } + if err := framer.WriteFrame(&pingFrame); err != nil { + t.Fatal("WriteFrame:", err) + } + if pingFrame.CFHeader.Flags != 0 { + t.Fatal("Incorrect frame type:", pingFrame) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame:", err) + } + parsedPingFrame, ok := frame.(*PingFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if parsedPingFrame.CFHeader.Flags != 0 { + t.Fatal("Parsed incorrect frame type:", parsedPingFrame) + } + if !reflect.DeepEqual(pingFrame, *parsedPingFrame) { + t.Fatal("got: ", *parsedPingFrame, "\nwant: ", pingFrame) + } +} + +func TestCreateParseGoAway(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + goAwayFrame := GoAwayFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeGoAway, + }, + LastGoodStreamId: 31337, + Status: 1, + } + if err := framer.WriteFrame(&goAwayFrame); err != nil { + t.Fatal("WriteFrame:", err) + } + if goAwayFrame.CFHeader.Flags != 0 { + t.Fatal("Incorrect frame type:", goAwayFrame) + } + if goAwayFrame.CFHeader.length != 8 { + t.Fatal("Incorrect frame type:", goAwayFrame) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame:", err) + } + parsedGoAwayFrame, ok := frame.(*GoAwayFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if parsedGoAwayFrame.CFHeader.Flags != 0 { + t.Fatal("Incorrect frame type:", parsedGoAwayFrame) + } + if parsedGoAwayFrame.CFHeader.length != 8 { + t.Fatal("Incorrect frame type:", parsedGoAwayFrame) + } + if !reflect.DeepEqual(goAwayFrame, *parsedGoAwayFrame) { + t.Fatal("got: ", *parsedGoAwayFrame, "\nwant: ", goAwayFrame) + } +} + +func TestCreateParseHeadersFrame(t *testing.T) { + buffer := new(bytes.Buffer) + framer := &Framer{ + headerCompressionDisabled: true, + w: buffer, + headerBuf: new(bytes.Buffer), + r: buffer, + } + headersFrame := HeadersFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeHeaders, + }, + StreamId: 2, + } + headersFrame.Headers = HeadersFixture + if err := framer.WriteFrame(&headersFrame); err != nil { + t.Fatal("WriteFrame without compression:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame without compression:", err) + } + parsedHeadersFrame, ok := frame.(*HeadersFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { + t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) + } +} + +func TestCreateParseHeadersFrameCompressionEnable(t *testing.T) { + buffer := new(bytes.Buffer) + headersFrame := HeadersFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeHeaders, + }, + StreamId: 2, + } + headersFrame.Headers = HeadersFixture + + framer, err := NewFramer(buffer, buffer) + if err := framer.WriteFrame(&headersFrame); err != nil { + t.Fatal("WriteFrame with compression:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame with compression:", err) + } + parsedHeadersFrame, ok := frame.(*HeadersFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { + t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) + } +} + +func TestCreateParseWindowUpdateFrame(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + windowUpdateFrame := WindowUpdateFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeWindowUpdate, + }, + StreamId: 31337, + DeltaWindowSize: 1, + } + if err := framer.WriteFrame(&windowUpdateFrame); err != nil { + t.Fatal("WriteFrame:", err) + } + if windowUpdateFrame.CFHeader.Flags != 0 { + t.Fatal("Incorrect frame type:", windowUpdateFrame) + } + if windowUpdateFrame.CFHeader.length != 8 { + t.Fatal("Incorrect frame type:", windowUpdateFrame) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame:", err) + } + parsedWindowUpdateFrame, ok := frame.(*WindowUpdateFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if parsedWindowUpdateFrame.CFHeader.Flags != 0 { + t.Fatal("Incorrect frame type:", parsedWindowUpdateFrame) + } + if parsedWindowUpdateFrame.CFHeader.length != 8 { + t.Fatal("Incorrect frame type:", parsedWindowUpdateFrame) + } + if !reflect.DeepEqual(windowUpdateFrame, *parsedWindowUpdateFrame) { + t.Fatal("got: ", *parsedWindowUpdateFrame, "\nwant: ", windowUpdateFrame) + } +} + +func TestCreateParseDataFrame(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + dataFrame := DataFrame{ + StreamId: 1, + Data: []byte{'h', 'e', 'l', 'l', 'o'}, + } + if err := framer.WriteFrame(&dataFrame); err != nil { + t.Fatal("WriteFrame:", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame:", err) + } + parsedDataFrame, ok := frame.(*DataFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(dataFrame, *parsedDataFrame) { + t.Fatal("got: ", *parsedDataFrame, "\nwant: ", dataFrame) + } +} + +func TestCompressionContextAcrossFrames(t *testing.T) { + buffer := new(bytes.Buffer) + framer, err := NewFramer(buffer, buffer) + if err != nil { + t.Fatal("Failed to create new framer:", err) + } + headersFrame := HeadersFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeHeaders, + }, + StreamId: 2, + Headers: HeadersFixture, + } + if err := framer.WriteFrame(&headersFrame); err != nil { + t.Fatal("WriteFrame (HEADERS):", err) + } + synStreamFrame := SynStreamFrame{ + ControlFrameHeader{ + Version, + TypeSynStream, + 0, // Flags + 0, // length + }, + 2, // StreamId + 0, // AssociatedTOStreamID + 0, // Priority + 1, // Slot + nil, // Headers + } + synStreamFrame.Headers = HeadersFixture + + if err := framer.WriteFrame(&synStreamFrame); err != nil { + t.Fatal("WriteFrame (SYN_STREAM):", err) + } + frame, err := framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame (HEADERS):", err, buffer.Bytes()) + } + parsedHeadersFrame, ok := frame.(*HeadersFrame) + if !ok { + t.Fatalf("expected HeadersFrame; got %T %v", frame, frame) + } + if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { + t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) + } + frame, err = framer.ReadFrame() + if err != nil { + t.Fatal("ReadFrame (SYN_STREAM):", err, buffer.Bytes()) + } + parsedSynStreamFrame, ok := frame.(*SynStreamFrame) + if !ok { + t.Fatalf("expected SynStreamFrame; got %T %v", frame, frame) + } + if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { + t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) + } +} + +func TestMultipleSPDYFrames(t *testing.T) { + // Initialize the framers. + pr1, pw1 := io.Pipe() + pr2, pw2 := io.Pipe() + writer, err := NewFramer(pw1, pr2) + if err != nil { + t.Fatal("Failed to create writer:", err) + } + reader, err := NewFramer(pw2, pr1) + if err != nil { + t.Fatal("Failed to create reader:", err) + } + + // Set up the frames we're actually transferring. + headersFrame := HeadersFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeHeaders, + }, + StreamId: 2, + Headers: HeadersFixture, + } + synStreamFrame := SynStreamFrame{ + CFHeader: ControlFrameHeader{ + version: Version, + frameType: TypeSynStream, + }, + StreamId: 2, + Headers: HeadersFixture, + } + + // Start the goroutines to write the frames. + go func() { + if err := writer.WriteFrame(&headersFrame); err != nil { + t.Fatal("WriteFrame (HEADERS): ", err) + } + if err := writer.WriteFrame(&synStreamFrame); err != nil { + t.Fatal("WriteFrame (SYN_STREAM): ", err) + } + }() + + // Read the frames and verify they look as expected. + frame, err := reader.ReadFrame() + if err != nil { + t.Fatal("ReadFrame (HEADERS): ", err) + } + parsedHeadersFrame, ok := frame.(*HeadersFrame) + if !ok { + t.Fatal("Parsed incorrect frame type:", frame) + } + if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { + t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) + } + frame, err = reader.ReadFrame() + if err != nil { + t.Fatal("ReadFrame (SYN_STREAM):", err) + } + parsedSynStreamFrame, ok := frame.(*SynStreamFrame) + if !ok { + t.Fatal("Parsed incorrect frame type.") + } + if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { + t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) + } +} + +func TestReadMalformedZlibHeader(t *testing.T) { + // These were constructed by corrupting the first byte of the zlib + // header after writing. + malformedStructs := map[string]string{ + "SynStreamFrame": "gAIAAQAAABgAAAACAAAAAAAAF/nfolGyYmAAAAAA//8=", + "SynReplyFrame": "gAIAAgAAABQAAAACAAAX+d+iUbJiYAAAAAD//w==", + "HeadersFrame": "gAIACAAAABQAAAACAAAX+d+iUbJiYAAAAAD//w==", + } + for name, bad := range malformedStructs { + b, err := base64.StdEncoding.DecodeString(bad) + if err != nil { + t.Errorf("Unable to decode base64 encoded frame %s: %v", name, err) + } + buf := bytes.NewBuffer(b) + reader, err := NewFramer(buf, buf) + if err != nil { + t.Fatalf("NewFramer: %v", err) + } + _, err = reader.ReadFrame() + if err != zlib.ErrHeader { + t.Errorf("Frame %s, expected: %#v, actual: %#v", name, zlib.ErrHeader, err) + } + } +} + +// TODO: these tests are too weak for updating SPDY spec. Fix me. + +type zeroStream struct { + frame Frame + encoded string +} + +var streamIdZeroFrames = map[string]zeroStream{ + "SynStreamFrame": { + &SynStreamFrame{StreamId: 0}, + "gAIAAQAAABgAAAAAAAAAAAAAePnfolGyYmAAAAAA//8=", + }, + "SynReplyFrame": { + &SynReplyFrame{StreamId: 0}, + "gAIAAgAAABQAAAAAAAB4+d+iUbJiYAAAAAD//w==", + }, + "RstStreamFrame": { + &RstStreamFrame{StreamId: 0}, + "gAIAAwAAAAgAAAAAAAAAAA==", + }, + "HeadersFrame": { + &HeadersFrame{StreamId: 0}, + "gAIACAAAABQAAAAAAAB4+d+iUbJiYAAAAAD//w==", + }, + "DataFrame": { + &DataFrame{StreamId: 0}, + "AAAAAAAAAAA=", + }, + "PingFrame": { + &PingFrame{Id: 0}, + "gAIABgAAAAQAAAAA", + }, +} + +func TestNoZeroStreamId(t *testing.T) { + t.Log("skipping") // TODO: update to work with SPDY3 + return + + for name, f := range streamIdZeroFrames { + b, err := base64.StdEncoding.DecodeString(f.encoded) + if err != nil { + t.Errorf("Unable to decode base64 encoded frame %s: %v", f, err) + continue + } + framer, err := NewFramer(ioutil.Discard, bytes.NewReader(b)) + if err != nil { + t.Fatalf("NewFramer: %v", err) + } + err = framer.WriteFrame(f.frame) + checkZeroStreamId(t, name, "WriteFrame", err) + + _, err = framer.ReadFrame() + checkZeroStreamId(t, name, "ReadFrame", err) + } +} + +func checkZeroStreamId(t *testing.T, frame string, method string, err error) { + if err == nil { + t.Errorf("%s ZeroStreamId, no error on %s", method, frame) + return + } + eerr, ok := err.(*Error) + if !ok || eerr.Err != ZeroStreamId { + t.Errorf("%s ZeroStreamId, incorrect error %#v, frame %s", method, eerr, frame) + } +} diff --git a/vendor/github.com/docker/spdystream/spdy/types.go b/vendor/github.com/docker/spdystream/spdy/types.go new file mode 100644 index 00000000..7b6ee9c6 --- /dev/null +++ b/vendor/github.com/docker/spdystream/spdy/types.go @@ -0,0 +1,275 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package spdy implements the SPDY protocol (currently SPDY/3), described in +// http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3. +package spdy + +import ( + "bytes" + "compress/zlib" + "io" + "net/http" +) + +// Version is the protocol version number that this package implements. +const Version = 3 + +// ControlFrameType stores the type field in a control frame header. +type ControlFrameType uint16 + +const ( + TypeSynStream ControlFrameType = 0x0001 + TypeSynReply = 0x0002 + TypeRstStream = 0x0003 + TypeSettings = 0x0004 + TypePing = 0x0006 + TypeGoAway = 0x0007 + TypeHeaders = 0x0008 + TypeWindowUpdate = 0x0009 +) + +// ControlFlags are the flags that can be set on a control frame. +type ControlFlags uint8 + +const ( + ControlFlagFin ControlFlags = 0x01 + ControlFlagUnidirectional = 0x02 + ControlFlagSettingsClearSettings = 0x01 +) + +// DataFlags are the flags that can be set on a data frame. +type DataFlags uint8 + +const ( + DataFlagFin DataFlags = 0x01 +) + +// MaxDataLength is the maximum number of bytes that can be stored in one frame. +const MaxDataLength = 1<<24 - 1 + +// headerValueSepator separates multiple header values. +const headerValueSeparator = "\x00" + +// Frame is a single SPDY frame in its unpacked in-memory representation. Use +// Framer to read and write it. +type Frame interface { + write(f *Framer) error +} + +// ControlFrameHeader contains all the fields in a control frame header, +// in its unpacked in-memory representation. +type ControlFrameHeader struct { + // Note, high bit is the "Control" bit. + version uint16 // spdy version number + frameType ControlFrameType + Flags ControlFlags + length uint32 // length of data field +} + +type controlFrame interface { + Frame + read(h ControlFrameHeader, f *Framer) error +} + +// StreamId represents a 31-bit value identifying the stream. +type StreamId uint32 + +// SynStreamFrame is the unpacked, in-memory representation of a SYN_STREAM +// frame. +type SynStreamFrame struct { + CFHeader ControlFrameHeader + StreamId StreamId + AssociatedToStreamId StreamId // stream id for a stream which this stream is associated to + Priority uint8 // priority of this frame (3-bit) + Slot uint8 // index in the server's credential vector of the client certificate + Headers http.Header +} + +// SynReplyFrame is the unpacked, in-memory representation of a SYN_REPLY frame. +type SynReplyFrame struct { + CFHeader ControlFrameHeader + StreamId StreamId + Headers http.Header +} + +// RstStreamStatus represents the status that led to a RST_STREAM. +type RstStreamStatus uint32 + +const ( + ProtocolError RstStreamStatus = iota + 1 + InvalidStream + RefusedStream + UnsupportedVersion + Cancel + InternalError + FlowControlError + StreamInUse + StreamAlreadyClosed + InvalidCredentials + FrameTooLarge +) + +// RstStreamFrame is the unpacked, in-memory representation of a RST_STREAM +// frame. +type RstStreamFrame struct { + CFHeader ControlFrameHeader + StreamId StreamId + Status RstStreamStatus +} + +// SettingsFlag represents a flag in a SETTINGS frame. +type SettingsFlag uint8 + +const ( + FlagSettingsPersistValue SettingsFlag = 0x1 + FlagSettingsPersisted = 0x2 +) + +// SettingsFlag represents the id of an id/value pair in a SETTINGS frame. +type SettingsId uint32 + +const ( + SettingsUploadBandwidth SettingsId = iota + 1 + SettingsDownloadBandwidth + SettingsRoundTripTime + SettingsMaxConcurrentStreams + SettingsCurrentCwnd + SettingsDownloadRetransRate + SettingsInitialWindowSize + SettingsClientCretificateVectorSize +) + +// SettingsFlagIdValue is the unpacked, in-memory representation of the +// combined flag/id/value for a setting in a SETTINGS frame. +type SettingsFlagIdValue struct { + Flag SettingsFlag + Id SettingsId + Value uint32 +} + +// SettingsFrame is the unpacked, in-memory representation of a SPDY +// SETTINGS frame. +type SettingsFrame struct { + CFHeader ControlFrameHeader + FlagIdValues []SettingsFlagIdValue +} + +// PingFrame is the unpacked, in-memory representation of a PING frame. +type PingFrame struct { + CFHeader ControlFrameHeader + Id uint32 // unique id for this ping, from server is even, from client is odd. +} + +// GoAwayStatus represents the status in a GoAwayFrame. +type GoAwayStatus uint32 + +const ( + GoAwayOK GoAwayStatus = iota + GoAwayProtocolError + GoAwayInternalError +) + +// GoAwayFrame is the unpacked, in-memory representation of a GOAWAY frame. +type GoAwayFrame struct { + CFHeader ControlFrameHeader + LastGoodStreamId StreamId // last stream id which was accepted by sender + Status GoAwayStatus +} + +// HeadersFrame is the unpacked, in-memory representation of a HEADERS frame. +type HeadersFrame struct { + CFHeader ControlFrameHeader + StreamId StreamId + Headers http.Header +} + +// WindowUpdateFrame is the unpacked, in-memory representation of a +// WINDOW_UPDATE frame. +type WindowUpdateFrame struct { + CFHeader ControlFrameHeader + StreamId StreamId + DeltaWindowSize uint32 // additional number of bytes to existing window size +} + +// TODO: Implement credential frame and related methods. + +// DataFrame is the unpacked, in-memory representation of a DATA frame. +type DataFrame struct { + // Note, high bit is the "Control" bit. Should be 0 for data frames. + StreamId StreamId + Flags DataFlags + Data []byte // payload data of this frame +} + +// A SPDY specific error. +type ErrorCode string + +const ( + UnlowercasedHeaderName ErrorCode = "header was not lowercased" + DuplicateHeaders = "multiple headers with same name" + WrongCompressedPayloadSize = "compressed payload size was incorrect" + UnknownFrameType = "unknown frame type" + InvalidControlFrame = "invalid control frame" + InvalidDataFrame = "invalid data frame" + InvalidHeaderPresent = "frame contained invalid header" + ZeroStreamId = "stream id zero is disallowed" +) + +// Error contains both the type of error and additional values. StreamId is 0 +// if Error is not associated with a stream. +type Error struct { + Err ErrorCode + StreamId StreamId +} + +func (e *Error) Error() string { + return string(e.Err) +} + +var invalidReqHeaders = map[string]bool{ + "Connection": true, + "Host": true, + "Keep-Alive": true, + "Proxy-Connection": true, + "Transfer-Encoding": true, +} + +var invalidRespHeaders = map[string]bool{ + "Connection": true, + "Keep-Alive": true, + "Proxy-Connection": true, + "Transfer-Encoding": true, +} + +// Framer handles serializing/deserializing SPDY frames, including compressing/ +// decompressing payloads. +type Framer struct { + headerCompressionDisabled bool + w io.Writer + headerBuf *bytes.Buffer + headerCompressor *zlib.Writer + r io.Reader + headerReader io.LimitedReader + headerDecompressor io.ReadCloser +} + +// NewFramer allocates a new Framer for a given SPDY connection, represented by +// a io.Writer and io.Reader. Note that Framer will read and write individual fields +// from/to the Reader and Writer, so the caller should pass in an appropriately +// buffered implementation to optimize performance. +func NewFramer(w io.Writer, r io.Reader) (*Framer, error) { + compressBuf := new(bytes.Buffer) + compressor, err := zlib.NewWriterLevelDict(compressBuf, zlib.BestCompression, []byte(headerDictionary)) + if err != nil { + return nil, err + } + framer := &Framer{ + w: w, + headerBuf: compressBuf, + headerCompressor: compressor, + r: r, + } + return framer, nil +} diff --git a/vendor/github.com/docker/spdystream/spdy/write.go b/vendor/github.com/docker/spdystream/spdy/write.go new file mode 100644 index 00000000..b212f66a --- /dev/null +++ b/vendor/github.com/docker/spdystream/spdy/write.go @@ -0,0 +1,318 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package spdy + +import ( + "encoding/binary" + "io" + "net/http" + "strings" +) + +func (frame *SynStreamFrame) write(f *Framer) error { + return f.writeSynStreamFrame(frame) +} + +func (frame *SynReplyFrame) write(f *Framer) error { + return f.writeSynReplyFrame(frame) +} + +func (frame *RstStreamFrame) write(f *Framer) (err error) { + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + frame.CFHeader.version = Version + frame.CFHeader.frameType = TypeRstStream + frame.CFHeader.Flags = 0 + frame.CFHeader.length = 8 + + // Serialize frame to Writer. + if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { + return + } + if frame.Status == 0 { + return &Error{InvalidControlFrame, frame.StreamId} + } + if err = binary.Write(f.w, binary.BigEndian, frame.Status); err != nil { + return + } + return +} + +func (frame *SettingsFrame) write(f *Framer) (err error) { + frame.CFHeader.version = Version + frame.CFHeader.frameType = TypeSettings + frame.CFHeader.length = uint32(len(frame.FlagIdValues)*8 + 4) + + // Serialize frame to Writer. + if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, uint32(len(frame.FlagIdValues))); err != nil { + return + } + for _, flagIdValue := range frame.FlagIdValues { + flagId := uint32(flagIdValue.Flag)<<24 | uint32(flagIdValue.Id) + if err = binary.Write(f.w, binary.BigEndian, flagId); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, flagIdValue.Value); err != nil { + return + } + } + return +} + +func (frame *PingFrame) write(f *Framer) (err error) { + if frame.Id == 0 { + return &Error{ZeroStreamId, 0} + } + frame.CFHeader.version = Version + frame.CFHeader.frameType = TypePing + frame.CFHeader.Flags = 0 + frame.CFHeader.length = 4 + + // Serialize frame to Writer. + if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, frame.Id); err != nil { + return + } + return +} + +func (frame *GoAwayFrame) write(f *Framer) (err error) { + frame.CFHeader.version = Version + frame.CFHeader.frameType = TypeGoAway + frame.CFHeader.Flags = 0 + frame.CFHeader.length = 8 + + // Serialize frame to Writer. + if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, frame.LastGoodStreamId); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, frame.Status); err != nil { + return + } + return nil +} + +func (frame *HeadersFrame) write(f *Framer) error { + return f.writeHeadersFrame(frame) +} + +func (frame *WindowUpdateFrame) write(f *Framer) (err error) { + frame.CFHeader.version = Version + frame.CFHeader.frameType = TypeWindowUpdate + frame.CFHeader.Flags = 0 + frame.CFHeader.length = 8 + + // Serialize frame to Writer. + if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, frame.DeltaWindowSize); err != nil { + return + } + return nil +} + +func (frame *DataFrame) write(f *Framer) error { + return f.writeDataFrame(frame) +} + +// WriteFrame writes a frame. +func (f *Framer) WriteFrame(frame Frame) error { + return frame.write(f) +} + +func writeControlFrameHeader(w io.Writer, h ControlFrameHeader) error { + if err := binary.Write(w, binary.BigEndian, 0x8000|h.version); err != nil { + return err + } + if err := binary.Write(w, binary.BigEndian, h.frameType); err != nil { + return err + } + flagsAndLength := uint32(h.Flags)<<24 | h.length + if err := binary.Write(w, binary.BigEndian, flagsAndLength); err != nil { + return err + } + return nil +} + +func writeHeaderValueBlock(w io.Writer, h http.Header) (n int, err error) { + n = 0 + if err = binary.Write(w, binary.BigEndian, uint32(len(h))); err != nil { + return + } + n += 2 + for name, values := range h { + if err = binary.Write(w, binary.BigEndian, uint32(len(name))); err != nil { + return + } + n += 2 + name = strings.ToLower(name) + if _, err = io.WriteString(w, name); err != nil { + return + } + n += len(name) + v := strings.Join(values, headerValueSeparator) + if err = binary.Write(w, binary.BigEndian, uint32(len(v))); err != nil { + return + } + n += 2 + if _, err = io.WriteString(w, v); err != nil { + return + } + n += len(v) + } + return +} + +func (f *Framer) writeSynStreamFrame(frame *SynStreamFrame) (err error) { + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + // Marshal the headers. + var writer io.Writer = f.headerBuf + if !f.headerCompressionDisabled { + writer = f.headerCompressor + } + if _, err = writeHeaderValueBlock(writer, frame.Headers); err != nil { + return + } + if !f.headerCompressionDisabled { + f.headerCompressor.Flush() + } + + // Set ControlFrameHeader. + frame.CFHeader.version = Version + frame.CFHeader.frameType = TypeSynStream + frame.CFHeader.length = uint32(len(f.headerBuf.Bytes()) + 10) + + // Serialize frame to Writer. + if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { + return err + } + if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { + return err + } + if err = binary.Write(f.w, binary.BigEndian, frame.AssociatedToStreamId); err != nil { + return err + } + if err = binary.Write(f.w, binary.BigEndian, frame.Priority<<5); err != nil { + return err + } + if err = binary.Write(f.w, binary.BigEndian, frame.Slot); err != nil { + return err + } + if _, err = f.w.Write(f.headerBuf.Bytes()); err != nil { + return err + } + f.headerBuf.Reset() + return nil +} + +func (f *Framer) writeSynReplyFrame(frame *SynReplyFrame) (err error) { + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + // Marshal the headers. + var writer io.Writer = f.headerBuf + if !f.headerCompressionDisabled { + writer = f.headerCompressor + } + if _, err = writeHeaderValueBlock(writer, frame.Headers); err != nil { + return + } + if !f.headerCompressionDisabled { + f.headerCompressor.Flush() + } + + // Set ControlFrameHeader. + frame.CFHeader.version = Version + frame.CFHeader.frameType = TypeSynReply + frame.CFHeader.length = uint32(len(f.headerBuf.Bytes()) + 4) + + // Serialize frame to Writer. + if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { + return + } + if _, err = f.w.Write(f.headerBuf.Bytes()); err != nil { + return + } + f.headerBuf.Reset() + return +} + +func (f *Framer) writeHeadersFrame(frame *HeadersFrame) (err error) { + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + // Marshal the headers. + var writer io.Writer = f.headerBuf + if !f.headerCompressionDisabled { + writer = f.headerCompressor + } + if _, err = writeHeaderValueBlock(writer, frame.Headers); err != nil { + return + } + if !f.headerCompressionDisabled { + f.headerCompressor.Flush() + } + + // Set ControlFrameHeader. + frame.CFHeader.version = Version + frame.CFHeader.frameType = TypeHeaders + frame.CFHeader.length = uint32(len(f.headerBuf.Bytes()) + 4) + + // Serialize frame to Writer. + if err = writeControlFrameHeader(f.w, frame.CFHeader); err != nil { + return + } + if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { + return + } + if _, err = f.w.Write(f.headerBuf.Bytes()); err != nil { + return + } + f.headerBuf.Reset() + return +} + +func (f *Framer) writeDataFrame(frame *DataFrame) (err error) { + if frame.StreamId == 0 { + return &Error{ZeroStreamId, 0} + } + if frame.StreamId&0x80000000 != 0 || len(frame.Data) > MaxDataLength { + return &Error{InvalidDataFrame, frame.StreamId} + } + + // Serialize frame to Writer. + if err = binary.Write(f.w, binary.BigEndian, frame.StreamId); err != nil { + return + } + flagsAndLength := uint32(frame.Flags)<<24 | uint32(len(frame.Data)) + if err = binary.Write(f.w, binary.BigEndian, flagsAndLength); err != nil { + return + } + if _, err = f.w.Write(frame.Data); err != nil { + return + } + return nil +} diff --git a/vendor/github.com/docker/spdystream/spdy_bench_test.go b/vendor/github.com/docker/spdystream/spdy_bench_test.go new file mode 100644 index 00000000..6f9e4910 --- /dev/null +++ b/vendor/github.com/docker/spdystream/spdy_bench_test.go @@ -0,0 +1,113 @@ +package spdystream + +import ( + "fmt" + "io" + "net" + "net/http" + "sync" + "testing" +) + +func configureServer() (io.Closer, string, *sync.WaitGroup) { + authenticated = true + wg := &sync.WaitGroup{} + server, listen, serverErr := runServer(wg) + + if serverErr != nil { + panic(serverErr) + } + + return server, listen, wg +} + +func BenchmarkDial10000(b *testing.B) { + server, addr, wg := configureServer() + + defer func() { + server.Close() + wg.Wait() + }() + + for i := 0; i < b.N; i++ { + conn, dialErr := net.Dial("tcp", addr) + if dialErr != nil { + panic(fmt.Sprintf("Error dialing server: %s", dialErr)) + } + conn.Close() + } +} + +func BenchmarkDialWithSPDYStream10000(b *testing.B) { + server, addr, wg := configureServer() + + defer func() { + server.Close() + wg.Wait() + }() + + for i := 0; i < b.N; i++ { + conn, dialErr := net.Dial("tcp", addr) + if dialErr != nil { + b.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + b.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + closeErr := spdyConn.Close() + if closeErr != nil { + b.Fatalf("Error closing connection: %s, closeErr") + } + } +} + +func benchmarkStreamWithDataAndSize(size uint64, b *testing.B) { + server, addr, wg := configureServer() + + defer func() { + server.Close() + wg.Wait() + }() + + for i := 0; i < b.N; i++ { + conn, dialErr := net.Dial("tcp", addr) + if dialErr != nil { + b.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + b.Fatalf("Error creating spdy connection: %s", spdyErr) + } + + go spdyConn.Serve(MirrorStreamHandler) + + stream, err := spdyConn.CreateStream(http.Header{}, nil, false) + + writer := make([]byte, size) + + stream.Write(writer) + + if err != nil { + panic(err) + } + + reader := make([]byte, size) + stream.Read(reader) + + stream.Close() + + closeErr := spdyConn.Close() + if closeErr != nil { + b.Fatalf("Error closing connection: %s, closeErr") + } + } +} + +func BenchmarkStreamWith1Byte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1, b) } +func BenchmarkStreamWith1KiloByte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1024, b) } +func BenchmarkStreamWith1Megabyte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1024*1024, b) } diff --git a/vendor/github.com/docker/spdystream/spdy_test.go b/vendor/github.com/docker/spdystream/spdy_test.go new file mode 100644 index 00000000..7f0e3a44 --- /dev/null +++ b/vendor/github.com/docker/spdystream/spdy_test.go @@ -0,0 +1,1171 @@ +package spdystream + +import ( + "bufio" + "bytes" + "fmt" + "io" + "io/ioutil" + "net" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/docker/spdystream/spdy" +) + +func TestSpdyStreams(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + authenticated = true + stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) + if streamErr != nil { + t.Fatalf("Error creating stream: %s", streamErr) + } + + waitErr := stream.Wait() + if waitErr != nil { + t.Fatalf("Error waiting for stream: %s", waitErr) + } + + message := []byte("hello") + writeErr := stream.WriteData(message, false) + if writeErr != nil { + t.Fatalf("Error writing data") + } + + buf := make([]byte, 10) + n, readErr := stream.Read(buf) + if readErr != nil { + t.Fatalf("Error reading data from stream: %s", readErr) + } + if n != 5 { + t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 5", n) + } + if bytes.Compare(buf[:n], message) != 0 { + t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", buf, message) + } + + headers := http.Header{ + "TestKey": []string{"TestVal"}, + } + sendErr := stream.SendHeader(headers, false) + if sendErr != nil { + t.Fatalf("Error sending headers: %s", sendErr) + } + receiveHeaders, receiveErr := stream.ReceiveHeader() + if receiveErr != nil { + t.Fatalf("Error receiving headers: %s", receiveErr) + } + if len(receiveHeaders) != 1 { + t.Fatalf("Unexpected number of headers:\nActual: %d\nExpecting:%d", len(receiveHeaders), 1) + } + testVal := receiveHeaders.Get("TestKey") + if testVal != "TestVal" { + t.Fatalf("Wrong test value:\nActual: %q\nExpecting: %q", testVal, "TestVal") + } + + writeErr = stream.WriteData(message, true) + if writeErr != nil { + t.Fatalf("Error writing data") + } + + smallBuf := make([]byte, 3) + n, readErr = stream.Read(smallBuf) + if readErr != nil { + t.Fatalf("Error reading data from stream: %s", readErr) + } + if n != 3 { + t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 3", n) + } + if bytes.Compare(smallBuf[:n], []byte("hel")) != 0 { + t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", smallBuf[:n], message) + } + n, readErr = stream.Read(smallBuf) + if readErr != nil { + t.Fatalf("Error reading data from stream: %s", readErr) + } + if n != 2 { + t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 2", n) + } + if bytes.Compare(smallBuf[:n], []byte("lo")) != 0 { + t.Fatalf("Did not receive expected message:\nActual: %s\nExpected: lo", smallBuf[:n]) + } + + n, readErr = stream.Read(buf) + if readErr != io.EOF { + t.Fatalf("Expected EOF reading from finished stream, read %d bytes", n) + } + + // Closing again should return error since stream is already closed + streamCloseErr := stream.Close() + if streamCloseErr == nil { + t.Fatalf("No error closing finished stream") + } + if streamCloseErr != ErrWriteClosedStream { + t.Fatalf("Unexpected error closing stream: %s", streamCloseErr) + } + + streamResetErr := stream.Reset() + if streamResetErr != nil { + t.Fatalf("Error reseting stream: %s", streamResetErr) + } + + authenticated = false + badStream, badStreamErr := spdyConn.CreateStream(http.Header{}, nil, false) + if badStreamErr != nil { + t.Fatalf("Error creating stream: %s", badStreamErr) + } + + waitErr = badStream.Wait() + if waitErr == nil { + t.Fatalf("Did not receive error creating stream") + } + if waitErr != ErrReset { + t.Fatalf("Unexpected error creating stream: %s", waitErr) + } + streamCloseErr = badStream.Close() + if streamCloseErr == nil { + t.Fatalf("No error closing bad stream") + } + + spdyCloseErr := spdyConn.Close() + if spdyCloseErr != nil { + t.Fatalf("Error closing spdy connection: %s", spdyCloseErr) + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestPing(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + pingTime, pingErr := spdyConn.Ping() + if pingErr != nil { + t.Fatalf("Error pinging server: %s", pingErr) + } + if pingTime == time.Duration(0) { + t.Fatalf("Expecting non-zero ping time") + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestHalfClose(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + authenticated = true + stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) + if streamErr != nil { + t.Fatalf("Error creating stream: %s", streamErr) + } + + waitErr := stream.Wait() + if waitErr != nil { + t.Fatalf("Error waiting for stream: %s", waitErr) + } + + message := []byte("hello and will read after close") + writeErr := stream.WriteData(message, false) + if writeErr != nil { + t.Fatalf("Error writing data") + } + + streamCloseErr := stream.Close() + if streamCloseErr != nil { + t.Fatalf("Error closing stream: %s", streamCloseErr) + } + + buf := make([]byte, 40) + n, readErr := stream.Read(buf) + if readErr != nil { + t.Fatalf("Error reading data from stream: %s", readErr) + } + if n != 31 { + t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 5", n) + } + if bytes.Compare(buf[:n], message) != 0 { + t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", buf, message) + } + + spdyCloseErr := spdyConn.Close() + if spdyCloseErr != nil { + t.Fatalf("Error closing spdy connection: %s", spdyCloseErr) + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestUnexpectedRemoteConnectionClosed(t *testing.T) { + tt := []struct { + closeReceiver bool + closeSender bool + }{ + {closeReceiver: true, closeSender: false}, + {closeReceiver: false, closeSender: true}, + {closeReceiver: false, closeSender: false}, + } + for tix, tc := range tt { + listener, listenErr := net.Listen("tcp", "localhost:0") + if listenErr != nil { + t.Fatalf("Error listening: %v", listenErr) + } + + var serverConn net.Conn + var connErr error + go func() { + serverConn, connErr = listener.Accept() + if connErr != nil { + t.Fatalf("Error accepting: %v", connErr) + } + + serverSpdyConn, _ := NewConnection(serverConn, true) + go serverSpdyConn.Serve(func(stream *Stream) { + stream.SendReply(http.Header{}, tc.closeSender) + }) + }() + + conn, dialErr := net.Dial("tcp", listener.Addr().String()) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + authenticated = true + stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) + if streamErr != nil { + t.Fatalf("Error creating stream: %s", streamErr) + } + + waitErr := stream.Wait() + if waitErr != nil { + t.Fatalf("Error waiting for stream: %s", waitErr) + } + + if tc.closeReceiver { + // make stream half closed, receive only + stream.Close() + } + + streamch := make(chan error, 1) + go func() { + b := make([]byte, 1) + _, err := stream.Read(b) + streamch <- err + }() + + closeErr := serverConn.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + + select { + case e := <-streamch: + if e == nil || e != io.EOF { + t.Fatalf("(%d) Expected to get an EOF stream error", tix) + } + } + + closeErr = conn.Close() + if closeErr != nil { + t.Fatalf("Error closing client connection: %s", closeErr) + } + + listenErr = listener.Close() + if listenErr != nil { + t.Fatalf("Error closing listener: %s", listenErr) + } + } +} + +func TestCloseNotification(t *testing.T) { + listener, listenErr := net.Listen("tcp", "localhost:0") + if listenErr != nil { + t.Fatalf("Error listening: %v", listenErr) + } + listen := listener.Addr().String() + + serverConnChan := make(chan net.Conn) + go func() { + serverConn, err := listener.Accept() + if err != nil { + t.Fatalf("Error accepting: %v", err) + } + + serverSpdyConn, err := NewConnection(serverConn, true) + if err != nil { + t.Fatalf("Error creating server connection: %v", err) + } + go serverSpdyConn.Serve(NoOpStreamHandler) + <-serverSpdyConn.CloseChan() + serverConnChan <- serverConn + }() + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + // close client conn + err := conn.Close() + if err != nil { + t.Fatalf("Error closing client connection: %v", err) + } + + var serverConn net.Conn + select { + case serverConn = <-serverConnChan: + } + + err = serverConn.Close() + if err != nil { + t.Fatalf("Error closing serverConn: %v", err) + } + + listenErr = listener.Close() + if listenErr != nil { + t.Fatalf("Error closing listener: %s", listenErr) + } +} + +func TestIdleShutdownRace(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + authenticated = true + stream, err := spdyConn.CreateStream(http.Header{}, nil, false) + if err != nil { + t.Fatalf("Error creating stream: %v", err) + } + + spdyConn.SetIdleTimeout(5 * time.Millisecond) + go func() { + time.Sleep(5 * time.Millisecond) + stream.Reset() + }() + + select { + case <-spdyConn.CloseChan(): + case <-time.After(20 * time.Millisecond): + t.Fatal("Timed out waiting for idle connection closure") + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestIdleNoTimeoutSet(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + select { + case <-spdyConn.CloseChan(): + t.Fatal("Unexpected connection closure") + case <-time.After(10 * time.Millisecond): + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestIdleClearTimeout(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + spdyConn.SetIdleTimeout(10 * time.Millisecond) + spdyConn.SetIdleTimeout(0) + select { + case <-spdyConn.CloseChan(): + t.Fatal("Unexpected connection closure") + case <-time.After(20 * time.Millisecond): + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestIdleNoData(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + spdyConn.SetIdleTimeout(10 * time.Millisecond) + <-spdyConn.CloseChan() + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestIdleWithData(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + spdyConn.SetIdleTimeout(25 * time.Millisecond) + + authenticated = true + stream, err := spdyConn.CreateStream(http.Header{}, nil, false) + if err != nil { + t.Fatalf("Error creating stream: %v", err) + } + + writeCh := make(chan struct{}) + + go func() { + b := []byte{1, 2, 3, 4, 5} + for i := 0; i < 10; i++ { + _, err = stream.Write(b) + if err != nil { + t.Fatalf("Error writing to stream: %v", err) + } + time.Sleep(10 * time.Millisecond) + } + close(writeCh) + }() + + writesFinished := false + +Loop: + for { + select { + case <-writeCh: + writesFinished = true + case <-spdyConn.CloseChan(): + if !writesFinished { + t.Fatal("Connection closed before all writes finished") + } + break Loop + } + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestIdleRace(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + spdyConn.SetIdleTimeout(10 * time.Millisecond) + + authenticated = true + + for i := 0; i < 10; i++ { + _, err := spdyConn.CreateStream(http.Header{}, nil, false) + if err != nil { + t.Fatalf("Error creating stream: %v", err) + } + } + + <-spdyConn.CloseChan() + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestHalfClosedIdleTimeout(t *testing.T) { + listener, listenErr := net.Listen("tcp", "localhost:0") + if listenErr != nil { + t.Fatalf("Error listening: %v", listenErr) + } + listen := listener.Addr().String() + + go func() { + serverConn, err := listener.Accept() + if err != nil { + t.Fatalf("Error accepting: %v", err) + } + + serverSpdyConn, err := NewConnection(serverConn, true) + if err != nil { + t.Fatalf("Error creating server connection: %v", err) + } + go serverSpdyConn.Serve(func(s *Stream) { + s.SendReply(http.Header{}, true) + }) + serverSpdyConn.SetIdleTimeout(10 * time.Millisecond) + }() + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + stream, err := spdyConn.CreateStream(http.Header{}, nil, false) + if err != nil { + t.Fatalf("Error creating stream: %v", err) + } + + time.Sleep(20 * time.Millisecond) + + stream.Reset() + + err = spdyConn.Close() + if err != nil { + t.Fatalf("Error closing client spdy conn: %v", err) + } +} + +func TestStreamReset(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + authenticated = true + stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) + if streamErr != nil { + t.Fatalf("Error creating stream: %s", streamErr) + } + + buf := []byte("dskjahfkdusahfkdsahfkdsafdkas") + for i := 0; i < 10; i++ { + if _, err := stream.Write(buf); err != nil { + t.Fatalf("Error writing to stream: %s", err) + } + } + for i := 0; i < 10; i++ { + if _, err := stream.Read(buf); err != nil { + t.Fatalf("Error reading from stream: %s", err) + } + } + + // fmt.Printf("Resetting...\n") + if err := stream.Reset(); err != nil { + t.Fatalf("Error reseting stream: %s", err) + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +func TestStreamResetWithDataRemaining(t *testing.T) { + var wg sync.WaitGroup + server, listen, serverErr := runServer(&wg) + if serverErr != nil { + t.Fatalf("Error initializing server: %s", serverErr) + } + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + authenticated = true + stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) + if streamErr != nil { + t.Fatalf("Error creating stream: %s", streamErr) + } + + buf := []byte("dskjahfkdusahfkdsahfkdsafdkas") + for i := 0; i < 10; i++ { + if _, err := stream.Write(buf); err != nil { + t.Fatalf("Error writing to stream: %s", err) + } + } + + // read a bit to make sure a goroutine gets to <-dataChan + if _, err := stream.Read(buf); err != nil { + t.Fatalf("Error reading from stream: %s", err) + } + + // fmt.Printf("Resetting...\n") + if err := stream.Reset(); err != nil { + t.Fatalf("Error reseting stream: %s", err) + } + + closeErr := server.Close() + if closeErr != nil { + t.Fatalf("Error shutting down server: %s", closeErr) + } + wg.Wait() +} + +type roundTripper struct { + conn net.Conn +} + +func (s *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + r := *req + req = &r + + conn, err := net.Dial("tcp", req.URL.Host) + if err != nil { + return nil, err + } + + err = req.Write(conn) + if err != nil { + return nil, err + } + + resp, err := http.ReadResponse(bufio.NewReader(conn), req) + if err != nil { + return nil, err + } + + s.conn = conn + + return resp, nil +} + +// see https://github.com/GoogleCloudPlatform/kubernetes/issues/4882 +func TestFramingAfterRemoteConnectionClosed(t *testing.T) { + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + streamCh := make(chan *Stream) + + w.WriteHeader(http.StatusSwitchingProtocols) + + netconn, _, _ := w.(http.Hijacker).Hijack() + conn, _ := NewConnection(netconn, true) + go conn.Serve(func(s *Stream) { + s.SendReply(http.Header{}, false) + streamCh <- s + }) + + stream := <-streamCh + io.Copy(stream, stream) + + closeChan := make(chan struct{}) + go func() { + stream.Reset() + conn.Close() + close(closeChan) + }() + + <-closeChan + })) + + server.Start() + defer server.Close() + + req, err := http.NewRequest("GET", server.URL, nil) + if err != nil { + t.Fatalf("Error creating request: %s", err) + } + + rt := &roundTripper{} + client := &http.Client{Transport: rt} + + _, err = client.Do(req) + if err != nil { + t.Fatalf("unexpected error from client.Do: %s", err) + } + + conn, err := NewConnection(rt.conn, false) + go conn.Serve(NoOpStreamHandler) + + stream, err := conn.CreateStream(http.Header{}, nil, false) + if err != nil { + t.Fatalf("error creating client stream: %s", err) + } + + n, err := stream.Write([]byte("hello")) + if err != nil { + t.Fatalf("error writing to stream: %s", err) + } + if n != 5 { + t.Fatalf("Expected to write 5 bytes, but actually wrote %d", n) + } + + b := make([]byte, 5) + n, err = stream.Read(b) + if err != nil { + t.Fatalf("error reading from stream: %s", err) + } + if n != 5 { + t.Fatalf("Expected to read 5 bytes, but actually read %d", n) + } + if e, a := "hello", string(b[0:n]); e != a { + t.Fatalf("expected '%s', got '%s'", e, a) + } + + stream.Reset() + conn.Close() +} + +func TestGoAwayRace(t *testing.T) { + var done sync.WaitGroup + listener, err := net.Listen("tcp", "localhost:0") + if err != nil { + t.Fatalf("Error listening: %v", err) + } + listen := listener.Addr().String() + + processDataFrame := make(chan struct{}) + serverClosed := make(chan struct{}) + + done.Add(1) + go func() { + defer done.Done() + serverConn, err := listener.Accept() + if err != nil { + t.Fatalf("Error accepting: %v", err) + } + + serverSpdyConn, err := NewConnection(serverConn, true) + if err != nil { + t.Fatalf("Error creating server connection: %v", err) + } + go func() { + <-serverSpdyConn.CloseChan() + close(serverClosed) + }() + + // force the data frame handler to sleep before delivering the frame + serverSpdyConn.dataFrameHandler = func(frame *spdy.DataFrame) error { + <-processDataFrame + return serverSpdyConn.handleDataFrame(frame) + } + + streamCh := make(chan *Stream) + go serverSpdyConn.Serve(func(s *Stream) { + s.SendReply(http.Header{}, false) + streamCh <- s + }) + + stream, ok := <-streamCh + if !ok { + t.Fatalf("didn't get a stream") + } + stream.Close() + data, err := ioutil.ReadAll(stream) + if err != nil { + t.Error(err) + } + if e, a := "hello1hello2hello3hello4hello5", string(data); e != a { + t.Errorf("Expected %q, got %q", e, a) + } + }() + + dialConn, err := net.Dial("tcp", listen) + if err != nil { + t.Fatalf("Error dialing server: %s", err) + } + conn, err := NewConnection(dialConn, false) + if err != nil { + t.Fatalf("Error creating client connectin: %v", err) + } + go conn.Serve(NoOpStreamHandler) + + stream, err := conn.CreateStream(http.Header{}, nil, false) + if err != nil { + t.Fatalf("error creating client stream: %s", err) + } + if err := stream.Wait(); err != nil { + t.Fatalf("error waiting for stream creation: %v", err) + } + + fmt.Fprint(stream, "hello1") + fmt.Fprint(stream, "hello2") + fmt.Fprint(stream, "hello3") + fmt.Fprint(stream, "hello4") + fmt.Fprint(stream, "hello5") + + stream.Close() + conn.Close() + + // wait for the server to get the go away frame + <-serverClosed + + // allow the data frames to be delivered to the server's stream + close(processDataFrame) + + done.Wait() +} + +func TestSetIdleTimeoutAfterRemoteConnectionClosed(t *testing.T) { + listener, err := net.Listen("tcp", "localhost:0") + if err != nil { + t.Fatalf("Error listening: %v", err) + } + listen := listener.Addr().String() + + serverConns := make(chan *Connection, 1) + go func() { + conn, connErr := listener.Accept() + if connErr != nil { + t.Fatal(connErr) + } + serverSpdyConn, err := NewConnection(conn, true) + if err != nil { + t.Fatalf("Error creating server connection: %v", err) + } + go serverSpdyConn.Serve(NoOpStreamHandler) + serverConns <- serverSpdyConn + }() + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + if err := spdyConn.Close(); err != nil { + t.Fatal(err) + } + + serverConn := <-serverConns + defer serverConn.Close() + <-serverConn.closeChan + + serverConn.SetIdleTimeout(10 * time.Second) +} + +func TestClientConnectionStopsServingAfterGoAway(t *testing.T) { + listener, err := net.Listen("tcp", "localhost:0") + if err != nil { + t.Fatalf("Error listening: %v", err) + } + listen := listener.Addr().String() + + serverConns := make(chan *Connection, 1) + go func() { + conn, connErr := listener.Accept() + if connErr != nil { + t.Fatal(connErr) + } + serverSpdyConn, err := NewConnection(conn, true) + if err != nil { + t.Fatalf("Error creating server connection: %v", err) + } + go serverSpdyConn.Serve(NoOpStreamHandler) + serverConns <- serverSpdyConn + }() + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + stream, err := spdyConn.CreateStream(http.Header{}, nil, false) + if err != nil { + t.Fatalf("Error creating stream: %v", err) + } + if err := stream.WaitTimeout(30 * time.Second); err != nil { + t.Fatalf("Timed out waiting for stream: %v", err) + } + + readChan := make(chan struct{}) + go func() { + _, err := ioutil.ReadAll(stream) + if err != nil { + t.Fatalf("Error reading stream: %v", err) + } + close(readChan) + }() + + serverConn := <-serverConns + serverConn.Close() + + // make sure the client conn breaks out of the main loop in Serve() + <-spdyConn.closeChan + // make sure the remote channels are closed and the stream read is unblocked + <-readChan +} + +func TestStreamReadUnblocksAfterCloseThenReset(t *testing.T) { + listener, err := net.Listen("tcp", "localhost:0") + if err != nil { + t.Fatalf("Error listening: %v", err) + } + listen := listener.Addr().String() + + serverConns := make(chan *Connection, 1) + go func() { + conn, connErr := listener.Accept() + if connErr != nil { + t.Fatal(connErr) + } + serverSpdyConn, err := NewConnection(conn, true) + if err != nil { + t.Fatalf("Error creating server connection: %v", err) + } + go serverSpdyConn.Serve(NoOpStreamHandler) + serverConns <- serverSpdyConn + }() + + conn, dialErr := net.Dial("tcp", listen) + if dialErr != nil { + t.Fatalf("Error dialing server: %s", dialErr) + } + + spdyConn, spdyErr := NewConnection(conn, false) + if spdyErr != nil { + t.Fatalf("Error creating spdy connection: %s", spdyErr) + } + go spdyConn.Serve(NoOpStreamHandler) + + stream, err := spdyConn.CreateStream(http.Header{}, nil, false) + if err != nil { + t.Fatalf("Error creating stream: %v", err) + } + if err := stream.WaitTimeout(30 * time.Second); err != nil { + t.Fatalf("Timed out waiting for stream: %v", err) + } + + readChan := make(chan struct{}) + go func() { + _, err := ioutil.ReadAll(stream) + if err != nil { + t.Fatalf("Error reading stream: %v", err) + } + close(readChan) + }() + + serverConn := <-serverConns + defer serverConn.Close() + + if err := stream.Close(); err != nil { + t.Fatal(err) + } + if err := stream.Reset(); err != nil { + t.Fatal(err) + } + + // make sure close followed by reset unblocks stream.Read() + select { + case <-readChan: + case <-time.After(10 * time.Second): + t.Fatal("Timed out waiting for stream read to unblock") + } +} + +var authenticated bool + +func authStreamHandler(stream *Stream) { + if !authenticated { + stream.Refuse() + } + MirrorStreamHandler(stream) +} + +func runServer(wg *sync.WaitGroup) (io.Closer, string, error) { + listener, listenErr := net.Listen("tcp", "localhost:0") + if listenErr != nil { + return nil, "", listenErr + } + wg.Add(1) + go func() { + for { + conn, connErr := listener.Accept() + if connErr != nil { + break + } + + spdyConn, _ := NewConnection(conn, true) + go spdyConn.Serve(authStreamHandler) + + } + wg.Done() + }() + return listener, listener.Addr().String(), nil +} diff --git a/vendor/github.com/docker/spdystream/stream.go b/vendor/github.com/docker/spdystream/stream.go new file mode 100644 index 00000000..f9e9ee26 --- /dev/null +++ b/vendor/github.com/docker/spdystream/stream.go @@ -0,0 +1,327 @@ +package spdystream + +import ( + "errors" + "fmt" + "io" + "net" + "net/http" + "sync" + "time" + + "github.com/docker/spdystream/spdy" +) + +var ( + ErrUnreadPartialData = errors.New("unread partial data") +) + +type Stream struct { + streamId spdy.StreamId + parent *Stream + conn *Connection + startChan chan error + + dataLock sync.RWMutex + dataChan chan []byte + unread []byte + + priority uint8 + headers http.Header + headerChan chan http.Header + finishLock sync.Mutex + finished bool + replyCond *sync.Cond + replied bool + closeLock sync.Mutex + closeChan chan bool +} + +// WriteData writes data to stream, sending a dataframe per call +func (s *Stream) WriteData(data []byte, fin bool) error { + s.waitWriteReply() + var flags spdy.DataFlags + + if fin { + flags = spdy.DataFlagFin + s.finishLock.Lock() + if s.finished { + s.finishLock.Unlock() + return ErrWriteClosedStream + } + s.finished = true + s.finishLock.Unlock() + } + + dataFrame := &spdy.DataFrame{ + StreamId: s.streamId, + Flags: flags, + Data: data, + } + + debugMessage("(%p) (%d) Writing data frame", s, s.streamId) + return s.conn.framer.WriteFrame(dataFrame) +} + +// Write writes bytes to a stream, calling write data for each call. +func (s *Stream) Write(data []byte) (n int, err error) { + err = s.WriteData(data, false) + if err == nil { + n = len(data) + } + return +} + +// Read reads bytes from a stream, a single read will never get more +// than what is sent on a single data frame, but a multiple calls to +// read may get data from the same data frame. +func (s *Stream) Read(p []byte) (n int, err error) { + if s.unread == nil { + select { + case <-s.closeChan: + return 0, io.EOF + case read, ok := <-s.dataChan: + if !ok { + return 0, io.EOF + } + s.unread = read + } + } + n = copy(p, s.unread) + if n < len(s.unread) { + s.unread = s.unread[n:] + } else { + s.unread = nil + } + return +} + +// ReadData reads an entire data frame and returns the byte array +// from the data frame. If there is unread data from the result +// of a Read call, this function will return an ErrUnreadPartialData. +func (s *Stream) ReadData() ([]byte, error) { + debugMessage("(%p) Reading data from %d", s, s.streamId) + if s.unread != nil { + return nil, ErrUnreadPartialData + } + select { + case <-s.closeChan: + return nil, io.EOF + case read, ok := <-s.dataChan: + if !ok { + return nil, io.EOF + } + return read, nil + } +} + +func (s *Stream) waitWriteReply() { + if s.replyCond != nil { + s.replyCond.L.Lock() + for !s.replied { + s.replyCond.Wait() + } + s.replyCond.L.Unlock() + } +} + +// Wait waits for the stream to receive a reply. +func (s *Stream) Wait() error { + return s.WaitTimeout(time.Duration(0)) +} + +// WaitTimeout waits for the stream to receive a reply or for timeout. +// When the timeout is reached, ErrTimeout will be returned. +func (s *Stream) WaitTimeout(timeout time.Duration) error { + var timeoutChan <-chan time.Time + if timeout > time.Duration(0) { + timeoutChan = time.After(timeout) + } + + select { + case err := <-s.startChan: + if err != nil { + return err + } + break + case <-timeoutChan: + return ErrTimeout + } + return nil +} + +// Close closes the stream by sending an empty data frame with the +// finish flag set, indicating this side is finished with the stream. +func (s *Stream) Close() error { + select { + case <-s.closeChan: + // Stream is now fully closed + s.conn.removeStream(s) + default: + break + } + return s.WriteData([]byte{}, true) +} + +// Reset sends a reset frame, putting the stream into the fully closed state. +func (s *Stream) Reset() error { + s.conn.removeStream(s) + return s.resetStream() +} + +func (s *Stream) resetStream() error { + // Always call closeRemoteChannels, even if s.finished is already true. + // This makes it so that stream.Close() followed by stream.Reset() allows + // stream.Read() to unblock. + s.closeRemoteChannels() + + s.finishLock.Lock() + if s.finished { + s.finishLock.Unlock() + return nil + } + s.finished = true + s.finishLock.Unlock() + + resetFrame := &spdy.RstStreamFrame{ + StreamId: s.streamId, + Status: spdy.Cancel, + } + return s.conn.framer.WriteFrame(resetFrame) +} + +// CreateSubStream creates a stream using the current as the parent +func (s *Stream) CreateSubStream(headers http.Header, fin bool) (*Stream, error) { + return s.conn.CreateStream(headers, s, fin) +} + +// SetPriority sets the stream priority, does not affect the +// remote priority of this stream after Open has been called. +// Valid values are 0 through 7, 0 being the highest priority +// and 7 the lowest. +func (s *Stream) SetPriority(priority uint8) { + s.priority = priority +} + +// SendHeader sends a header frame across the stream +func (s *Stream) SendHeader(headers http.Header, fin bool) error { + return s.conn.sendHeaders(headers, s, fin) +} + +// SendReply sends a reply on a stream, only valid to be called once +// when handling a new stream +func (s *Stream) SendReply(headers http.Header, fin bool) error { + if s.replyCond == nil { + return errors.New("cannot reply on initiated stream") + } + s.replyCond.L.Lock() + defer s.replyCond.L.Unlock() + if s.replied { + return nil + } + + err := s.conn.sendReply(headers, s, fin) + if err != nil { + return err + } + + s.replied = true + s.replyCond.Broadcast() + return nil +} + +// Refuse sends a reset frame with the status refuse, only +// valid to be called once when handling a new stream. This +// may be used to indicate that a stream is not allowed +// when http status codes are not being used. +func (s *Stream) Refuse() error { + if s.replied { + return nil + } + s.replied = true + return s.conn.sendReset(spdy.RefusedStream, s) +} + +// Cancel sends a reset frame with the status canceled. This +// can be used at any time by the creator of the Stream to +// indicate the stream is no longer needed. +func (s *Stream) Cancel() error { + return s.conn.sendReset(spdy.Cancel, s) +} + +// ReceiveHeader receives a header sent on the other side +// of the stream. This function will block until a header +// is received or stream is closed. +func (s *Stream) ReceiveHeader() (http.Header, error) { + select { + case <-s.closeChan: + break + case header, ok := <-s.headerChan: + if !ok { + return nil, fmt.Errorf("header chan closed") + } + return header, nil + } + return nil, fmt.Errorf("stream closed") +} + +// Parent returns the parent stream +func (s *Stream) Parent() *Stream { + return s.parent +} + +// Headers returns the headers used to create the stream +func (s *Stream) Headers() http.Header { + return s.headers +} + +// String returns the string version of stream using the +// streamId to uniquely identify the stream +func (s *Stream) String() string { + return fmt.Sprintf("stream:%d", s.streamId) +} + +// Identifier returns a 32 bit identifier for the stream +func (s *Stream) Identifier() uint32 { + return uint32(s.streamId) +} + +// IsFinished returns whether the stream has finished +// sending data +func (s *Stream) IsFinished() bool { + return s.finished +} + +// Implement net.Conn interface + +func (s *Stream) LocalAddr() net.Addr { + return s.conn.conn.LocalAddr() +} + +func (s *Stream) RemoteAddr() net.Addr { + return s.conn.conn.RemoteAddr() +} + +// TODO set per stream values instead of connection-wide + +func (s *Stream) SetDeadline(t time.Time) error { + return s.conn.conn.SetDeadline(t) +} + +func (s *Stream) SetReadDeadline(t time.Time) error { + return s.conn.conn.SetReadDeadline(t) +} + +func (s *Stream) SetWriteDeadline(t time.Time) error { + return s.conn.conn.SetWriteDeadline(t) +} + +func (s *Stream) closeRemoteChannels() { + s.closeLock.Lock() + defer s.closeLock.Unlock() + select { + case <-s.closeChan: + default: + close(s.closeChan) + } +} diff --git a/vendor/github.com/docker/spdystream/utils.go b/vendor/github.com/docker/spdystream/utils.go new file mode 100644 index 00000000..1b2c199a --- /dev/null +++ b/vendor/github.com/docker/spdystream/utils.go @@ -0,0 +1,16 @@ +package spdystream + +import ( + "log" + "os" +) + +var ( + DEBUG = os.Getenv("DEBUG") +) + +func debugMessage(fmt string, args ...interface{}) { + if DEBUG != "" { + log.Printf(fmt, args...) + } +} diff --git a/vendor/github.com/docker/spdystream/ws/connection.go b/vendor/github.com/docker/spdystream/ws/connection.go new file mode 100644 index 00000000..d0ea001b --- /dev/null +++ b/vendor/github.com/docker/spdystream/ws/connection.go @@ -0,0 +1,65 @@ +package ws + +import ( + "github.com/gorilla/websocket" + "io" + "log" + "time" +) + +// Wrap an HTTP2 connection over WebSockets and +// use the underlying WebSocket framing for proxy +// compatibility. +type Conn struct { + *websocket.Conn + reader io.Reader +} + +func NewConnection(w *websocket.Conn) *Conn { + return &Conn{Conn: w} +} + +func (c Conn) Write(b []byte) (int, error) { + err := c.WriteMessage(websocket.BinaryMessage, b) + if err != nil { + return 0, err + } + return len(b), nil +} + +func (c Conn) Read(b []byte) (int, error) { + if c.reader == nil { + t, r, err := c.NextReader() + if err != nil { + return 0, err + } + if t != websocket.BinaryMessage { + log.Printf("ws: ignored non-binary message in stream") + return 0, nil + } + c.reader = r + } + n, err := c.reader.Read(b) + if err != nil { + if err == io.EOF { + c.reader = nil + } + return n, err + } + return n, nil +} + +func (c Conn) SetDeadline(t time.Time) error { + if err := c.Conn.SetReadDeadline(t); err != nil { + return err + } + if err := c.Conn.SetWriteDeadline(t); err != nil { + return err + } + return nil +} + +func (c Conn) Close() error { + err := c.Conn.Close() + return err +} diff --git a/vendor/github.com/docker/spdystream/ws/ws_test.go b/vendor/github.com/docker/spdystream/ws/ws_test.go new file mode 100644 index 00000000..36c4a46a --- /dev/null +++ b/vendor/github.com/docker/spdystream/ws/ws_test.go @@ -0,0 +1,175 @@ +package ws + +import ( + "bytes" + "github.com/docker/spdystream" + "github.com/gorilla/websocket" + "io" + "log" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, +} + +var serverSpdyConn *spdystream.Connection + +// Connect to the Websocket endpoint at ws://localhost +// using SPDY over Websockets framing. +func ExampleConn() { + wsconn, _, _ := websocket.DefaultDialer.Dial("ws://localhost/", http.Header{"Origin": {"http://localhost/"}}) + conn, _ := spdystream.NewConnection(NewConnection(wsconn), false) + go conn.Serve(spdystream.NoOpStreamHandler, spdystream.NoAuthHandler) + stream, _ := conn.CreateStream(http.Header{}, nil, false) + stream.Wait() +} + +func serveWs(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + http.Error(w, "Method not allowed", 405) + return + } + + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + if _, ok := err.(websocket.HandshakeError); !ok { + log.Println(err) + } + return + } + + wrap := NewConnection(ws) + spdyConn, err := spdystream.NewConnection(wrap, true) + if err != nil { + log.Fatal(err) + return + } + serverSpdyConn = spdyConn + go spdyConn.Serve(spdystream.MirrorStreamHandler, authStreamHandler) +} + +func TestSpdyStreamOverWs(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(serveWs)) + defer server.Close() + defer func() { + if serverSpdyConn != nil { + serverSpdyConn.Close() + } + }() + + wsconn, _, err := websocket.DefaultDialer.Dial(strings.Replace(server.URL, "http://", "ws://", 1), http.Header{"Origin": {server.URL}}) + if err != nil { + t.Fatal(err) + } + + wrap := NewConnection(wsconn) + spdyConn, err := spdystream.NewConnection(wrap, false) + if err != nil { + defer wsconn.Close() + t.Fatal(err) + } + defer spdyConn.Close() + authenticated = true + go spdyConn.Serve(spdystream.NoOpStreamHandler, spdystream.RejectAuthHandler) + + stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) + if streamErr != nil { + t.Fatalf("Error creating stream: %s", streamErr) + } + + waitErr := stream.Wait() + if waitErr != nil { + t.Fatalf("Error waiting for stream: %s", waitErr) + } + + message := []byte("hello") + writeErr := stream.WriteData(message, false) + if writeErr != nil { + t.Fatalf("Error writing data") + } + + buf := make([]byte, 10) + n, readErr := stream.Read(buf) + if readErr != nil { + t.Fatalf("Error reading data from stream: %s", readErr) + } + if n != 5 { + t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 5", n) + } + if bytes.Compare(buf[:n], message) != 0 { + t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", buf, message) + } + + writeErr = stream.WriteData(message, true) + if writeErr != nil { + t.Fatalf("Error writing data") + } + + smallBuf := make([]byte, 3) + n, readErr = stream.Read(smallBuf) + if readErr != nil { + t.Fatalf("Error reading data from stream: %s", readErr) + } + if n != 3 { + t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 3", n) + } + if bytes.Compare(smallBuf[:n], []byte("hel")) != 0 { + t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", smallBuf[:n], message) + } + n, readErr = stream.Read(smallBuf) + if readErr != nil { + t.Fatalf("Error reading data from stream: %s", readErr) + } + if n != 2 { + t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 2", n) + } + if bytes.Compare(smallBuf[:n], []byte("lo")) != 0 { + t.Fatalf("Did not receive expected message:\nActual: %s\nExpected: lo", smallBuf[:n]) + } + + n, readErr = stream.Read(buf) + if readErr != io.EOF { + t.Fatalf("Expected EOF reading from finished stream, read %d bytes", n) + } + + streamCloseErr := stream.Close() + if streamCloseErr != nil { + t.Fatalf("Error closing stream: %s", streamCloseErr) + } + + // Closing again should return nil + streamCloseErr = stream.Close() + if streamCloseErr != nil { + t.Fatalf("Error closing stream: %s", streamCloseErr) + } + + authenticated = false + badStream, badStreamErr := spdyConn.CreateStream(http.Header{}, nil, false) + if badStreamErr != nil { + t.Fatalf("Error creating stream: %s", badStreamErr) + } + + waitErr = badStream.Wait() + if waitErr == nil { + t.Fatalf("Did not receive error creating stream") + } + if waitErr != spdystream.ErrReset { + t.Fatalf("Unexpected error creating stream: %s", waitErr) + } + + spdyCloseErr := spdyConn.Close() + if spdyCloseErr != nil { + t.Fatalf("Error closing spdy connection: %s", spdyCloseErr) + } +} + +var authenticated bool + +func authStreamHandler(header http.Header, slot uint8, parent uint32) bool { + return authenticated +} diff --git a/vendor/github.com/emicklei/go-restful/.gitignore b/vendor/github.com/emicklei/go-restful/.gitignore new file mode 100644 index 00000000..cece7be6 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/.gitignore @@ -0,0 +1,70 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe + +restful.html + +*.out + +tmp.prof + +go-restful.test + +examples/restful-basic-authentication + +examples/restful-encoding-filter + +examples/restful-filters + +examples/restful-hello-world + +examples/restful-resource-functions + +examples/restful-serve-static + +examples/restful-user-service + +*.DS_Store +examples/restful-user-resource + +examples/restful-multi-containers + +examples/restful-form-handling + +examples/restful-CORS-filter + +examples/restful-options-filter + +examples/restful-curly-router + +examples/restful-cpuprofiler-service + +examples/restful-pre-post-filters + +curly.prof + +examples/restful-NCSA-logging + +examples/restful-html-template + +s.html +restful-path-tail diff --git a/vendor/github.com/emicklei/go-restful/CHANGES.md b/vendor/github.com/emicklei/go-restful/CHANGES.md new file mode 100644 index 00000000..824068ca --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/CHANGES.md @@ -0,0 +1,220 @@ +Change history of go-restful += +2017-01-30 + + [IMPORTANT] For swagger users, change your import statement to: + swagger "github.com/emicklei/go-restful-swagger12" + +- moved swagger 1.2 code to go-restful-swagger12 +- created TAG 2.0.0 + +2017-01-27 + +- remove defer request body close +- expose Dispatch for testing filters and Routefunctions +- swagger response model cannot be array +- created TAG 1.0.0 + +2016-12-22 + +- (API change) Remove code related to caching request content. Removes SetCacheReadEntity(doCache bool) + +2016-11-26 + +- Default change! now use CurlyRouter (was RouterJSR311) +- Default change! no more caching of request content +- Default change! do not recover from panics + +2016-09-22 + +- fix the DefaultRequestContentType feature + +2016-02-14 + +- take the qualify factor of the Accept header mediatype into account when deciding the contentype of the response +- add constructors for custom entity accessors for xml and json + +2015-09-27 + +- rename new WriteStatusAnd... to WriteHeaderAnd... for consistency + +2015-09-25 + +- fixed problem with changing Header after WriteHeader (issue 235) + +2015-09-14 + +- changed behavior of WriteHeader (immediate write) and WriteEntity (no status write) +- added support for custom EntityReaderWriters. + +2015-08-06 + +- add support for reading entities from compressed request content +- use sync.Pool for compressors of http response and request body +- add Description to Parameter for documentation in Swagger UI + +2015-03-20 + +- add configurable logging + +2015-03-18 + +- if not specified, the Operation is derived from the Route function + +2015-03-17 + +- expose Parameter creation functions +- make trace logger an interface +- fix OPTIONSFilter +- customize rendering of ServiceError +- JSR311 router now handles wildcards +- add Notes to Route + +2014-11-27 + +- (api add) PrettyPrint per response. (as proposed in #167) + +2014-11-12 + +- (api add) ApiVersion(.) for documentation in Swagger UI + +2014-11-10 + +- (api change) struct fields tagged with "description" show up in Swagger UI + +2014-10-31 + +- (api change) ReturnsError -> Returns +- (api add) RouteBuilder.Do(aBuilder) for DRY use of RouteBuilder +- fix swagger nested structs +- sort Swagger response messages by code + +2014-10-23 + +- (api add) ReturnsError allows you to document Http codes in swagger +- fixed problem with greedy CurlyRouter +- (api add) Access-Control-Max-Age in CORS +- add tracing functionality (injectable) for debugging purposes +- support JSON parse 64bit int +- fix empty parameters for swagger +- WebServicesUrl is now optional for swagger +- fixed duplicate AccessControlAllowOrigin in CORS +- (api change) expose ServeMux in container +- (api add) added AllowedDomains in CORS +- (api add) ParameterNamed for detailed documentation + +2014-04-16 + +- (api add) expose constructor of Request for testing. + +2014-06-27 + +- (api add) ParameterNamed gives access to a Parameter definition and its data (for further specification). +- (api add) SetCacheReadEntity allow scontrol over whether or not the request body is being cached (default true for compatibility reasons). + +2014-07-03 + +- (api add) CORS can be configured with a list of allowed domains + +2014-03-12 + +- (api add) Route path parameters can use wildcard or regular expressions. (requires CurlyRouter) + +2014-02-26 + +- (api add) Request now provides information about the matched Route, see method SelectedRoutePath + +2014-02-17 + +- (api change) renamed parameter constants (go-lint checks) + +2014-01-10 + +- (api add) support for CloseNotify, see http://golang.org/pkg/net/http/#CloseNotifier + +2014-01-07 + +- (api change) Write* methods in Response now return the error or nil. +- added example of serving HTML from a Go template. +- fixed comparing Allowed headers in CORS (is now case-insensitive) + +2013-11-13 + +- (api add) Response knows how many bytes are written to the response body. + +2013-10-29 + +- (api add) RecoverHandler(handler RecoverHandleFunction) to change how panic recovery is handled. Default behavior is to log and return a stacktrace. This may be a security issue as it exposes sourcecode information. + +2013-10-04 + +- (api add) Response knows what HTTP status has been written +- (api add) Request can have attributes (map of string->interface, also called request-scoped variables + +2013-09-12 + +- (api change) Router interface simplified +- Implemented CurlyRouter, a Router that does not use|allow regular expressions in paths + +2013-08-05 + - add OPTIONS support + - add CORS support + +2013-08-27 + +- fixed some reported issues (see github) +- (api change) deprecated use of WriteError; use WriteErrorString instead + +2014-04-15 + +- (fix) v1.0.1 tag: fix Issue 111: WriteErrorString + +2013-08-08 + +- (api add) Added implementation Container: a WebServices collection with its own http.ServeMux allowing multiple endpoints per program. Existing uses of go-restful will register their services to the DefaultContainer. +- (api add) the swagger package has be extended to have a UI per container. +- if panic is detected then a small stack trace is printed (thanks to runner-mei) +- (api add) WriteErrorString to Response + +Important API changes: + +- (api remove) package variable DoNotRecover no longer works ; use restful.DefaultContainer.DoNotRecover(true) instead. +- (api remove) package variable EnableContentEncoding no longer works ; use restful.DefaultContainer.EnableContentEncoding(true) instead. + + +2013-07-06 + +- (api add) Added support for response encoding (gzip and deflate(zlib)). This feature is disabled on default (for backwards compatibility). Use restful.EnableContentEncoding = true in your initialization to enable this feature. + +2013-06-19 + +- (improve) DoNotRecover option, moved request body closer, improved ReadEntity + +2013-06-03 + +- (api change) removed Dispatcher interface, hide PathExpression +- changed receiver names of type functions to be more idiomatic Go + +2013-06-02 + +- (optimize) Cache the RegExp compilation of Paths. + +2013-05-22 + +- (api add) Added support for request/response filter functions + +2013-05-18 + + +- (api add) Added feature to change the default Http Request Dispatch function (travis cline) +- (api change) Moved Swagger Webservice to swagger package (see example restful-user) + +[2012-11-14 .. 2013-05-18> + +- See https://github.com/emicklei/go-restful/commits + +2012-11-14 + +- Initial commit + + diff --git a/vendor/github.com/emicklei/go-restful/LICENSE b/vendor/github.com/emicklei/go-restful/LICENSE new file mode 100644 index 00000000..ece7ec61 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012,2013 Ernest Micklei + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/README.md b/vendor/github.com/emicklei/go-restful/README.md new file mode 100644 index 00000000..9f5e4a92 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/README.md @@ -0,0 +1,74 @@ +go-restful +========== + +[![Build Status](https://drone.io/github.com/emicklei/go-restful/status.png)](https://drone.io/github.com/emicklei/go-restful/latest) + +package for building REST-style Web Services using Google Go + +- [Documentation on godoc.org](http://godoc.org/github.com/emicklei/go-restful) +- [Code examples](https://github.com/emicklei/go-restful/tree/master/examples) + +REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping: + +- GET = Retrieve a representation of a resource +- POST = Create if you are sending content to the server to create a subordinate of the specified resource collection, using some server-side algorithm. +- PUT = Create if you are sending the full content of the specified resource (URI). +- PUT = Update if you are updating the full content of the specified resource. +- DELETE = Delete if you are requesting the server to delete the resource +- PATCH = Update partial content of a resource +- OPTIONS = Get information about the communication options for the request URI + +### Example + +```Go +ws := new(restful.WebService) +ws. + Path("/users"). + Consumes(restful.MIME_XML, restful.MIME_JSON). + Produces(restful.MIME_JSON, restful.MIME_XML) + +ws.Route(ws.GET("/{user-id}").To(u.findUser). + Doc("get a user"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). + Writes(User{})) +... + +func (u UserResource) findUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + ... +} +``` + +[Full API of a UserResource](https://github.com/emicklei/go-restful/tree/master/examples/restful-user-resource.go) + +### Features + +- Routes for request → function mapping with path parameter (e.g. {id}) support +- Configurable router: + - (default) Fast routing algorithm that allows static elements, regular expressions and dynamic parameters in the URL path (e.g. /meetings/{id} or /static/{subpath:*} + - Routing algorithm after [JSR311](http://jsr311.java.net/nonav/releases/1.1/spec/spec.html) that is implemented using (but does **not** accept) regular expressions +- Request API for reading structs from JSON/XML and accesing parameters (path,query,header) +- Response API for writing structs to JSON/XML and setting headers +- Customizable encoding using EntityReaderWriter registration +- Filters for intercepting the request → response flow on Service or Route level +- Request-scoped variables using attributes +- Containers for WebServices on different HTTP endpoints +- Content encoding (gzip,deflate) of request and response payloads +- Automatic responses on OPTIONS (using a filter) +- Automatic CORS request handling (using a filter) +- API declaration for Swagger UI (see go-restful-swagger12,go-restful-swagger20 packages) +- Panic recovery to produce HTTP 500, customizable using RecoverHandler(...) +- Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...) +- Configurable (trace) logging +- Customizable gzip/deflate readers and writers using CompressorProvider registration + +### Resources + +- [Example posted on blog](http://ernestmicklei.com/2012/11/go-restful-first-working-example/) +- [Design explained on blog](http://ernestmicklei.com/2012/11/go-restful-api-design/) +- [sourcegraph](https://sourcegraph.com/github.com/emicklei/go-restful) +- [showcase: Mora - MongoDB REST Api server](https://github.com/emicklei/mora) + +(c) 2012 - 2017, http://ernestmicklei.com. MIT License. Contributions are welcome. + +Type ```git shortlog -s``` for a full list of contributors. diff --git a/vendor/github.com/emicklei/go-restful/Srcfile b/vendor/github.com/emicklei/go-restful/Srcfile new file mode 100644 index 00000000..16fd1868 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/Srcfile @@ -0,0 +1 @@ +{"SkipDirs": ["examples"]} diff --git a/vendor/github.com/emicklei/go-restful/bench_curly_test.go b/vendor/github.com/emicklei/go-restful/bench_curly_test.go new file mode 100644 index 00000000..db6a1a75 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/bench_curly_test.go @@ -0,0 +1,51 @@ +package restful + +import ( + "fmt" + "net/http" + "net/http/httptest" + "testing" +) + +func setupCurly(container *Container) []string { + wsCount := 26 + rtCount := 26 + urisCurly := []string{} + + container.Router(CurlyRouter{}) + for i := 0; i < wsCount; i++ { + root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) + ws := new(WebService).Path(root) + for j := 0; j < rtCount; j++ { + sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) + ws.Route(ws.GET(sub).Consumes("application/xml").Produces("application/xml").To(echoCurly)) + } + container.Add(ws) + for _, each := range ws.Routes() { + urisCurly = append(urisCurly, "http://bench.com"+each.Path) + } + } + return urisCurly +} + +func echoCurly(req *Request, resp *Response) {} + +func BenchmarkManyCurly(b *testing.B) { + container := NewContainer() + urisCurly := setupCurly(container) + b.ResetTimer() + for t := 0; t < b.N; t++ { + for r := 0; r < 1000; r++ { + for _, each := range urisCurly { + sendNoReturnTo(each, container, t) + } + } + } +} + +func sendNoReturnTo(address string, container *Container, t int) { + httpRequest, _ := http.NewRequest("GET", address, nil) + httpRequest.Header.Set("Accept", "application/xml") + httpWriter := httptest.NewRecorder() + container.dispatch(httpWriter, httpRequest) +} diff --git a/vendor/github.com/emicklei/go-restful/bench_test.go b/vendor/github.com/emicklei/go-restful/bench_test.go new file mode 100644 index 00000000..3e77c2d2 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/bench_test.go @@ -0,0 +1,43 @@ +package restful + +import ( + "fmt" + "io" + "testing" +) + +var uris = []string{} + +func setup(container *Container) { + wsCount := 26 + rtCount := 26 + + for i := 0; i < wsCount; i++ { + root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) + ws := new(WebService).Path(root) + for j := 0; j < rtCount; j++ { + sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) + ws.Route(ws.GET(sub).To(echo)) + } + container.Add(ws) + for _, each := range ws.Routes() { + uris = append(uris, "http://bench.com"+each.Path) + } + } +} + +func echo(req *Request, resp *Response) { + io.WriteString(resp.ResponseWriter, "echo") +} + +func BenchmarkMany(b *testing.B) { + container := NewContainer() + setup(container) + b.ResetTimer() + for t := 0; t < b.N; t++ { + for _, each := range uris { + // println(each) + sendItTo(each, container) + } + } +} diff --git a/vendor/github.com/emicklei/go-restful/bench_test.sh b/vendor/github.com/emicklei/go-restful/bench_test.sh new file mode 100644 index 00000000..47ffbe4a --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/bench_test.sh @@ -0,0 +1,10 @@ +#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out + +go test -c +./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany +./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly + +#go tool pprof go-restful.test tmp.prof +go tool pprof go-restful.test curly.prof + + diff --git a/vendor/github.com/emicklei/go-restful/compress.go b/vendor/github.com/emicklei/go-restful/compress.go new file mode 100644 index 00000000..220b3771 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/compress.go @@ -0,0 +1,123 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "bufio" + "compress/gzip" + "compress/zlib" + "errors" + "io" + "net" + "net/http" + "strings" +) + +// OBSOLETE : use restful.DefaultContainer.EnableContentEncoding(true) to change this setting. +var EnableContentEncoding = false + +// CompressingResponseWriter is a http.ResponseWriter that can perform content encoding (gzip and zlib) +type CompressingResponseWriter struct { + writer http.ResponseWriter + compressor io.WriteCloser + encoding string +} + +// Header is part of http.ResponseWriter interface +func (c *CompressingResponseWriter) Header() http.Header { + return c.writer.Header() +} + +// WriteHeader is part of http.ResponseWriter interface +func (c *CompressingResponseWriter) WriteHeader(status int) { + c.writer.WriteHeader(status) +} + +// Write is part of http.ResponseWriter interface +// It is passed through the compressor +func (c *CompressingResponseWriter) Write(bytes []byte) (int, error) { + if c.isCompressorClosed() { + return -1, errors.New("Compressing error: tried to write data using closed compressor") + } + return c.compressor.Write(bytes) +} + +// CloseNotify is part of http.CloseNotifier interface +func (c *CompressingResponseWriter) CloseNotify() <-chan bool { + return c.writer.(http.CloseNotifier).CloseNotify() +} + +// Close the underlying compressor +func (c *CompressingResponseWriter) Close() error { + if c.isCompressorClosed() { + return errors.New("Compressing error: tried to close already closed compressor") + } + + c.compressor.Close() + if ENCODING_GZIP == c.encoding { + currentCompressorProvider.ReleaseGzipWriter(c.compressor.(*gzip.Writer)) + } + if ENCODING_DEFLATE == c.encoding { + currentCompressorProvider.ReleaseZlibWriter(c.compressor.(*zlib.Writer)) + } + // gc hint needed? + c.compressor = nil + return nil +} + +func (c *CompressingResponseWriter) isCompressorClosed() bool { + return nil == c.compressor +} + +// Hijack implements the Hijacker interface +// This is especially useful when combining Container.EnabledContentEncoding +// in combination with websockets (for instance gorilla/websocket) +func (c *CompressingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + hijacker, ok := c.writer.(http.Hijacker) + if !ok { + return nil, nil, errors.New("ResponseWriter doesn't support Hijacker interface") + } + return hijacker.Hijack() +} + +// WantsCompressedResponse reads the Accept-Encoding header to see if and which encoding is requested. +func wantsCompressedResponse(httpRequest *http.Request) (bool, string) { + header := httpRequest.Header.Get(HEADER_AcceptEncoding) + gi := strings.Index(header, ENCODING_GZIP) + zi := strings.Index(header, ENCODING_DEFLATE) + // use in order of appearance + if gi == -1 { + return zi != -1, ENCODING_DEFLATE + } else if zi == -1 { + return gi != -1, ENCODING_GZIP + } else { + if gi < zi { + return true, ENCODING_GZIP + } + return true, ENCODING_DEFLATE + } +} + +// NewCompressingResponseWriter create a CompressingResponseWriter for a known encoding = {gzip,deflate} +func NewCompressingResponseWriter(httpWriter http.ResponseWriter, encoding string) (*CompressingResponseWriter, error) { + httpWriter.Header().Set(HEADER_ContentEncoding, encoding) + c := new(CompressingResponseWriter) + c.writer = httpWriter + var err error + if ENCODING_GZIP == encoding { + w := currentCompressorProvider.AcquireGzipWriter() + w.Reset(httpWriter) + c.compressor = w + c.encoding = ENCODING_GZIP + } else if ENCODING_DEFLATE == encoding { + w := currentCompressorProvider.AcquireZlibWriter() + w.Reset(httpWriter) + c.compressor = w + c.encoding = ENCODING_DEFLATE + } else { + return nil, errors.New("Unknown encoding:" + encoding) + } + return c, err +} diff --git a/vendor/github.com/emicklei/go-restful/compress_test.go b/vendor/github.com/emicklei/go-restful/compress_test.go new file mode 100644 index 00000000..cc3e93d5 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/compress_test.go @@ -0,0 +1,125 @@ +package restful + +import ( + "bytes" + "compress/gzip" + "compress/zlib" + "io" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" +) + +// go test -v -test.run TestGzip ...restful +func TestGzip(t *testing.T) { + EnableContentEncoding = true + httpRequest, _ := http.NewRequest("GET", "/test", nil) + httpRequest.Header.Set("Accept-Encoding", "gzip,deflate") + httpWriter := httptest.NewRecorder() + wanted, encoding := wantsCompressedResponse(httpRequest) + if !wanted { + t.Fatal("should accept gzip") + } + if encoding != "gzip" { + t.Fatal("expected gzip") + } + c, err := NewCompressingResponseWriter(httpWriter, encoding) + if err != nil { + t.Fatal(err.Error()) + } + c.Write([]byte("Hello World")) + c.Close() + if httpWriter.Header().Get("Content-Encoding") != "gzip" { + t.Fatal("Missing gzip header") + } + reader, err := gzip.NewReader(httpWriter.Body) + if err != nil { + t.Fatal(err.Error()) + } + data, err := ioutil.ReadAll(reader) + if err != nil { + t.Fatal(err.Error()) + } + if got, want := string(data), "Hello World"; got != want { + t.Errorf("got %v want %v", got, want) + } +} + +func TestDeflate(t *testing.T) { + EnableContentEncoding = true + httpRequest, _ := http.NewRequest("GET", "/test", nil) + httpRequest.Header.Set("Accept-Encoding", "deflate,gzip") + httpWriter := httptest.NewRecorder() + wanted, encoding := wantsCompressedResponse(httpRequest) + if !wanted { + t.Fatal("should accept deflate") + } + if encoding != "deflate" { + t.Fatal("expected deflate") + } + c, err := NewCompressingResponseWriter(httpWriter, encoding) + if err != nil { + t.Fatal(err.Error()) + } + c.Write([]byte("Hello World")) + c.Close() + if httpWriter.Header().Get("Content-Encoding") != "deflate" { + t.Fatal("Missing deflate header") + } + reader, err := zlib.NewReader(httpWriter.Body) + if err != nil { + t.Fatal(err.Error()) + } + data, err := ioutil.ReadAll(reader) + if err != nil { + t.Fatal(err.Error()) + } + if got, want := string(data), "Hello World"; got != want { + t.Errorf("got %v want %v", got, want) + } +} + +func TestGzipDecompressRequestBody(t *testing.T) { + b := new(bytes.Buffer) + w := newGzipWriter() + w.Reset(b) + io.WriteString(w, `{"msg":"hi"}`) + w.Flush() + w.Close() + + req := new(Request) + httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) + httpRequest.Header.Set("Content-Type", "application/json") + httpRequest.Header.Set("Content-Encoding", "gzip") + req.Request = httpRequest + + doc := make(map[string]interface{}) + req.ReadEntity(&doc) + + if got, want := doc["msg"], "hi"; got != want { + t.Errorf("got %v want %v", got, want) + } +} + +func TestZlibDecompressRequestBody(t *testing.T) { + b := new(bytes.Buffer) + w := newZlibWriter() + w.Reset(b) + io.WriteString(w, `{"msg":"hi"}`) + w.Flush() + w.Close() + + req := new(Request) + httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) + httpRequest.Header.Set("Content-Type", "application/json") + httpRequest.Header.Set("Content-Encoding", "deflate") + req.Request = httpRequest + + doc := make(map[string]interface{}) + req.ReadEntity(&doc) + + if got, want := doc["msg"], "hi"; got != want { + t.Errorf("got %v want %v", got, want) + } +} diff --git a/vendor/github.com/emicklei/go-restful/compressor_cache.go b/vendor/github.com/emicklei/go-restful/compressor_cache.go new file mode 100644 index 00000000..ee426010 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/compressor_cache.go @@ -0,0 +1,103 @@ +package restful + +// Copyright 2015 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "compress/gzip" + "compress/zlib" +) + +// BoundedCachedCompressors is a CompressorProvider that uses a cache with a fixed amount +// of writers and readers (resources). +// If a new resource is acquired and all are in use, it will return a new unmanaged resource. +type BoundedCachedCompressors struct { + gzipWriters chan *gzip.Writer + gzipReaders chan *gzip.Reader + zlibWriters chan *zlib.Writer + writersCapacity int + readersCapacity int +} + +// NewBoundedCachedCompressors returns a new, with filled cache, BoundedCachedCompressors. +func NewBoundedCachedCompressors(writersCapacity, readersCapacity int) *BoundedCachedCompressors { + b := &BoundedCachedCompressors{ + gzipWriters: make(chan *gzip.Writer, writersCapacity), + gzipReaders: make(chan *gzip.Reader, readersCapacity), + zlibWriters: make(chan *zlib.Writer, writersCapacity), + writersCapacity: writersCapacity, + readersCapacity: readersCapacity, + } + for ix := 0; ix < writersCapacity; ix++ { + b.gzipWriters <- newGzipWriter() + b.zlibWriters <- newZlibWriter() + } + for ix := 0; ix < readersCapacity; ix++ { + b.gzipReaders <- newGzipReader() + } + return b +} + +// AcquireGzipWriter returns an resettable *gzip.Writer. Needs to be released. +func (b *BoundedCachedCompressors) AcquireGzipWriter() *gzip.Writer { + var writer *gzip.Writer + select { + case writer, _ = <-b.gzipWriters: + default: + // return a new unmanaged one + writer = newGzipWriter() + } + return writer +} + +// ReleaseGzipWriter accepts a writer (does not have to be one that was cached) +// only when the cache has room for it. It will ignore it otherwise. +func (b *BoundedCachedCompressors) ReleaseGzipWriter(w *gzip.Writer) { + // forget the unmanaged ones + if len(b.gzipWriters) < b.writersCapacity { + b.gzipWriters <- w + } +} + +// AcquireGzipReader returns a *gzip.Reader. Needs to be released. +func (b *BoundedCachedCompressors) AcquireGzipReader() *gzip.Reader { + var reader *gzip.Reader + select { + case reader, _ = <-b.gzipReaders: + default: + // return a new unmanaged one + reader = newGzipReader() + } + return reader +} + +// ReleaseGzipReader accepts a reader (does not have to be one that was cached) +// only when the cache has room for it. It will ignore it otherwise. +func (b *BoundedCachedCompressors) ReleaseGzipReader(r *gzip.Reader) { + // forget the unmanaged ones + if len(b.gzipReaders) < b.readersCapacity { + b.gzipReaders <- r + } +} + +// AcquireZlibWriter returns an resettable *zlib.Writer. Needs to be released. +func (b *BoundedCachedCompressors) AcquireZlibWriter() *zlib.Writer { + var writer *zlib.Writer + select { + case writer, _ = <-b.zlibWriters: + default: + // return a new unmanaged one + writer = newZlibWriter() + } + return writer +} + +// ReleaseZlibWriter accepts a writer (does not have to be one that was cached) +// only when the cache has room for it. It will ignore it otherwise. +func (b *BoundedCachedCompressors) ReleaseZlibWriter(w *zlib.Writer) { + // forget the unmanaged ones + if len(b.zlibWriters) < b.writersCapacity { + b.zlibWriters <- w + } +} diff --git a/vendor/github.com/emicklei/go-restful/compressor_pools.go b/vendor/github.com/emicklei/go-restful/compressor_pools.go new file mode 100644 index 00000000..d866ce64 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/compressor_pools.go @@ -0,0 +1,91 @@ +package restful + +// Copyright 2015 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "bytes" + "compress/gzip" + "compress/zlib" + "sync" +) + +// SyncPoolCompessors is a CompressorProvider that use the standard sync.Pool. +type SyncPoolCompessors struct { + GzipWriterPool *sync.Pool + GzipReaderPool *sync.Pool + ZlibWriterPool *sync.Pool +} + +// NewSyncPoolCompessors returns a new ("empty") SyncPoolCompessors. +func NewSyncPoolCompessors() *SyncPoolCompessors { + return &SyncPoolCompessors{ + GzipWriterPool: &sync.Pool{ + New: func() interface{} { return newGzipWriter() }, + }, + GzipReaderPool: &sync.Pool{ + New: func() interface{} { return newGzipReader() }, + }, + ZlibWriterPool: &sync.Pool{ + New: func() interface{} { return newZlibWriter() }, + }, + } +} + +func (s *SyncPoolCompessors) AcquireGzipWriter() *gzip.Writer { + return s.GzipWriterPool.Get().(*gzip.Writer) +} + +func (s *SyncPoolCompessors) ReleaseGzipWriter(w *gzip.Writer) { + s.GzipWriterPool.Put(w) +} + +func (s *SyncPoolCompessors) AcquireGzipReader() *gzip.Reader { + return s.GzipReaderPool.Get().(*gzip.Reader) +} + +func (s *SyncPoolCompessors) ReleaseGzipReader(r *gzip.Reader) { + s.GzipReaderPool.Put(r) +} + +func (s *SyncPoolCompessors) AcquireZlibWriter() *zlib.Writer { + return s.ZlibWriterPool.Get().(*zlib.Writer) +} + +func (s *SyncPoolCompessors) ReleaseZlibWriter(w *zlib.Writer) { + s.ZlibWriterPool.Put(w) +} + +func newGzipWriter() *gzip.Writer { + // create with an empty bytes writer; it will be replaced before using the gzipWriter + writer, err := gzip.NewWriterLevel(new(bytes.Buffer), gzip.BestSpeed) + if err != nil { + panic(err.Error()) + } + return writer +} + +func newGzipReader() *gzip.Reader { + // create with an empty reader (but with GZIP header); it will be replaced before using the gzipReader + // we can safely use currentCompressProvider because it is set on package initialization. + w := currentCompressorProvider.AcquireGzipWriter() + defer currentCompressorProvider.ReleaseGzipWriter(w) + b := new(bytes.Buffer) + w.Reset(b) + w.Flush() + w.Close() + reader, err := gzip.NewReader(bytes.NewReader(b.Bytes())) + if err != nil { + panic(err.Error()) + } + return reader +} + +func newZlibWriter() *zlib.Writer { + writer, err := zlib.NewWriterLevel(new(bytes.Buffer), gzip.BestSpeed) + if err != nil { + panic(err.Error()) + } + return writer +} diff --git a/vendor/github.com/emicklei/go-restful/compressors.go b/vendor/github.com/emicklei/go-restful/compressors.go new file mode 100644 index 00000000..f028456e --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/compressors.go @@ -0,0 +1,53 @@ +package restful + +// Copyright 2015 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "compress/gzip" + "compress/zlib" +) + +type CompressorProvider interface { + // Returns a *gzip.Writer which needs to be released later. + // Before using it, call Reset(). + AcquireGzipWriter() *gzip.Writer + + // Releases an aqcuired *gzip.Writer. + ReleaseGzipWriter(w *gzip.Writer) + + // Returns a *gzip.Reader which needs to be released later. + AcquireGzipReader() *gzip.Reader + + // Releases an aqcuired *gzip.Reader. + ReleaseGzipReader(w *gzip.Reader) + + // Returns a *zlib.Writer which needs to be released later. + // Before using it, call Reset(). + AcquireZlibWriter() *zlib.Writer + + // Releases an aqcuired *zlib.Writer. + ReleaseZlibWriter(w *zlib.Writer) +} + +// DefaultCompressorProvider is the actual provider of compressors (zlib or gzip). +var currentCompressorProvider CompressorProvider + +func init() { + currentCompressorProvider = NewSyncPoolCompessors() +} + +// CurrentCompressorProvider returns the current CompressorProvider. +// It is initialized using a SyncPoolCompessors. +func CurrentCompressorProvider() CompressorProvider { + return currentCompressorProvider +} + +// CompressorProvider sets the actual provider of compressors (zlib or gzip). +func SetCompressorProvider(p CompressorProvider) { + if p == nil { + panic("cannot set compressor provider to nil") + } + currentCompressorProvider = p +} diff --git a/vendor/github.com/emicklei/go-restful/constants.go b/vendor/github.com/emicklei/go-restful/constants.go new file mode 100644 index 00000000..203439c5 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/constants.go @@ -0,0 +1,30 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +const ( + MIME_XML = "application/xml" // Accept or Content-Type used in Consumes() and/or Produces() + MIME_JSON = "application/json" // Accept or Content-Type used in Consumes() and/or Produces() + MIME_OCTET = "application/octet-stream" // If Content-Type is not present in request, use the default + + HEADER_Allow = "Allow" + HEADER_Accept = "Accept" + HEADER_Origin = "Origin" + HEADER_ContentType = "Content-Type" + HEADER_LastModified = "Last-Modified" + HEADER_AcceptEncoding = "Accept-Encoding" + HEADER_ContentEncoding = "Content-Encoding" + HEADER_AccessControlExposeHeaders = "Access-Control-Expose-Headers" + HEADER_AccessControlRequestMethod = "Access-Control-Request-Method" + HEADER_AccessControlRequestHeaders = "Access-Control-Request-Headers" + HEADER_AccessControlAllowMethods = "Access-Control-Allow-Methods" + HEADER_AccessControlAllowOrigin = "Access-Control-Allow-Origin" + HEADER_AccessControlAllowCredentials = "Access-Control-Allow-Credentials" + HEADER_AccessControlAllowHeaders = "Access-Control-Allow-Headers" + HEADER_AccessControlMaxAge = "Access-Control-Max-Age" + + ENCODING_GZIP = "gzip" + ENCODING_DEFLATE = "deflate" +) diff --git a/vendor/github.com/emicklei/go-restful/container.go b/vendor/github.com/emicklei/go-restful/container.go new file mode 100644 index 00000000..05027718 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/container.go @@ -0,0 +1,366 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "bytes" + "errors" + "fmt" + "net/http" + "os" + "runtime" + "strings" + "sync" + + "github.com/emicklei/go-restful/log" +) + +// Container holds a collection of WebServices and a http.ServeMux to dispatch http requests. +// The requests are further dispatched to routes of WebServices using a RouteSelector +type Container struct { + webServicesLock sync.RWMutex + webServices []*WebService + ServeMux *http.ServeMux + isRegisteredOnRoot bool + containerFilters []FilterFunction + doNotRecover bool // default is true + recoverHandleFunc RecoverHandleFunction + serviceErrorHandleFunc ServiceErrorHandleFunction + router RouteSelector // default is a CurlyRouter (RouterJSR311 is a slower alternative) + contentEncodingEnabled bool // default is false +} + +// NewContainer creates a new Container using a new ServeMux and default router (RouterJSR311) +func NewContainer() *Container { + return &Container{ + webServices: []*WebService{}, + ServeMux: http.NewServeMux(), + isRegisteredOnRoot: false, + containerFilters: []FilterFunction{}, + doNotRecover: true, + recoverHandleFunc: logStackOnRecover, + serviceErrorHandleFunc: writeServiceError, + router: CurlyRouter{}, + contentEncodingEnabled: false} +} + +// RecoverHandleFunction declares functions that can be used to handle a panic situation. +// The first argument is what recover() returns. The second must be used to communicate an error response. +type RecoverHandleFunction func(interface{}, http.ResponseWriter) + +// RecoverHandler changes the default function (logStackOnRecover) to be called +// when a panic is detected. DoNotRecover must be have its default value (=false). +func (c *Container) RecoverHandler(handler RecoverHandleFunction) { + c.recoverHandleFunc = handler +} + +// ServiceErrorHandleFunction declares functions that can be used to handle a service error situation. +// The first argument is the service error, the second is the request that resulted in the error and +// the third must be used to communicate an error response. +type ServiceErrorHandleFunction func(ServiceError, *Request, *Response) + +// ServiceErrorHandler changes the default function (writeServiceError) to be called +// when a ServiceError is detected. +func (c *Container) ServiceErrorHandler(handler ServiceErrorHandleFunction) { + c.serviceErrorHandleFunc = handler +} + +// DoNotRecover controls whether panics will be caught to return HTTP 500. +// If set to true, Route functions are responsible for handling any error situation. +// Default value is true. +func (c *Container) DoNotRecover(doNot bool) { + c.doNotRecover = doNot +} + +// Router changes the default Router (currently RouterJSR311) +func (c *Container) Router(aRouter RouteSelector) { + c.router = aRouter +} + +// EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses. +func (c *Container) EnableContentEncoding(enabled bool) { + c.contentEncodingEnabled = enabled +} + +// Add a WebService to the Container. It will detect duplicate root paths and exit in that case. +func (c *Container) Add(service *WebService) *Container { + c.webServicesLock.Lock() + defer c.webServicesLock.Unlock() + + // if rootPath was not set then lazy initialize it + if len(service.rootPath) == 0 { + service.Path("/") + } + + // cannot have duplicate root paths + for _, each := range c.webServices { + if each.RootPath() == service.RootPath() { + log.Printf("[restful] WebService with duplicate root path detected:['%v']", each) + os.Exit(1) + } + } + + // If not registered on root then add specific mapping + if !c.isRegisteredOnRoot { + c.isRegisteredOnRoot = c.addHandler(service, c.ServeMux) + } + c.webServices = append(c.webServices, service) + return c +} + +// addHandler may set a new HandleFunc for the serveMux +// this function must run inside the critical region protected by the webServicesLock. +// returns true if the function was registered on root ("/") +func (c *Container) addHandler(service *WebService, serveMux *http.ServeMux) bool { + pattern := fixedPrefixPath(service.RootPath()) + // check if root path registration is needed + if "/" == pattern || "" == pattern { + serveMux.HandleFunc("/", c.dispatch) + return true + } + // detect if registration already exists + alreadyMapped := false + for _, each := range c.webServices { + if each.RootPath() == service.RootPath() { + alreadyMapped = true + break + } + } + if !alreadyMapped { + serveMux.HandleFunc(pattern, c.dispatch) + if !strings.HasSuffix(pattern, "/") { + serveMux.HandleFunc(pattern+"/", c.dispatch) + } + } + return false +} + +func (c *Container) Remove(ws *WebService) error { + if c.ServeMux == http.DefaultServeMux { + errMsg := fmt.Sprintf("[restful] cannot remove a WebService from a Container using the DefaultServeMux: ['%v']", ws) + log.Printf(errMsg) + return errors.New(errMsg) + } + c.webServicesLock.Lock() + defer c.webServicesLock.Unlock() + // build a new ServeMux and re-register all WebServices + newServeMux := http.NewServeMux() + newServices := []*WebService{} + newIsRegisteredOnRoot := false + for _, each := range c.webServices { + if each.rootPath != ws.rootPath { + // If not registered on root then add specific mapping + if !newIsRegisteredOnRoot { + newIsRegisteredOnRoot = c.addHandler(each, newServeMux) + } + newServices = append(newServices, each) + } + } + c.webServices, c.ServeMux, c.isRegisteredOnRoot = newServices, newServeMux, newIsRegisteredOnRoot + return nil +} + +// logStackOnRecover is the default RecoverHandleFunction and is called +// when DoNotRecover is false and the recoverHandleFunc is not set for the container. +// Default implementation logs the stacktrace and writes the stacktrace on the response. +// This may be a security issue as it exposes sourcecode information. +func logStackOnRecover(panicReason interface{}, httpWriter http.ResponseWriter) { + var buffer bytes.Buffer + buffer.WriteString(fmt.Sprintf("[restful] recover from panic situation: - %v\r\n", panicReason)) + for i := 2; ; i += 1 { + _, file, line, ok := runtime.Caller(i) + if !ok { + break + } + buffer.WriteString(fmt.Sprintf(" %s:%d\r\n", file, line)) + } + log.Print(buffer.String()) + httpWriter.WriteHeader(http.StatusInternalServerError) + httpWriter.Write(buffer.Bytes()) +} + +// writeServiceError is the default ServiceErrorHandleFunction and is called +// when a ServiceError is returned during route selection. Default implementation +// calls resp.WriteErrorString(err.Code, err.Message) +func writeServiceError(err ServiceError, req *Request, resp *Response) { + resp.WriteErrorString(err.Code, err.Message) +} + +// Dispatch the incoming Http Request to a matching WebService. +func (c *Container) Dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) { + if httpWriter == nil { + panic("httpWriter cannot be nil") + } + if httpRequest == nil { + panic("httpRequest cannot be nil") + } + c.dispatch(httpWriter, httpRequest) +} + +// Dispatch the incoming Http Request to a matching WebService. +func (c *Container) dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) { + writer := httpWriter + + // CompressingResponseWriter should be closed after all operations are done + defer func() { + if compressWriter, ok := writer.(*CompressingResponseWriter); ok { + compressWriter.Close() + } + }() + + // Instal panic recovery unless told otherwise + if !c.doNotRecover { // catch all for 500 response + defer func() { + if r := recover(); r != nil { + c.recoverHandleFunc(r, writer) + return + } + }() + } + + // Detect if compression is needed + // assume without compression, test for override + if c.contentEncodingEnabled { + doCompress, encoding := wantsCompressedResponse(httpRequest) + if doCompress { + var err error + writer, err = NewCompressingResponseWriter(httpWriter, encoding) + if err != nil { + log.Print("[restful] unable to install compressor: ", err) + httpWriter.WriteHeader(http.StatusInternalServerError) + return + } + } + } + // Find best match Route ; err is non nil if no match was found + var webService *WebService + var route *Route + var err error + func() { + c.webServicesLock.RLock() + defer c.webServicesLock.RUnlock() + webService, route, err = c.router.SelectRoute( + c.webServices, + httpRequest) + }() + if err != nil { + // a non-200 response has already been written + // run container filters anyway ; they should not touch the response... + chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) { + switch err.(type) { + case ServiceError: + ser := err.(ServiceError) + c.serviceErrorHandleFunc(ser, req, resp) + } + // TODO + }} + chain.ProcessFilter(NewRequest(httpRequest), NewResponse(writer)) + return + } + wrappedRequest, wrappedResponse := route.wrapRequestResponse(writer, httpRequest) + // pass through filters (if any) + if len(c.containerFilters)+len(webService.filters)+len(route.Filters) > 0 { + // compose filter chain + allFilters := []FilterFunction{} + allFilters = append(allFilters, c.containerFilters...) + allFilters = append(allFilters, webService.filters...) + allFilters = append(allFilters, route.Filters...) + chain := FilterChain{Filters: allFilters, Target: func(req *Request, resp *Response) { + // handle request by route after passing all filters + route.Function(wrappedRequest, wrappedResponse) + }} + chain.ProcessFilter(wrappedRequest, wrappedResponse) + } else { + // no filters, handle request by route + route.Function(wrappedRequest, wrappedResponse) + } +} + +// fixedPrefixPath returns the fixed part of the partspec ; it may include template vars {} +func fixedPrefixPath(pathspec string) string { + varBegin := strings.Index(pathspec, "{") + if -1 == varBegin { + return pathspec + } + return pathspec[:varBegin] +} + +// ServeHTTP implements net/http.Handler therefore a Container can be a Handler in a http.Server +func (c *Container) ServeHTTP(httpwriter http.ResponseWriter, httpRequest *http.Request) { + c.ServeMux.ServeHTTP(httpwriter, httpRequest) +} + +// Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics. +func (c *Container) Handle(pattern string, handler http.Handler) { + c.ServeMux.Handle(pattern, handler) +} + +// HandleWithFilter registers the handler for the given pattern. +// Container's filter chain is applied for handler. +// If a handler already exists for pattern, HandleWithFilter panics. +func (c *Container) HandleWithFilter(pattern string, handler http.Handler) { + f := func(httpResponse http.ResponseWriter, httpRequest *http.Request) { + if len(c.containerFilters) == 0 { + handler.ServeHTTP(httpResponse, httpRequest) + return + } + + chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) { + handler.ServeHTTP(httpResponse, httpRequest) + }} + chain.ProcessFilter(NewRequest(httpRequest), NewResponse(httpResponse)) + } + + c.Handle(pattern, http.HandlerFunc(f)) +} + +// Filter appends a container FilterFunction. These are called before dispatching +// a http.Request to a WebService from the container +func (c *Container) Filter(filter FilterFunction) { + c.containerFilters = append(c.containerFilters, filter) +} + +// RegisteredWebServices returns the collections of added WebServices +func (c *Container) RegisteredWebServices() []*WebService { + c.webServicesLock.RLock() + defer c.webServicesLock.RUnlock() + result := make([]*WebService, len(c.webServices)) + for ix := range c.webServices { + result[ix] = c.webServices[ix] + } + return result +} + +// computeAllowedMethods returns a list of HTTP methods that are valid for a Request +func (c *Container) computeAllowedMethods(req *Request) []string { + // Go through all RegisteredWebServices() and all its Routes to collect the options + methods := []string{} + requestPath := req.Request.URL.Path + for _, ws := range c.RegisteredWebServices() { + matches := ws.pathExpr.Matcher.FindStringSubmatch(requestPath) + if matches != nil { + finalMatch := matches[len(matches)-1] + for _, rt := range ws.Routes() { + matches := rt.pathExpr.Matcher.FindStringSubmatch(finalMatch) + if matches != nil { + lastMatch := matches[len(matches)-1] + if lastMatch == "" || lastMatch == "/" { // do not include if value is neither empty nor ‘/’. + methods = append(methods, rt.Method) + } + } + } + } + } + // methods = append(methods, "OPTIONS") not sure about this + return methods +} + +// newBasicRequestResponse creates a pair of Request,Response from its http versions. +// It is basic because no parameter or (produces) content-type information is given. +func newBasicRequestResponse(httpWriter http.ResponseWriter, httpRequest *http.Request) (*Request, *Response) { + resp := NewResponse(httpWriter) + resp.requestAccept = httpRequest.Header.Get(HEADER_Accept) + return NewRequest(httpRequest), resp +} diff --git a/vendor/github.com/emicklei/go-restful/container_test.go b/vendor/github.com/emicklei/go-restful/container_test.go new file mode 100644 index 00000000..491c793a --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/container_test.go @@ -0,0 +1,83 @@ +package restful + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +// go test -v -test.run TestContainer_computeAllowedMethods ...restful +func TestContainer_computeAllowedMethods(t *testing.T) { + wc := NewContainer() + ws1 := new(WebService).Path("/users") + ws1.Route(ws1.GET("{i}").To(dummy)) + ws1.Route(ws1.POST("{i}").To(dummy)) + wc.Add(ws1) + httpRequest, _ := http.NewRequest("GET", "http://api.his.com/users/1", nil) + rreq := Request{Request: httpRequest} + m := wc.computeAllowedMethods(&rreq) + if len(m) != 2 { + t.Errorf("got %d expected 2 methods, %v", len(m), m) + } +} + +func TestContainer_HandleWithFilter(t *testing.T) { + prefilterCalled := false + postfilterCalled := false + httpHandlerCalled := false + + wc := NewContainer() + wc.Filter(func(request *Request, response *Response, chain *FilterChain) { + prefilterCalled = true + chain.ProcessFilter(request, response) + }) + wc.HandleWithFilter("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + httpHandlerCalled = true + w.Write([]byte("ok")) + })) + wc.Filter(func(request *Request, response *Response, chain *FilterChain) { + postfilterCalled = true + chain.ProcessFilter(request, response) + }) + + recorder := httptest.NewRecorder() + request, _ := http.NewRequest("GET", "/", nil) + wc.ServeHTTP(recorder, request) + if recorder.Code != http.StatusOK { + t.Errorf("unexpected code %d", recorder.Code) + } + if recorder.Body.String() != "ok" { + t.Errorf("unexpected body %s", recorder.Body.String()) + } + if !prefilterCalled { + t.Errorf("filter added before calling HandleWithFilter wasn't called") + } + if !postfilterCalled { + t.Errorf("filter added after calling HandleWithFilter wasn't called") + } + if !httpHandlerCalled { + t.Errorf("handler added by calling HandleWithFilter wasn't called") + } +} + +func TestContainerAddAndRemove(t *testing.T) { + ws1 := new(WebService).Path("/") + ws2 := new(WebService).Path("/users") + wc := NewContainer() + wc.Add(ws1) + wc.Add(ws2) + wc.Remove(ws2) + if len(wc.webServices) != 1 { + t.Errorf("expected one webservices") + } + if !wc.isRegisteredOnRoot { + t.Errorf("expected on root registered") + } + wc.Remove(ws1) + if len(wc.webServices) > 0 { + t.Errorf("expected zero webservices") + } + if wc.isRegisteredOnRoot { + t.Errorf("expected not on root registered") + } +} diff --git a/vendor/github.com/emicklei/go-restful/cors_filter.go b/vendor/github.com/emicklei/go-restful/cors_filter.go new file mode 100644 index 00000000..1efeef07 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/cors_filter.go @@ -0,0 +1,202 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "regexp" + "strconv" + "strings" +) + +// CrossOriginResourceSharing is used to create a Container Filter that implements CORS. +// Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page +// to make XMLHttpRequests to another domain, not the domain the JavaScript originated from. +// +// http://en.wikipedia.org/wiki/Cross-origin_resource_sharing +// http://enable-cors.org/server.html +// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request +type CrossOriginResourceSharing struct { + ExposeHeaders []string // list of Header names + AllowedHeaders []string // list of Header names + AllowedDomains []string // list of allowed values for Http Origin. An allowed value can be a regular expression to support subdomain matching. If empty all are allowed. + AllowedMethods []string + MaxAge int // number of seconds before requiring new Options request + CookiesAllowed bool + Container *Container + + allowedOriginPatterns []*regexp.Regexp // internal field for origin regexp check. +} + +// Filter is a filter function that implements the CORS flow as documented on http://enable-cors.org/server.html +// and http://www.html5rocks.com/static/images/cors_server_flowchart.png +func (c CrossOriginResourceSharing) Filter(req *Request, resp *Response, chain *FilterChain) { + origin := req.Request.Header.Get(HEADER_Origin) + if len(origin) == 0 { + if trace { + traceLogger.Print("no Http header Origin set") + } + chain.ProcessFilter(req, resp) + return + } + if !c.isOriginAllowed(origin) { // check whether this origin is allowed + if trace { + traceLogger.Printf("HTTP Origin:%s is not part of %v, neither matches any part of %v", origin, c.AllowedDomains, c.allowedOriginPatterns) + } + chain.ProcessFilter(req, resp) + return + } + if req.Request.Method != "OPTIONS" { + c.doActualRequest(req, resp) + chain.ProcessFilter(req, resp) + return + } + if acrm := req.Request.Header.Get(HEADER_AccessControlRequestMethod); acrm != "" { + c.doPreflightRequest(req, resp) + } else { + c.doActualRequest(req, resp) + chain.ProcessFilter(req, resp) + return + } +} + +func (c CrossOriginResourceSharing) doActualRequest(req *Request, resp *Response) { + c.setOptionsHeaders(req, resp) + // continue processing the response +} + +func (c *CrossOriginResourceSharing) doPreflightRequest(req *Request, resp *Response) { + if len(c.AllowedMethods) == 0 { + if c.Container == nil { + c.AllowedMethods = DefaultContainer.computeAllowedMethods(req) + } else { + c.AllowedMethods = c.Container.computeAllowedMethods(req) + } + } + + acrm := req.Request.Header.Get(HEADER_AccessControlRequestMethod) + if !c.isValidAccessControlRequestMethod(acrm, c.AllowedMethods) { + if trace { + traceLogger.Printf("Http header %s:%s is not in %v", + HEADER_AccessControlRequestMethod, + acrm, + c.AllowedMethods) + } + return + } + acrhs := req.Request.Header.Get(HEADER_AccessControlRequestHeaders) + if len(acrhs) > 0 { + for _, each := range strings.Split(acrhs, ",") { + if !c.isValidAccessControlRequestHeader(strings.Trim(each, " ")) { + if trace { + traceLogger.Printf("Http header %s:%s is not in %v", + HEADER_AccessControlRequestHeaders, + acrhs, + c.AllowedHeaders) + } + return + } + } + } + resp.AddHeader(HEADER_AccessControlAllowMethods, strings.Join(c.AllowedMethods, ",")) + resp.AddHeader(HEADER_AccessControlAllowHeaders, acrhs) + c.setOptionsHeaders(req, resp) + + // return http 200 response, no body +} + +func (c CrossOriginResourceSharing) setOptionsHeaders(req *Request, resp *Response) { + c.checkAndSetExposeHeaders(resp) + c.setAllowOriginHeader(req, resp) + c.checkAndSetAllowCredentials(resp) + if c.MaxAge > 0 { + resp.AddHeader(HEADER_AccessControlMaxAge, strconv.Itoa(c.MaxAge)) + } +} + +func (c CrossOriginResourceSharing) isOriginAllowed(origin string) bool { + if len(origin) == 0 { + return false + } + if len(c.AllowedDomains) == 0 { + return true + } + + allowed := false + for _, domain := range c.AllowedDomains { + if domain == origin { + allowed = true + break + } + } + + if !allowed { + if len(c.allowedOriginPatterns) == 0 { + // compile allowed domains to allowed origin patterns + allowedOriginRegexps, err := compileRegexps(c.AllowedDomains) + if err != nil { + return false + } + c.allowedOriginPatterns = allowedOriginRegexps + } + + for _, pattern := range c.allowedOriginPatterns { + if allowed = pattern.MatchString(origin); allowed { + break + } + } + } + + return allowed +} + +func (c CrossOriginResourceSharing) setAllowOriginHeader(req *Request, resp *Response) { + origin := req.Request.Header.Get(HEADER_Origin) + if c.isOriginAllowed(origin) { + resp.AddHeader(HEADER_AccessControlAllowOrigin, origin) + } +} + +func (c CrossOriginResourceSharing) checkAndSetExposeHeaders(resp *Response) { + if len(c.ExposeHeaders) > 0 { + resp.AddHeader(HEADER_AccessControlExposeHeaders, strings.Join(c.ExposeHeaders, ",")) + } +} + +func (c CrossOriginResourceSharing) checkAndSetAllowCredentials(resp *Response) { + if c.CookiesAllowed { + resp.AddHeader(HEADER_AccessControlAllowCredentials, "true") + } +} + +func (c CrossOriginResourceSharing) isValidAccessControlRequestMethod(method string, allowedMethods []string) bool { + for _, each := range allowedMethods { + if each == method { + return true + } + } + return false +} + +func (c CrossOriginResourceSharing) isValidAccessControlRequestHeader(header string) bool { + for _, each := range c.AllowedHeaders { + if strings.ToLower(each) == strings.ToLower(header) { + return true + } + } + return false +} + +// Take a list of strings and compile them into a list of regular expressions. +func compileRegexps(regexpStrings []string) ([]*regexp.Regexp, error) { + regexps := []*regexp.Regexp{} + for _, regexpStr := range regexpStrings { + r, err := regexp.Compile(regexpStr) + if err != nil { + return regexps, err + } + regexps = append(regexps, r) + } + return regexps, nil +} diff --git a/vendor/github.com/emicklei/go-restful/cors_filter_test.go b/vendor/github.com/emicklei/go-restful/cors_filter_test.go new file mode 100644 index 00000000..09c5d330 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/cors_filter_test.go @@ -0,0 +1,129 @@ +package restful + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +// go test -v -test.run TestCORSFilter_Preflight ...restful +// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request +func TestCORSFilter_Preflight(t *testing.T) { + tearDown() + ws := new(WebService) + ws.Route(ws.PUT("/cors").To(dummy)) + Add(ws) + + cors := CrossOriginResourceSharing{ + ExposeHeaders: []string{"X-Custom-Header"}, + AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, + CookiesAllowed: true, + Container: DefaultContainer} + Filter(cors.Filter) + + // Preflight + httpRequest, _ := http.NewRequest("OPTIONS", "http://api.alice.com/cors", nil) + httpRequest.Method = "OPTIONS" + httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") + httpRequest.Header.Set(HEADER_AccessControlRequestMethod, "PUT") + httpRequest.Header.Set(HEADER_AccessControlRequestHeaders, "X-Custom-Header, X-Additional-Header") + + httpWriter := httptest.NewRecorder() + DefaultContainer.Dispatch(httpWriter, httpRequest) + + actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) + if "http://api.bob.com" != actual { + t.Fatal("expected: http://api.bob.com but got:" + actual) + } + actual = httpWriter.Header().Get(HEADER_AccessControlAllowMethods) + if "PUT" != actual { + t.Fatal("expected: PUT but got:" + actual) + } + actual = httpWriter.Header().Get(HEADER_AccessControlAllowHeaders) + if "X-Custom-Header, X-Additional-Header" != actual { + t.Fatal("expected: X-Custom-Header, X-Additional-Header but got:" + actual) + } + + if !cors.isOriginAllowed("somewhere") { + t.Fatal("origin expected to be allowed") + } + cors.AllowedDomains = []string{"overthere.com"} + if cors.isOriginAllowed("somewhere") { + t.Fatal("origin [somewhere] expected NOT to be allowed") + } + if !cors.isOriginAllowed("overthere.com") { + t.Fatal("origin [overthere] expected to be allowed") + } + +} + +// go test -v -test.run TestCORSFilter_Actual ...restful +// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request +func TestCORSFilter_Actual(t *testing.T) { + tearDown() + ws := new(WebService) + ws.Route(ws.PUT("/cors").To(dummy)) + Add(ws) + + cors := CrossOriginResourceSharing{ + ExposeHeaders: []string{"X-Custom-Header"}, + AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, + CookiesAllowed: true, + Container: DefaultContainer} + Filter(cors.Filter) + + // Actual + httpRequest, _ := http.NewRequest("PUT", "http://api.alice.com/cors", nil) + httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") + httpRequest.Header.Set("X-Custom-Header", "value") + + httpWriter := httptest.NewRecorder() + DefaultContainer.Dispatch(httpWriter, httpRequest) + actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) + if "http://api.bob.com" != actual { + t.Fatal("expected: http://api.bob.com but got:" + actual) + } + if httpWriter.Body.String() != "dummy" { + t.Fatal("expected: dummy but got:" + httpWriter.Body.String()) + } +} + +var allowedDomainInput = []struct { + domains []string + origin string + allowed bool +}{ + {[]string{}, "http://anything.com", true}, + {[]string{"example.com"}, "example.com", true}, + {[]string{"example.com"}, "not-allowed", false}, + {[]string{"not-matching.com", "example.com"}, "example.com", true}, + {[]string{".*"}, "example.com", true}, +} + +// go test -v -test.run TestCORSFilter_AllowedDomains ...restful +func TestCORSFilter_AllowedDomains(t *testing.T) { + for _, each := range allowedDomainInput { + tearDown() + ws := new(WebService) + ws.Route(ws.PUT("/cors").To(dummy)) + Add(ws) + + cors := CrossOriginResourceSharing{ + AllowedDomains: each.domains, + CookiesAllowed: true, + Container: DefaultContainer} + Filter(cors.Filter) + + httpRequest, _ := http.NewRequest("PUT", "http://api.his.com/cors", nil) + httpRequest.Header.Set(HEADER_Origin, each.origin) + httpWriter := httptest.NewRecorder() + DefaultContainer.Dispatch(httpWriter, httpRequest) + actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) + if actual != each.origin && each.allowed { + t.Fatal("expected to be accepted") + } + if actual == each.origin && !each.allowed { + t.Fatal("did not expect to be accepted") + } + } +} diff --git a/vendor/github.com/emicklei/go-restful/coverage.sh b/vendor/github.com/emicklei/go-restful/coverage.sh new file mode 100644 index 00000000..e27dbf1a --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/coverage.sh @@ -0,0 +1,2 @@ +go test -coverprofile=coverage.out +go tool cover -html=coverage.out \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/curly.go b/vendor/github.com/emicklei/go-restful/curly.go new file mode 100644 index 00000000..79f1f5aa --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/curly.go @@ -0,0 +1,164 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "net/http" + "regexp" + "sort" + "strings" +) + +// CurlyRouter expects Routes with paths that contain zero or more parameters in curly brackets. +type CurlyRouter struct{} + +// SelectRoute is part of the Router interface and returns the best match +// for the WebService and its Route for the given Request. +func (c CurlyRouter) SelectRoute( + webServices []*WebService, + httpRequest *http.Request) (selectedService *WebService, selected *Route, err error) { + + requestTokens := tokenizePath(httpRequest.URL.Path) + + detectedService := c.detectWebService(requestTokens, webServices) + if detectedService == nil { + if trace { + traceLogger.Printf("no WebService was found to match URL path:%s\n", httpRequest.URL.Path) + } + return nil, nil, NewError(http.StatusNotFound, "404: Page Not Found") + } + candidateRoutes := c.selectRoutes(detectedService, requestTokens) + if len(candidateRoutes) == 0 { + if trace { + traceLogger.Printf("no Route in WebService with path %s was found to match URL path:%s\n", detectedService.rootPath, httpRequest.URL.Path) + } + return detectedService, nil, NewError(http.StatusNotFound, "404: Page Not Found") + } + selectedRoute, err := c.detectRoute(candidateRoutes, httpRequest) + if selectedRoute == nil { + return detectedService, nil, err + } + return detectedService, selectedRoute, nil +} + +// selectRoutes return a collection of Route from a WebService that matches the path tokens from the request. +func (c CurlyRouter) selectRoutes(ws *WebService, requestTokens []string) sortableCurlyRoutes { + candidates := sortableCurlyRoutes{} + for _, each := range ws.routes { + matches, paramCount, staticCount := c.matchesRouteByPathTokens(each.pathParts, requestTokens) + if matches { + candidates.add(curlyRoute{each, paramCount, staticCount}) // TODO make sure Routes() return pointers? + } + } + sort.Sort(sort.Reverse(candidates)) + return candidates +} + +// matchesRouteByPathTokens computes whether it matches, howmany parameters do match and what the number of static path elements are. +func (c CurlyRouter) matchesRouteByPathTokens(routeTokens, requestTokens []string) (matches bool, paramCount int, staticCount int) { + if len(routeTokens) < len(requestTokens) { + // proceed in matching only if last routeToken is wildcard + count := len(routeTokens) + if count == 0 || !strings.HasSuffix(routeTokens[count-1], "*}") { + return false, 0, 0 + } + // proceed + } + for i, routeToken := range routeTokens { + if i == len(requestTokens) { + // reached end of request path + return false, 0, 0 + } + requestToken := requestTokens[i] + if strings.HasPrefix(routeToken, "{") { + paramCount++ + if colon := strings.Index(routeToken, ":"); colon != -1 { + // match by regex + matchesToken, matchesRemainder := c.regularMatchesPathToken(routeToken, colon, requestToken) + if !matchesToken { + return false, 0, 0 + } + if matchesRemainder { + break + } + } + } else { // no { prefix + if requestToken != routeToken { + return false, 0, 0 + } + staticCount++ + } + } + return true, paramCount, staticCount +} + +// regularMatchesPathToken tests whether the regular expression part of routeToken matches the requestToken or all remaining tokens +// format routeToken is {someVar:someExpression}, e.g. {zipcode:[\d][\d][\d][\d][A-Z][A-Z]} +func (c CurlyRouter) regularMatchesPathToken(routeToken string, colon int, requestToken string) (matchesToken bool, matchesRemainder bool) { + regPart := routeToken[colon+1 : len(routeToken)-1] + if regPart == "*" { + if trace { + traceLogger.Printf("wildcard parameter detected in route token %s that matches %s\n", routeToken, requestToken) + } + return true, true + } + matched, err := regexp.MatchString(regPart, requestToken) + return (matched && err == nil), false +} + +var jsr311Router = RouterJSR311{} + +// detectRoute selectes from a list of Route the first match by inspecting both the Accept and Content-Type +// headers of the Request. See also RouterJSR311 in jsr311.go +func (c CurlyRouter) detectRoute(candidateRoutes sortableCurlyRoutes, httpRequest *http.Request) (*Route, error) { + // tracing is done inside detectRoute + return jsr311Router.detectRoute(candidateRoutes.routes(), httpRequest) +} + +// detectWebService returns the best matching webService given the list of path tokens. +// see also computeWebserviceScore +func (c CurlyRouter) detectWebService(requestTokens []string, webServices []*WebService) *WebService { + var best *WebService + score := -1 + for _, each := range webServices { + matches, eachScore := c.computeWebserviceScore(requestTokens, each.pathExpr.tokens) + if matches && (eachScore > score) { + best = each + score = eachScore + } + } + return best +} + +// computeWebserviceScore returns whether tokens match and +// the weighted score of the longest matching consecutive tokens from the beginning. +func (c CurlyRouter) computeWebserviceScore(requestTokens []string, tokens []string) (bool, int) { + if len(tokens) > len(requestTokens) { + return false, 0 + } + score := 0 + for i := 0; i < len(tokens); i++ { + each := requestTokens[i] + other := tokens[i] + if len(each) == 0 && len(other) == 0 { + score++ + continue + } + if len(other) > 0 && strings.HasPrefix(other, "{") { + // no empty match + if len(each) == 0 { + return false, score + } + score += 1 + } else { + // not a parameter + if each != other { + return false, score + } + score += (len(tokens) - i) * 10 //fuzzy + } + } + return true, score +} diff --git a/vendor/github.com/emicklei/go-restful/curly_route.go b/vendor/github.com/emicklei/go-restful/curly_route.go new file mode 100644 index 00000000..296f9465 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/curly_route.go @@ -0,0 +1,52 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +// curlyRoute exits for sorting Routes by the CurlyRouter based on number of parameters and number of static path elements. +type curlyRoute struct { + route Route + paramCount int + staticCount int +} + +type sortableCurlyRoutes []curlyRoute + +func (s *sortableCurlyRoutes) add(route curlyRoute) { + *s = append(*s, route) +} + +func (s sortableCurlyRoutes) routes() (routes []Route) { + for _, each := range s { + routes = append(routes, each.route) // TODO change return type + } + return routes +} + +func (s sortableCurlyRoutes) Len() int { + return len(s) +} +func (s sortableCurlyRoutes) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} +func (s sortableCurlyRoutes) Less(i, j int) bool { + ci := s[i] + cj := s[j] + + // primary key + if ci.staticCount < cj.staticCount { + return true + } + if ci.staticCount > cj.staticCount { + return false + } + // secundary key + if ci.paramCount < cj.paramCount { + return true + } + if ci.paramCount > cj.paramCount { + return false + } + return ci.route.Path < cj.route.Path +} diff --git a/vendor/github.com/emicklei/go-restful/curly_test.go b/vendor/github.com/emicklei/go-restful/curly_test.go new file mode 100644 index 00000000..bec017ca --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/curly_test.go @@ -0,0 +1,231 @@ +package restful + +import ( + "io" + "net/http" + "testing" +) + +var requestPaths = []struct { + // url with path (1) is handled by service with root (2) and remainder has value final (3) + path, root string +}{ + {"/", "/"}, + {"/p", "/p"}, + {"/p/x", "/p/{q}"}, + {"/q/x", "/q"}, + {"/p/x/", "/p/{q}"}, + {"/p/x/y", "/p/{q}"}, + {"/q/x/y", "/q"}, + {"/z/q", "/{p}/q"}, + {"/a/b/c/q", "/"}, +} + +// go test -v -test.run TestCurlyDetectWebService ...restful +func TestCurlyDetectWebService(t *testing.T) { + ws1 := new(WebService).Path("/") + ws2 := new(WebService).Path("/p") + ws3 := new(WebService).Path("/q") + ws4 := new(WebService).Path("/p/q") + ws5 := new(WebService).Path("/p/{q}") + ws7 := new(WebService).Path("/{p}/q") + var wss = []*WebService{ws1, ws2, ws3, ws4, ws5, ws7} + + for _, each := range wss { + t.Logf("path=%s,toks=%v\n", each.pathExpr.Source, each.pathExpr.tokens) + } + + router := CurlyRouter{} + + ok := true + for i, fixture := range requestPaths { + requestTokens := tokenizePath(fixture.path) + who := router.detectWebService(requestTokens, wss) + if who != nil && who.RootPath() != fixture.root { + t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) + ok = false + } + } + if !ok { + t.Fail() + } +} + +var serviceDetects = []struct { + path string + found bool + root string +}{ + {"/a/b", true, "/{p}/{q}/{r}"}, + {"/p/q", true, "/p/q"}, + {"/q/p", true, "/q"}, + {"/", true, "/"}, + {"/p/q/r", true, "/p/q"}, +} + +// go test -v -test.run Test_detectWebService ...restful +func Test_detectWebService(t *testing.T) { + router := CurlyRouter{} + ws1 := new(WebService).Path("/") + ws2 := new(WebService).Path("/p") + ws3 := new(WebService).Path("/q") + ws4 := new(WebService).Path("/p/q") + ws5 := new(WebService).Path("/p/{q}") + ws6 := new(WebService).Path("/p/{q}/") + ws7 := new(WebService).Path("/{p}/q") + ws8 := new(WebService).Path("/{p}/{q}/{r}") + var wss = []*WebService{ws8, ws7, ws6, ws5, ws4, ws3, ws2, ws1} + for _, fix := range serviceDetects { + requestPath := fix.path + requestTokens := tokenizePath(requestPath) + for _, ws := range wss { + serviceTokens := ws.pathExpr.tokens + matches, score := router.computeWebserviceScore(requestTokens, serviceTokens) + t.Logf("req=%s,toks:%v,ws=%s,toks:%v,score=%d,matches=%v", requestPath, requestTokens, ws.RootPath(), serviceTokens, score, matches) + } + best := router.detectWebService(requestTokens, wss) + if best != nil { + if fix.found { + t.Logf("best=%s", best.RootPath()) + } else { + t.Fatalf("should have found:%s", fix.root) + } + } + } +} + +var routeMatchers = []struct { + route string + path string + matches bool + paramCount int + staticCount int +}{ + // route, request-path + {"/a", "/a", true, 0, 1}, + {"/a", "/b", false, 0, 0}, + {"/a", "/b", false, 0, 0}, + {"/a/{b}/c/", "/a/2/c", true, 1, 2}, + {"/{a}/{b}/{c}/", "/a/b", false, 0, 0}, + {"/{x:*}", "/", false, 0, 0}, + {"/{x:*}", "/a", true, 1, 0}, + {"/{x:*}", "/a/b", true, 1, 0}, + {"/a/{x:*}", "/a/b", true, 1, 1}, + {"/a/{x:[A-Z][A-Z]}", "/a/ZX", true, 1, 1}, + {"/basepath/{resource:*}", "/basepath/some/other/location/test.xml", true, 1, 1}, +} + +// clear && go test -v -test.run Test_matchesRouteByPathTokens ...restful +func Test_matchesRouteByPathTokens(t *testing.T) { + router := CurlyRouter{} + for i, each := range routeMatchers { + routeToks := tokenizePath(each.route) + reqToks := tokenizePath(each.path) + matches, pCount, sCount := router.matchesRouteByPathTokens(routeToks, reqToks) + if matches != each.matches { + t.Fatalf("[%d] unexpected matches outcome route:%s, path:%s, matches:%v", i, each.route, each.path, matches) + } + if pCount != each.paramCount { + t.Fatalf("[%d] unexpected paramCount got:%d want:%d ", i, pCount, each.paramCount) + } + if sCount != each.staticCount { + t.Fatalf("[%d] unexpected staticCount got:%d want:%d ", i, sCount, each.staticCount) + } + } +} + +// clear && go test -v -test.run TestExtractParameters_Wildcard1 ...restful +func TestExtractParameters_Wildcard1(t *testing.T) { + params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remainder", t) + if params["var"] != "remainder" { + t.Errorf("parameter mismatch var: %s", params["var"]) + } +} + +// clear && go test -v -test.run TestExtractParameters_Wildcard2 ...restful +func TestExtractParameters_Wildcard2(t *testing.T) { + params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remain/der", t) + if params["var"] != "remain/der" { + t.Errorf("parameter mismatch var: %s", params["var"]) + } +} + +// clear && go test -v -test.run TestExtractParameters_Wildcard3 ...restful +func TestExtractParameters_Wildcard3(t *testing.T) { + params := doExtractParams("/static/{var:*}", 2, "/static/test/sub/hi.html", t) + if params["var"] != "test/sub/hi.html" { + t.Errorf("parameter mismatch var: %s", params["var"]) + } +} + +// clear && go test -v -test.run TestCurly_ISSUE_34 ...restful +func TestCurly_ISSUE_34(t *testing.T) { + ws1 := new(WebService).Path("/") + ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) + ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) + croutes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) + if len(croutes) != 2 { + t.Fatal("expected 2 routes") + } + if got, want := croutes[0].route.Path, "/network/{id}"; got != want { + t.Errorf("got %v want %v", got, want) + } +} + +// clear && go test -v -test.run TestCurly_ISSUE_34_2 ...restful +func TestCurly_ISSUE_34_2(t *testing.T) { + ws1 := new(WebService) + ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) + ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) + croutes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) + if len(croutes) != 2 { + t.Fatal("expected 2 routes") + } + if got, want := croutes[0].route.Path, "/network/{id}"; got != want { + t.Errorf("got %v want %v", got, want) + } +} + +// clear && go test -v -test.run TestCurly_JsonHtml ...restful +func TestCurly_JsonHtml(t *testing.T) { + ws1 := new(WebService) + ws1.Path("/") + ws1.Route(ws1.GET("/some.html").To(curlyDummy).Consumes("*/*").Produces("text/html")) + req, _ := http.NewRequest("GET", "/some.html", nil) + req.Header.Set("Accept", "application/json") + _, route, err := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) + if err == nil { + t.Error("error expected") + } + if route != nil { + t.Error("no route expected") + } +} + +// go test -v -test.run TestCurly_ISSUE_137 ...restful +func TestCurly_ISSUE_137(t *testing.T) { + ws1 := new(WebService) + ws1.Route(ws1.GET("/hello").To(curlyDummy)) + ws1.Path("/") + req, _ := http.NewRequest("GET", "/", nil) + _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) + t.Log(route) + if route != nil { + t.Error("no route expected") + } +} + +// go test -v -test.run TestCurly_ISSUE_137_2 ...restful +func TestCurly_ISSUE_137_2(t *testing.T) { + ws1 := new(WebService) + ws1.Route(ws1.GET("/hello").To(curlyDummy)) + ws1.Path("/") + req, _ := http.NewRequest("GET", "/hello/bob", nil) + _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) + t.Log(route) + if route != nil { + t.Errorf("no route expected, got %v", route) + } +} + +func curlyDummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "curlyDummy") } diff --git a/vendor/github.com/emicklei/go-restful/doc.go b/vendor/github.com/emicklei/go-restful/doc.go new file mode 100644 index 00000000..21b26ac5 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/doc.go @@ -0,0 +1,185 @@ +/* +Package restful, a lean package for creating REST-style WebServices without magic. + +WebServices and Routes + +A WebService has a collection of Route objects that dispatch incoming Http Requests to a function calls. +Typically, a WebService has a root path (e.g. /users) and defines common MIME types for its routes. +WebServices must be added to a container (see below) in order to handler Http requests from a server. + +A Route is defined by a HTTP method, an URL path and (optionally) the MIME types it consumes (Content-Type) and produces (Accept). +This package has the logic to find the best matching Route and if found, call its Function. + + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes(restful.MIME_JSON, restful.MIME_XML). + Produces(restful.MIME_JSON, restful.MIME_XML) + + ws.Route(ws.GET("/{user-id}").To(u.findUser)) // u is a UserResource + + ... + + // GET http://localhost:8080/users/1 + func (u UserResource) findUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + ... + } + +The (*Request, *Response) arguments provide functions for reading information from the request and writing information back to the response. + +See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-user-resource.go with a full implementation. + +Regular expression matching Routes + +A Route parameter can be specified using the format "uri/{var[:regexp]}" or the special version "uri/{var:*}" for matching the tail of the path. +For example, /persons/{name:[A-Z][A-Z]} can be used to restrict values for the parameter "name" to only contain capital alphabetic characters. +Regular expressions must use the standard Go syntax as described in the regexp package. (https://code.google.com/p/re2/wiki/Syntax) +This feature requires the use of a CurlyRouter. + +Containers + +A Container holds a collection of WebServices, Filters and a http.ServeMux for multiplexing http requests. +Using the statements "restful.Add(...) and restful.Filter(...)" will register WebServices and Filters to the Default Container. +The Default container of go-restful uses the http.DefaultServeMux. +You can create your own Container and create a new http.Server for that particular container. + + container := restful.NewContainer() + server := &http.Server{Addr: ":8081", Handler: container} + +Filters + +A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. +You can use filters to perform generic logging, measurement, authentication, redirect, set response headers etc. +In the restful package there are three hooks into the request,response flow where filters can be added. +Each filter must define a FilterFunction: + + func (req *restful.Request, resp *restful.Response, chain *restful.FilterChain) + +Use the following statement to pass the request,response pair to the next filter or RouteFunction + + chain.ProcessFilter(req, resp) + +Container Filters + +These are processed before any registered WebService. + + // install a (global) filter for the default container (processed before any webservice) + restful.Filter(globalLogging) + +WebService Filters + +These are processed before any Route of a WebService. + + // install a webservice filter (processed before any route) + ws.Filter(webserviceLogging).Filter(measureTime) + + +Route Filters + +These are processed before calling the function associated with the Route. + + // install 2 chained route filters (processed before calling findUser) + ws.Route(ws.GET("/{user-id}").Filter(routeLogging).Filter(NewCountFilter().routeCounter).To(findUser)) + +See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-filters.go with full implementations. + +Response Encoding + +Two encodings are supported: gzip and deflate. To enable this for all responses: + + restful.DefaultContainer.EnableContentEncoding(true) + +If a Http request includes the Accept-Encoding header then the response content will be compressed using the specified encoding. +Alternatively, you can create a Filter that performs the encoding and install it per WebService or Route. + +See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-encoding-filter.go + +OPTIONS support + +By installing a pre-defined container filter, your Webservice(s) can respond to the OPTIONS Http request. + + Filter(OPTIONSFilter()) + +CORS + +By installing the filter of a CrossOriginResourceSharing (CORS), your WebService(s) can handle CORS requests. + + cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} + Filter(cors.Filter) + +Error Handling + +Unexpected things happen. If a request cannot be processed because of a failure, your service needs to tell via the response what happened and why. +For this reason HTTP status codes exist and it is important to use the correct code in every exceptional situation. + + 400: Bad Request + +If path or query parameters are not valid (content or type) then use http.StatusBadRequest. + + 404: Not Found + +Despite a valid URI, the resource requested may not be available + + 500: Internal Server Error + +If the application logic could not process the request (or write the response) then use http.StatusInternalServerError. + + 405: Method Not Allowed + +The request has a valid URL but the method (GET,PUT,POST,...) is not allowed. + + 406: Not Acceptable + +The request does not have or has an unknown Accept Header set for this operation. + + 415: Unsupported Media Type + +The request does not have or has an unknown Content-Type Header set for this operation. + +ServiceError + +In addition to setting the correct (error) Http status code, you can choose to write a ServiceError message on the response. + +Performance options + +This package has several options that affect the performance of your service. It is important to understand them and how you can change it. + + restful.DefaultContainer.DoNotRecover(false) + +DoNotRecover controls whether panics will be caught to return HTTP 500. +If set to false, the container will recover from panics. +Default value is true + + restful.SetCompressorProvider(NewBoundedCachedCompressors(20, 20)) + +If content encoding is enabled then the default strategy for getting new gzip/zlib writers and readers is to use a sync.Pool. +Because writers are expensive structures, performance is even more improved when using a preloaded cache. You can also inject your own implementation. + +Trouble shooting + +This package has the means to produce detail logging of the complete Http request matching process and filter invocation. +Enabling this feature requires you to set an implementation of restful.StdLogger (e.g. log.Logger) instance such as: + + restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) + +Logging + +The restful.SetLogger() method allows you to override the logger used by the package. By default restful +uses the standard library `log` package and logs to stdout. Different logging packages are supported as +long as they conform to `StdLogger` interface defined in the `log` sub-package, writing an adapter for your +preferred package is simple. + +Resources + +[project]: https://github.com/emicklei/go-restful + +[examples]: https://github.com/emicklei/go-restful/blob/master/examples + +[design]: http://ernestmicklei.com/2012/11/11/go-restful-api-design/ + +[showcases]: https://github.com/emicklei/mora, https://github.com/emicklei/landskape + +(c) 2012-2015, http://ernestmicklei.com. MIT License +*/ +package restful diff --git a/vendor/github.com/emicklei/go-restful/doc_examples_test.go b/vendor/github.com/emicklei/go-restful/doc_examples_test.go new file mode 100644 index 00000000..0af636e5 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/doc_examples_test.go @@ -0,0 +1,41 @@ +package restful + +import "net/http" + +func ExampleOPTIONSFilter() { + // Install the OPTIONS filter on the default Container + Filter(OPTIONSFilter()) +} +func ExampleContainer_OPTIONSFilter() { + // Install the OPTIONS filter on a Container + myContainer := new(Container) + myContainer.Filter(myContainer.OPTIONSFilter) +} + +func ExampleContainer() { + // The Default container of go-restful uses the http.DefaultServeMux. + // You can create your own Container using restful.NewContainer() and create a new http.Server for that particular container + + ws := new(WebService) + wsContainer := NewContainer() + wsContainer.Add(ws) + server := &http.Server{Addr: ":8080", Handler: wsContainer} + server.ListenAndServe() +} + +func ExampleCrossOriginResourceSharing() { + // To install this filter on the Default Container use: + cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} + Filter(cors.Filter) +} + +func ExampleServiceError() { + resp := new(Response) + resp.WriteEntity(NewError(http.StatusBadRequest, "Non-integer {id} path parameter")) +} + +func ExampleBoundedCachedCompressors() { + // Register a compressor provider (gzip/deflate read/write) that uses + // a bounded cache with a maximum of 20 writers and 20 readers. + SetCompressorProvider(NewBoundedCachedCompressors(20, 20)) +} diff --git a/vendor/github.com/emicklei/go-restful/entity_accessors.go b/vendor/github.com/emicklei/go-restful/entity_accessors.go new file mode 100644 index 00000000..6ecf6c7f --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/entity_accessors.go @@ -0,0 +1,163 @@ +package restful + +// Copyright 2015 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "encoding/json" + "encoding/xml" + "strings" + "sync" +) + +// EntityReaderWriter can read and write values using an encoding such as JSON,XML. +type EntityReaderWriter interface { + // Read a serialized version of the value from the request. + // The Request may have a decompressing reader. Depends on Content-Encoding. + Read(req *Request, v interface{}) error + + // Write a serialized version of the value on the response. + // The Response may have a compressing writer. Depends on Accept-Encoding. + // status should be a valid Http Status code + Write(resp *Response, status int, v interface{}) error +} + +// entityAccessRegistry is a singleton +var entityAccessRegistry = &entityReaderWriters{ + protection: new(sync.RWMutex), + accessors: map[string]EntityReaderWriter{}, +} + +// entityReaderWriters associates MIME to an EntityReaderWriter +type entityReaderWriters struct { + protection *sync.RWMutex + accessors map[string]EntityReaderWriter +} + +func init() { + RegisterEntityAccessor(MIME_JSON, NewEntityAccessorJSON(MIME_JSON)) + RegisterEntityAccessor(MIME_XML, NewEntityAccessorXML(MIME_XML)) +} + +// RegisterEntityAccessor add/overrides the ReaderWriter for encoding content with this MIME type. +func RegisterEntityAccessor(mime string, erw EntityReaderWriter) { + entityAccessRegistry.protection.Lock() + defer entityAccessRegistry.protection.Unlock() + entityAccessRegistry.accessors[mime] = erw +} + +// NewEntityAccessorJSON returns a new EntityReaderWriter for accessing JSON content. +// This package is already initialized with such an accessor using the MIME_JSON contentType. +func NewEntityAccessorJSON(contentType string) EntityReaderWriter { + return entityJSONAccess{ContentType: contentType} +} + +// NewEntityAccessorXML returns a new EntityReaderWriter for accessing XML content. +// This package is already initialized with such an accessor using the MIME_XML contentType. +func NewEntityAccessorXML(contentType string) EntityReaderWriter { + return entityXMLAccess{ContentType: contentType} +} + +// accessorAt returns the registered ReaderWriter for this MIME type. +func (r *entityReaderWriters) accessorAt(mime string) (EntityReaderWriter, bool) { + r.protection.RLock() + defer r.protection.RUnlock() + er, ok := r.accessors[mime] + if !ok { + // retry with reverse lookup + // more expensive but we are in an exceptional situation anyway + for k, v := range r.accessors { + if strings.Contains(mime, k) { + return v, true + } + } + } + return er, ok +} + +// entityXMLAccess is a EntityReaderWriter for XML encoding +type entityXMLAccess struct { + // This is used for setting the Content-Type header when writing + ContentType string +} + +// Read unmarshalls the value from XML +func (e entityXMLAccess) Read(req *Request, v interface{}) error { + return xml.NewDecoder(req.Request.Body).Decode(v) +} + +// Write marshalls the value to JSON and set the Content-Type Header. +func (e entityXMLAccess) Write(resp *Response, status int, v interface{}) error { + return writeXML(resp, status, e.ContentType, v) +} + +// writeXML marshalls the value to JSON and set the Content-Type Header. +func writeXML(resp *Response, status int, contentType string, v interface{}) error { + if v == nil { + resp.WriteHeader(status) + // do not write a nil representation + return nil + } + if resp.prettyPrint { + // pretty output must be created and written explicitly + output, err := xml.MarshalIndent(v, " ", " ") + if err != nil { + return err + } + resp.Header().Set(HEADER_ContentType, contentType) + resp.WriteHeader(status) + _, err = resp.Write([]byte(xml.Header)) + if err != nil { + return err + } + _, err = resp.Write(output) + return err + } + // not-so-pretty + resp.Header().Set(HEADER_ContentType, contentType) + resp.WriteHeader(status) + return xml.NewEncoder(resp).Encode(v) +} + +// entityJSONAccess is a EntityReaderWriter for JSON encoding +type entityJSONAccess struct { + // This is used for setting the Content-Type header when writing + ContentType string +} + +// Read unmarshalls the value from JSON +func (e entityJSONAccess) Read(req *Request, v interface{}) error { + decoder := json.NewDecoder(req.Request.Body) + decoder.UseNumber() + return decoder.Decode(v) +} + +// Write marshalls the value to JSON and set the Content-Type Header. +func (e entityJSONAccess) Write(resp *Response, status int, v interface{}) error { + return writeJSON(resp, status, e.ContentType, v) +} + +// write marshalls the value to JSON and set the Content-Type Header. +func writeJSON(resp *Response, status int, contentType string, v interface{}) error { + if v == nil { + resp.WriteHeader(status) + // do not write a nil representation + return nil + } + if resp.prettyPrint { + // pretty output must be created and written explicitly + output, err := json.MarshalIndent(v, " ", " ") + if err != nil { + return err + } + resp.Header().Set(HEADER_ContentType, contentType) + resp.WriteHeader(status) + _, err = resp.Write(output) + return err + } + // not-so-pretty + resp.Header().Set(HEADER_ContentType, contentType) + resp.WriteHeader(status) + return json.NewEncoder(resp).Encode(v) +} diff --git a/vendor/github.com/emicklei/go-restful/entity_accessors_test.go b/vendor/github.com/emicklei/go-restful/entity_accessors_test.go new file mode 100644 index 00000000..943093ae --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/entity_accessors_test.go @@ -0,0 +1,69 @@ +package restful + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "testing" +) + +type keyvalue struct { + readCalled bool + writeCalled bool +} + +func (kv *keyvalue) Read(req *Request, v interface{}) error { + //t := reflect.TypeOf(v) + //rv := reflect.ValueOf(v) + kv.readCalled = true + return nil +} + +func (kv *keyvalue) Write(resp *Response, status int, v interface{}) error { + t := reflect.TypeOf(v) + rv := reflect.ValueOf(v) + for ix := 0; ix < t.NumField(); ix++ { + sf := t.Field(ix) + io.WriteString(resp, sf.Name) + io.WriteString(resp, "=") + io.WriteString(resp, fmt.Sprintf("%v\n", rv.Field(ix).Interface())) + } + kv.writeCalled = true + return nil +} + +// go test -v -test.run TestKeyValueEncoding ...restful +func TestKeyValueEncoding(t *testing.T) { + type Book struct { + Title string + Author string + PublishedYear int + } + kv := new(keyvalue) + RegisterEntityAccessor("application/kv", kv) + b := Book{"Singing for Dummies", "john doe", 2015} + + // Write + httpWriter := httptest.NewRecorder() + // Accept Produces + resp := Response{httpWriter, "application/kv,*/*;q=0.8", []string{"application/kv"}, 0, 0, true, nil} + resp.WriteEntity(b) + t.Log(string(httpWriter.Body.Bytes())) + if !kv.writeCalled { + t.Error("Write never called") + } + + // Read + bodyReader := bytes.NewReader(httpWriter.Body.Bytes()) + httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) + httpRequest.Header.Set("Content-Type", "application/kv; charset=UTF-8") + request := NewRequest(httpRequest) + var bb Book + request.ReadEntity(&bb) + if !kv.readCalled { + t.Error("Read never called") + } +} diff --git a/vendor/github.com/emicklei/go-restful/examples/.goconvey b/vendor/github.com/emicklei/go-restful/examples/.goconvey new file mode 100644 index 00000000..8485e986 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/.goconvey @@ -0,0 +1 @@ +ignore \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/examples/google_app_engine/.goconvey b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/.goconvey new file mode 100644 index 00000000..8485e986 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/.goconvey @@ -0,0 +1 @@ +ignore \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/examples/google_app_engine/app.yaml b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/app.yaml new file mode 100644 index 00000000..362db6b0 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/app.yaml @@ -0,0 +1,20 @@ +# +# Include your application ID here +# +application: +version: 1 +runtime: go +api_version: go1 + +handlers: +# +# Regex for all swagger files to make as static content. +# You should create the folder static/swagger and copy +# swagger-ui into it. +# +- url: /apidocs/(.*?)/(.*\.(js|html|css)) + static_files: static/swagger/\1/\2 + upload: static/swagger/(.*?)/(.*\.(js|html|css)) + +- url: /.* + script: _go_app diff --git a/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/.goconvey b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/.goconvey new file mode 100644 index 00000000..8485e986 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/.goconvey @@ -0,0 +1 @@ +ignore \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/app.yaml b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/app.yaml new file mode 100644 index 00000000..1ac9dca2 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/app.yaml @@ -0,0 +1,18 @@ +application: +version: 1 +runtime: go +api_version: go1 + +handlers: +# Regex for all swagger files to make as static content. +# You should create the folder static/swagger and copy +# swagger-ui into it. +# +- url: /apidocs/(.*?)/(.*\.(js|html|css)) + static_files: static/swagger/\1/\2 + upload: static/swagger/(.*?)/(.*\.(js|html|css)) + +# Catch all. +- url: /.* + script: _go_app + login: required diff --git a/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/main.go b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/main.go new file mode 100644 index 00000000..ca290818 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/main.go @@ -0,0 +1,266 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "github.com/emicklei/go-restful/swagger" + "google.golang.org/appengine" + "google.golang.org/appengine/datastore" + "google.golang.org/appengine/user" + "net/http" + "time" +) + +// This example demonstrates a reasonably complete suite of RESTful operations backed +// by DataStore on Google App Engine. + +// Our simple example struct. +type Profile struct { + LastModified time.Time `json:"-" xml:"-"` + Email string `json:"-" xml:"-"` + FirstName string `json:"first_name" xml:"first-name"` + NickName string `json:"nick_name" xml:"nick-name"` + LastName string `json:"last_name" xml:"last-name"` +} + +type ProfileApi struct { + Path string +} + +func gaeUrl() string { + if appengine.IsDevAppServer() { + return "http://localhost:8080" + } else { + // Include your URL on App Engine here. + // I found no way to get AppID without appengine.Context and this always + // based on a http.Request. + return "http://federatedservices.appspot.com" + } +} + +func init() { + u := ProfileApi{Path: "/profiles"} + u.register() + + // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API + // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. + // Open .appspot.com/apidocs and enter + // Place the Swagger UI files into a folder called static/swagger if you wish to use Swagger + // http://.appspot.com/apidocs.json in the api input field. + // For testing, you can use http://localhost:8080/apidocs.json + config := swagger.Config{ + // You control what services are visible + WebServices: restful.RegisteredWebServices(), + WebServicesUrl: gaeUrl(), + ApiPath: "/apidocs.json", + + // Optionally, specifiy where the UI is located + SwaggerPath: "/apidocs/", + + // GAE support static content which is configured in your app.yaml. + // This example expect the swagger-ui in static/swagger so you should place it there :) + SwaggerFilePath: "static/swagger"} + swagger.InstallSwaggerService(config) +} + +func (u ProfileApi) register() { + ws := new(restful.WebService) + + ws. + Path(u.Path). + // You can specify consumes and produces per route as well. + Consumes(restful.MIME_JSON, restful.MIME_XML). + Produces(restful.MIME_JSON, restful.MIME_XML) + + ws.Route(ws.POST("").To(u.insert). + // Swagger documentation. + Doc("insert a new profile"). + Param(ws.BodyParameter("Profile", "representation of a profile").DataType("main.Profile")). + Reads(Profile{})) + + ws.Route(ws.GET("/{profile-id}").To(u.read). + // Swagger documentation. + Doc("read a profile"). + Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string")). + Writes(Profile{})) + + ws.Route(ws.PUT("/{profile-id}").To(u.update). + // Swagger documentation. + Doc("update an existing profile"). + Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string")). + Param(ws.BodyParameter("Profile", "representation of a profile").DataType("main.Profile")). + Reads(Profile{})) + + ws.Route(ws.DELETE("/{profile-id}").To(u.remove). + // Swagger documentation. + Doc("remove a profile"). + Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string"))) + + restful.Add(ws) +} + +// POST http://localhost:8080/profiles +// {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"} +// +func (u *ProfileApi) insert(r *restful.Request, w *restful.Response) { + c := appengine.NewContext(r.Request) + + // Marshall the entity from the request into a struct. + p := new(Profile) + err := r.ReadEntity(&p) + if err != nil { + w.WriteError(http.StatusNotAcceptable, err) + return + } + + // Ensure we start with a sensible value for this field. + p.LastModified = time.Now() + + // The profile belongs to this user. + p.Email = user.Current(c).String() + + k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "profiles", nil), p) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Let them know the location of the newly created resource. + // TODO: Use a safe Url path append function. + w.AddHeader("Location", u.Path+"/"+k.Encode()) + + // Return the resultant entity. + w.WriteHeader(http.StatusCreated) + w.WriteEntity(p) +} + +// GET http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM +// +func (u ProfileApi) read(r *restful.Request, w *restful.Response) { + c := appengine.NewContext(r.Request) + + // Decode the request parameter to determine the key for the entity. + k, err := datastore.DecodeKey(r.PathParameter("profile-id")) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Retrieve the entity from the datastore. + p := Profile{} + if err := datastore.Get(c, k, &p); err != nil { + if err.Error() == "datastore: no such entity" { + http.Error(w, err.Error(), http.StatusNotFound) + } else { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + return + } + + // Check we own the profile before allowing them to view it. + // Optionally, return a 404 instead to help prevent guessing ids. + // TODO: Allow admins access. + if p.Email != user.Current(c).String() { + http.Error(w, "You do not have access to this resource", http.StatusForbidden) + return + } + + w.WriteEntity(p) +} + +// PUT http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM +// {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"} +// +func (u *ProfileApi) update(r *restful.Request, w *restful.Response) { + c := appengine.NewContext(r.Request) + + // Decode the request parameter to determine the key for the entity. + k, err := datastore.DecodeKey(r.PathParameter("profile-id")) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Marshall the entity from the request into a struct. + p := new(Profile) + err = r.ReadEntity(&p) + if err != nil { + w.WriteError(http.StatusNotAcceptable, err) + return + } + + // Retrieve the old entity from the datastore. + old := Profile{} + if err := datastore.Get(c, k, &old); err != nil { + if err.Error() == "datastore: no such entity" { + http.Error(w, err.Error(), http.StatusNotFound) + } else { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + return + } + + // Check we own the profile before allowing them to update it. + // Optionally, return a 404 instead to help prevent guessing ids. + // TODO: Allow admins access. + if old.Email != user.Current(c).String() { + http.Error(w, "You do not have access to this resource", http.StatusForbidden) + return + } + + // Since the whole entity is re-written, we need to assign any invariant fields again + // e.g. the owner of the entity. + p.Email = user.Current(c).String() + + // Keep track of the last modification date. + p.LastModified = time.Now() + + // Attempt to overwrite the old entity. + _, err = datastore.Put(c, k, p) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Let them know it succeeded. + w.WriteHeader(http.StatusNoContent) +} + +// DELETE http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM +// +func (u *ProfileApi) remove(r *restful.Request, w *restful.Response) { + c := appengine.NewContext(r.Request) + + // Decode the request parameter to determine the key for the entity. + k, err := datastore.DecodeKey(r.PathParameter("profile-id")) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // Retrieve the old entity from the datastore. + old := Profile{} + if err := datastore.Get(c, k, &old); err != nil { + if err.Error() == "datastore: no such entity" { + http.Error(w, err.Error(), http.StatusNotFound) + } else { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + return + } + + // Check we own the profile before allowing them to delete it. + // Optionally, return a 404 instead to help prevent guessing ids. + // TODO: Allow admins access. + if old.Email != user.Current(c).String() { + http.Error(w, "You do not have access to this resource", http.StatusForbidden) + return + } + + // Delete the entity. + if err := datastore.Delete(c, k); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + + // Success notification. + w.WriteHeader(http.StatusNoContent) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-appstats-integration.go b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-appstats-integration.go new file mode 100644 index 00000000..a871133b --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-appstats-integration.go @@ -0,0 +1,12 @@ +package main + +import ( + "github.com/mjibson/appstats" +) + +func stats(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + c := appstats.NewContext(req.Request) + chain.ProcessFilter(req, resp) + c.Stats.Status = resp.StatusCode() + c.Save() +} diff --git a/vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-user-service.go b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-user-service.go new file mode 100644 index 00000000..3f38fd6b --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-user-service.go @@ -0,0 +1,161 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "github.com/emicklei/go-restful/swagger" + "google.golang.org/appengine" + "google.golang.org/appengine/memcache" + "net/http" +) + +// This example is functionally the same as ../restful-user-service.go +// but it`s supposed to run on Goole App Engine (GAE) +// +// contributed by ivanhawkes + +type User struct { + Id, Name string +} + +type UserService struct { + // normally one would use DAO (data access object) + // but in this example we simple use memcache. +} + +func (u UserService) Register() { + ws := new(restful.WebService) + + ws. + Path("/users"). + Consumes(restful.MIME_XML, restful.MIME_JSON). + Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well + + ws.Route(ws.GET("/{user-id}").To(u.findUser). + // docs + Doc("get a user"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). + Writes(User{})) // on the response + + ws.Route(ws.PATCH("").To(u.updateUser). + // docs + Doc("update a user"). + Reads(User{})) // from the request + + ws.Route(ws.PUT("/{user-id}").To(u.createUser). + // docs + Doc("create a user"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). + Reads(User{})) // from the request + + ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). + // docs + Doc("delete a user"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) + + restful.Add(ws) +} + +// GET http://localhost:8080/users/1 +// +func (u UserService) findUser(request *restful.Request, response *restful.Response) { + c := appengine.NewContext(request.Request) + id := request.PathParameter("user-id") + usr := new(User) + _, err := memcache.Gob.Get(c, id, &usr) + if err != nil || len(usr.Id) == 0 { + response.WriteErrorString(http.StatusNotFound, "User could not be found.") + } else { + response.WriteEntity(usr) + } +} + +// PATCH http://localhost:8080/users +// 1Melissa Raspberry +// +func (u *UserService) updateUser(request *restful.Request, response *restful.Response) { + c := appengine.NewContext(request.Request) + usr := new(User) + err := request.ReadEntity(&usr) + if err == nil { + item := &memcache.Item{ + Key: usr.Id, + Object: &usr, + } + err = memcache.Gob.Set(c, item) + if err != nil { + response.WriteError(http.StatusInternalServerError, err) + return + } + response.WriteEntity(usr) + } else { + response.WriteError(http.StatusInternalServerError, err) + } +} + +// PUT http://localhost:8080/users/1 +// 1Melissa +// +func (u *UserService) createUser(request *restful.Request, response *restful.Response) { + c := appengine.NewContext(request.Request) + usr := User{Id: request.PathParameter("user-id")} + err := request.ReadEntity(&usr) + if err == nil { + item := &memcache.Item{ + Key: usr.Id, + Object: &usr, + } + err = memcache.Gob.Add(c, item) + if err != nil { + response.WriteError(http.StatusInternalServerError, err) + return + } + response.WriteHeader(http.StatusCreated) + response.WriteEntity(usr) + } else { + response.WriteError(http.StatusInternalServerError, err) + } +} + +// DELETE http://localhost:8080/users/1 +// +func (u *UserService) removeUser(request *restful.Request, response *restful.Response) { + c := appengine.NewContext(request.Request) + id := request.PathParameter("user-id") + err := memcache.Delete(c, id) + if err != nil { + response.WriteError(http.StatusInternalServerError, err) + } +} + +func getGaeURL() string { + if appengine.IsDevAppServer() { + return "http://localhost:8080" + } else { + /** + * Include your URL on App Engine here. + * I found no way to get AppID without appengine.Context and this always + * based on a http.Request. + */ + return "http://.appspot.com" + } +} + +func init() { + u := UserService{} + u.Register() + + // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API + // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. + // Open .appspot.com/apidocs and enter http://.appspot.com/apidocs.json in the api input field. + config := swagger.Config{ + WebServices: restful.RegisteredWebServices(), // you control what services are visible + WebServicesUrl: getGaeURL(), + ApiPath: "/apidocs.json", + + // Optionally, specifiy where the UI is located + SwaggerPath: "/apidocs/", + // GAE support static content which is configured in your app.yaml. + // This example expect the swagger-ui in static/swagger so you should place it there :) + SwaggerFilePath: "static/swagger"} + swagger.InstallSwaggerService(config) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/home.html b/vendor/github.com/emicklei/go-restful/examples/home.html new file mode 100644 index 00000000..e5d49b42 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/home.html @@ -0,0 +1,7 @@ + + + + +

{{.Text}}

+ + \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/examples/msgpack/msgpack_entity.go b/vendor/github.com/emicklei/go-restful/examples/msgpack/msgpack_entity.go new file mode 100644 index 00000000..330e4589 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/msgpack/msgpack_entity.go @@ -0,0 +1,34 @@ +package restPack + +import ( + restful "github.com/emicklei/go-restful" + "gopkg.in/vmihailenco/msgpack.v2" +) + +const MIME_MSGPACK = "application/x-msgpack" // Accept or Content-Type used in Consumes() and/or Produces() + +// NewEntityAccessorMPack returns a new EntityReaderWriter for accessing MessagePack content. +// This package is not initialized with such an accessor using the MIME_MSGPACK contentType. +func NewEntityAccessorMsgPack() restful.EntityReaderWriter { + return entityMsgPackAccess{} +} + +// entityOctetAccess is a EntityReaderWriter for Octet encoding +type entityMsgPackAccess struct { +} + +// Read unmarshalls the value from byte slice and using msgpack to unmarshal +func (e entityMsgPackAccess) Read(req *restful.Request, v interface{}) error { + return msgpack.NewDecoder(req.Request.Body).Decode(v) +} + +// Write marshals the value to byte slice and set the Content-Type Header. +func (e entityMsgPackAccess) Write(resp *restful.Response, status int, v interface{}) error { + if v == nil { + resp.WriteHeader(status) + // do not write a nil representation + return nil + } + resp.WriteHeader(status) + return msgpack.NewEncoder(resp).Encode(v) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/msgpack/msgpack_entity_test.go b/vendor/github.com/emicklei/go-restful/examples/msgpack/msgpack_entity_test.go new file mode 100644 index 00000000..aa8de650 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/msgpack/msgpack_entity_test.go @@ -0,0 +1,160 @@ +package restPack + +import ( + "bytes" + "errors" + "log" + "net/http" + "net/http/httptest" + "reflect" + "testing" + "time" + + restful "github.com/emicklei/go-restful" + "gopkg.in/vmihailenco/msgpack.v2" + "io/ioutil" +) + +func TestMsgPack(t *testing.T) { + + // register msg pack entity + restful.RegisterEntityAccessor(MIME_MSGPACK, NewEntityAccessorMsgPack()) + type Tool struct { + Name string + Vendor string + } + + // Write + httpWriter := httptest.NewRecorder() + mpack := &Tool{Name: "json", Vendor: "apple"} + resp := restful.NewResponse(httpWriter) + resp.SetRequestAccepts("application/x-msgpack,*/*;q=0.8") + + err := resp.WriteEntity(mpack) + if err != nil { + t.Errorf("err %v", err) + } + + // Read + bodyReader := bytes.NewReader(httpWriter.Body.Bytes()) + httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) + httpRequest.Header.Set("Content-Type", MIME_MSGPACK) + request := restful.NewRequest(httpRequest) + readMsgPack := new(Tool) + err = request.ReadEntity(&readMsgPack) + if err != nil { + t.Errorf("err %v", err) + } + if equal := reflect.DeepEqual(mpack, readMsgPack); !equal { + t.Fatalf("should not be error") + } +} + +func TestWithWebService(t *testing.T) { + serverURL := "http://127.0.0.1:8090" + go func() { + runRestfulMsgPackRouterServer() + }() + if err := waitForServerUp(serverURL); err != nil { + t.Errorf("%v", err) + } + + // send a post request + userData := user{Id: "0001", Name: "Tony"} + msgPackData, err := msgpack.Marshal(userData) + req, err := http.NewRequest("POST", serverURL+"/test/msgpack", bytes.NewBuffer(msgPackData)) + req.Header.Set("Content-Type", MIME_MSGPACK) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + t.Errorf("unexpected error in sending req: %v", err) + } + if resp.StatusCode != http.StatusOK { + t.Errorf("unexpected response: %v, expected: %v", resp.StatusCode, http.StatusOK) + } + + ur := &userResponse{} + expectMsgPackDocument(t, resp, ur) + if ur.Status != statusActive { + t.Fatalf("should not error") + } + log.Printf("user response:%v", ur) +} + +func expectMsgPackDocument(t *testing.T, r *http.Response, doc interface{}) { + data, err := ioutil.ReadAll(r.Body) + defer r.Body.Close() + if err != nil { + t.Error("ExpectMsgPackDocument: unable to read response body :%v", err) + return + } + // put the body back for re-reads + r.Body = ioutil.NopCloser(bytes.NewReader(data)) + + err = msgpack.Unmarshal(data, doc) + if err != nil { + t.Error("ExpectMsgPackDocument: unable to unmarshal MsgPack:%v", err) + } +} + +func runRestfulMsgPackRouterServer() { + + container := restful.NewContainer() + register(container) + + log.Printf("start listening on localhost:8090") + server := &http.Server{Addr: ":8090", Handler: container} + log.Fatal(server.ListenAndServe()) +} + +func waitForServerUp(serverURL string) error { + for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) { + _, err := http.Get(serverURL + "/") + if err == nil { + return nil + } + } + return errors.New("waiting for server timed out") +} + +var ( + statusActive = "active" +) + +type user struct { + Id, Name string +} + +type userResponse struct { + Status string +} + +func register(container *restful.Container) { + restful.RegisterEntityAccessor(MIME_MSGPACK, NewEntityAccessorMsgPack()) + ws := new(restful.WebService) + ws. + Path("/test"). + Consumes(restful.MIME_JSON, MIME_MSGPACK). + Produces(restful.MIME_JSON, MIME_MSGPACK) + // route user api + ws.Route(ws.POST("/msgpack"). + To(do). + Reads(user{}). + Writes(userResponse{})) + container.Add(ws) +} + +func do(request *restful.Request, response *restful.Response) { + u := &user{} + err := request.ReadEntity(u) + if err != nil { + log.Printf("should be no error, got:%v", err) + } + log.Printf("got:%v", u) + + ur := &userResponse{Status: statusActive} + + response.SetRequestAccepts(MIME_MSGPACK) + response.WriteEntity(ur) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-CORS-filter.go b/vendor/github.com/emicklei/go-restful/examples/restful-CORS-filter.go new file mode 100644 index 00000000..6419d253 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-CORS-filter.go @@ -0,0 +1,68 @@ +package main + +import ( + "io" + "log" + "net/http" + + "github.com/emicklei/go-restful" +) + +// Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page +// to make XMLHttpRequests to another domain, not the domain the JavaScript originated from. +// +// http://en.wikipedia.org/wiki/Cross-origin_resource_sharing +// http://enable-cors.org/server.html +// +// GET http://localhost:8080/users +// +// GET http://localhost:8080/users/1 +// +// PUT http://localhost:8080/users/1 +// +// DELETE http://localhost:8080/users/1 +// +// OPTIONS http://localhost:8080/users/1 with Header "Origin" set to some domain and + +type UserResource struct{} + +func (u UserResource) RegisterTo(container *restful.Container) { + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes("*/*"). + Produces("*/*") + + ws.Route(ws.GET("/{user-id}").To(u.nop)) + ws.Route(ws.POST("").To(u.nop)) + ws.Route(ws.PUT("/{user-id}").To(u.nop)) + ws.Route(ws.DELETE("/{user-id}").To(u.nop)) + + container.Add(ws) +} + +func (u UserResource) nop(request *restful.Request, response *restful.Response) { + io.WriteString(response.ResponseWriter, "this would be a normal response") +} + +func main() { + wsContainer := restful.NewContainer() + u := UserResource{} + u.RegisterTo(wsContainer) + + // Add container filter to enable CORS + cors := restful.CrossOriginResourceSharing{ + ExposeHeaders: []string{"X-My-Header"}, + AllowedHeaders: []string{"Content-Type", "Accept"}, + AllowedMethods: []string{"GET", "POST"}, + CookiesAllowed: false, + Container: wsContainer} + wsContainer.Filter(cors.Filter) + + // Add container filter to respond to OPTIONS + wsContainer.Filter(wsContainer.OPTIONSFilter) + + log.Printf("start listening on localhost:8080") + server := &http.Server{Addr: ":8080", Handler: wsContainer} + log.Fatal(server.ListenAndServe()) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-NCSA-logging.go b/vendor/github.com/emicklei/go-restful/examples/restful-NCSA-logging.go new file mode 100644 index 00000000..0cda50d3 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-NCSA-logging.go @@ -0,0 +1,54 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "io" + "log" + "net/http" + "os" + "strings" + "time" +) + +// This example shows how to create a filter that produces log lines +// according to the Common Log Format, also known as the NCSA standard. +// +// kindly contributed by leehambley +// +// GET http://localhost:8080/ping + +var logger *log.Logger = log.New(os.Stdout, "", 0) + +func NCSACommonLogFormatLogger() restful.FilterFunction { + return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + var username = "-" + if req.Request.URL.User != nil { + if name := req.Request.URL.User.Username(); name != "" { + username = name + } + } + chain.ProcessFilter(req, resp) + logger.Printf("%s - %s [%s] \"%s %s %s\" %d %d", + strings.Split(req.Request.RemoteAddr, ":")[0], + username, + time.Now().Format("02/Jan/2006:15:04:05 -0700"), + req.Request.Method, + req.Request.URL.RequestURI(), + req.Request.Proto, + resp.StatusCode(), + resp.ContentLength(), + ) + } +} + +func main() { + ws := new(restful.WebService) + ws.Filter(NCSACommonLogFormatLogger()) + ws.Route(ws.GET("/ping").To(hello)) + restful.Add(ws) + http.ListenAndServe(":8080", nil) +} + +func hello(req *restful.Request, resp *restful.Response) { + io.WriteString(resp, "pong") +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-basic-authentication.go b/vendor/github.com/emicklei/go-restful/examples/restful-basic-authentication.go new file mode 100644 index 00000000..5dd3067e --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-basic-authentication.go @@ -0,0 +1,35 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "io" + "net/http" +) + +// This example shows how to create a (Route) Filter that performs Basic Authentication on the Http request. +// +// GET http://localhost:8080/secret +// and use admin,admin for the credentials + +func main() { + ws := new(restful.WebService) + ws.Route(ws.GET("/secret").Filter(basicAuthenticate).To(secret)) + restful.Add(ws) + http.ListenAndServe(":8080", nil) +} + +func basicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + encoded := req.Request.Header.Get("Authorization") + // usr/pwd = admin/admin + // real code does some decoding + if len(encoded) == 0 || "Basic YWRtaW46YWRtaW4=" != encoded { + resp.AddHeader("WWW-Authenticate", "Basic realm=Protected Area") + resp.WriteErrorString(401, "401: Not Authorized") + return + } + chain.ProcessFilter(req, resp) +} + +func secret(req *restful.Request, resp *restful.Response) { + io.WriteString(resp, "42") +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-cpuprofiler-service.go b/vendor/github.com/emicklei/go-restful/examples/restful-cpuprofiler-service.go new file mode 100644 index 00000000..9148213c --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-cpuprofiler-service.go @@ -0,0 +1,65 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "io" + "log" + "os" + "runtime/pprof" +) + +// ProfilingService is a WebService that can start/stop a CPU profile and write results to a file +// GET /{rootPath}/start will activate CPU profiling +// GET /{rootPath}/stop will stop profiling +// +// NewProfileService("/profiler", "ace.prof").AddWebServiceTo(restful.DefaultContainer) +// +type ProfilingService struct { + rootPath string // the base (root) of the service, e.g. /profiler + cpuprofile string // the output filename to write profile results, e.g. myservice.prof + cpufile *os.File // if not nil, then profiling is active +} + +func NewProfileService(rootPath string, outputFilename string) *ProfilingService { + ps := new(ProfilingService) + ps.rootPath = rootPath + ps.cpuprofile = outputFilename + return ps +} + +// Add this ProfileService to a restful Container +func (p ProfilingService) AddWebServiceTo(container *restful.Container) { + ws := new(restful.WebService) + ws.Path(p.rootPath).Consumes("*/*").Produces(restful.MIME_JSON) + ws.Route(ws.GET("/start").To(p.startProfiler)) + ws.Route(ws.GET("/stop").To(p.stopProfiler)) + container.Add(ws) +} + +func (p *ProfilingService) startProfiler(req *restful.Request, resp *restful.Response) { + if p.cpufile != nil { + io.WriteString(resp.ResponseWriter, "[restful] CPU profiling already running") + return // error? + } + cpufile, err := os.Create(p.cpuprofile) + if err != nil { + log.Fatal(err) + } + // remember for close + p.cpufile = cpufile + pprof.StartCPUProfile(cpufile) + io.WriteString(resp.ResponseWriter, "[restful] CPU profiling started, writing on:"+p.cpuprofile) +} + +func (p *ProfilingService) stopProfiler(req *restful.Request, resp *restful.Response) { + if p.cpufile == nil { + io.WriteString(resp.ResponseWriter, "[restful] CPU profiling not active") + return // error? + } + pprof.StopCPUProfile() + p.cpufile.Close() + p.cpufile = nil + io.WriteString(resp.ResponseWriter, "[restful] CPU profiling stopped, closing:"+p.cpuprofile) +} + +func main() {} // exists for example compilation only diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-curly-router.go b/vendor/github.com/emicklei/go-restful/examples/restful-curly-router.go new file mode 100644 index 00000000..26da2f1c --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-curly-router.go @@ -0,0 +1,107 @@ +package main + +import ( + "log" + "net/http" + + "github.com/emicklei/go-restful" +) + +// This example has the same service definition as restful-user-resource +// but uses a different router (CurlyRouter) that does not use regular expressions +// +// POST http://localhost:8080/users +// 1Melissa Raspberry +// +// GET http://localhost:8080/users/1 +// +// PUT http://localhost:8080/users/1 +// 1Melissa +// +// DELETE http://localhost:8080/users/1 +// + +type User struct { + Id, Name string +} + +type UserResource struct { + // normally one would use DAO (data access object) + users map[string]User +} + +func (u UserResource) Register(container *restful.Container) { + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes(restful.MIME_XML, restful.MIME_JSON). + Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well + + ws.Route(ws.GET("/{user-id}").To(u.findUser)) + ws.Route(ws.POST("").To(u.updateUser)) + ws.Route(ws.PUT("/{user-id}").To(u.createUser)) + ws.Route(ws.DELETE("/{user-id}").To(u.removeUser)) + + container.Add(ws) +} + +// GET http://localhost:8080/users/1 +// +func (u UserResource) findUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + usr := u.users[id] + if len(usr.Id) == 0 { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusNotFound, "User could not be found.") + } else { + response.WriteEntity(usr) + } +} + +// POST http://localhost:8080/users +// 1Melissa Raspberry +// +func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) { + usr := new(User) + err := request.ReadEntity(&usr) + if err == nil { + u.users[usr.Id] = *usr + response.WriteEntity(usr) + } else { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusInternalServerError, err.Error()) + } +} + +// PUT http://localhost:8080/users/1 +// 1Melissa +// +func (u *UserResource) createUser(request *restful.Request, response *restful.Response) { + usr := User{Id: request.PathParameter("user-id")} + err := request.ReadEntity(&usr) + if err == nil { + u.users[usr.Id] = usr + response.WriteHeaderAndEntity(http.StatusCreated, usr) + } else { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusInternalServerError, err.Error()) + } +} + +// DELETE http://localhost:8080/users/1 +// +func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + delete(u.users, id) +} + +func main() { + wsContainer := restful.NewContainer() + wsContainer.Router(restful.CurlyRouter{}) + u := UserResource{map[string]User{}} + u.Register(wsContainer) + + log.Printf("start listening on localhost:8080") + server := &http.Server{Addr: ":8080", Handler: wsContainer} + log.Fatal(server.ListenAndServe()) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-curly-router_test.go b/vendor/github.com/emicklei/go-restful/examples/restful-curly-router_test.go new file mode 100644 index 00000000..d0760d34 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-curly-router_test.go @@ -0,0 +1,149 @@ +package main + +import ( + "bytes" + "errors" + "log" + "net/http" + "testing" + "time" + + "github.com/emicklei/go-restful" +) + +type User struct { + Id, Name string +} + +type UserResource struct { + users map[string]User +} + +func (u UserResource) Register(container *restful.Container) { + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes(restful.MIME_XML, restful.MIME_JSON). + Produces(restful.MIME_JSON, restful.MIME_XML) + + ws.Route(ws.GET("/{user-id}").To(u.findUser)) + ws.Route(ws.POST("").To(u.updateUser)) + ws.Route(ws.PUT("/{user-id}").To(u.createUser)) + ws.Route(ws.DELETE("/{user-id}").To(u.removeUser)) + + container.Add(ws) +} + +// GET http://localhost:8090/users/1 +// +func (u UserResource) findUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + usr := u.users[id] + if len(usr.Id) == 0 { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusNotFound, "User could not be found.") + } else { + response.WriteEntity(usr) + } +} + +// POST http://localhost:8090/users +// 1Melissa Raspberry +// +func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) { + usr := new(User) + err := request.ReadEntity(&usr) + if err == nil { + u.users[usr.Id] = *usr + response.WriteEntity(usr) + } else { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusInternalServerError, err.Error()) + } +} + +// PUT http://localhost:8090/users/1 +// 1Melissa +// +func (u *UserResource) createUser(request *restful.Request, response *restful.Response) { + usr := User{Id: request.PathParameter("user-id")} + err := request.ReadEntity(&usr) + if err == nil { + u.users[usr.Id] = usr + response.WriteHeader(http.StatusCreated) + response.WriteEntity(usr) + } else { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusInternalServerError, err.Error()) + } +} + +// DELETE http://localhost:8090/users/1 +// +func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + delete(u.users, id) +} + +func RunRestfulCurlyRouterServer() { + wsContainer := restful.NewContainer() + wsContainer.Router(restful.CurlyRouter{}) + u := UserResource{map[string]User{}} + u.Register(wsContainer) + + log.Printf("start listening on localhost:8090") + server := &http.Server{Addr: ":8090", Handler: wsContainer} + log.Fatal(server.ListenAndServe()) +} + +func waitForServerUp(serverURL string) error { + for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) { + _, err := http.Get(serverURL + "/") + if err == nil { + return nil + } + } + return errors.New("waiting for server timed out") +} + +func TestServer(t *testing.T) { + serverURL := "http://localhost:8090" + go func() { + RunRestfulCurlyRouterServer() + }() + if err := waitForServerUp(serverURL); err != nil { + t.Errorf("%v", err) + } + + // GET should give a 405 + resp, err := http.Get(serverURL + "/users/") + if err != nil { + t.Errorf("unexpected error in GET /users/: %v", err) + } + if resp.StatusCode != http.StatusMethodNotAllowed { + t.Errorf("unexpected response: %v, expected: %v", resp.StatusCode, http.StatusOK) + } + + // Send a POST request. + var jsonStr = []byte(`{"id":"1","name":"user1"}`) + req, err := http.NewRequest("POST", serverURL+"/users/", bytes.NewBuffer(jsonStr)) + req.Header.Set("Content-Type", restful.MIME_JSON) + + client := &http.Client{} + resp, err = client.Do(req) + if err != nil { + t.Errorf("unexpected error in sending req: %v", err) + } + if resp.StatusCode != http.StatusOK { + t.Errorf("unexpected response: %v, expected: %v", resp.StatusCode, http.StatusOK) + } + + // Test that GET works. + resp, err = http.Get(serverURL + "/users/1") + if err != nil { + t.Errorf("unexpected error in GET /users/1: %v", err) + } + if resp.StatusCode != http.StatusOK { + t.Errorf("unexpected response: %v, expected: %v", resp.StatusCode, http.StatusOK) + } +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-encoding-filter.go b/vendor/github.com/emicklei/go-restful/examples/restful-encoding-filter.go new file mode 100644 index 00000000..6094c490 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-encoding-filter.go @@ -0,0 +1,61 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "log" + "net/http" +) + +type User struct { + Id, Name string +} + +type UserList struct { + Users []User +} + +// +// This example shows how to use the CompressingResponseWriter by a Filter +// such that encoding can be enabled per WebService or per Route (instead of per container) +// Using restful.DefaultContainer.EnableContentEncoding(true) will encode all responses served by WebServices in the DefaultContainer. +// +// Set Accept-Encoding to gzip or deflate +// GET http://localhost:8080/users/42 +// and look at the response headers + +func main() { + restful.Add(NewUserService()) + log.Printf("start listening on localhost:8080") + log.Fatal(http.ListenAndServe(":8080", nil)) +} + +func NewUserService() *restful.WebService { + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes(restful.MIME_XML, restful.MIME_JSON). + Produces(restful.MIME_JSON, restful.MIME_XML) + + // install a response encoding filter + ws.Route(ws.GET("/{user-id}").Filter(encodingFilter).To(findUser)) + return ws +} + +// Route Filter (defines FilterFunction) +func encodingFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + log.Printf("[encoding-filter] %s,%s\n", req.Request.Method, req.Request.URL) + // wrap responseWriter into a compressing one + compress, _ := restful.NewCompressingResponseWriter(resp.ResponseWriter, restful.ENCODING_GZIP) + resp.ResponseWriter = compress + defer func() { + compress.Close() + }() + chain.ProcessFilter(req, resp) +} + +// GET http://localhost:8080/users/42 +// +func findUser(request *restful.Request, response *restful.Response) { + log.Printf("findUser") + response.WriteEntity(User{"42", "Gandalf"}) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-filters.go b/vendor/github.com/emicklei/go-restful/examples/restful-filters.go new file mode 100644 index 00000000..478aceac --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-filters.go @@ -0,0 +1,114 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "log" + "net/http" + "time" +) + +type User struct { + Id, Name string +} + +type UserList struct { + Users []User +} + +// This example show how to create and use the three different Filters (Container,WebService and Route) +// When applied to the restful.DefaultContainer, we refer to them as a global filter. +// +// GET http://locahost:8080/users/42 +// and see the logging per filter (try repeating this request) + +func main() { + // install a global (=DefaultContainer) filter (processed before any webservice in the DefaultContainer) + restful.Filter(globalLogging) + + restful.Add(NewUserService()) + log.Printf("start listening on localhost:8080") + log.Fatal(http.ListenAndServe(":8080", nil)) +} + +func NewUserService() *restful.WebService { + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes(restful.MIME_XML, restful.MIME_JSON). + Produces(restful.MIME_JSON, restful.MIME_XML) + + // install a webservice filter (processed before any route) + ws.Filter(webserviceLogging).Filter(measureTime) + + // install a counter filter + ws.Route(ws.GET("").Filter(NewCountFilter().routeCounter).To(getAllUsers)) + + // install 2 chained route filters (processed before calling findUser) + ws.Route(ws.GET("/{user-id}").Filter(routeLogging).Filter(NewCountFilter().routeCounter).To(findUser)) + return ws +} + +// Global Filter +func globalLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + log.Printf("[global-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) + chain.ProcessFilter(req, resp) +} + +// WebService Filter +func webserviceLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + log.Printf("[webservice-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) + chain.ProcessFilter(req, resp) +} + +// WebService (post-process) Filter (as a struct that defines a FilterFunction) +func measureTime(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + now := time.Now() + chain.ProcessFilter(req, resp) + log.Printf("[webservice-filter (timer)] %v\n", time.Now().Sub(now)) +} + +// Route Filter (defines FilterFunction) +func routeLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + log.Printf("[route-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) + chain.ProcessFilter(req, resp) +} + +// Route Filter (as a struct that defines a FilterFunction) +// CountFilter implements a FilterFunction for counting requests. +type CountFilter struct { + count int + counter chan int // for go-routine safe count increments +} + +// NewCountFilter creates and initializes a new CountFilter. +func NewCountFilter() *CountFilter { + c := new(CountFilter) + c.counter = make(chan int) + go func() { + for { + c.count += <-c.counter + } + }() + return c +} + +// routeCounter increments the count of the filter (through a channel) +func (c *CountFilter) routeCounter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + c.counter <- 1 + log.Printf("[route-filter (counter)] count:%d", c.count) + chain.ProcessFilter(req, resp) +} + +// GET http://localhost:8080/users +// +func getAllUsers(request *restful.Request, response *restful.Response) { + log.Printf("getAllUsers") + response.WriteEntity(UserList{[]User{{"42", "Gandalf"}, {"3.14", "Pi"}}}) +} + +// GET http://localhost:8080/users/42 +// +func findUser(request *restful.Request, response *restful.Response) { + log.Printf("findUser") + response.WriteEntity(User{"42", "Gandalf"}) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-form-handling.go b/vendor/github.com/emicklei/go-restful/examples/restful-form-handling.go new file mode 100644 index 00000000..a83db449 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-form-handling.go @@ -0,0 +1,62 @@ +package main + +import ( + "fmt" + "github.com/emicklei/go-restful" + "github.com/gorilla/schema" + "io" + "net/http" +) + +// This example shows how to handle a POST of a HTML form that uses the standard x-www-form-urlencoded content-type. +// It uses the gorilla web tool kit schema package to decode the form data into a struct. +// +// GET http://localhost:8080/profiles +// + +type Profile struct { + Name string + Age int +} + +var decoder *schema.Decoder + +func main() { + decoder = schema.NewDecoder() + ws := new(restful.WebService) + ws.Route(ws.POST("/profiles").Consumes("application/x-www-form-urlencoded").To(postAdddress)) + ws.Route(ws.GET("/profiles").To(addresssForm)) + restful.Add(ws) + http.ListenAndServe(":8080", nil) +} + +func postAdddress(req *restful.Request, resp *restful.Response) { + err := req.Request.ParseForm() + if err != nil { + resp.WriteErrorString(http.StatusBadRequest, err.Error()) + return + } + p := new(Profile) + err = decoder.Decode(p, req.Request.PostForm) + if err != nil { + resp.WriteErrorString(http.StatusBadRequest, err.Error()) + return + } + io.WriteString(resp.ResponseWriter, fmt.Sprintf("Name=%s, Age=%d", p.Name, p.Age)) +} + +func addresssForm(req *restful.Request, resp *restful.Response) { + io.WriteString(resp.ResponseWriter, + ` + +

Enter Profile

+
+ + + + + +
+ + `) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-hello-world.go b/vendor/github.com/emicklei/go-restful/examples/restful-hello-world.go new file mode 100644 index 00000000..a21c2a69 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-hello-world.go @@ -0,0 +1,22 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "io" + "net/http" +) + +// This example shows the minimal code needed to get a restful.WebService working. +// +// GET http://localhost:8080/hello + +func main() { + ws := new(restful.WebService) + ws.Route(ws.GET("/hello").To(hello)) + restful.Add(ws) + http.ListenAndServe(":8080", nil) +} + +func hello(req *restful.Request, resp *restful.Response) { + io.WriteString(resp, "world") +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-html-template.go b/vendor/github.com/emicklei/go-restful/examples/restful-html-template.go new file mode 100644 index 00000000..de51c591 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-html-template.go @@ -0,0 +1,35 @@ +package main + +import ( + "log" + "net/http" + "text/template" + + "github.com/emicklei/go-restful" +) + +// This example shows how to serve a HTML page using the standard Go template engine. +// +// GET http://localhost:8080/ + +func main() { + ws := new(restful.WebService) + ws.Route(ws.GET("/").To(home)) + restful.Add(ws) + print("open browser on http://localhost:8080/\n") + http.ListenAndServe(":8080", nil) +} + +type Message struct { + Text string +} + +func home(req *restful.Request, resp *restful.Response) { + p := &Message{"restful-html-template demo"} + // you might want to cache compiled templates + t, err := template.ParseFiles("home.html") + if err != nil { + log.Fatalf("Template gave: %s", err) + } + t.Execute(resp.ResponseWriter, p) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-multi-containers.go b/vendor/github.com/emicklei/go-restful/examples/restful-multi-containers.go new file mode 100644 index 00000000..3f1650b3 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-multi-containers.go @@ -0,0 +1,43 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "io" + "log" + "net/http" +) + +// This example shows how to have a program with 2 WebServices containers +// each having a http server listening on its own port. +// +// The first "hello" is added to the restful.DefaultContainer (and uses DefaultServeMux) +// For the second "hello", a new container and ServeMux is created +// and requires a new http.Server with the container being the Handler. +// This first server is spawn in its own go-routine such that the program proceeds to create the second. +// +// GET http://localhost:8080/hello +// GET http://localhost:8081/hello + +func main() { + ws := new(restful.WebService) + ws.Route(ws.GET("/hello").To(hello)) + restful.Add(ws) + go func() { + http.ListenAndServe(":8080", nil) + }() + + container2 := restful.NewContainer() + ws2 := new(restful.WebService) + ws2.Route(ws2.GET("/hello").To(hello2)) + container2.Add(ws2) + server := &http.Server{Addr: ":8081", Handler: container2} + log.Fatal(server.ListenAndServe()) +} + +func hello(req *restful.Request, resp *restful.Response) { + io.WriteString(resp, "default world") +} + +func hello2(req *restful.Request, resp *restful.Response) { + io.WriteString(resp, "second world") +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-no-cache-filter.go b/vendor/github.com/emicklei/go-restful/examples/restful-no-cache-filter.go new file mode 100644 index 00000000..2af932a1 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-no-cache-filter.go @@ -0,0 +1,24 @@ +package main + +import ( + "io" + "net/http" + + "github.com/emicklei/go-restful" +) + +// This example shows how to use a WebService filter that passed the Http headers to disable browser cacheing. +// +// GET http://localhost:8080/hello + +func main() { + ws := new(restful.WebService) + ws.Filter(restful.NoBrowserCacheFilter) + ws.Route(ws.GET("/hello").To(hello)) + restful.Add(ws) + http.ListenAndServe(":8080", nil) +} + +func hello(req *restful.Request, resp *restful.Response) { + io.WriteString(resp, "world") +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-options-filter.go b/vendor/github.com/emicklei/go-restful/examples/restful-options-filter.go new file mode 100644 index 00000000..73dc3cfe --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-options-filter.go @@ -0,0 +1,51 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "io" + "log" + "net/http" +) + +// This example shows how to use the OPTIONSFilter on a Container +// +// OPTIONS http://localhost:8080/users +// +// OPTIONS http://localhost:8080/users/1 + +type UserResource struct{} + +func (u UserResource) RegisterTo(container *restful.Container) { + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes("*/*"). + Produces("*/*") + + ws.Route(ws.GET("/{user-id}").To(u.nop)) + ws.Route(ws.POST("").To(u.nop)) + ws.Route(ws.PUT("/{user-id}").To(u.nop)) + ws.Route(ws.DELETE("/{user-id}").To(u.nop)) + + container.Add(ws) +} + +func (u UserResource) nop(request *restful.Request, response *restful.Response) { + io.WriteString(response.ResponseWriter, "this would be a normal response") +} + +func main() { + wsContainer := restful.NewContainer() + u := UserResource{} + u.RegisterTo(wsContainer) + + // Add container filter to respond to OPTIONS + wsContainer.Filter(wsContainer.OPTIONSFilter) + + // For use on the default container, you can write + // restful.Filter(restful.OPTIONSFilter()) + + log.Printf("start listening on localhost:8080") + server := &http.Server{Addr: ":8080", Handler: wsContainer} + log.Fatal(server.ListenAndServe()) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-path-tail.go b/vendor/github.com/emicklei/go-restful/examples/restful-path-tail.go new file mode 100644 index 00000000..e1f16329 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-path-tail.go @@ -0,0 +1,26 @@ +package main + +import ( + . "github.com/emicklei/go-restful" + "io" + "net/http" +) + +// This example shows how to a Route that matches the "tail" of a path. +// Requires the use of a CurlyRouter and the star "*" path parameter pattern. +// +// GET http://localhost:8080/basepath/some/other/location/test.xml + +func main() { + DefaultContainer.Router(CurlyRouter{}) + ws := new(WebService) + ws.Route(ws.GET("/basepath/{resource:*}").To(staticFromPathParam)) + Add(ws) + + println("[go-restful] serve path tails from http://localhost:8080/basepath") + http.ListenAndServe(":8080", nil) +} + +func staticFromPathParam(req *Request, resp *Response) { + io.WriteString(resp, "Tail="+req.PathParameter("resource")) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-pre-post-filters.go b/vendor/github.com/emicklei/go-restful/examples/restful-pre-post-filters.go new file mode 100644 index 00000000..0b55f149 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-pre-post-filters.go @@ -0,0 +1,98 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "io" + "log" + "net/http" +) + +// This example shows how the different types of filters are called in the request-response flow. +// The call chain is logged on the console when sending an http request. +// +// GET http://localhost:8080/1 +// GET http://localhost:8080/2 + +var indentLevel int + +func container_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + log.Printf("url path:%v\n", req.Request.URL) + trace("container_filter_A: before", 1) + chain.ProcessFilter(req, resp) + trace("container_filter_A: after", -1) +} + +func container_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + trace("container_filter_B: before", 1) + chain.ProcessFilter(req, resp) + trace("container_filter_B: after", -1) +} + +func service_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + trace("service_filter_A: before", 1) + chain.ProcessFilter(req, resp) + trace("service_filter_A: after", -1) +} + +func service_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + trace("service_filter_B: before", 1) + chain.ProcessFilter(req, resp) + trace("service_filter_B: after", -1) +} + +func route_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + trace("route_filter_A: before", 1) + chain.ProcessFilter(req, resp) + trace("route_filter_A: after", -1) +} + +func route_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { + trace("route_filter_B: before", 1) + chain.ProcessFilter(req, resp) + trace("route_filter_B: after", -1) +} + +func trace(what string, delta int) { + indented := what + if delta < 0 { + indentLevel += delta + } + for t := 0; t < indentLevel; t++ { + indented = "." + indented + } + log.Printf("%s", indented) + if delta > 0 { + indentLevel += delta + } +} + +func main() { + restful.Filter(container_filter_A) + restful.Filter(container_filter_B) + + ws1 := new(restful.WebService) + ws1.Path("/1") + ws1.Filter(service_filter_A) + ws1.Filter(service_filter_B) + ws1.Route(ws1.GET("").To(doit1).Filter(route_filter_A).Filter(route_filter_B)) + + ws2 := new(restful.WebService) + ws2.Path("/2") + ws2.Filter(service_filter_A) + ws2.Filter(service_filter_B) + ws2.Route(ws2.GET("").To(doit2).Filter(route_filter_A).Filter(route_filter_B)) + + restful.Add(ws1) + restful.Add(ws2) + + log.Print("go-restful example listing on http://localhost:8080/1 and http://localhost:8080/2") + log.Fatal(http.ListenAndServe(":8080", nil)) +} + +func doit1(req *restful.Request, resp *restful.Response) { + io.WriteString(resp, "nothing to see in 1") +} + +func doit2(req *restful.Request, resp *restful.Response) { + io.WriteString(resp, "nothing to see in 2") +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-resource-functions.go b/vendor/github.com/emicklei/go-restful/examples/restful-resource-functions.go new file mode 100644 index 00000000..fb1012a0 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-resource-functions.go @@ -0,0 +1,63 @@ +package main + +import ( + "github.com/emicklei/go-restful" + "log" + "net/http" +) + +// This example shows how to use methods as RouteFunctions for WebServices. +// The ProductResource has a Register() method that creates and initializes +// a WebService to expose its methods as REST operations. +// The WebService is added to the restful.DefaultContainer. +// A ProductResource is typically created using some data access object. +// +// GET http://localhost:8080/products/1 +// POST http://localhost:8080/products +// 1The First + +type Product struct { + Id, Title string +} + +type ProductResource struct { + // typically reference a DAO (data-access-object) +} + +func (p ProductResource) getOne(req *restful.Request, resp *restful.Response) { + id := req.PathParameter("id") + log.Println("getting product with id:" + id) + resp.WriteEntity(Product{Id: id, Title: "test"}) +} + +func (p ProductResource) postOne(req *restful.Request, resp *restful.Response) { + updatedProduct := new(Product) + err := req.ReadEntity(updatedProduct) + if err != nil { // bad request + resp.WriteErrorString(http.StatusBadRequest, err.Error()) + return + } + log.Println("updating product with id:" + updatedProduct.Id) +} + +func (p ProductResource) Register() { + ws := new(restful.WebService) + ws.Path("/products") + ws.Consumes(restful.MIME_XML) + ws.Produces(restful.MIME_XML) + + ws.Route(ws.GET("/{id}").To(p.getOne). + Doc("get the product by its id"). + Param(ws.PathParameter("id", "identifier of the product").DataType("string"))) + + ws.Route(ws.POST("").To(p.postOne). + Doc("update or create a product"). + Param(ws.BodyParameter("Product", "a Product (XML)").DataType("main.Product"))) + + restful.Add(ws) +} + +func main() { + ProductResource{}.Register() + http.ListenAndServe(":8080", nil) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-route_test.go b/vendor/github.com/emicklei/go-restful/examples/restful-route_test.go new file mode 100644 index 00000000..20c366bf --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-route_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/emicklei/go-restful" +) + +var ( + Result string +) + +func TestRouteExtractParameter(t *testing.T) { + // setup service + ws := new(restful.WebService) + ws.Consumes(restful.MIME_XML) + ws.Route(ws.GET("/test/{param}").To(DummyHandler)) + restful.Add(ws) + + // setup request + writer + bodyReader := strings.NewReader("42") + httpRequest, _ := http.NewRequest("GET", "/test/THIS", bodyReader) + httpRequest.Header.Set("Content-Type", restful.MIME_XML) + httpWriter := httptest.NewRecorder() + + // run + restful.DefaultContainer.ServeHTTP(httpWriter, httpRequest) + + if Result != "THIS" { + t.Fatalf("Result is actually: %s", Result) + } +} + +func DummyHandler(rq *restful.Request, rp *restful.Response) { + Result = rq.PathParameter("param") +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-routefunction_test.go b/vendor/github.com/emicklei/go-restful/examples/restful-routefunction_test.go new file mode 100644 index 00000000..957c0555 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-routefunction_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/emicklei/go-restful" +) + +// This example show how to test one particular RouteFunction (getIt) +// It uses the httptest.ResponseRecorder to capture output + +func getIt(req *restful.Request, resp *restful.Response) { + resp.WriteHeader(204) +} + +func TestCallFunction(t *testing.T) { + httpReq, _ := http.NewRequest("GET", "/", nil) + req := restful.NewRequest(httpReq) + + recorder := new(httptest.ResponseRecorder) + resp := restful.NewResponse(recorder) + + getIt(req, resp) + if recorder.Code != 204 { + t.Fatalf("Missing or wrong status code:%d", recorder.Code) + } +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-serve-static.go b/vendor/github.com/emicklei/go-restful/examples/restful-serve-static.go new file mode 100644 index 00000000..8cb7848c --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-serve-static.go @@ -0,0 +1,47 @@ +package main + +import ( + "fmt" + "net/http" + "path" + + "github.com/emicklei/go-restful" +) + +// This example shows how to define methods that serve static files +// It uses the standard http.ServeFile method +// +// GET http://localhost:8080/static/test.xml +// GET http://localhost:8080/static/ +// +// GET http://localhost:8080/static?resource=subdir/test.xml + +var rootdir = "/tmp" + +func main() { + restful.DefaultContainer.Router(restful.CurlyRouter{}) + + ws := new(restful.WebService) + ws.Route(ws.GET("/static/{subpath:*}").To(staticFromPathParam)) + ws.Route(ws.GET("/static").To(staticFromQueryParam)) + restful.Add(ws) + + println("[go-restful] serving files on http://localhost:8080/static from local /tmp") + http.ListenAndServe(":8080", nil) +} + +func staticFromPathParam(req *restful.Request, resp *restful.Response) { + actual := path.Join(rootdir, req.PathParameter("subpath")) + fmt.Printf("serving %s ... (from %s)\n", actual, req.PathParameter("subpath")) + http.ServeFile( + resp.ResponseWriter, + req.Request, + actual) +} + +func staticFromQueryParam(req *restful.Request, resp *restful.Response) { + http.ServeFile( + resp.ResponseWriter, + req.Request, + path.Join(rootdir, req.QueryParameter("resource"))) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-swagger.go b/vendor/github.com/emicklei/go-restful/examples/restful-swagger.go new file mode 100644 index 00000000..261f29d2 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-swagger.go @@ -0,0 +1,61 @@ +package main + +import ( + "log" + "net/http" + + "github.com/emicklei/go-restful" + "github.com/emicklei/go-restful-swagger12" +) + +type Book struct { + Title string + Author string +} + +func main() { + ws := new(restful.WebService) + ws.Path("/books") + ws.Consumes(restful.MIME_JSON, restful.MIME_XML) + ws.Produces(restful.MIME_JSON, restful.MIME_XML) + restful.Add(ws) + + ws.Route(ws.GET("/{medium}").To(noop). + Doc("Search all books"). + Param(ws.PathParameter("medium", "digital or paperback").DataType("string")). + Param(ws.QueryParameter("language", "en,nl,de").DataType("string")). + Param(ws.HeaderParameter("If-Modified-Since", "last known timestamp").DataType("datetime")). + Do(returns200, returns500)) + + ws.Route(ws.PUT("/{medium}").To(noop). + Doc("Add a new book"). + Param(ws.PathParameter("medium", "digital or paperback").DataType("string")). + Reads(Book{})) + + // You can install the Swagger Service which provides a nice Web UI on your REST API + // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. + // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. + config := swagger.Config{ + WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible + WebServicesUrl: "http://localhost:8080", + ApiPath: "/apidocs.json", + + // Optionally, specifiy where the UI is located + SwaggerPath: "/apidocs/", + SwaggerFilePath: "/Users/emicklei/xProjects/swagger-ui/dist"} + swagger.RegisterSwaggerService(config, restful.DefaultContainer) + + log.Printf("start listening on localhost:8080") + server := &http.Server{Addr: ":8080", Handler: restful.DefaultContainer} + log.Fatal(server.ListenAndServe()) +} + +func noop(req *restful.Request, resp *restful.Response) {} + +func returns200(b *restful.RouteBuilder) { + b.Returns(http.StatusOK, "OK", Book{}) +} + +func returns500(b *restful.RouteBuilder) { + b.Returns(http.StatusInternalServerError, "Bummer, something went wrong", nil) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-user-resource.go b/vendor/github.com/emicklei/go-restful/examples/restful-user-resource.go new file mode 100644 index 00000000..4c18dad1 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-user-resource.go @@ -0,0 +1,152 @@ +package main + +import ( + "log" + "net/http" + "strconv" + + "github.com/emicklei/go-restful" + "github.com/emicklei/go-restful-swagger12" +) + +// This example show a complete (GET,PUT,POST,DELETE) conventional example of +// a REST Resource including documentation to be served by e.g. a Swagger UI +// It is recommended to create a Resource struct (UserResource) that can encapsulate +// an object that provide domain access (a DAO) +// It has a Register method including the complete Route mapping to methods together +// with all the appropriate documentation +// +// POST http://localhost:8080/users +// 1Melissa Raspberry +// +// GET http://localhost:8080/users/1 +// +// PUT http://localhost:8080/users/1 +// 1Melissa +// +// DELETE http://localhost:8080/users/1 +// + +type User struct { + Id, Name string +} + +type UserResource struct { + // normally one would use DAO (data access object) + users map[string]User +} + +func (u UserResource) Register(container *restful.Container) { + ws := new(restful.WebService) + ws. + Path("/users"). + Doc("Manage Users"). + Consumes(restful.MIME_XML, restful.MIME_JSON). + Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well + + ws.Route(ws.GET("/{user-id}").To(u.findUser). + // docs + Doc("get a user"). + Operation("findUser"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). + Writes(User{})) // on the response + + ws.Route(ws.PUT("/{user-id}").To(u.updateUser). + // docs + Doc("update a user"). + Operation("updateUser"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). + ReturnsError(409, "duplicate user-id", nil). + Reads(User{})) // from the request + + ws.Route(ws.POST("").To(u.createUser). + // docs + Doc("create a user"). + Operation("createUser"). + Reads(User{})) // from the request + + ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). + // docs + Doc("delete a user"). + Operation("removeUser"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) + + container.Add(ws) +} + +// GET http://localhost:8080/users/1 +// +func (u UserResource) findUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + usr := u.users[id] + if len(usr.Id) == 0 { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusNotFound, "404: User could not be found.") + return + } + response.WriteEntity(usr) +} + +// POST http://localhost:8080/users +// Melissa +// +func (u *UserResource) createUser(request *restful.Request, response *restful.Response) { + usr := new(User) + err := request.ReadEntity(usr) + if err != nil { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusInternalServerError, err.Error()) + return + } + usr.Id = strconv.Itoa(len(u.users) + 1) // simple id generation + u.users[usr.Id] = *usr + response.WriteHeaderAndEntity(http.StatusCreated, usr) +} + +// PUT http://localhost:8080/users/1 +// 1Melissa Raspberry +// +func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) { + usr := new(User) + err := request.ReadEntity(&usr) + if err != nil { + response.AddHeader("Content-Type", "text/plain") + response.WriteErrorString(http.StatusInternalServerError, err.Error()) + return + } + u.users[usr.Id] = *usr + response.WriteEntity(usr) +} + +// DELETE http://localhost:8080/users/1 +// +func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + delete(u.users, id) +} + +func main() { + // to see what happens in the package, uncomment the following + //restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) + + wsContainer := restful.NewContainer() + u := UserResource{map[string]User{}} + u.Register(wsContainer) + + // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API + // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. + // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. + config := swagger.Config{ + WebServices: wsContainer.RegisteredWebServices(), // you control what services are visible + WebServicesUrl: "http://localhost:8080", + ApiPath: "/apidocs.json", + + // Optionally, specifiy where the UI is located + SwaggerPath: "/apidocs/", + SwaggerFilePath: "/Users/emicklei/xProjects/swagger-ui/dist"} + swagger.RegisterSwaggerService(config, wsContainer) + + log.Printf("start listening on localhost:8080") + server := &http.Server{Addr: ":8080", Handler: wsContainer} + log.Fatal(server.ListenAndServe()) +} diff --git a/vendor/github.com/emicklei/go-restful/examples/restful-user-service.go b/vendor/github.com/emicklei/go-restful/examples/restful-user-service.go new file mode 100644 index 00000000..83297fc7 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/examples/restful-user-service.go @@ -0,0 +1,143 @@ +package main + +import ( + "log" + "net/http" + + "github.com/emicklei/go-restful" + "github.com/emicklei/go-restful-swagger12" +) + +// This example is functionally the same as the example in restful-user-resource.go +// with the only difference that is served using the restful.DefaultContainer + +type User struct { + Id, Name string +} + +type UserService struct { + // normally one would use DAO (data access object) + users map[string]User +} + +func (u UserService) Register() { + ws := new(restful.WebService) + ws. + Path("/users"). + Consumes(restful.MIME_XML, restful.MIME_JSON). + Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well + + ws.Route(ws.GET("/").To(u.findAllUsers). + // docs + Doc("get all users"). + Operation("findAllUsers"). + Writes([]User{}). + Returns(200, "OK", nil)) + + ws.Route(ws.GET("/{user-id}").To(u.findUser). + // docs + Doc("get a user"). + Operation("findUser"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). + Writes(User{}). // on the response + Returns(404, "Not Found", nil)) + + ws.Route(ws.PUT("/{user-id}").To(u.updateUser). + // docs + Doc("update a user"). + Operation("updateUser"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). + Reads(User{})) // from the request + + ws.Route(ws.PUT("").To(u.createUser). + // docs + Doc("create a user"). + Operation("createUser"). + Reads(User{})) // from the request + + ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). + // docs + Doc("delete a user"). + Operation("removeUser"). + Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) + + restful.Add(ws) +} + +// GET http://localhost:8080/users +// +func (u UserService) findAllUsers(request *restful.Request, response *restful.Response) { + list := []User{} + for _, each := range u.users { + list = append(list, each) + } + response.WriteEntity(list) +} + +// GET http://localhost:8080/users/1 +// +func (u UserService) findUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + usr := u.users[id] + if len(usr.Id) == 0 { + response.WriteErrorString(http.StatusNotFound, "User could not be found.") + } else { + response.WriteEntity(usr) + } +} + +// PUT http://localhost:8080/users/1 +// 1Melissa Raspberry +// +func (u *UserService) updateUser(request *restful.Request, response *restful.Response) { + usr := new(User) + err := request.ReadEntity(&usr) + if err == nil { + u.users[usr.Id] = *usr + response.WriteEntity(usr) + } else { + response.WriteError(http.StatusInternalServerError, err) + } +} + +// PUT http://localhost:8080/users/1 +// 1Melissa +// +func (u *UserService) createUser(request *restful.Request, response *restful.Response) { + usr := User{Id: request.PathParameter("user-id")} + err := request.ReadEntity(&usr) + if err == nil { + u.users[usr.Id] = usr + response.WriteHeaderAndEntity(http.StatusCreated, usr) + } else { + response.WriteError(http.StatusInternalServerError, err) + } +} + +// DELETE http://localhost:8080/users/1 +// +func (u *UserService) removeUser(request *restful.Request, response *restful.Response) { + id := request.PathParameter("user-id") + delete(u.users, id) +} + +func main() { + u := UserService{map[string]User{}} + u.Register() + + // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API + // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. + // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. + config := swagger.Config{ + WebServices: restful.RegisteredWebServices(), // you control what services are visible + WebServicesUrl: "http://localhost:8080", + ApiPath: "/apidocs.json", + + // Optionally, specifiy where the UI is located + SwaggerPath: "/apidocs/", + SwaggerFilePath: "/Users/emicklei/Projects/swagger-ui/dist"} + swagger.InstallSwaggerService(config) + + log.Printf("start listening on localhost:8080") + log.Fatal(http.ListenAndServe(":8080", nil)) +} diff --git a/vendor/github.com/emicklei/go-restful/filter.go b/vendor/github.com/emicklei/go-restful/filter.go new file mode 100644 index 00000000..c23bfb59 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/filter.go @@ -0,0 +1,35 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +// FilterChain is a request scoped object to process one or more filters before calling the target RouteFunction. +type FilterChain struct { + Filters []FilterFunction // ordered list of FilterFunction + Index int // index into filters that is currently in progress + Target RouteFunction // function to call after passing all filters +} + +// ProcessFilter passes the request,response pair through the next of Filters. +// Each filter can decide to proceed to the next Filter or handle the Response itself. +func (f *FilterChain) ProcessFilter(request *Request, response *Response) { + if f.Index < len(f.Filters) { + f.Index++ + f.Filters[f.Index-1](request, response, f) + } else { + f.Target(request, response) + } +} + +// FilterFunction definitions must call ProcessFilter on the FilterChain to pass on the control and eventually call the RouteFunction +type FilterFunction func(*Request, *Response, *FilterChain) + +// NoBrowserCacheFilter is a filter function to set HTTP headers that disable browser caching +// See examples/restful-no-cache-filter.go for usage +func NoBrowserCacheFilter(req *Request, resp *Response, chain *FilterChain) { + resp.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1. + resp.Header().Set("Pragma", "no-cache") // HTTP 1.0. + resp.Header().Set("Expires", "0") // Proxies. + chain.ProcessFilter(req, resp) +} diff --git a/vendor/github.com/emicklei/go-restful/filter_test.go b/vendor/github.com/emicklei/go-restful/filter_test.go new file mode 100644 index 00000000..fadfb570 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/filter_test.go @@ -0,0 +1,141 @@ +package restful + +import ( + "io" + "net/http" + "net/http/httptest" + "testing" +) + +func setupServices(addGlobalFilter bool, addServiceFilter bool, addRouteFilter bool) { + if addGlobalFilter { + Filter(globalFilter) + } + Add(newTestService(addServiceFilter, addRouteFilter)) +} + +func tearDown() { + DefaultContainer.webServices = []*WebService{} + DefaultContainer.isRegisteredOnRoot = true // this allows for setupServices multiple times + DefaultContainer.containerFilters = []FilterFunction{} +} + +func newTestService(addServiceFilter bool, addRouteFilter bool) *WebService { + ws := new(WebService).Path("") + if addServiceFilter { + ws.Filter(serviceFilter) + } + rb := ws.GET("/foo").To(foo) + if addRouteFilter { + rb.Filter(routeFilter) + } + ws.Route(rb) + ws.Route(ws.GET("/bar").To(bar)) + return ws +} + +func foo(req *Request, resp *Response) { + io.WriteString(resp.ResponseWriter, "foo") +} + +func bar(req *Request, resp *Response) { + io.WriteString(resp.ResponseWriter, "bar") +} + +func fail(req *Request, resp *Response) { + http.Error(resp.ResponseWriter, "something failed", http.StatusInternalServerError) +} + +func globalFilter(req *Request, resp *Response, chain *FilterChain) { + io.WriteString(resp.ResponseWriter, "global-") + chain.ProcessFilter(req, resp) +} + +func serviceFilter(req *Request, resp *Response, chain *FilterChain) { + io.WriteString(resp.ResponseWriter, "service-") + chain.ProcessFilter(req, resp) +} + +func routeFilter(req *Request, resp *Response, chain *FilterChain) { + io.WriteString(resp.ResponseWriter, "route-") + chain.ProcessFilter(req, resp) +} + +func TestNoFilter(t *testing.T) { + tearDown() + setupServices(false, false, false) + actual := sendIt("http://example.com/foo") + if "foo" != actual { + t.Fatal("expected: foo but got:" + actual) + } +} + +func TestGlobalFilter(t *testing.T) { + tearDown() + setupServices(true, false, false) + actual := sendIt("http://example.com/foo") + if "global-foo" != actual { + t.Fatal("expected: global-foo but got:" + actual) + } +} + +func TestWebServiceFilter(t *testing.T) { + tearDown() + setupServices(true, true, false) + actual := sendIt("http://example.com/foo") + if "global-service-foo" != actual { + t.Fatal("expected: global-service-foo but got:" + actual) + } +} + +func TestRouteFilter(t *testing.T) { + tearDown() + setupServices(true, true, true) + actual := sendIt("http://example.com/foo") + if "global-service-route-foo" != actual { + t.Fatal("expected: global-service-route-foo but got:" + actual) + } +} + +func TestRouteFilterOnly(t *testing.T) { + tearDown() + setupServices(false, false, true) + actual := sendIt("http://example.com/foo") + if "route-foo" != actual { + t.Fatal("expected: route-foo but got:" + actual) + } +} + +func TestBar(t *testing.T) { + tearDown() + setupServices(false, true, false) + actual := sendIt("http://example.com/bar") + if "service-bar" != actual { + t.Fatal("expected: service-bar but got:" + actual) + } +} + +func TestAllFiltersBar(t *testing.T) { + tearDown() + setupServices(true, true, true) + actual := sendIt("http://example.com/bar") + if "global-service-bar" != actual { + t.Fatal("expected: global-service-bar but got:" + actual) + } +} + +func sendIt(address string) string { + httpRequest, _ := http.NewRequest("GET", address, nil) + httpRequest.Header.Set("Accept", "*/*") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + return httpWriter.Body.String() +} + +func sendItTo(address string, container *Container) string { + httpRequest, _ := http.NewRequest("GET", address, nil) + httpRequest.Header.Set("Accept", "*/*") + httpWriter := httptest.NewRecorder() + container.dispatch(httpWriter, httpRequest) + return httpWriter.Body.String() +} diff --git a/vendor/github.com/emicklei/go-restful/install.sh b/vendor/github.com/emicklei/go-restful/install.sh new file mode 100644 index 00000000..36cbf25f --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/install.sh @@ -0,0 +1,10 @@ +go test -test.v ...restful && \ +go test -test.v ...swagger && \ +go vet ...restful && \ +go fmt ...swagger && \ +go install ...swagger && \ +go fmt ...restful && \ +go install ...restful +cd examples + ls *.go | xargs -I {} go build -o /tmp/ignore {} + cd .. \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/jsr311.go b/vendor/github.com/emicklei/go-restful/jsr311.go new file mode 100644 index 00000000..511444ac --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/jsr311.go @@ -0,0 +1,248 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "errors" + "fmt" + "net/http" + "sort" +) + +// RouterJSR311 implements the flow for matching Requests to Routes (and consequently Resource Functions) +// as specified by the JSR311 http://jsr311.java.net/nonav/releases/1.1/spec/spec.html. +// RouterJSR311 implements the Router interface. +// Concept of locators is not implemented. +type RouterJSR311 struct{} + +// SelectRoute is part of the Router interface and returns the best match +// for the WebService and its Route for the given Request. +func (r RouterJSR311) SelectRoute( + webServices []*WebService, + httpRequest *http.Request) (selectedService *WebService, selectedRoute *Route, err error) { + + // Identify the root resource class (WebService) + dispatcher, finalMatch, err := r.detectDispatcher(httpRequest.URL.Path, webServices) + if err != nil { + return nil, nil, NewError(http.StatusNotFound, "") + } + // Obtain the set of candidate methods (Routes) + routes := r.selectRoutes(dispatcher, finalMatch) + if len(routes) == 0 { + return dispatcher, nil, NewError(http.StatusNotFound, "404: Page Not Found") + } + + // Identify the method (Route) that will handle the request + route, ok := r.detectRoute(routes, httpRequest) + return dispatcher, route, ok +} + +// http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 +func (r RouterJSR311) detectRoute(routes []Route, httpRequest *http.Request) (*Route, error) { + // http method + methodOk := []Route{} + for _, each := range routes { + if httpRequest.Method == each.Method { + methodOk = append(methodOk, each) + } + } + if len(methodOk) == 0 { + if trace { + traceLogger.Printf("no Route found (in %d routes) that matches HTTP method %s\n", len(routes), httpRequest.Method) + } + return nil, NewError(http.StatusMethodNotAllowed, "405: Method Not Allowed") + } + inputMediaOk := methodOk + + // content-type + contentType := httpRequest.Header.Get(HEADER_ContentType) + inputMediaOk = []Route{} + for _, each := range methodOk { + if each.matchesContentType(contentType) { + inputMediaOk = append(inputMediaOk, each) + } + } + if len(inputMediaOk) == 0 { + if trace { + traceLogger.Printf("no Route found (from %d) that matches HTTP Content-Type: %s\n", len(methodOk), contentType) + } + return nil, NewError(http.StatusUnsupportedMediaType, "415: Unsupported Media Type") + } + + // accept + outputMediaOk := []Route{} + accept := httpRequest.Header.Get(HEADER_Accept) + if len(accept) == 0 { + accept = "*/*" + } + for _, each := range inputMediaOk { + if each.matchesAccept(accept) { + outputMediaOk = append(outputMediaOk, each) + } + } + if len(outputMediaOk) == 0 { + if trace { + traceLogger.Printf("no Route found (from %d) that matches HTTP Accept: %s\n", len(inputMediaOk), accept) + } + return nil, NewError(http.StatusNotAcceptable, "406: Not Acceptable") + } + // return r.bestMatchByMedia(outputMediaOk, contentType, accept), nil + return &outputMediaOk[0], nil +} + +// http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 +// n/m > n/* > */* +func (r RouterJSR311) bestMatchByMedia(routes []Route, contentType string, accept string) *Route { + // TODO + return &routes[0] +} + +// http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 (step 2) +func (r RouterJSR311) selectRoutes(dispatcher *WebService, pathRemainder string) []Route { + filtered := &sortableRouteCandidates{} + for _, each := range dispatcher.Routes() { + pathExpr := each.pathExpr + matches := pathExpr.Matcher.FindStringSubmatch(pathRemainder) + if matches != nil { + lastMatch := matches[len(matches)-1] + if len(lastMatch) == 0 || lastMatch == "/" { // do not include if value is neither empty nor ‘/’. + filtered.candidates = append(filtered.candidates, + routeCandidate{each, len(matches) - 1, pathExpr.LiteralCount, pathExpr.VarCount}) + } + } + } + if len(filtered.candidates) == 0 { + if trace { + traceLogger.Printf("WebService on path %s has no routes that match URL path remainder:%s\n", dispatcher.rootPath, pathRemainder) + } + return []Route{} + } + sort.Sort(sort.Reverse(filtered)) + + // select other routes from candidates whoes expression matches rmatch + matchingRoutes := []Route{filtered.candidates[0].route} + for c := 1; c < len(filtered.candidates); c++ { + each := filtered.candidates[c] + if each.route.pathExpr.Matcher.MatchString(pathRemainder) { + matchingRoutes = append(matchingRoutes, each.route) + } + } + return matchingRoutes +} + +// http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 (step 1) +func (r RouterJSR311) detectDispatcher(requestPath string, dispatchers []*WebService) (*WebService, string, error) { + filtered := &sortableDispatcherCandidates{} + for _, each := range dispatchers { + matches := each.pathExpr.Matcher.FindStringSubmatch(requestPath) + if matches != nil { + filtered.candidates = append(filtered.candidates, + dispatcherCandidate{each, matches[len(matches)-1], len(matches), each.pathExpr.LiteralCount, each.pathExpr.VarCount}) + } + } + if len(filtered.candidates) == 0 { + if trace { + traceLogger.Printf("no WebService was found to match URL path:%s\n", requestPath) + } + return nil, "", errors.New("not found") + } + sort.Sort(sort.Reverse(filtered)) + return filtered.candidates[0].dispatcher, filtered.candidates[0].finalMatch, nil +} + +// Types and functions to support the sorting of Routes + +type routeCandidate struct { + route Route + matchesCount int // the number of capturing groups + literalCount int // the number of literal characters (means those not resulting from template variable substitution) + nonDefaultCount int // the number of capturing groups with non-default regular expressions (i.e. not ‘([^ /]+?)’) +} + +func (r routeCandidate) expressionToMatch() string { + return r.route.pathExpr.Source +} + +func (r routeCandidate) String() string { + return fmt.Sprintf("(m=%d,l=%d,n=%d)", r.matchesCount, r.literalCount, r.nonDefaultCount) +} + +type sortableRouteCandidates struct { + candidates []routeCandidate +} + +func (rcs *sortableRouteCandidates) Len() int { + return len(rcs.candidates) +} +func (rcs *sortableRouteCandidates) Swap(i, j int) { + rcs.candidates[i], rcs.candidates[j] = rcs.candidates[j], rcs.candidates[i] +} +func (rcs *sortableRouteCandidates) Less(i, j int) bool { + ci := rcs.candidates[i] + cj := rcs.candidates[j] + // primary key + if ci.literalCount < cj.literalCount { + return true + } + if ci.literalCount > cj.literalCount { + return false + } + // secundary key + if ci.matchesCount < cj.matchesCount { + return true + } + if ci.matchesCount > cj.matchesCount { + return false + } + // tertiary key + if ci.nonDefaultCount < cj.nonDefaultCount { + return true + } + if ci.nonDefaultCount > cj.nonDefaultCount { + return false + } + // quaternary key ("source" is interpreted as Path) + return ci.route.Path < cj.route.Path +} + +// Types and functions to support the sorting of Dispatchers + +type dispatcherCandidate struct { + dispatcher *WebService + finalMatch string + matchesCount int // the number of capturing groups + literalCount int // the number of literal characters (means those not resulting from template variable substitution) + nonDefaultCount int // the number of capturing groups with non-default regular expressions (i.e. not ‘([^ /]+?)’) +} +type sortableDispatcherCandidates struct { + candidates []dispatcherCandidate +} + +func (dc *sortableDispatcherCandidates) Len() int { + return len(dc.candidates) +} +func (dc *sortableDispatcherCandidates) Swap(i, j int) { + dc.candidates[i], dc.candidates[j] = dc.candidates[j], dc.candidates[i] +} +func (dc *sortableDispatcherCandidates) Less(i, j int) bool { + ci := dc.candidates[i] + cj := dc.candidates[j] + // primary key + if ci.matchesCount < cj.matchesCount { + return true + } + if ci.matchesCount > cj.matchesCount { + return false + } + // secundary key + if ci.literalCount < cj.literalCount { + return true + } + if ci.literalCount > cj.literalCount { + return false + } + // tertiary key + return ci.nonDefaultCount < cj.nonDefaultCount +} diff --git a/vendor/github.com/emicklei/go-restful/jsr311_test.go b/vendor/github.com/emicklei/go-restful/jsr311_test.go new file mode 100644 index 00000000..3e79a6de --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/jsr311_test.go @@ -0,0 +1,212 @@ +package restful + +import ( + "io" + "sort" + "testing" +) + +// +// Step 1 tests +// +var paths = []struct { + // url with path (1) is handled by service with root (2) and last capturing group has value final (3) + path, root, final string +}{ + {"/", "/", "/"}, + {"/p", "/p", ""}, + {"/p/x", "/p/{q}", ""}, + {"/q/x", "/q", "/x"}, + {"/p/x/", "/p/{q}", "/"}, + {"/p/x/y", "/p/{q}", "/y"}, + {"/q/x/y", "/q", "/x/y"}, + {"/z/q", "/{p}/q", ""}, + {"/a/b/c/q", "/", "/a/b/c/q"}, +} + +func TestDetectDispatcher(t *testing.T) { + ws1 := new(WebService).Path("/") + ws2 := new(WebService).Path("/p") + ws3 := new(WebService).Path("/q") + ws4 := new(WebService).Path("/p/q") + ws5 := new(WebService).Path("/p/{q}") + ws6 := new(WebService).Path("/p/{q}/") + ws7 := new(WebService).Path("/{p}/q") + var dispatchers = []*WebService{ws1, ws2, ws3, ws4, ws5, ws6, ws7} + + wc := NewContainer() + for _, each := range dispatchers { + wc.Add(each) + } + + router := RouterJSR311{} + + ok := true + for i, fixture := range paths { + who, final, err := router.detectDispatcher(fixture.path, dispatchers) + if err != nil { + t.Logf("error in detection:%v", err) + ok = false + } + if who.RootPath() != fixture.root { + t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) + ok = false + } + if final != fixture.final { + t.Logf("[line:%v] Unexpected final, expected:%v, actual:%v", i, fixture.final, final) + ok = false + } + } + if !ok { + t.Fail() + } +} + +// +// Step 2 tests +// + +// go test -v -test.run TestISSUE_179 ...restful +func TestISSUE_179(t *testing.T) { + ws1 := new(WebService) + ws1.Route(ws1.GET("/v1/category/{param:*}").To(dummy)) + routes := RouterJSR311{}.selectRoutes(ws1, "/v1/category/sub/sub") + t.Logf("%v", routes) +} + +// go test -v -test.run TestISSUE_30 ...restful +func TestISSUE_30(t *testing.T) { + ws1 := new(WebService).Path("/users") + ws1.Route(ws1.GET("/{id}").To(dummy)) + ws1.Route(ws1.POST("/login").To(dummy)) + routes := RouterJSR311{}.selectRoutes(ws1, "/login") + if len(routes) != 2 { + t.Fatal("expected 2 routes") + } + if routes[0].Path != "/users/login" { + t.Error("first is", routes[0].Path) + t.Logf("routes:%v", routes) + } +} + +// go test -v -test.run TestISSUE_34 ...restful +func TestISSUE_34(t *testing.T) { + ws1 := new(WebService).Path("/") + ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) + ws1.Route(ws1.GET("/network/{id}").To(dummy)) + routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") + if len(routes) != 2 { + t.Fatal("expected 2 routes") + } + if routes[0].Path != "/network/{id}" { + t.Error("first is", routes[0].Path) + t.Logf("routes:%v", routes) + } +} + +// go test -v -test.run TestISSUE_34_2 ...restful +func TestISSUE_34_2(t *testing.T) { + ws1 := new(WebService).Path("/") + // change the registration order + ws1.Route(ws1.GET("/network/{id}").To(dummy)) + ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) + routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") + if len(routes) != 2 { + t.Fatal("expected 2 routes") + } + if routes[0].Path != "/network/{id}" { + t.Error("first is", routes[0].Path) + } +} + +// go test -v -test.run TestISSUE_137 ...restful +func TestISSUE_137(t *testing.T) { + ws1 := new(WebService) + ws1.Route(ws1.GET("/hello").To(dummy)) + routes := RouterJSR311{}.selectRoutes(ws1, "/") + t.Log(routes) + if len(routes) > 0 { + t.Error("no route expected") + } +} + +func TestSelectRoutesSlash(t *testing.T) { + ws1 := new(WebService).Path("/") + ws1.Route(ws1.GET("").To(dummy)) + ws1.Route(ws1.GET("/").To(dummy)) + ws1.Route(ws1.GET("/u").To(dummy)) + ws1.Route(ws1.POST("/u").To(dummy)) + ws1.Route(ws1.POST("/u/v").To(dummy)) + ws1.Route(ws1.POST("/u/{w}").To(dummy)) + ws1.Route(ws1.POST("/u/{w}/z").To(dummy)) + routes := RouterJSR311{}.selectRoutes(ws1, "/u") + checkRoutesContains(routes, "/u", t) + checkRoutesContainsNo(routes, "/u/v", t) + checkRoutesContainsNo(routes, "/", t) + checkRoutesContainsNo(routes, "/u/{w}/z", t) +} +func TestSelectRoutesU(t *testing.T) { + ws1 := new(WebService).Path("/u") + ws1.Route(ws1.GET("").To(dummy)) + ws1.Route(ws1.GET("/").To(dummy)) + ws1.Route(ws1.GET("/v").To(dummy)) + ws1.Route(ws1.POST("/{w}").To(dummy)) + ws1.Route(ws1.POST("/{w}/z").To(dummy)) // so full path = /u/{w}/z + routes := RouterJSR311{}.selectRoutes(ws1, "/v") // test against /u/v + checkRoutesContains(routes, "/u/{w}", t) +} + +func TestSelectRoutesUsers1(t *testing.T) { + ws1 := new(WebService).Path("/users") + ws1.Route(ws1.POST("").To(dummy)) + ws1.Route(ws1.POST("/").To(dummy)) + ws1.Route(ws1.PUT("/{id}").To(dummy)) + routes := RouterJSR311{}.selectRoutes(ws1, "/1") + checkRoutesContains(routes, "/users/{id}", t) +} +func checkRoutesContains(routes []Route, path string, t *testing.T) { + if !containsRoutePath(routes, path, t) { + for _, r := range routes { + t.Logf("route %v %v", r.Method, r.Path) + } + t.Fatalf("routes should include [%v]:", path) + } +} +func checkRoutesContainsNo(routes []Route, path string, t *testing.T) { + if containsRoutePath(routes, path, t) { + for _, r := range routes { + t.Logf("route %v %v", r.Method, r.Path) + } + t.Fatalf("routes should not include [%v]:", path) + } +} +func containsRoutePath(routes []Route, path string, t *testing.T) bool { + for _, each := range routes { + if each.Path == path { + return true + } + } + return false +} + +// go test -v -test.run TestSortableRouteCandidates ...restful +func TestSortableRouteCandidates(t *testing.T) { + fixture := &sortableRouteCandidates{} + r1 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 0} + r2 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 1} + r3 := routeCandidate{matchesCount: 0, literalCount: 1, nonDefaultCount: 1} + r4 := routeCandidate{matchesCount: 1, literalCount: 1, nonDefaultCount: 0} + r5 := routeCandidate{matchesCount: 1, literalCount: 0, nonDefaultCount: 0} + fixture.candidates = append(fixture.candidates, r5, r4, r3, r2, r1) + sort.Sort(sort.Reverse(fixture)) + first := fixture.candidates[0] + if first.matchesCount != 1 && first.literalCount != 1 && first.nonDefaultCount != 0 { + t.Fatal("expected r4") + } + last := fixture.candidates[len(fixture.candidates)-1] + if last.matchesCount != 0 && last.literalCount != 0 && last.nonDefaultCount != 0 { + t.Fatal("expected r1") + } +} + +func dummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "dummy") } diff --git a/vendor/github.com/emicklei/go-restful/log/log.go b/vendor/github.com/emicklei/go-restful/log/log.go new file mode 100644 index 00000000..f70d8952 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/log/log.go @@ -0,0 +1,31 @@ +package log + +import ( + stdlog "log" + "os" +) + +// Logger corresponds to a minimal subset of the interface satisfied by stdlib log.Logger +type StdLogger interface { + Print(v ...interface{}) + Printf(format string, v ...interface{}) +} + +var Logger StdLogger + +func init() { + // default Logger + SetLogger(stdlog.New(os.Stderr, "[restful] ", stdlog.LstdFlags|stdlog.Lshortfile)) +} + +func SetLogger(customLogger StdLogger) { + Logger = customLogger +} + +func Print(v ...interface{}) { + Logger.Print(v...) +} + +func Printf(format string, v ...interface{}) { + Logger.Printf(format, v...) +} diff --git a/vendor/github.com/emicklei/go-restful/logger.go b/vendor/github.com/emicklei/go-restful/logger.go new file mode 100644 index 00000000..3f1c4db8 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/logger.go @@ -0,0 +1,32 @@ +package restful + +// Copyright 2014 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. +import ( + "github.com/emicklei/go-restful/log" +) + +var trace bool = false +var traceLogger log.StdLogger + +func init() { + traceLogger = log.Logger // use the package logger by default +} + +// TraceLogger enables detailed logging of Http request matching and filter invocation. Default no logger is set. +// You may call EnableTracing() directly to enable trace logging to the package-wide logger. +func TraceLogger(logger log.StdLogger) { + traceLogger = logger + EnableTracing(logger != nil) +} + +// expose the setter for the global logger on the top-level package +func SetLogger(customLogger log.StdLogger) { + log.SetLogger(customLogger) +} + +// EnableTracing can be used to Trace logging on and off. +func EnableTracing(enabled bool) { + trace = enabled +} diff --git a/vendor/github.com/emicklei/go-restful/mime.go b/vendor/github.com/emicklei/go-restful/mime.go new file mode 100644 index 00000000..d7ea2b61 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/mime.go @@ -0,0 +1,45 @@ +package restful + +import ( + "strconv" + "strings" +) + +type mime struct { + media string + quality float64 +} + +// insertMime adds a mime to a list and keeps it sorted by quality. +func insertMime(l []mime, e mime) []mime { + for i, each := range l { + // if current mime has lower quality then insert before + if e.quality > each.quality { + left := append([]mime{}, l[0:i]...) + return append(append(left, e), l[i:]...) + } + } + return append(l, e) +} + +// sortedMimes returns a list of mime sorted (desc) by its specified quality. +func sortedMimes(accept string) (sorted []mime) { + for _, each := range strings.Split(accept, ",") { + typeAndQuality := strings.Split(strings.Trim(each, " "), ";") + if len(typeAndQuality) == 1 { + sorted = insertMime(sorted, mime{typeAndQuality[0], 1.0}) + } else { + // take factor + parts := strings.Split(typeAndQuality[1], "=") + if len(parts) == 2 { + f, err := strconv.ParseFloat(parts[1], 64) + if err != nil { + traceLogger.Printf("unable to parse quality in %s, %v", each, err) + } else { + sorted = insertMime(sorted, mime{typeAndQuality[0], f}) + } + } + } + } + return +} diff --git a/vendor/github.com/emicklei/go-restful/mime_test.go b/vendor/github.com/emicklei/go-restful/mime_test.go new file mode 100644 index 00000000..a910bb10 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/mime_test.go @@ -0,0 +1,17 @@ +package restful + +import ( + "fmt" + "testing" +) + +// go test -v -test.run TestSortMimes ...restful +func TestSortMimes(t *testing.T) { + accept := "text/html; q=0.8, text/plain, image/gif, */*; q=0.01, image/jpeg" + result := sortedMimes(accept) + got := fmt.Sprintf("%v", result) + want := "[{text/plain 1} {image/gif 1} {image/jpeg 1} {text/html 0.8} {*/* 0.01}]" + if got != want { + t.Errorf("bad sort order of mime types:%s", got) + } +} diff --git a/vendor/github.com/emicklei/go-restful/options_filter.go b/vendor/github.com/emicklei/go-restful/options_filter.go new file mode 100644 index 00000000..4514eadc --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/options_filter.go @@ -0,0 +1,26 @@ +package restful + +import "strings" + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +// OPTIONSFilter is a filter function that inspects the Http Request for the OPTIONS method +// and provides the response with a set of allowed methods for the request URL Path. +// As for any filter, you can also install it for a particular WebService within a Container. +// Note: this filter is not needed when using CrossOriginResourceSharing (for CORS). +func (c *Container) OPTIONSFilter(req *Request, resp *Response, chain *FilterChain) { + if "OPTIONS" != req.Request.Method { + chain.ProcessFilter(req, resp) + return + } + resp.AddHeader(HEADER_Allow, strings.Join(c.computeAllowedMethods(req), ",")) +} + +// OPTIONSFilter is a filter function that inspects the Http Request for the OPTIONS method +// and provides the response with a set of allowed methods for the request URL Path. +// Note: this filter is not needed when using CrossOriginResourceSharing (for CORS). +func OPTIONSFilter() FilterFunction { + return DefaultContainer.OPTIONSFilter +} diff --git a/vendor/github.com/emicklei/go-restful/options_filter_test.go b/vendor/github.com/emicklei/go-restful/options_filter_test.go new file mode 100644 index 00000000..f0fceb83 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/options_filter_test.go @@ -0,0 +1,34 @@ +package restful + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +// go test -v -test.run TestOptionsFilter ...restful +func TestOptionsFilter(t *testing.T) { + tearDown() + ws := new(WebService) + ws.Route(ws.GET("/candy/{kind}").To(dummy)) + ws.Route(ws.DELETE("/candy/{kind}").To(dummy)) + ws.Route(ws.POST("/candies").To(dummy)) + Add(ws) + Filter(OPTIONSFilter()) + + httpRequest, _ := http.NewRequest("OPTIONS", "http://here.io/candy/gum", nil) + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + actual := httpWriter.Header().Get(HEADER_Allow) + if "GET,DELETE" != actual { + t.Fatal("expected: GET,DELETE but got:" + actual) + } + + httpRequest, _ = http.NewRequest("OPTIONS", "http://here.io/candies", nil) + httpWriter = httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + actual = httpWriter.Header().Get(HEADER_Allow) + if "POST" != actual { + t.Fatal("expected: POST but got:" + actual) + } +} diff --git a/vendor/github.com/emicklei/go-restful/parameter.go b/vendor/github.com/emicklei/go-restful/parameter.go new file mode 100644 index 00000000..e11c8162 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/parameter.go @@ -0,0 +1,114 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +const ( + // PathParameterKind = indicator of Request parameter type "path" + PathParameterKind = iota + + // QueryParameterKind = indicator of Request parameter type "query" + QueryParameterKind + + // BodyParameterKind = indicator of Request parameter type "body" + BodyParameterKind + + // HeaderParameterKind = indicator of Request parameter type "header" + HeaderParameterKind + + // FormParameterKind = indicator of Request parameter type "form" + FormParameterKind +) + +// Parameter is for documententing the parameter used in a Http Request +// ParameterData kinds are Path,Query and Body +type Parameter struct { + data *ParameterData +} + +// ParameterData represents the state of a Parameter. +// It is made public to make it accessible to e.g. the Swagger package. +type ParameterData struct { + Name, Description, DataType, DataFormat string + Kind int + Required bool + AllowableValues map[string]string + AllowMultiple bool + DefaultValue string +} + +// Data returns the state of the Parameter +func (p *Parameter) Data() ParameterData { + return *p.data +} + +// Kind returns the parameter type indicator (see const for valid values) +func (p *Parameter) Kind() int { + return p.data.Kind +} + +func (p *Parameter) bePath() *Parameter { + p.data.Kind = PathParameterKind + return p +} +func (p *Parameter) beQuery() *Parameter { + p.data.Kind = QueryParameterKind + return p +} +func (p *Parameter) beBody() *Parameter { + p.data.Kind = BodyParameterKind + return p +} + +func (p *Parameter) beHeader() *Parameter { + p.data.Kind = HeaderParameterKind + return p +} + +func (p *Parameter) beForm() *Parameter { + p.data.Kind = FormParameterKind + return p +} + +// Required sets the required field and returns the receiver +func (p *Parameter) Required(required bool) *Parameter { + p.data.Required = required + return p +} + +// AllowMultiple sets the allowMultiple field and returns the receiver +func (p *Parameter) AllowMultiple(multiple bool) *Parameter { + p.data.AllowMultiple = multiple + return p +} + +// AllowableValues sets the allowableValues field and returns the receiver +func (p *Parameter) AllowableValues(values map[string]string) *Parameter { + p.data.AllowableValues = values + return p +} + +// DataType sets the dataType field and returns the receiver +func (p *Parameter) DataType(typeName string) *Parameter { + p.data.DataType = typeName + return p +} + +// DataFormat sets the dataFormat field for Swagger UI +func (p *Parameter) DataFormat(formatName string) *Parameter { + p.data.DataFormat = formatName + return p +} + +// DefaultValue sets the default value field and returns the receiver +func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter { + p.data.DefaultValue = stringRepresentation + return p +} + +// Description sets the description value field and returns the receiver +func (p *Parameter) Description(doc string) *Parameter { + p.data.Description = doc + return p +} diff --git a/vendor/github.com/emicklei/go-restful/path_expression.go b/vendor/github.com/emicklei/go-restful/path_expression.go new file mode 100644 index 00000000..a921e6f2 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/path_expression.go @@ -0,0 +1,69 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "bytes" + "fmt" + "regexp" + "strings" +) + +// PathExpression holds a compiled path expression (RegExp) needed to match against +// Http request paths and to extract path parameter values. +type pathExpression struct { + LiteralCount int // the number of literal characters (means those not resulting from template variable substitution) + VarCount int // the number of named parameters (enclosed by {}) in the path + Matcher *regexp.Regexp + Source string // Path as defined by the RouteBuilder + tokens []string +} + +// NewPathExpression creates a PathExpression from the input URL path. +// Returns an error if the path is invalid. +func newPathExpression(path string) (*pathExpression, error) { + expression, literalCount, varCount, tokens := templateToRegularExpression(path) + compiled, err := regexp.Compile(expression) + if err != nil { + return nil, err + } + return &pathExpression{literalCount, varCount, compiled, expression, tokens}, nil +} + +// http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-370003.7.3 +func templateToRegularExpression(template string) (expression string, literalCount int, varCount int, tokens []string) { + var buffer bytes.Buffer + buffer.WriteString("^") + //tokens = strings.Split(template, "/") + tokens = tokenizePath(template) + for _, each := range tokens { + if each == "" { + continue + } + buffer.WriteString("/") + if strings.HasPrefix(each, "{") { + // check for regular expression in variable + colon := strings.Index(each, ":") + if colon != -1 { + // extract expression + paramExpr := strings.TrimSpace(each[colon+1 : len(each)-1]) + if paramExpr == "*" { // special case + buffer.WriteString("(.*)") + } else { + buffer.WriteString(fmt.Sprintf("(%s)", paramExpr)) // between colon and closing moustache + } + } else { + // plain var + buffer.WriteString("([^/]+?)") + } + varCount += 1 + } else { + literalCount += len(each) + encoded := each // TODO URI encode + buffer.WriteString(regexp.QuoteMeta(encoded)) + } + } + return strings.TrimRight(buffer.String(), "/") + "(/.*)?$", literalCount, varCount, tokens +} diff --git a/vendor/github.com/emicklei/go-restful/path_expression_test.go b/vendor/github.com/emicklei/go-restful/path_expression_test.go new file mode 100644 index 00000000..334fcef7 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/path_expression_test.go @@ -0,0 +1,37 @@ +package restful + +import "testing" + +var tempregexs = []struct { + template, regex string + literalCount, varCount int +}{ + {"", "^(/.*)?$", 0, 0}, + {"/a/{b}/c/", "^/a/([^/]+?)/c(/.*)?$", 2, 1}, + {"/{a}/{b}/{c-d-e}/", "^/([^/]+?)/([^/]+?)/([^/]+?)(/.*)?$", 0, 3}, + {"/{p}/abcde", "^/([^/]+?)/abcde(/.*)?$", 5, 1}, + {"/a/{b:*}", "^/a/(.*)(/.*)?$", 1, 1}, + {"/a/{b:[a-z]+}", "^/a/([a-z]+)(/.*)?$", 1, 1}, +} + +func TestTemplateToRegularExpression(t *testing.T) { + ok := true + for i, fixture := range tempregexs { + actual, lCount, vCount, _ := templateToRegularExpression(fixture.template) + if actual != fixture.regex { + t.Logf("regex mismatch, expected:%v , actual:%v, line:%v\n", fixture.regex, actual, i) // 11 = where the data starts + ok = false + } + if lCount != fixture.literalCount { + t.Logf("literal count mismatch, expected:%v , actual:%v, line:%v\n", fixture.literalCount, lCount, i) + ok = false + } + if vCount != fixture.varCount { + t.Logf("variable count mismatch, expected:%v , actual:%v, line:%v\n", fixture.varCount, vCount, i) + ok = false + } + } + if !ok { + t.Fatal("one or more expression did not match") + } +} diff --git a/vendor/github.com/emicklei/go-restful/request.go b/vendor/github.com/emicklei/go-restful/request.go new file mode 100644 index 00000000..8c23af12 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/request.go @@ -0,0 +1,113 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "compress/zlib" + "net/http" +) + +var defaultRequestContentType string + +// Request is a wrapper for a http Request that provides convenience methods +type Request struct { + Request *http.Request + pathParameters map[string]string + attributes map[string]interface{} // for storing request-scoped values + selectedRoutePath string // root path + route path that matched the request, e.g. /meetings/{id}/attendees +} + +func NewRequest(httpRequest *http.Request) *Request { + return &Request{ + Request: httpRequest, + pathParameters: map[string]string{}, + attributes: map[string]interface{}{}, + } // empty parameters, attributes +} + +// If ContentType is missing or */* is given then fall back to this type, otherwise +// a "Unable to unmarshal content of type:" response is returned. +// Valid values are restful.MIME_JSON and restful.MIME_XML +// Example: +// restful.DefaultRequestContentType(restful.MIME_JSON) +func DefaultRequestContentType(mime string) { + defaultRequestContentType = mime +} + +// PathParameter accesses the Path parameter value by its name +func (r *Request) PathParameter(name string) string { + return r.pathParameters[name] +} + +// PathParameters accesses the Path parameter values +func (r *Request) PathParameters() map[string]string { + return r.pathParameters +} + +// QueryParameter returns the (first) Query parameter value by its name +func (r *Request) QueryParameter(name string) string { + return r.Request.FormValue(name) +} + +// BodyParameter parses the body of the request (once for typically a POST or a PUT) and returns the value of the given name or an error. +func (r *Request) BodyParameter(name string) (string, error) { + err := r.Request.ParseForm() + if err != nil { + return "", err + } + return r.Request.PostFormValue(name), nil +} + +// HeaderParameter returns the HTTP Header value of a Header name or empty if missing +func (r *Request) HeaderParameter(name string) string { + return r.Request.Header.Get(name) +} + +// ReadEntity checks the Accept header and reads the content into the entityPointer. +func (r *Request) ReadEntity(entityPointer interface{}) (err error) { + contentType := r.Request.Header.Get(HEADER_ContentType) + contentEncoding := r.Request.Header.Get(HEADER_ContentEncoding) + + // check if the request body needs decompression + if ENCODING_GZIP == contentEncoding { + gzipReader := currentCompressorProvider.AcquireGzipReader() + defer currentCompressorProvider.ReleaseGzipReader(gzipReader) + gzipReader.Reset(r.Request.Body) + r.Request.Body = gzipReader + } else if ENCODING_DEFLATE == contentEncoding { + zlibReader, err := zlib.NewReader(r.Request.Body) + if err != nil { + return err + } + r.Request.Body = zlibReader + } + + // lookup the EntityReader, use defaultRequestContentType if needed and provided + entityReader, ok := entityAccessRegistry.accessorAt(contentType) + if !ok { + if len(defaultRequestContentType) != 0 { + entityReader, ok = entityAccessRegistry.accessorAt(defaultRequestContentType) + } + if !ok { + return NewError(http.StatusBadRequest, "Unable to unmarshal content of type:"+contentType) + } + } + return entityReader.Read(r, entityPointer) +} + +// SetAttribute adds or replaces the attribute with the given value. +func (r *Request) SetAttribute(name string, value interface{}) { + r.attributes[name] = value +} + +// Attribute returns the value associated to the given name. Returns nil if absent. +func (r Request) Attribute(name string) interface{} { + return r.attributes[name] +} + +// SelectedRoutePath root path + route path that matched the request, e.g. /meetings/{id}/attendees +func (r Request) SelectedRoutePath() string { + return r.selectedRoutePath +} diff --git a/vendor/github.com/emicklei/go-restful/request_test.go b/vendor/github.com/emicklei/go-restful/request_test.go new file mode 100644 index 00000000..31f50965 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/request_test.go @@ -0,0 +1,141 @@ +package restful + +import ( + "encoding/json" + "net/http" + "net/url" + "strconv" + "strings" + "testing" +) + +func TestQueryParameter(t *testing.T) { + hreq := http.Request{Method: "GET"} + hreq.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar") + rreq := Request{Request: &hreq} + if rreq.QueryParameter("q") != "foo" { + t.Errorf("q!=foo %#v", rreq) + } +} + +type Anything map[string]interface{} + +type Number struct { + ValueFloat float64 + ValueInt int64 +} + +type Sample struct { + Value string +} + +func TestReadEntityJson(t *testing.T) { + bodyReader := strings.NewReader(`{"Value" : "42"}`) + httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) + httpRequest.Header.Set("Content-Type", "application/json") + request := &Request{Request: httpRequest} + sam := new(Sample) + request.ReadEntity(sam) + if sam.Value != "42" { + t.Fatal("read failed") + } +} + +func TestReadEntityJsonCharset(t *testing.T) { + bodyReader := strings.NewReader(`{"Value" : "42"}`) + httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) + httpRequest.Header.Set("Content-Type", "application/json; charset=UTF-8") + request := NewRequest(httpRequest) + sam := new(Sample) + request.ReadEntity(sam) + if sam.Value != "42" { + t.Fatal("read failed") + } +} + +func TestReadEntityJsonNumber(t *testing.T) { + bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) + httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) + httpRequest.Header.Set("Content-Type", "application/json") + request := &Request{Request: httpRequest} + any := make(Anything) + request.ReadEntity(&any) + number, ok := any["Value"].(json.Number) + if !ok { + t.Fatal("read failed") + } + vint, err := number.Int64() + if err != nil { + t.Fatal("convert failed") + } + if vint != 4899710515899924123 { + t.Fatal("read failed") + } + vfloat, err := number.Float64() + if err != nil { + t.Fatal("convert failed") + } + // match the default behaviour + vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) + if vstring != "4.899710515899924e+18" { + t.Fatal("convert float64 failed") + } +} + +func TestReadEntityJsonLong(t *testing.T) { + bodyReader := strings.NewReader(`{"ValueFloat" : 4899710515899924123, "ValueInt": 4899710515899924123}`) + httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) + httpRequest.Header.Set("Content-Type", "application/json") + request := &Request{Request: httpRequest} + number := new(Number) + request.ReadEntity(&number) + if number.ValueInt != 4899710515899924123 { + t.Fatal("read failed") + } + // match the default behaviour + vstring := strconv.FormatFloat(number.ValueFloat, 'e', 15, 64) + if vstring != "4.899710515899924e+18" { + t.Fatal("convert float64 failed") + } +} + +func TestBodyParameter(t *testing.T) { + bodyReader := strings.NewReader(`value1=42&value2=43`) + httpRequest, _ := http.NewRequest("POST", "/test?value1=44", bodyReader) // POST and PUT body parameters take precedence over URL query string + httpRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") + request := NewRequest(httpRequest) + v1, err := request.BodyParameter("value1") + if err != nil { + t.Error(err) + } + v2, err := request.BodyParameter("value2") + if err != nil { + t.Error(err) + } + if v1 != "42" || v2 != "43" { + t.Fatal("read failed") + } +} + +func TestReadEntityUnkown(t *testing.T) { + bodyReader := strings.NewReader("?") + httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) + httpRequest.Header.Set("Content-Type", "application/rubbish") + request := NewRequest(httpRequest) + sam := new(Sample) + err := request.ReadEntity(sam) + if err == nil { + t.Fatal("read should be in error") + } +} + +func TestSetAttribute(t *testing.T) { + bodyReader := strings.NewReader("?") + httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) + request := NewRequest(httpRequest) + request.SetAttribute("go", "there") + there := request.Attribute("go") + if there != "there" { + t.Fatalf("missing request attribute:%v", there) + } +} diff --git a/vendor/github.com/emicklei/go-restful/response.go b/vendor/github.com/emicklei/go-restful/response.go new file mode 100644 index 00000000..971cd0b4 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/response.go @@ -0,0 +1,235 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "errors" + "net/http" +) + +// DEPRECATED, use DefaultResponseContentType(mime) +var DefaultResponseMimeType string + +//PrettyPrintResponses controls the indentation feature of XML and JSON serialization +var PrettyPrintResponses = true + +// Response is a wrapper on the actual http ResponseWriter +// It provides several convenience methods to prepare and write response content. +type Response struct { + http.ResponseWriter + requestAccept string // mime-type what the Http Request says it wants to receive + routeProduces []string // mime-types what the Route says it can produce + statusCode int // HTTP status code that has been written explicity (if zero then net/http has written 200) + contentLength int // number of bytes written for the response body + prettyPrint bool // controls the indentation feature of XML and JSON serialization. It is initialized using var PrettyPrintResponses. + err error // err property is kept when WriteError is called +} + +// Creates a new response based on a http ResponseWriter. +func NewResponse(httpWriter http.ResponseWriter) *Response { + return &Response{httpWriter, "", []string{}, http.StatusOK, 0, PrettyPrintResponses, nil} // empty content-types +} + +// If Accept header matching fails, fall back to this type. +// Valid values are restful.MIME_JSON and restful.MIME_XML +// Example: +// restful.DefaultResponseContentType(restful.MIME_JSON) +func DefaultResponseContentType(mime string) { + DefaultResponseMimeType = mime +} + +// InternalServerError writes the StatusInternalServerError header. +// DEPRECATED, use WriteErrorString(http.StatusInternalServerError,reason) +func (r Response) InternalServerError() Response { + r.WriteHeader(http.StatusInternalServerError) + return r +} + +// PrettyPrint changes whether this response must produce pretty (line-by-line, indented) JSON or XML output. +func (r *Response) PrettyPrint(bePretty bool) { + r.prettyPrint = bePretty +} + +// AddHeader is a shortcut for .Header().Add(header,value) +func (r Response) AddHeader(header string, value string) Response { + r.Header().Add(header, value) + return r +} + +// SetRequestAccepts tells the response what Mime-type(s) the HTTP request said it wants to accept. Exposed for testing. +func (r *Response) SetRequestAccepts(mime string) { + r.requestAccept = mime +} + +// EntityWriter returns the registered EntityWriter that the entity (requested resource) +// can write according to what the request wants (Accept) and what the Route can produce or what the restful defaults say. +// If called before WriteEntity and WriteHeader then a false return value can be used to write a 406: Not Acceptable. +func (r *Response) EntityWriter() (EntityReaderWriter, bool) { + sorted := sortedMimes(r.requestAccept) + for _, eachAccept := range sorted { + for _, eachProduce := range r.routeProduces { + if eachProduce == eachAccept.media { + if w, ok := entityAccessRegistry.accessorAt(eachAccept.media); ok { + return w, true + } + } + } + if eachAccept.media == "*/*" { + for _, each := range r.routeProduces { + if w, ok := entityAccessRegistry.accessorAt(each); ok { + return w, true + } + } + } + } + // if requestAccept is empty + writer, ok := entityAccessRegistry.accessorAt(r.requestAccept) + if !ok { + // if not registered then fallback to the defaults (if set) + if DefaultResponseMimeType == MIME_JSON { + return entityAccessRegistry.accessorAt(MIME_JSON) + } + if DefaultResponseMimeType == MIME_XML { + return entityAccessRegistry.accessorAt(MIME_XML) + } + // Fallback to whatever the route says it can produce. + // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html + for _, each := range r.routeProduces { + if w, ok := entityAccessRegistry.accessorAt(each); ok { + return w, true + } + } + if trace { + traceLogger.Printf("no registered EntityReaderWriter found for %s", r.requestAccept) + } + } + return writer, ok +} + +// WriteEntity calls WriteHeaderAndEntity with Http Status OK (200) +func (r *Response) WriteEntity(value interface{}) error { + return r.WriteHeaderAndEntity(http.StatusOK, value) +} + +// WriteHeaderAndEntity marshals the value using the representation denoted by the Accept Header and the registered EntityWriters. +// If no Accept header is specified (or */*) then respond with the Content-Type as specified by the first in the Route.Produces. +// If an Accept header is specified then respond with the Content-Type as specified by the first in the Route.Produces that is matched with the Accept header. +// If the value is nil then no response is send except for the Http status. You may want to call WriteHeader(http.StatusNotFound) instead. +// If there is no writer available that can represent the value in the requested MIME type then Http Status NotAcceptable is written. +// Current implementation ignores any q-parameters in the Accept Header. +// Returns an error if the value could not be written on the response. +func (r *Response) WriteHeaderAndEntity(status int, value interface{}) error { + writer, ok := r.EntityWriter() + if !ok { + r.WriteHeader(http.StatusNotAcceptable) + return nil + } + return writer.Write(r, status, value) +} + +// WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value) +// It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter. +func (r *Response) WriteAsXml(value interface{}) error { + return writeXML(r, http.StatusOK, MIME_XML, value) +} + +// WriteHeaderAndXml is a convenience method for writing a status and value in xml (requires Xml tags on the value) +// It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter. +func (r *Response) WriteHeaderAndXml(status int, value interface{}) error { + return writeXML(r, status, MIME_XML, value) +} + +// WriteAsJson is a convenience method for writing a value in json. +// It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter. +func (r *Response) WriteAsJson(value interface{}) error { + return writeJSON(r, http.StatusOK, MIME_JSON, value) +} + +// WriteJson is a convenience method for writing a value in Json with a given Content-Type. +// It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter. +func (r *Response) WriteJson(value interface{}, contentType string) error { + return writeJSON(r, http.StatusOK, contentType, value) +} + +// WriteHeaderAndJson is a convenience method for writing the status and a value in Json with a given Content-Type. +// It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter. +func (r *Response) WriteHeaderAndJson(status int, value interface{}, contentType string) error { + return writeJSON(r, status, contentType, value) +} + +// WriteError write the http status and the error string on the response. +func (r *Response) WriteError(httpStatus int, err error) error { + r.err = err + return r.WriteErrorString(httpStatus, err.Error()) +} + +// WriteServiceError is a convenience method for a responding with a status and a ServiceError +func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error { + r.err = err + return r.WriteHeaderAndEntity(httpStatus, err) +} + +// WriteErrorString is a convenience method for an error status with the actual error +func (r *Response) WriteErrorString(httpStatus int, errorReason string) error { + if r.err == nil { + // if not called from WriteError + r.err = errors.New(errorReason) + } + r.WriteHeader(httpStatus) + if _, err := r.Write([]byte(errorReason)); err != nil { + return err + } + return nil +} + +// Flush implements http.Flusher interface, which sends any buffered data to the client. +func (r *Response) Flush() { + if f, ok := r.ResponseWriter.(http.Flusher); ok { + f.Flush() + } else if trace { + traceLogger.Printf("ResponseWriter %v doesn't support Flush", r) + } +} + +// WriteHeader is overridden to remember the Status Code that has been written. +// Changes to the Header of the response have no effect after this. +func (r *Response) WriteHeader(httpStatus int) { + r.statusCode = httpStatus + r.ResponseWriter.WriteHeader(httpStatus) +} + +// StatusCode returns the code that has been written using WriteHeader. +func (r Response) StatusCode() int { + if 0 == r.statusCode { + // no status code has been written yet; assume OK + return http.StatusOK + } + return r.statusCode +} + +// Write writes the data to the connection as part of an HTTP reply. +// Write is part of http.ResponseWriter interface. +func (r *Response) Write(bytes []byte) (int, error) { + written, err := r.ResponseWriter.Write(bytes) + r.contentLength += written + return written, err +} + +// ContentLength returns the number of bytes written for the response content. +// Note that this value is only correct if all data is written through the Response using its Write* methods. +// Data written directly using the underlying http.ResponseWriter is not accounted for. +func (r Response) ContentLength() int { + return r.contentLength +} + +// CloseNotify is part of http.CloseNotifier interface +func (r Response) CloseNotify() <-chan bool { + return r.ResponseWriter.(http.CloseNotifier).CloseNotify() +} + +// Error returns the err created by WriteError +func (r Response) Error() error { + return r.err +} diff --git a/vendor/github.com/emicklei/go-restful/response_test.go b/vendor/github.com/emicklei/go-restful/response_test.go new file mode 100644 index 00000000..31102491 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/response_test.go @@ -0,0 +1,213 @@ +package restful + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestWriteHeader(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} + resp.WriteHeader(123) + if resp.StatusCode() != 123 { + t.Errorf("Unexpected status code:%d", resp.StatusCode()) + } +} + +func TestNoWriteHeader(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} + if resp.StatusCode() != http.StatusOK { + t.Errorf("Unexpected status code:%d", resp.StatusCode()) + } +} + +type food struct { + Kind string +} + +// go test -v -test.run TestMeasureContentLengthXml ...restful +func TestMeasureContentLengthXml(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} + resp.WriteAsXml(food{"apple"}) + if resp.ContentLength() != 76 { + t.Errorf("Incorrect measured length:%d", resp.ContentLength()) + } +} + +// go test -v -test.run TestMeasureContentLengthJson ...restful +func TestMeasureContentLengthJson(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} + resp.WriteAsJson(food{"apple"}) + if resp.ContentLength() != 22 { + t.Errorf("Incorrect measured length:%d", resp.ContentLength()) + } +} + +// go test -v -test.run TestMeasureContentLengthJsonNotPretty ...restful +func TestMeasureContentLengthJsonNotPretty(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, false, nil} + resp.WriteAsJson(food{"apple"}) + if resp.ContentLength() != 17 { // 16+1 using the Encoder directly yields another /n + t.Errorf("Incorrect measured length:%d", resp.ContentLength()) + } +} + +// go test -v -test.run TestMeasureContentLengthWriteErrorString ...restful +func TestMeasureContentLengthWriteErrorString(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} + resp.WriteErrorString(404, "Invalid") + if resp.ContentLength() != len("Invalid") { + t.Errorf("Incorrect measured length:%d", resp.ContentLength()) + } +} + +// go test -v -test.run TestStatusIsPassedToResponse ...restful +func TestStatusIsPassedToResponse(t *testing.T) { + for _, each := range []struct { + write, read int + }{ + {write: 204, read: 204}, + {write: 304, read: 304}, + {write: 200, read: 200}, + {write: 400, read: 400}, + } { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} + resp.WriteHeader(each.write) + if got, want := httpWriter.Code, each.read; got != want { + t.Errorf("got %v want %v", got, want) + } + } +} + +// go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue54 ...restful +func TestStatusCreatedAndContentTypeJson_Issue54(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} + resp.WriteHeader(201) + resp.WriteAsJson(food{"Juicy"}) + if httpWriter.HeaderMap.Get("Content-Type") != "application/json" { + t.Errorf("Expected content type json but got:%s", httpWriter.HeaderMap.Get("Content-Type")) + } + if httpWriter.Code != 201 { + t.Errorf("Expected status 201 but got:%d", httpWriter.Code) + } +} + +type errorOnWriteRecorder struct { + *httptest.ResponseRecorder +} + +func (e errorOnWriteRecorder) Write(bytes []byte) (int, error) { + return 0, errors.New("fail") +} + +// go test -v -test.run TestLastWriteErrorCaught ...restful +func TestLastWriteErrorCaught(t *testing.T) { + httpWriter := errorOnWriteRecorder{httptest.NewRecorder()} + resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} + err := resp.WriteAsJson(food{"Juicy"}) + if err.Error() != "fail" { + t.Errorf("Unexpected error message:%v", err) + } +} + +// go test -v -test.run TestAcceptStarStar_Issue83 ...restful +func TestAcceptStarStar_Issue83(t *testing.T) { + httpWriter := httptest.NewRecorder() + // Accept Produces + resp := Response{httpWriter, "application/bogus,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} + resp.WriteEntity(food{"Juicy"}) + ct := httpWriter.Header().Get("Content-Type") + if "application/json" != ct { + t.Errorf("Unexpected content type:%s", ct) + } +} + +// go test -v -test.run TestAcceptSkipStarStar_Issue83 ...restful +func TestAcceptSkipStarStar_Issue83(t *testing.T) { + httpWriter := httptest.NewRecorder() + // Accept Produces + resp := Response{httpWriter, " application/xml ,*/* ; q=0.8", []string{"application/json", "application/xml"}, 0, 0, true, nil} + resp.WriteEntity(food{"Juicy"}) + ct := httpWriter.Header().Get("Content-Type") + if "application/xml" != ct { + t.Errorf("Unexpected content type:%s", ct) + } +} + +// go test -v -test.run TestAcceptXmlBeforeStarStar_Issue83 ...restful +func TestAcceptXmlBeforeStarStar_Issue83(t *testing.T) { + httpWriter := httptest.NewRecorder() + // Accept Produces + resp := Response{httpWriter, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} + resp.WriteEntity(food{"Juicy"}) + ct := httpWriter.Header().Get("Content-Type") + if "application/json" != ct { + t.Errorf("Unexpected content type:%s", ct) + } +} + +// go test -v -test.run TestWriteHeaderNoContent_Issue124 ...restful +func TestWriteHeaderNoContent_Issue124(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "text/plain", []string{"text/plain"}, 0, 0, true, nil} + resp.WriteHeader(http.StatusNoContent) + if httpWriter.Code != http.StatusNoContent { + t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) + } +} + +// go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue163 ...restful +func TestStatusCreatedAndContentTypeJson_Issue163(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} + resp.WriteHeader(http.StatusNotModified) + if httpWriter.Code != http.StatusNotModified { + t.Errorf("Got %d want %d", httpWriter.Code, http.StatusNotModified) + } +} + +func TestWriteHeaderAndEntity_Issue235(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} + var pong = struct { + Foo string `json:"foo"` + }{Foo: "123"} + resp.WriteHeaderAndEntity(404, pong) + if httpWriter.Code != http.StatusNotFound { + t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) + } + if got, want := httpWriter.Header().Get("Content-Type"), "application/json"; got != want { + t.Errorf("got %v want %v", got, want) + } + if !strings.HasPrefix(httpWriter.Body.String(), "{") { + t.Errorf("expected pong struct in json:%s", httpWriter.Body.String()) + } +} + +func TestWriteEntityNoAcceptMatchWithProduces(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "application/bogus", []string{"application/json"}, 0, 0, true, nil} + resp.WriteEntity("done") + if httpWriter.Code != http.StatusOK { + t.Errorf("got %d want %d", httpWriter.Code, http.StatusOK) + } +} + +func TestWriteEntityNoAcceptMatchNoProduces(t *testing.T) { + httpWriter := httptest.NewRecorder() + resp := Response{httpWriter, "application/bogus", []string{}, 0, 0, true, nil} + resp.WriteEntity("done") + if httpWriter.Code != http.StatusNotAcceptable { + t.Errorf("got %d want %d", httpWriter.Code, http.StatusNotAcceptable) + } +} diff --git a/vendor/github.com/emicklei/go-restful/route.go b/vendor/github.com/emicklei/go-restful/route.go new file mode 100644 index 00000000..f54e8622 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/route.go @@ -0,0 +1,183 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "bytes" + "net/http" + "strings" +) + +// RouteFunction declares the signature of a function that can be bound to a Route. +type RouteFunction func(*Request, *Response) + +// Route binds a HTTP Method,Path,Consumes combination to a RouteFunction. +type Route struct { + Method string + Produces []string + Consumes []string + Path string // webservice root path + described path + Function RouteFunction + Filters []FilterFunction + + // cached values for dispatching + relativePath string + pathParts []string + pathExpr *pathExpression // cached compilation of relativePath as RegExp + + // documentation + Doc string + Notes string + Operation string + ParameterDocs []*Parameter + ResponseErrors map[int]ResponseError + ReadSample, WriteSample interface{} // structs that model an example request or response payload +} + +// Initialize for Route +func (r *Route) postBuild() { + r.pathParts = tokenizePath(r.Path) +} + +// Create Request and Response from their http versions +func (r *Route) wrapRequestResponse(httpWriter http.ResponseWriter, httpRequest *http.Request) (*Request, *Response) { + params := r.extractParameters(httpRequest.URL.Path) + wrappedRequest := NewRequest(httpRequest) + wrappedRequest.pathParameters = params + wrappedRequest.selectedRoutePath = r.Path + wrappedResponse := NewResponse(httpWriter) + wrappedResponse.requestAccept = httpRequest.Header.Get(HEADER_Accept) + wrappedResponse.routeProduces = r.Produces + return wrappedRequest, wrappedResponse +} + +// dispatchWithFilters call the function after passing through its own filters +func (r *Route) dispatchWithFilters(wrappedRequest *Request, wrappedResponse *Response) { + if len(r.Filters) > 0 { + chain := FilterChain{Filters: r.Filters, Target: r.Function} + chain.ProcessFilter(wrappedRequest, wrappedResponse) + } else { + // unfiltered + r.Function(wrappedRequest, wrappedResponse) + } +} + +// Return whether the mimeType matches to what this Route can produce. +func (r Route) matchesAccept(mimeTypesWithQuality string) bool { + parts := strings.Split(mimeTypesWithQuality, ",") + for _, each := range parts { + var withoutQuality string + if strings.Contains(each, ";") { + withoutQuality = strings.Split(each, ";")[0] + } else { + withoutQuality = each + } + // trim before compare + withoutQuality = strings.Trim(withoutQuality, " ") + if withoutQuality == "*/*" { + return true + } + for _, producibleType := range r.Produces { + if producibleType == "*/*" || producibleType == withoutQuality { + return true + } + } + } + return false +} + +// Return whether this Route can consume content with a type specified by mimeTypes (can be empty). +func (r Route) matchesContentType(mimeTypes string) bool { + + if len(r.Consumes) == 0 { + // did not specify what it can consume ; any media type (“*/*”) is assumed + return true + } + + if len(mimeTypes) == 0 { + // idempotent methods with (most-likely or garanteed) empty content match missing Content-Type + m := r.Method + if m == "GET" || m == "HEAD" || m == "OPTIONS" || m == "DELETE" || m == "TRACE" { + return true + } + // proceed with default + mimeTypes = MIME_OCTET + } + + parts := strings.Split(mimeTypes, ",") + for _, each := range parts { + var contentType string + if strings.Contains(each, ";") { + contentType = strings.Split(each, ";")[0] + } else { + contentType = each + } + // trim before compare + contentType = strings.Trim(contentType, " ") + for _, consumeableType := range r.Consumes { + if consumeableType == "*/*" || consumeableType == contentType { + return true + } + } + } + return false +} + +// Extract the parameters from the request url path +func (r Route) extractParameters(urlPath string) map[string]string { + urlParts := tokenizePath(urlPath) + pathParameters := map[string]string{} + for i, key := range r.pathParts { + var value string + if i >= len(urlParts) { + value = "" + } else { + value = urlParts[i] + } + if strings.HasPrefix(key, "{") { // path-parameter + if colon := strings.Index(key, ":"); colon != -1 { + // extract by regex + regPart := key[colon+1 : len(key)-1] + keyPart := key[1:colon] + if regPart == "*" { + pathParameters[keyPart] = untokenizePath(i, urlParts) + break + } else { + pathParameters[keyPart] = value + } + } else { + // without enclosing {} + pathParameters[key[1:len(key)-1]] = value + } + } + } + return pathParameters +} + +// Untokenize back into an URL path using the slash separator +func untokenizePath(offset int, parts []string) string { + var buffer bytes.Buffer + for p := offset; p < len(parts); p++ { + buffer.WriteString(parts[p]) + // do not end + if p < len(parts)-1 { + buffer.WriteString("/") + } + } + return buffer.String() +} + +// Tokenize an URL path using the slash separator ; the result does not have empty tokens +func tokenizePath(path string) []string { + if "/" == path { + return []string{} + } + return strings.Split(strings.Trim(path, "/"), "/") +} + +// for debugging +func (r Route) String() string { + return r.Method + " " + r.Path +} diff --git a/vendor/github.com/emicklei/go-restful/route_builder.go b/vendor/github.com/emicklei/go-restful/route_builder.go new file mode 100644 index 00000000..cba091d3 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/route_builder.go @@ -0,0 +1,255 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "os" + "reflect" + "runtime" + "strings" + + "github.com/emicklei/go-restful/log" +) + +// RouteBuilder is a helper to construct Routes. +type RouteBuilder struct { + rootPath string + currentPath string + produces []string + consumes []string + httpMethod string // required + function RouteFunction // required + filters []FilterFunction + + typeNameHandleFunc TypeNameHandleFunction // required + + // documentation + doc string + notes string + operation string + readSample, writeSample interface{} + parameters []*Parameter + errorMap map[int]ResponseError +} + +// Do evaluates each argument with the RouteBuilder itself. +// This allows you to follow DRY principles without breaking the fluent programming style. +// Example: +// ws.Route(ws.DELETE("/{name}").To(t.deletePerson).Do(Returns200, Returns500)) +// +// func Returns500(b *RouteBuilder) { +// b.Returns(500, "Internal Server Error", restful.ServiceError{}) +// } +func (b *RouteBuilder) Do(oneArgBlocks ...func(*RouteBuilder)) *RouteBuilder { + for _, each := range oneArgBlocks { + each(b) + } + return b +} + +// To bind the route to a function. +// If this route is matched with the incoming Http Request then call this function with the *Request,*Response pair. Required. +func (b *RouteBuilder) To(function RouteFunction) *RouteBuilder { + b.function = function + return b +} + +// Method specifies what HTTP method to match. Required. +func (b *RouteBuilder) Method(method string) *RouteBuilder { + b.httpMethod = method + return b +} + +// Produces specifies what MIME types can be produced ; the matched one will appear in the Content-Type Http header. +func (b *RouteBuilder) Produces(mimeTypes ...string) *RouteBuilder { + b.produces = mimeTypes + return b +} + +// Consumes specifies what MIME types can be consumes ; the Accept Http header must matched any of these +func (b *RouteBuilder) Consumes(mimeTypes ...string) *RouteBuilder { + b.consumes = mimeTypes + return b +} + +// Path specifies the relative (w.r.t WebService root path) URL path to match. Default is "/". +func (b *RouteBuilder) Path(subPath string) *RouteBuilder { + b.currentPath = subPath + return b +} + +// Doc tells what this route is all about. Optional. +func (b *RouteBuilder) Doc(documentation string) *RouteBuilder { + b.doc = documentation + return b +} + +// A verbose explanation of the operation behavior. Optional. +func (b *RouteBuilder) Notes(notes string) *RouteBuilder { + b.notes = notes + return b +} + +// Reads tells what resource type will be read from the request payload. Optional. +// A parameter of type "body" is added ,required is set to true and the dataType is set to the qualified name of the sample's type. +func (b *RouteBuilder) Reads(sample interface{}) *RouteBuilder { + fn := b.typeNameHandleFunc + if fn == nil { + fn = reflectTypeName + } + typeAsName := fn(sample) + + b.readSample = sample + bodyParameter := &Parameter{&ParameterData{Name: "body"}} + bodyParameter.beBody() + bodyParameter.Required(true) + bodyParameter.DataType(typeAsName) + b.Param(bodyParameter) + return b +} + +// ParameterNamed returns a Parameter already known to the RouteBuilder. Returns nil if not. +// Use this to modify or extend information for the Parameter (through its Data()). +func (b RouteBuilder) ParameterNamed(name string) (p *Parameter) { + for _, each := range b.parameters { + if each.Data().Name == name { + return each + } + } + return p +} + +// Writes tells what resource type will be written as the response payload. Optional. +func (b *RouteBuilder) Writes(sample interface{}) *RouteBuilder { + b.writeSample = sample + return b +} + +// Param allows you to document the parameters of the Route. It adds a new Parameter (does not check for duplicates). +func (b *RouteBuilder) Param(parameter *Parameter) *RouteBuilder { + if b.parameters == nil { + b.parameters = []*Parameter{} + } + b.parameters = append(b.parameters, parameter) + return b +} + +// Operation allows you to document what the actual method/function call is of the Route. +// Unless called, the operation name is derived from the RouteFunction set using To(..). +func (b *RouteBuilder) Operation(name string) *RouteBuilder { + b.operation = name + return b +} + +// ReturnsError is deprecated, use Returns instead. +func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder { + log.Print("ReturnsError is deprecated, use Returns instead.") + return b.Returns(code, message, model) +} + +// Returns allows you to document what responses (errors or regular) can be expected. +// The model parameter is optional ; either pass a struct instance or use nil if not applicable. +func (b *RouteBuilder) Returns(code int, message string, model interface{}) *RouteBuilder { + err := ResponseError{ + Code: code, + Message: message, + Model: model, + } + // lazy init because there is no NewRouteBuilder (yet) + if b.errorMap == nil { + b.errorMap = map[int]ResponseError{} + } + b.errorMap[code] = err + return b +} + +type ResponseError struct { + Code int + Message string + Model interface{} +} + +func (b *RouteBuilder) servicePath(path string) *RouteBuilder { + b.rootPath = path + return b +} + +// Filter appends a FilterFunction to the end of filters for this Route to build. +func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder { + b.filters = append(b.filters, filter) + return b +} + +// If no specific Route path then set to rootPath +// If no specific Produces then set to rootProduces +// If no specific Consumes then set to rootConsumes +func (b *RouteBuilder) copyDefaults(rootProduces, rootConsumes []string) { + if len(b.produces) == 0 { + b.produces = rootProduces + } + if len(b.consumes) == 0 { + b.consumes = rootConsumes + } +} + +// typeNameHandler sets the function that will convert types to strings in the parameter +// and model definitions. +func (b *RouteBuilder) typeNameHandler(handler TypeNameHandleFunction) *RouteBuilder { + b.typeNameHandleFunc = handler + return b +} + +// Build creates a new Route using the specification details collected by the RouteBuilder +func (b *RouteBuilder) Build() Route { + pathExpr, err := newPathExpression(b.currentPath) + if err != nil { + log.Printf("[restful] Invalid path:%s because:%v", b.currentPath, err) + os.Exit(1) + } + if b.function == nil { + log.Printf("[restful] No function specified for route:" + b.currentPath) + os.Exit(1) + } + operationName := b.operation + if len(operationName) == 0 && b.function != nil { + // extract from definition + operationName = nameOfFunction(b.function) + } + route := Route{ + Method: b.httpMethod, + Path: concatPath(b.rootPath, b.currentPath), + Produces: b.produces, + Consumes: b.consumes, + Function: b.function, + Filters: b.filters, + relativePath: b.currentPath, + pathExpr: pathExpr, + Doc: b.doc, + Notes: b.notes, + Operation: operationName, + ParameterDocs: b.parameters, + ResponseErrors: b.errorMap, + ReadSample: b.readSample, + WriteSample: b.writeSample} + route.postBuild() + return route +} + +func concatPath(path1, path2 string) string { + return strings.TrimRight(path1, "/") + "/" + strings.TrimLeft(path2, "/") +} + +// nameOfFunction returns the short name of the function f for documentation. +// It uses a runtime feature for debugging ; its value may change for later Go versions. +func nameOfFunction(f interface{}) string { + fun := runtime.FuncForPC(reflect.ValueOf(f).Pointer()) + tokenized := strings.Split(fun.Name(), ".") + last := tokenized[len(tokenized)-1] + last = strings.TrimSuffix(last, ")·fm") // < Go 1.5 + last = strings.TrimSuffix(last, ")-fm") // Go 1.5 + last = strings.TrimSuffix(last, "·fm") // < Go 1.5 + last = strings.TrimSuffix(last, "-fm") // Go 1.5 + return last +} diff --git a/vendor/github.com/emicklei/go-restful/route_builder_test.go b/vendor/github.com/emicklei/go-restful/route_builder_test.go new file mode 100644 index 00000000..56dbe02e --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/route_builder_test.go @@ -0,0 +1,58 @@ +package restful + +import ( + "testing" +) + +func TestRouteBuilder_PathParameter(t *testing.T) { + p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} + p.AllowMultiple(true) + p.DataType("int") + p.Required(true) + values := map[string]string{"a": "b"} + p.AllowableValues(values) + p.bePath() + + b := new(RouteBuilder) + b.function = dummy + b.Param(p) + r := b.Build() + if !r.ParameterDocs[0].Data().AllowMultiple { + t.Error("AllowMultiple invalid") + } + if r.ParameterDocs[0].Data().DataType != "int" { + t.Error("dataType invalid") + } + if !r.ParameterDocs[0].Data().Required { + t.Error("required invalid") + } + if r.ParameterDocs[0].Data().Kind != PathParameterKind { + t.Error("kind invalid") + } + if r.ParameterDocs[0].Data().AllowableValues["a"] != "b" { + t.Error("allowableValues invalid") + } + if b.ParameterNamed("name") == nil { + t.Error("access to parameter failed") + } +} + +func TestRouteBuilder(t *testing.T) { + json := "application/json" + b := new(RouteBuilder) + b.To(dummy) + b.Path("/routes").Method("HEAD").Consumes(json).Produces(json) + r := b.Build() + if r.Path != "/routes" { + t.Error("path invalid") + } + if r.Produces[0] != json { + t.Error("produces invalid") + } + if r.Consumes[0] != json { + t.Error("consumes invalid") + } + if r.Operation != "dummy" { + t.Error("Operation not set") + } +} diff --git a/vendor/github.com/emicklei/go-restful/route_test.go b/vendor/github.com/emicklei/go-restful/route_test.go new file mode 100644 index 00000000..6a104aff --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/route_test.go @@ -0,0 +1,127 @@ +package restful + +import ( + "testing" +) + +// accept should match produces +func TestMatchesAcceptPlainTextWhenProducePlainTextAsLast(t *testing.T) { + r := Route{Produces: []string{"application/json", "text/plain"}} + if !r.matchesAccept("text/plain") { + t.Errorf("accept should match text/plain") + } +} + +// accept should match produces +func TestMatchesAcceptStar(t *testing.T) { + r := Route{Produces: []string{"application/xml"}} + if !r.matchesAccept("*/*") { + t.Errorf("accept should match star") + } +} + +// accept should match produces +func TestMatchesAcceptIE(t *testing.T) { + r := Route{Produces: []string{"application/xml"}} + if !r.matchesAccept("text/html, application/xhtml+xml, */*") { + t.Errorf("accept should match star") + } +} + +// accept should match produces +func TestMatchesAcceptXml(t *testing.T) { + r := Route{Produces: []string{"application/xml"}} + if r.matchesAccept("application/json") { + t.Errorf("accept should not match json") + } + if !r.matchesAccept("application/xml") { + t.Errorf("accept should match xml") + } +} + +// accept should match produces +func TestMatchesAcceptAny(t *testing.T) { + r := Route{Produces: []string{"*/*"}} + if !r.matchesAccept("application/json") { + t.Errorf("accept should match json") + } + if !r.matchesAccept("application/xml") { + t.Errorf("accept should match xml") + } +} + +// content type should match consumes +func TestMatchesContentTypeXml(t *testing.T) { + r := Route{Consumes: []string{"application/xml"}} + if r.matchesContentType("application/json") { + t.Errorf("accept should not match json") + } + if !r.matchesContentType("application/xml") { + t.Errorf("accept should match xml") + } +} + +// content type should match consumes +func TestMatchesContentTypeCharsetInformation(t *testing.T) { + r := Route{Consumes: []string{"application/json"}} + if !r.matchesContentType("application/json; charset=UTF-8") { + t.Errorf("matchesContentType should ignore charset information") + } +} + +func TestMatchesPath_OneParam(t *testing.T) { + params := doExtractParams("/from/{source}", 2, "/from/here", t) + if params["source"] != "here" { + t.Errorf("parameter mismatch here") + } +} + +func TestMatchesPath_Slash(t *testing.T) { + params := doExtractParams("/", 0, "/", t) + if len(params) != 0 { + t.Errorf("expected empty parameters") + } +} + +func TestMatchesPath_SlashNonVar(t *testing.T) { + params := doExtractParams("/any", 1, "/any", t) + if len(params) != 0 { + t.Errorf("expected empty parameters") + } +} + +func TestMatchesPath_TwoVars(t *testing.T) { + params := doExtractParams("/from/{source}/to/{destination}", 4, "/from/AMS/to/NY", t) + if params["source"] != "AMS" { + t.Errorf("parameter mismatch AMS") + } +} + +func TestMatchesPath_VarOnFront(t *testing.T) { + params := doExtractParams("{what}/from/{source}/", 3, "who/from/SOS/", t) + if params["source"] != "SOS" { + t.Errorf("parameter mismatch SOS") + } +} + +func TestExtractParameters_EmptyValue(t *testing.T) { + params := doExtractParams("/fixed/{var}", 2, "/fixed/", t) + if params["var"] != "" { + t.Errorf("parameter mismatch var") + } +} + +func TestTokenizePath(t *testing.T) { + if len(tokenizePath("/")) != 0 { + t.Errorf("not empty path tokens") + } +} + +func doExtractParams(routePath string, size int, urlPath string, t *testing.T) map[string]string { + r := Route{Path: routePath} + r.postBuild() + if len(r.pathParts) != size { + t.Fatalf("len not %v %v, but %v", size, r.pathParts, len(r.pathParts)) + } + return r.extractParameters(urlPath) +} diff --git a/vendor/github.com/emicklei/go-restful/router.go b/vendor/github.com/emicklei/go-restful/router.go new file mode 100644 index 00000000..9b32fb67 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/router.go @@ -0,0 +1,18 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import "net/http" + +// A RouteSelector finds the best matching Route given the input HTTP Request +type RouteSelector interface { + + // SelectRoute finds a Route given the input HTTP Request and a list of WebServices. + // It returns a selected Route and its containing WebService or an error indicating + // a problem. + SelectRoute( + webServices []*WebService, + httpRequest *http.Request) (selectedService *WebService, selected *Route, err error) +} diff --git a/vendor/github.com/emicklei/go-restful/service_error.go b/vendor/github.com/emicklei/go-restful/service_error.go new file mode 100644 index 00000000..62d1108b --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/service_error.go @@ -0,0 +1,23 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import "fmt" + +// ServiceError is a transport object to pass information about a non-Http error occurred in a WebService while processing a request. +type ServiceError struct { + Code int + Message string +} + +// NewError returns a ServiceError using the code and reason +func NewError(code int, message string) ServiceError { + return ServiceError{Code: code, Message: message} +} + +// Error returns a text representation of the service error +func (s ServiceError) Error() string { + return fmt.Sprintf("[ServiceError:%v] %v", s.Code, s.Message) +} diff --git a/vendor/github.com/emicklei/go-restful/tracer_test.go b/vendor/github.com/emicklei/go-restful/tracer_test.go new file mode 100644 index 00000000..60c1e9fc --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/tracer_test.go @@ -0,0 +1,18 @@ +package restful + +import "testing" + +// Use like this: +// +// TraceLogger(testLogger{t}) +type testLogger struct { + t *testing.T +} + +func (l testLogger) Print(v ...interface{}) { + l.t.Log(v...) +} + +func (l testLogger) Printf(format string, v ...interface{}) { + l.t.Logf(format, v...) +} diff --git a/vendor/github.com/emicklei/go-restful/web_service.go b/vendor/github.com/emicklei/go-restful/web_service.go new file mode 100644 index 00000000..7af60233 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/web_service.go @@ -0,0 +1,290 @@ +package restful + +import ( + "errors" + "os" + "reflect" + "sync" + + "github.com/emicklei/go-restful/log" +) + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +// WebService holds a collection of Route values that bind a Http Method + URL Path to a function. +type WebService struct { + rootPath string + pathExpr *pathExpression // cached compilation of rootPath as RegExp + routes []Route + produces []string + consumes []string + pathParameters []*Parameter + filters []FilterFunction + documentation string + apiVersion string + + typeNameHandleFunc TypeNameHandleFunction + + dynamicRoutes bool + + // protects 'routes' if dynamic routes are enabled + routesLock sync.RWMutex +} + +func (w *WebService) SetDynamicRoutes(enable bool) { + w.dynamicRoutes = enable +} + +// TypeNameHandleFunction declares functions that can handle translating the name of a sample object +// into the restful documentation for the service. +type TypeNameHandleFunction func(sample interface{}) string + +// TypeNameHandler sets the function that will convert types to strings in the parameter +// and model definitions. If not set, the web service will invoke +// reflect.TypeOf(object).String(). +func (w *WebService) TypeNameHandler(handler TypeNameHandleFunction) *WebService { + w.typeNameHandleFunc = handler + return w +} + +// reflectTypeName is the default TypeNameHandleFunction and for a given object +// returns the name that Go identifies it with (e.g. "string" or "v1.Object") via +// the reflection API. +func reflectTypeName(sample interface{}) string { + return reflect.TypeOf(sample).String() +} + +// compilePathExpression ensures that the path is compiled into a RegEx for those routers that need it. +func (w *WebService) compilePathExpression() { + compiled, err := newPathExpression(w.rootPath) + if err != nil { + log.Printf("[restful] invalid path:%s because:%v", w.rootPath, err) + os.Exit(1) + } + w.pathExpr = compiled +} + +// ApiVersion sets the API version for documentation purposes. +func (w *WebService) ApiVersion(apiVersion string) *WebService { + w.apiVersion = apiVersion + return w +} + +// Version returns the API version for documentation purposes. +func (w *WebService) Version() string { return w.apiVersion } + +// Path specifies the root URL template path of the WebService. +// All Routes will be relative to this path. +func (w *WebService) Path(root string) *WebService { + w.rootPath = root + if len(w.rootPath) == 0 { + w.rootPath = "/" + } + w.compilePathExpression() + return w +} + +// Param adds a PathParameter to document parameters used in the root path. +func (w *WebService) Param(parameter *Parameter) *WebService { + if w.pathParameters == nil { + w.pathParameters = []*Parameter{} + } + w.pathParameters = append(w.pathParameters, parameter) + return w +} + +// PathParameter creates a new Parameter of kind Path for documentation purposes. +// It is initialized as required with string as its DataType. +func (w *WebService) PathParameter(name, description string) *Parameter { + return PathParameter(name, description) +} + +// PathParameter creates a new Parameter of kind Path for documentation purposes. +// It is initialized as required with string as its DataType. +func PathParameter(name, description string) *Parameter { + p := &Parameter{&ParameterData{Name: name, Description: description, Required: true, DataType: "string"}} + p.bePath() + return p +} + +// QueryParameter creates a new Parameter of kind Query for documentation purposes. +// It is initialized as not required with string as its DataType. +func (w *WebService) QueryParameter(name, description string) *Parameter { + return QueryParameter(name, description) +} + +// QueryParameter creates a new Parameter of kind Query for documentation purposes. +// It is initialized as not required with string as its DataType. +func QueryParameter(name, description string) *Parameter { + p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}} + p.beQuery() + return p +} + +// BodyParameter creates a new Parameter of kind Body for documentation purposes. +// It is initialized as required without a DataType. +func (w *WebService) BodyParameter(name, description string) *Parameter { + return BodyParameter(name, description) +} + +// BodyParameter creates a new Parameter of kind Body for documentation purposes. +// It is initialized as required without a DataType. +func BodyParameter(name, description string) *Parameter { + p := &Parameter{&ParameterData{Name: name, Description: description, Required: true}} + p.beBody() + return p +} + +// HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes. +// It is initialized as not required with string as its DataType. +func (w *WebService) HeaderParameter(name, description string) *Parameter { + return HeaderParameter(name, description) +} + +// HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes. +// It is initialized as not required with string as its DataType. +func HeaderParameter(name, description string) *Parameter { + p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}} + p.beHeader() + return p +} + +// FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes. +// It is initialized as required with string as its DataType. +func (w *WebService) FormParameter(name, description string) *Parameter { + return FormParameter(name, description) +} + +// FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes. +// It is initialized as required with string as its DataType. +func FormParameter(name, description string) *Parameter { + p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}} + p.beForm() + return p +} + +// Route creates a new Route using the RouteBuilder and add to the ordered list of Routes. +func (w *WebService) Route(builder *RouteBuilder) *WebService { + w.routesLock.Lock() + defer w.routesLock.Unlock() + builder.copyDefaults(w.produces, w.consumes) + w.routes = append(w.routes, builder.Build()) + return w +} + +// RemoveRoute removes the specified route, looks for something that matches 'path' and 'method' +func (w *WebService) RemoveRoute(path, method string) error { + if !w.dynamicRoutes { + return errors.New("dynamic routes are not enabled.") + } + w.routesLock.Lock() + defer w.routesLock.Unlock() + newRoutes := make([]Route, (len(w.routes) - 1)) + current := 0 + for ix := range w.routes { + if w.routes[ix].Method == method && w.routes[ix].Path == path { + continue + } + newRoutes[current] = w.routes[ix] + current = current + 1 + } + w.routes = newRoutes + return nil +} + +// Method creates a new RouteBuilder and initialize its http method +func (w *WebService) Method(httpMethod string) *RouteBuilder { + return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method(httpMethod) +} + +// Produces specifies that this WebService can produce one or more MIME types. +// Http requests must have one of these values set for the Accept header. +func (w *WebService) Produces(contentTypes ...string) *WebService { + w.produces = contentTypes + return w +} + +// Consumes specifies that this WebService can consume one or more MIME types. +// Http requests must have one of these values set for the Content-Type header. +func (w *WebService) Consumes(accepts ...string) *WebService { + w.consumes = accepts + return w +} + +// Routes returns the Routes associated with this WebService +func (w *WebService) Routes() []Route { + if !w.dynamicRoutes { + return w.routes + } + // Make a copy of the array to prevent concurrency problems + w.routesLock.RLock() + defer w.routesLock.RUnlock() + result := make([]Route, len(w.routes)) + for ix := range w.routes { + result[ix] = w.routes[ix] + } + return result +} + +// RootPath returns the RootPath associated with this WebService. Default "/" +func (w *WebService) RootPath() string { + return w.rootPath +} + +// PathParameters return the path parameter names for (shared amoung its Routes) +func (w *WebService) PathParameters() []*Parameter { + return w.pathParameters +} + +// Filter adds a filter function to the chain of filters applicable to all its Routes +func (w *WebService) Filter(filter FilterFunction) *WebService { + w.filters = append(w.filters, filter) + return w +} + +// Doc is used to set the documentation of this service. +func (w *WebService) Doc(plainText string) *WebService { + w.documentation = plainText + return w +} + +// Documentation returns it. +func (w *WebService) Documentation() string { + return w.documentation +} + +/* + Convenience methods +*/ + +// HEAD is a shortcut for .Method("HEAD").Path(subPath) +func (w *WebService) HEAD(subPath string) *RouteBuilder { + return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("HEAD").Path(subPath) +} + +// GET is a shortcut for .Method("GET").Path(subPath) +func (w *WebService) GET(subPath string) *RouteBuilder { + return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("GET").Path(subPath) +} + +// POST is a shortcut for .Method("POST").Path(subPath) +func (w *WebService) POST(subPath string) *RouteBuilder { + return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("POST").Path(subPath) +} + +// PUT is a shortcut for .Method("PUT").Path(subPath) +func (w *WebService) PUT(subPath string) *RouteBuilder { + return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("PUT").Path(subPath) +} + +// PATCH is a shortcut for .Method("PATCH").Path(subPath) +func (w *WebService) PATCH(subPath string) *RouteBuilder { + return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("PATCH").Path(subPath) +} + +// DELETE is a shortcut for .Method("DELETE").Path(subPath) +func (w *WebService) DELETE(subPath string) *RouteBuilder { + return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method("DELETE").Path(subPath) +} diff --git a/vendor/github.com/emicklei/go-restful/web_service_container.go b/vendor/github.com/emicklei/go-restful/web_service_container.go new file mode 100644 index 00000000..c9d31b06 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/web_service_container.go @@ -0,0 +1,39 @@ +package restful + +// Copyright 2013 Ernest Micklei. All rights reserved. +// Use of this source code is governed by a license +// that can be found in the LICENSE file. + +import ( + "net/http" +) + +// DefaultContainer is a restful.Container that uses http.DefaultServeMux +var DefaultContainer *Container + +func init() { + DefaultContainer = NewContainer() + DefaultContainer.ServeMux = http.DefaultServeMux +} + +// If set the true then panics will not be caught to return HTTP 500. +// In that case, Route functions are responsible for handling any error situation. +// Default value is false = recover from panics. This has performance implications. +// OBSOLETE ; use restful.DefaultContainer.DoNotRecover(true) +var DoNotRecover = false + +// Add registers a new WebService add it to the DefaultContainer. +func Add(service *WebService) { + DefaultContainer.Add(service) +} + +// Filter appends a container FilterFunction from the DefaultContainer. +// These are called before dispatching a http.Request to a WebService. +func Filter(filter FilterFunction) { + DefaultContainer.Filter(filter) +} + +// RegisteredWebServices returns the collections of WebServices from the DefaultContainer +func RegisteredWebServices() []*WebService { + return DefaultContainer.RegisteredWebServices() +} diff --git a/vendor/github.com/emicklei/go-restful/web_service_test.go b/vendor/github.com/emicklei/go-restful/web_service_test.go new file mode 100644 index 00000000..73493813 --- /dev/null +++ b/vendor/github.com/emicklei/go-restful/web_service_test.go @@ -0,0 +1,343 @@ +package restful + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +const ( + pathGetFriends = "/get/{userId}/friends" +) + +func TestParameter(t *testing.T) { + p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} + p.AllowMultiple(true) + p.DataType("int") + p.Required(true) + values := map[string]string{"a": "b"} + p.AllowableValues(values) + p.bePath() + + ws := new(WebService) + ws.Param(p) + if ws.pathParameters[0].Data().Name != "name" { + t.Error("path parameter (or name) invalid") + } +} +func TestWebService_CanCreateParameterKinds(t *testing.T) { + ws := new(WebService) + if ws.BodyParameter("b", "b").Kind() != BodyParameterKind { + t.Error("body parameter expected") + } + if ws.PathParameter("p", "p").Kind() != PathParameterKind { + t.Error("path parameter expected") + } + if ws.QueryParameter("q", "q").Kind() != QueryParameterKind { + t.Error("query parameter expected") + } +} + +func TestCapturePanic(t *testing.T) { + tearDown() + Add(newPanicingService()) + httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) + httpRequest.Header.Set("Accept", "*/*") + httpWriter := httptest.NewRecorder() + // override the default here + DefaultContainer.DoNotRecover(false) + DefaultContainer.dispatch(httpWriter, httpRequest) + if 500 != httpWriter.Code { + t.Error("500 expected on fire") + } +} + +func TestCapturePanicWithEncoded(t *testing.T) { + tearDown() + Add(newPanicingService()) + DefaultContainer.EnableContentEncoding(true) + httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) + httpRequest.Header.Set("Accept", "*/*") + httpRequest.Header.Set("Accept-Encoding", "gzip") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 500 != httpWriter.Code { + t.Error("500 expected on fire, got", httpWriter.Code) + } +} + +func TestNotFound(t *testing.T) { + tearDown() + httpRequest, _ := http.NewRequest("GET", "http://here.com/missing", nil) + httpRequest.Header.Set("Accept", "*/*") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 404 != httpWriter.Code { + t.Error("404 expected on missing") + } +} + +func TestMethodNotAllowed(t *testing.T) { + tearDown() + Add(newGetOnlyService()) + httpRequest, _ := http.NewRequest("POST", "http://here.com/get", nil) + httpRequest.Header.Set("Accept", "*/*") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 405 != httpWriter.Code { + t.Error("405 expected method not allowed") + } +} + +func TestSelectedRoutePath_Issue100(t *testing.T) { + tearDown() + Add(newSelectedRouteTestingService()) + httpRequest, _ := http.NewRequest("GET", "http://here.com/get/232452/friends", nil) + httpRequest.Header.Set("Accept", "*/*") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if http.StatusOK != httpWriter.Code { + t.Error(http.StatusOK, "expected,", httpWriter.Code, "received.") + } +} + +func TestContentType415_Issue170(t *testing.T) { + tearDown() + Add(newGetOnlyJsonOnlyService()) + httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 200 != httpWriter.Code { + t.Errorf("Expected 200, got %d", httpWriter.Code) + } +} + +func TestNoContentTypePOST(t *testing.T) { + tearDown() + Add(newPostNoConsumesService()) + httpRequest, _ := http.NewRequest("POST", "http://here.com/post", nil) + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 204 != httpWriter.Code { + t.Errorf("Expected 204, got %d", httpWriter.Code) + } +} + +func TestContentType415_POST_Issue170(t *testing.T) { + tearDown() + Add(newPostOnlyJsonOnlyService()) + httpRequest, _ := http.NewRequest("POST", "http://here.com/post", nil) + httpRequest.Header.Set("Content-Type", "application/json") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 200 != httpWriter.Code { + t.Errorf("Expected 200, got %d", httpWriter.Code) + } +} + +// go test -v -test.run TestContentType406PlainJson ...restful +func TestContentType406PlainJson(t *testing.T) { + tearDown() + TraceLogger(testLogger{t}) + Add(newGetPlainTextOrJsonService()) + httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) + httpRequest.Header.Set("Accept", "text/plain") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if got, want := httpWriter.Code, 200; got != want { + t.Errorf("got %v, want %v", got, want) + } +} + +func TestRemoveRoute(t *testing.T) { + tearDown() + TraceLogger(testLogger{t}) + ws := newGetPlainTextOrJsonService() + Add(ws) + httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) + httpRequest.Header.Set("Accept", "text/plain") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if got, want := httpWriter.Code, 200; got != want { + t.Errorf("got %v, want %v", got, want) + } + + // dynamic apis are disabled, should error and do nothing + if err := ws.RemoveRoute("/get", "GET"); err == nil { + t.Error("unexpected non-error") + } + + httpWriter = httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if got, want := httpWriter.Code, 200; got != want { + t.Errorf("got %v, want %v", got, want) + } + + ws.SetDynamicRoutes(true) + if err := ws.RemoveRoute("/get", "GET"); err != nil { + t.Errorf("unexpected error %v", err) + } + + httpWriter = httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if got, want := httpWriter.Code, 404; got != want { + t.Errorf("got %v, want %v", got, want) + } +} +func TestRemoveLastRoute(t *testing.T) { + tearDown() + TraceLogger(testLogger{t}) + ws := newGetPlainTextOrJsonServiceMultiRoute() + Add(ws) + httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) + httpRequest.Header.Set("Accept", "text/plain") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if got, want := httpWriter.Code, 200; got != want { + t.Errorf("got %v, want %v", got, want) + } + + // dynamic apis are disabled, should error and do nothing + if err := ws.RemoveRoute("/get", "GET"); err == nil { + t.Error("unexpected non-error") + } + + httpWriter = httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if got, want := httpWriter.Code, 200; got != want { + t.Errorf("got %v, want %v", got, want) + } + + ws.SetDynamicRoutes(true) + if err := ws.RemoveRoute("/get", "GET"); err != nil { + t.Errorf("unexpected error %v", err) + } + + httpWriter = httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if got, want := httpWriter.Code, 404; got != want { + t.Errorf("got %v, want %v", got, want) + } +} + +// go test -v -test.run TestContentTypeOctet_Issue170 ...restful +func TestContentTypeOctet_Issue170(t *testing.T) { + tearDown() + Add(newGetConsumingOctetStreamService()) + // with content-type + httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) + httpRequest.Header.Set("Content-Type", MIME_OCTET) + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 200 != httpWriter.Code { + t.Errorf("Expected 200, got %d", httpWriter.Code) + } + // without content-type + httpRequest, _ = http.NewRequest("GET", "http://here.com/get", nil) + httpWriter = httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 200 != httpWriter.Code { + t.Errorf("Expected 200, got %d", httpWriter.Code) + } +} + +type exampleBody struct{} + +func TestParameterDataTypeDefaults(t *testing.T) { + tearDown() + ws := new(WebService) + route := ws.POST("/post").Reads(&exampleBody{}) + if route.parameters[0].data.DataType != "*restful.exampleBody" { + t.Errorf("body parameter incorrect name: %#v", route.parameters[0].data) + } +} + +func TestParameterDataTypeCustomization(t *testing.T) { + tearDown() + ws := new(WebService) + ws.TypeNameHandler(func(sample interface{}) string { + return "my.custom.type.name" + }) + route := ws.POST("/post").Reads(&exampleBody{}) + if route.parameters[0].data.DataType != "my.custom.type.name" { + t.Errorf("body parameter incorrect name: %#v", route.parameters[0].data) + } +} + +func newPanicingService() *WebService { + ws := new(WebService).Path("") + ws.Route(ws.GET("/fire").To(doPanic)) + return ws +} + +func newGetOnlyService() *WebService { + ws := new(WebService).Path("") + ws.Route(ws.GET("/get").To(doPanic)) + return ws +} + +func newPostOnlyJsonOnlyService() *WebService { + ws := new(WebService).Path("") + ws.Consumes("application/json") + ws.Route(ws.POST("/post").To(doNothing)) + return ws +} + +func newGetOnlyJsonOnlyService() *WebService { + ws := new(WebService).Path("") + ws.Consumes("application/json") + ws.Route(ws.GET("/get").To(doNothing)) + return ws +} + +func newGetPlainTextOrJsonService() *WebService { + ws := new(WebService).Path("") + ws.Produces("text/plain", "application/json") + ws.Route(ws.GET("/get").To(doNothing)) + return ws +} + +func newGetPlainTextOrJsonServiceMultiRoute() *WebService { + ws := new(WebService).Path("") + ws.Produces("text/plain", "application/json") + ws.Route(ws.GET("/get").To(doNothing)) + ws.Route(ws.GET("/status").To(doNothing)) + return ws +} + +func newGetConsumingOctetStreamService() *WebService { + ws := new(WebService).Path("") + ws.Consumes("application/octet-stream") + ws.Route(ws.GET("/get").To(doNothing)) + return ws +} + +func newPostNoConsumesService() *WebService { + ws := new(WebService).Path("") + ws.Route(ws.POST("/post").To(return204)) + return ws +} + +func newSelectedRouteTestingService() *WebService { + ws := new(WebService).Path("") + ws.Route(ws.GET(pathGetFriends).To(selectedRouteChecker)) + return ws +} + +func selectedRouteChecker(req *Request, resp *Response) { + if req.SelectedRoutePath() != pathGetFriends { + resp.InternalServerError() + } +} + +func doPanic(req *Request, resp *Response) { + println("lightning...") + panic("fire") +} + +func doNothing(req *Request, resp *Response) { +} + +func return204(req *Request, resp *Response) { + resp.WriteHeader(204) +} diff --git a/vendor/github.com/go-openapi/jsonpointer/.editorconfig b/vendor/github.com/go-openapi/jsonpointer/.editorconfig new file mode 100644 index 00000000..3152da69 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/.editorconfig @@ -0,0 +1,26 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +# Set default charset +[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] +charset = utf-8 + +# Tab indentation (no size specified) +[*.go] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false + +# Matches the exact files either package.json or .travis.yml +[{package.json,.travis.yml}] +indent_style = space +indent_size = 2 diff --git a/vendor/github.com/go-openapi/jsonpointer/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/jsonpointer/.github/CONTRIBUTING.md new file mode 100644 index 00000000..7dea4240 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/.github/CONTRIBUTING.md @@ -0,0 +1,117 @@ +## Contribution Guidelines + +### Pull requests are always welcome + +We are always thrilled to receive pull requests, and do our best to +process them as fast as possible. Not sure if that typo is worth a pull +request? Do it! We will appreciate it. + +If your pull request is not accepted on the first try, don't be +discouraged! If there's a problem with the implementation, hopefully you +received feedback on what to improve. + +We're trying very hard to keep go-swagger lean and focused. We don't want it +to do everything for everybody. This means that we might decide against +incorporating a new feature. However, there might be a way to implement +that feature *on top of* go-swagger. + + +### Conventions + +Fork the repo and make changes on your fork in a feature branch: + +- If it's a bugfix branch, name it XXX-something where XXX is the number of the + issue +- If it's a feature branch, create an enhancement issue to announce your + intentions, and name it XXX-something where XXX is the number of the issue. + +Submit unit tests for your changes. Go has a great test framework built in; use +it! Take a look at existing tests for inspiration. Run the full test suite on +your branch before submitting a pull request. + +Update the documentation when creating or modifying features. Test +your documentation changes for clarity, concision, and correctness, as +well as a clean documentation build. See ``docs/README.md`` for more +information on building the docs and how docs get released. + +Write clean code. Universally formatted code promotes ease of writing, reading, +and maintenance. Always run `gofmt -s -w file.go` on each changed file before +committing your changes. Most editors have plugins that do this automatically. + +Pull requests descriptions should be as clear as possible and include a +reference to all the issues that they address. + +Pull requests must not contain commits from other users or branches. + +Commit messages must start with a capitalized and short summary (max. 50 +chars) written in the imperative, followed by an optional, more detailed +explanatory text which is separated from the summary by an empty line. + +Code review comments may be added to your pull request. Discuss, then make the +suggested modifications and push additional commits to your feature branch. Be +sure to post a comment after pushing. The new commits will show up in the pull +request automatically, but the reviewers will not be notified unless you +comment. + +Before the pull request is merged, make sure that you squash your commits into +logical units of work using `git rebase -i` and `git push -f`. After every +commit the test suite should be passing. Include documentation changes in the +same commit so that a revert would remove all traces of the feature or fix. + +Commits that fix or close an issue should include a reference like `Closes #XXX` +or `Fixes #XXX`, which will automatically close the issue when merged. + +### Sign your work + +The sign-off is a simple line at the end of the explanation for the +patch, which certifies that you wrote it or otherwise have the right to +pass it on as an open-source patch. The rules are pretty simple: if you +can certify the below (from +[developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +660 York Street, Suite 102, +San Francisco, CA 94110 USA + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +using your real name (sorry, no pseudonyms or anonymous contributions.) + +You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/jsonpointer/.gitignore b/vendor/github.com/go-openapi/jsonpointer/.gitignore new file mode 100644 index 00000000..769c2440 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/.gitignore @@ -0,0 +1 @@ +secrets.yml diff --git a/vendor/github.com/go-openapi/jsonpointer/.travis.yml b/vendor/github.com/go-openapi/jsonpointer/.travis.yml new file mode 100644 index 00000000..d0f383a2 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/.travis.yml @@ -0,0 +1,13 @@ +language: go +go: +- 1.7 +install: +- go get -u github.com/stretchr/testify/assert +- go get -u github.com/go-openapi/swag +script: +- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... +after_success: +- bash <(curl -s https://codecov.io/bash) +notifications: + slack: + secure: a5VgoiwB1G/AZqzmephPZIhEB9avMlsWSlVnM1dSAtYAwdrQHGTQxAmpOxYIoSPDhWNN5bfZmjd29++UlTwLcHSR+e0kJhH6IfDlsHj/HplNCJ9tyI0zYc7XchtdKgeMxMzBKCzgwFXGSbQGydXTliDNBo0HOzmY3cou/daMFTP60K+offcjS+3LRAYb1EroSRXZqrk1nuF/xDL3792DZUdPMiFR/L/Df6y74D6/QP4sTkTDFQitz4Wy/7jbsfj8dG6qK2zivgV6/l+w4OVjFkxVpPXogDWY10vVXNVynqxfJ7to2d1I9lNCHE2ilBCkWMIPdyJF7hjF8pKW+82yP4EzRh0vu8Xn0HT5MZpQxdRY/YMxNrWaG7SxsoEaO4q5uhgdzAqLYY3TRa7MjIK+7Ur+aqOeTXn6OKwVi0CjvZ6mIU3WUKSwiwkFZMbjRAkSb5CYwMEfGFO/z964xz83qGt6WAtBXNotqCQpTIiKtDHQeLOMfksHImCg6JLhQcWBVxamVgu0G3Pdh8Y6DyPnxraXY95+QDavbjqv7TeYT9T/FNnrkXaTTK0s4iWE5H4ACU0Qvz0wUYgfQrZv0/Hp7V17+rabUwnzYySHCy9SWX/7OV9Cfh31iMp9ZIffr76xmmThtOEqs8TrTtU6BWI3rWwvA9cXQipZTVtL0oswrGw= diff --git a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..9322b065 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at ivan+abuse@flanders.co.nz. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonpointer/LICENSE b/vendor/github.com/go-openapi/jsonpointer/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md new file mode 100644 index 00000000..813788af --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/README.md @@ -0,0 +1,15 @@ +# gojsonpointer [![Build Status](https://travis-ci.org/go-openapi/jsonpointer.svg?branch=master)](https://travis-ci.org/go-openapi/jsonpointer) [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) + +[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonpointer/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonpointer?status.svg)](http://godoc.org/github.com/go-openapi/jsonpointer) +An implementation of JSON Pointer - Go language + +## Status +Completed YES + +Tested YES + +## References +http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 + +### Note +The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go new file mode 100644 index 00000000..fe2d6ee5 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/pointer.go @@ -0,0 +1,390 @@ +// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// +// 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. + +// author sigu-399 +// author-github https://github.com/sigu-399 +// author-mail sigu.399@gmail.com +// +// repository-name jsonpointer +// repository-desc An implementation of JSON Pointer - Go language +// +// description Main and unique file. +// +// created 25-02-2013 + +package jsonpointer + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "strings" + + "github.com/go-openapi/swag" +) + +const ( + emptyPointer = `` + pointerSeparator = `/` + + invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator +) + +var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() +var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() + +// JSONPointable is an interface for structs to implement when they need to customize the +// json pointer process +type JSONPointable interface { + JSONLookup(string) (interface{}, error) +} + +// JSONSetable is an interface for structs to implement when they need to customize the +// json pointer process +type JSONSetable interface { + JSONSet(string, interface{}) error +} + +// New creates a new json pointer for the given string +func New(jsonPointerString string) (Pointer, error) { + + var p Pointer + err := p.parse(jsonPointerString) + return p, err + +} + +// Pointer the json pointer reprsentation +type Pointer struct { + referenceTokens []string +} + +// "Constructor", parses the given string JSON pointer +func (p *Pointer) parse(jsonPointerString string) error { + + var err error + + if jsonPointerString != emptyPointer { + if !strings.HasPrefix(jsonPointerString, pointerSeparator) { + err = errors.New(invalidStart) + } else { + referenceTokens := strings.Split(jsonPointerString, pointerSeparator) + for _, referenceToken := range referenceTokens[1:] { + p.referenceTokens = append(p.referenceTokens, referenceToken) + } + } + } + + return err +} + +// Get uses the pointer to retrieve a value from a JSON document +func (p *Pointer) Get(document interface{}) (interface{}, reflect.Kind, error) { + return p.get(document, swag.DefaultJSONNameProvider) +} + +// Set uses the pointer to set a value from a JSON document +func (p *Pointer) Set(document interface{}, value interface{}) (interface{}, error) { + return document, p.set(document, value, swag.DefaultJSONNameProvider) +} + +// GetForToken gets a value for a json pointer token 1 level deep +func GetForToken(document interface{}, decodedToken string) (interface{}, reflect.Kind, error) { + return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) +} + +// SetForToken gets a value for a json pointer token 1 level deep +func SetForToken(document interface{}, decodedToken string, value interface{}) (interface{}, error) { + return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) +} + +func getSingleImpl(node interface{}, decodedToken string, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) { + rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() + + switch kind { + + case reflect.Struct: + if rValue.Type().Implements(jsonPointableType) { + r, err := node.(JSONPointable).JSONLookup(decodedToken) + if err != nil { + return nil, kind, err + } + return r, kind, nil + } + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return nil, kind, fmt.Errorf("object has no field %q", decodedToken) + } + fld := rValue.FieldByName(nm) + return fld.Interface(), kind, nil + + case reflect.Map: + kv := reflect.ValueOf(decodedToken) + mv := rValue.MapIndex(kv) + + if mv.IsValid() && !swag.IsZero(mv) { + return mv.Interface(), kind, nil + } + return nil, kind, fmt.Errorf("object has no key %q", decodedToken) + + case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return nil, kind, err + } + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength-1, tokenIndex) + } + + elem := rValue.Index(tokenIndex) + return elem.Interface(), kind, nil + + default: + return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken) + } + +} + +func setSingleImpl(node, data interface{}, decodedToken string, nameProvider *swag.NameProvider) error { + rValue := reflect.Indirect(reflect.ValueOf(node)) + switch rValue.Kind() { + + case reflect.Struct: + if ns, ok := node.(JSONSetable); ok { // pointer impl + return ns.JSONSet(decodedToken, data) + } + + if rValue.Type().Implements(jsonSetableType) { + return node.(JSONSetable).JSONSet(decodedToken, data) + } + + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return fmt.Errorf("object has no field %q", decodedToken) + } + fld := rValue.FieldByName(nm) + if fld.IsValid() { + fld.Set(reflect.ValueOf(data)) + } + return nil + + case reflect.Map: + kv := reflect.ValueOf(decodedToken) + rValue.SetMapIndex(kv, reflect.ValueOf(data)) + return nil + + case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return err + } + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) + } + + elem := rValue.Index(tokenIndex) + if !elem.CanSet() { + return fmt.Errorf("can't set slice index %s to %v", decodedToken, data) + } + elem.Set(reflect.ValueOf(data)) + return nil + + default: + return fmt.Errorf("invalid token reference %q", decodedToken) + } + +} + +func (p *Pointer) get(node interface{}, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) { + + if nameProvider == nil { + nameProvider = swag.DefaultJSONNameProvider + } + + kind := reflect.Invalid + + // Full document when empty + if len(p.referenceTokens) == 0 { + return node, kind, nil + } + + for _, token := range p.referenceTokens { + + decodedToken := Unescape(token) + + r, knd, err := getSingleImpl(node, decodedToken, nameProvider) + if err != nil { + return nil, knd, err + } + node, kind = r, knd + + } + + rValue := reflect.ValueOf(node) + kind = rValue.Kind() + + return node, kind, nil +} + +func (p *Pointer) set(node, data interface{}, nameProvider *swag.NameProvider) error { + knd := reflect.ValueOf(node).Kind() + + if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { + return fmt.Errorf("only structs, pointers, maps and slices are supported for setting values") + } + + if nameProvider == nil { + nameProvider = swag.DefaultJSONNameProvider + } + + // Full document when empty + if len(p.referenceTokens) == 0 { + return nil + } + + lastI := len(p.referenceTokens) - 1 + for i, token := range p.referenceTokens { + isLastToken := i == lastI + decodedToken := Unescape(token) + + if isLastToken { + + return setSingleImpl(node, data, decodedToken, nameProvider) + } + + rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() + + switch kind { + + case reflect.Struct: + if rValue.Type().Implements(jsonPointableType) { + r, err := node.(JSONPointable).JSONLookup(decodedToken) + if err != nil { + return err + } + fld := reflect.ValueOf(r) + if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { + node = fld.Addr().Interface() + continue + } + node = r + continue + } + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return fmt.Errorf("object has no field %q", decodedToken) + } + fld := rValue.FieldByName(nm) + if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { + node = fld.Addr().Interface() + continue + } + node = fld.Interface() + + case reflect.Map: + kv := reflect.ValueOf(decodedToken) + mv := rValue.MapIndex(kv) + + if !mv.IsValid() { + return fmt.Errorf("object has no key %q", decodedToken) + } + if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr { + node = mv.Addr().Interface() + continue + } + node = mv.Interface() + + case reflect.Slice: + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return err + } + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) + } + + elem := rValue.Index(tokenIndex) + if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr { + node = elem.Addr().Interface() + continue + } + node = elem.Interface() + + default: + return fmt.Errorf("invalid token reference %q", decodedToken) + } + + } + + return nil +} + +// DecodedTokens returns the decoded tokens +func (p *Pointer) DecodedTokens() []string { + result := make([]string, 0, len(p.referenceTokens)) + for _, t := range p.referenceTokens { + result = append(result, Unescape(t)) + } + return result +} + +// IsEmpty returns true if this is an empty json pointer +// this indicates that it points to the root document +func (p *Pointer) IsEmpty() bool { + return len(p.referenceTokens) == 0 +} + +// Pointer to string representation function +func (p *Pointer) String() string { + + if len(p.referenceTokens) == 0 { + return emptyPointer + } + + pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) + + return pointerString +} + +// Specific JSON pointer encoding here +// ~0 => ~ +// ~1 => / +// ... and vice versa + +const ( + encRefTok0 = `~0` + encRefTok1 = `~1` + decRefTok0 = `~` + decRefTok1 = `/` +) + +// Unescape unescapes a json pointer reference token string to the original representation +func Unescape(token string) string { + step1 := strings.Replace(token, encRefTok1, decRefTok1, -1) + step2 := strings.Replace(step1, encRefTok0, decRefTok0, -1) + return step2 +} + +// Escape escapes a pointer reference token string +func Escape(token string) string { + step1 := strings.Replace(token, decRefTok0, encRefTok0, -1) + step2 := strings.Replace(step1, decRefTok1, encRefTok1, -1) + return step2 +} diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer_test.go b/vendor/github.com/go-openapi/jsonpointer/pointer_test.go new file mode 100644 index 00000000..eabd5860 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonpointer/pointer_test.go @@ -0,0 +1,573 @@ +// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// +// 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. + +// author sigu-399 +// author-github https://github.com/sigu-399 +// author-mail sigu.399@gmail.com +// +// repository-name jsonpointer +// repository-desc An implementation of JSON Pointer - Go language +// +// description Automated tests on package. +// +// created 03-03-2013 + +package jsonpointer + +import ( + "encoding/json" + "fmt" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" +) + +const ( + TestDocumentNBItems = 11 + TestNodeObjNBItems = 4 + TestDocumentString = `{ +"foo": ["bar", "baz"], +"obj": { "a":1, "b":2, "c":[3,4], "d":[ {"e":9}, {"f":[50,51]} ] }, +"": 0, +"a/b": 1, +"c%d": 2, +"e^f": 3, +"g|h": 4, +"i\\j": 5, +"k\"l": 6, +" ": 7, +"m~n": 8 +}` +) + +var testDocumentJSON interface{} + +type testStructJSON struct { + Foo []string `json:"foo"` + Obj struct { + A int `json:"a"` + B int `json:"b"` + C []int `json:"c"` + D []struct { + E int `json:"e"` + F []int `json:"f"` + } `json:"d"` + } `json:"obj"` +} + +type aliasedMap map[string]interface{} + +var testStructJSONDoc testStructJSON +var testStructJSONPtr *testStructJSON + +func init() { + json.Unmarshal([]byte(TestDocumentString), &testDocumentJSON) + json.Unmarshal([]byte(TestDocumentString), &testStructJSONDoc) + testStructJSONPtr = &testStructJSONDoc +} + +func TestEscaping(t *testing.T) { + + ins := []string{`/`, `/`, `/a~1b`, `/a~1b`, `/c%d`, `/e^f`, `/g|h`, `/i\j`, `/k"l`, `/ `, `/m~0n`} + outs := []float64{0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8} + + for i := range ins { + p, err := New(ins[i]) + if assert.NoError(t, err, "input: %v", ins[i]) { + result, _, err := p.Get(testDocumentJSON) + if assert.NoError(t, err, "input: %v", ins[i]) { + assert.Equal(t, outs[i], result, "input: %v", ins[i]) + } + } + } + +} + +func TestFullDocument(t *testing.T) { + + in := `` + + p, err := New(in) + if err != nil { + t.Errorf("New(%v) error %v", in, err.Error()) + } + + result, _, err := p.Get(testDocumentJSON) + if err != nil { + t.Errorf("Get(%v) error %v", in, err.Error()) + } + + if len(result.(map[string]interface{})) != TestDocumentNBItems { + t.Errorf("Get(%v) = %v, expect full document", in, result) + } + + result, _, err = p.get(testDocumentJSON, nil) + if err != nil { + t.Errorf("Get(%v) error %v", in, err.Error()) + } + + if len(result.(map[string]interface{})) != TestDocumentNBItems { + t.Errorf("Get(%v) = %v, expect full document", in, result) + } +} + +func TestDecodedTokens(t *testing.T) { + p, err := New("/obj/a~1b") + assert.NoError(t, err) + assert.Equal(t, []string{"obj", "a/b"}, p.DecodedTokens()) +} + +func TestIsEmpty(t *testing.T) { + p, err := New("") + assert.NoError(t, err) + assert.True(t, p.IsEmpty()) + p, err = New("/obj") + assert.NoError(t, err) + assert.False(t, p.IsEmpty()) +} + +func TestGetSingle(t *testing.T) { + in := `/obj` + + _, err := New(in) + assert.NoError(t, err) + result, _, err := GetForToken(testDocumentJSON, "obj") + assert.NoError(t, err) + assert.Len(t, result, TestNodeObjNBItems) + + result, _, err = GetForToken(testStructJSONDoc, "Obj") + assert.Error(t, err) + assert.Nil(t, result) + + result, _, err = GetForToken(testStructJSONDoc, "Obj2") + assert.Error(t, err) + assert.Nil(t, result) +} + +type pointableImpl struct { + a string +} + +func (p pointableImpl) JSONLookup(token string) (interface{}, error) { + if token == "some" { + return p.a, nil + } + return nil, fmt.Errorf("object has no field %q", token) +} + +func TestPointableInterface(t *testing.T) { + p := &pointableImpl{"hello"} + + result, _, err := GetForToken(p, "some") + assert.NoError(t, err) + assert.Equal(t, p.a, result) + + result, _, err = GetForToken(p, "something") + assert.Error(t, err) + assert.Nil(t, result) +} + +func TestGetNode(t *testing.T) { + + in := `/obj` + + p, err := New(in) + assert.NoError(t, err) + result, _, err := p.Get(testDocumentJSON) + assert.NoError(t, err) + assert.Len(t, result, TestNodeObjNBItems) + + result, _, err = p.Get(aliasedMap(testDocumentJSON.(map[string]interface{}))) + assert.NoError(t, err) + assert.Len(t, result, TestNodeObjNBItems) + + result, _, err = p.Get(testStructJSONDoc) + assert.NoError(t, err) + assert.Equal(t, testStructJSONDoc.Obj, result) + + result, _, err = p.Get(testStructJSONPtr) + assert.NoError(t, err) + assert.Equal(t, testStructJSONDoc.Obj, result) +} + +func TestArray(t *testing.T) { + + ins := []string{`/foo/0`, `/foo/0`, `/foo/1`} + outs := []string{"bar", "bar", "baz"} + + for i := range ins { + p, err := New(ins[i]) + assert.NoError(t, err) + + result, _, err := p.Get(testStructJSONDoc) + assert.NoError(t, err) + assert.Equal(t, outs[i], result) + + result, _, err = p.Get(testStructJSONPtr) + assert.NoError(t, err) + assert.Equal(t, outs[i], result) + + result, _, err = p.Get(testDocumentJSON) + assert.NoError(t, err) + assert.Equal(t, outs[i], result) + } +} + +func TestOtherThings(t *testing.T) { + _, err := New("abc") + assert.Error(t, err) + + p, err := New("") + assert.NoError(t, err) + assert.Equal(t, "", p.String()) + + p, err = New("/obj/a") + assert.Equal(t, "/obj/a", p.String()) + + s := Escape("m~n") + assert.Equal(t, "m~0n", s) + s = Escape("m/n") + assert.Equal(t, "m~1n", s) + + p, err = New("/foo/3") + assert.NoError(t, err) + _, _, err = p.Get(testDocumentJSON) + assert.Error(t, err) + + p, err = New("/foo/a") + assert.NoError(t, err) + _, _, err = p.Get(testDocumentJSON) + assert.Error(t, err) + + p, err = New("/notthere") + assert.NoError(t, err) + _, _, err = p.Get(testDocumentJSON) + assert.Error(t, err) + + p, err = New("/invalid") + assert.NoError(t, err) + _, _, err = p.Get(1234) + assert.Error(t, err) + + p, err = New("/foo/1") + assert.NoError(t, err) + expected := "hello" + bbb := testDocumentJSON.(map[string]interface{})["foo"] + bbb.([]interface{})[1] = "hello" + + v, _, err := p.Get(testDocumentJSON) + assert.NoError(t, err) + assert.Equal(t, expected, v) + + esc := Escape("a/") + assert.Equal(t, "a~1", esc) + unesc := Unescape(esc) + assert.Equal(t, "a/", unesc) + + unesc = Unescape("~01") + assert.Equal(t, "~1", unesc) + assert.Equal(t, "~0~1", Escape("~/")) + assert.Equal(t, "~/", Unescape("~0~1")) +} + +func TestObject(t *testing.T) { + + ins := []string{`/obj/a`, `/obj/b`, `/obj/c/0`, `/obj/c/1`, `/obj/c/1`, `/obj/d/1/f/0`} + outs := []float64{1, 2, 3, 4, 4, 50} + + for i := range ins { + + p, err := New(ins[i]) + assert.NoError(t, err) + + result, _, err := p.Get(testDocumentJSON) + assert.NoError(t, err) + assert.Equal(t, outs[i], result) + + result, _, err = p.Get(testStructJSONDoc) + assert.NoError(t, err) + assert.EqualValues(t, outs[i], result) + + result, _, err = p.Get(testStructJSONPtr) + assert.NoError(t, err) + assert.EqualValues(t, outs[i], result) + } +} + +type setJsonDocEle struct { + B int `json:"b"` + C int `json:"c"` +} +type setJsonDoc struct { + A []struct { + B int `json:"b"` + C int `json:"c"` + } `json:"a"` + D int `json:"d"` +} + +type settableDoc struct { + Coll settableColl + Int settableInt +} + +func (s settableDoc) MarshalJSON() ([]byte, error) { + var res struct { + A settableColl `json:"a"` + D settableInt `json:"d"` + } + res.A = s.Coll + res.D = s.Int + return json.Marshal(res) +} +func (s *settableDoc) UnmarshalJSON(data []byte) error { + var res struct { + A settableColl `json:"a"` + D settableInt `json:"d"` + } + + if err := json.Unmarshal(data, &res); err != nil { + return err + } + s.Coll = res.A + s.Int = res.D + return nil +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s settableDoc) JSONLookup(token string) (interface{}, error) { + switch token { + case "a": + return &s.Coll, nil + case "d": + return &s.Int, nil + default: + return nil, fmt.Errorf("%s is not a known field", token) + } +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s *settableDoc) JSONSet(token string, data interface{}) error { + switch token { + case "a": + switch dt := data.(type) { + case settableColl: + s.Coll = dt + return nil + case *settableColl: + if dt != nil { + s.Coll = *dt + } else { + s.Coll = settableColl{} + } + return nil + case []settableCollItem: + s.Coll.Items = dt + return nil + } + case "d": + switch dt := data.(type) { + case settableInt: + s.Int = dt + return nil + case int: + s.Int.Value = dt + return nil + case int8: + s.Int.Value = int(dt) + return nil + case int16: + s.Int.Value = int(dt) + return nil + case int32: + s.Int.Value = int(dt) + return nil + case int64: + s.Int.Value = int(dt) + return nil + default: + return fmt.Errorf("invalid type %T for %s", data, token) + } + } + return fmt.Errorf("%s is not a known field", token) +} + +type settableColl struct { + Items []settableCollItem +} + +func (s settableColl) MarshalJSON() ([]byte, error) { + return json.Marshal(s.Items) +} +func (s *settableColl) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &s.Items) +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s settableColl) JSONLookup(token string) (interface{}, error) { + if tok, err := strconv.Atoi(token); err == nil { + return &s.Items[tok], nil + } + return nil, fmt.Errorf("%s is not a valid index", token) +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s *settableColl) JSONSet(token string, data interface{}) error { + if _, err := strconv.Atoi(token); err == nil { + _, err := SetForToken(s.Items, token, data) + return err + } + return fmt.Errorf("%s is not a valid index", token) +} + +type settableCollItem struct { + B int `json:"b"` + C int `json:"c"` +} + +type settableInt struct { + Value int +} + +func (s settableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(s.Value) +} +func (s *settableInt) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &s.Value) +} + +func TestSetNode(t *testing.T) { + + jsonText := `{"a":[{"b": 1, "c": 2}], "d": 3}` + + var jsonDocument interface{} + if assert.NoError(t, json.Unmarshal([]byte(jsonText), &jsonDocument)) { + in := "/a/0/c" + p, err := New(in) + if assert.NoError(t, err) { + + _, err = p.Set(jsonDocument, 999) + assert.NoError(t, err) + + firstNode := jsonDocument.(map[string]interface{}) + assert.Len(t, firstNode, 2) + + sliceNode := firstNode["a"].([]interface{}) + assert.Len(t, sliceNode, 1) + + changedNode := sliceNode[0].(map[string]interface{}) + chNodeVI := changedNode["c"] + if assert.IsType(t, 0, chNodeVI) { + changedNodeValue := chNodeVI.(int) + if assert.Equal(t, 999, changedNodeValue) { + assert.Len(t, sliceNode, 1) + } + } + } + + v, err := New("/a/0") + if assert.NoError(t, err) { + _, err = v.Set(jsonDocument, map[string]interface{}{"b": 3, "c": 8}) + if assert.NoError(t, err) { + firstNode := jsonDocument.(map[string]interface{}) + assert.Len(t, firstNode, 2) + + sliceNode := firstNode["a"].([]interface{}) + assert.Len(t, sliceNode, 1) + changedNode := sliceNode[0].(map[string]interface{}) + assert.Equal(t, 3, changedNode["b"]) + assert.Equal(t, 8, changedNode["c"]) + } + } + } + + var structDoc setJsonDoc + if assert.NoError(t, json.Unmarshal([]byte(jsonText), &structDoc)) { + g, err := New("/a") + if assert.NoError(t, err) { + _, err = g.Set(&structDoc, []struct { + B int `json:"b"` + C int `json:"c"` + }{{B: 4, C: 7}}) + + if assert.NoError(t, err) { + assert.Len(t, structDoc.A, 1) + changedNode := structDoc.A[0] + assert.Equal(t, 4, changedNode.B) + assert.Equal(t, 7, changedNode.C) + } + } + + v, err := New("/a/0") + if assert.NoError(t, err) { + _, err = v.Set(structDoc, struct { + B int `json:"b"` + C int `json:"c"` + }{B: 3, C: 8}) + + if assert.NoError(t, err) { + assert.Len(t, structDoc.A, 1) + changedNode := structDoc.A[0] + assert.Equal(t, 3, changedNode.B) + assert.Equal(t, 8, changedNode.C) + } + } + + p, err := New("/a/0/c") + if assert.NoError(t, err) { + _, err = p.Set(&structDoc, 999) + assert.NoError(t, err) + if assert.Len(t, structDoc.A, 1) { + assert.Equal(t, 999, structDoc.A[0].C) + } + } + } + + var setDoc settableDoc + if assert.NoError(t, json.Unmarshal([]byte(jsonText), &setDoc)) { + g, err := New("/a") + if assert.NoError(t, err) { + _, err = g.Set(&setDoc, []settableCollItem{{B: 4, C: 7}}) + + if assert.NoError(t, err) { + assert.Len(t, setDoc.Coll.Items, 1) + changedNode := setDoc.Coll.Items[0] + assert.Equal(t, 4, changedNode.B) + assert.Equal(t, 7, changedNode.C) + } + } + + v, err := New("/a/0") + if assert.NoError(t, err) { + _, err = v.Set(setDoc, settableCollItem{B: 3, C: 8}) + + if assert.NoError(t, err) { + assert.Len(t, setDoc.Coll.Items, 1) + changedNode := setDoc.Coll.Items[0] + assert.Equal(t, 3, changedNode.B) + assert.Equal(t, 8, changedNode.C) + } + } + + p, err := New("/a/0/c") + if assert.NoError(t, err) { + _, err = p.Set(setDoc, 999) + assert.NoError(t, err) + if assert.Len(t, setDoc.Coll.Items, 1) { + assert.Equal(t, 999, setDoc.Coll.Items[0].C) + } + } + } +} diff --git a/vendor/github.com/go-openapi/jsonreference/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/jsonreference/.github/CONTRIBUTING.md new file mode 100644 index 00000000..7dea4240 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/.github/CONTRIBUTING.md @@ -0,0 +1,117 @@ +## Contribution Guidelines + +### Pull requests are always welcome + +We are always thrilled to receive pull requests, and do our best to +process them as fast as possible. Not sure if that typo is worth a pull +request? Do it! We will appreciate it. + +If your pull request is not accepted on the first try, don't be +discouraged! If there's a problem with the implementation, hopefully you +received feedback on what to improve. + +We're trying very hard to keep go-swagger lean and focused. We don't want it +to do everything for everybody. This means that we might decide against +incorporating a new feature. However, there might be a way to implement +that feature *on top of* go-swagger. + + +### Conventions + +Fork the repo and make changes on your fork in a feature branch: + +- If it's a bugfix branch, name it XXX-something where XXX is the number of the + issue +- If it's a feature branch, create an enhancement issue to announce your + intentions, and name it XXX-something where XXX is the number of the issue. + +Submit unit tests for your changes. Go has a great test framework built in; use +it! Take a look at existing tests for inspiration. Run the full test suite on +your branch before submitting a pull request. + +Update the documentation when creating or modifying features. Test +your documentation changes for clarity, concision, and correctness, as +well as a clean documentation build. See ``docs/README.md`` for more +information on building the docs and how docs get released. + +Write clean code. Universally formatted code promotes ease of writing, reading, +and maintenance. Always run `gofmt -s -w file.go` on each changed file before +committing your changes. Most editors have plugins that do this automatically. + +Pull requests descriptions should be as clear as possible and include a +reference to all the issues that they address. + +Pull requests must not contain commits from other users or branches. + +Commit messages must start with a capitalized and short summary (max. 50 +chars) written in the imperative, followed by an optional, more detailed +explanatory text which is separated from the summary by an empty line. + +Code review comments may be added to your pull request. Discuss, then make the +suggested modifications and push additional commits to your feature branch. Be +sure to post a comment after pushing. The new commits will show up in the pull +request automatically, but the reviewers will not be notified unless you +comment. + +Before the pull request is merged, make sure that you squash your commits into +logical units of work using `git rebase -i` and `git push -f`. After every +commit the test suite should be passing. Include documentation changes in the +same commit so that a revert would remove all traces of the feature or fix. + +Commits that fix or close an issue should include a reference like `Closes #XXX` +or `Fixes #XXX`, which will automatically close the issue when merged. + +### Sign your work + +The sign-off is a simple line at the end of the explanation for the +patch, which certifies that you wrote it or otherwise have the right to +pass it on as an open-source patch. The rules are pretty simple: if you +can certify the below (from +[developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +660 York Street, Suite 102, +San Francisco, CA 94110 USA + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +using your real name (sorry, no pseudonyms or anonymous contributions.) + +You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/jsonreference/.gitignore b/vendor/github.com/go-openapi/jsonreference/.gitignore new file mode 100644 index 00000000..769c2440 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/.gitignore @@ -0,0 +1 @@ +secrets.yml diff --git a/vendor/github.com/go-openapi/jsonreference/.travis.yml b/vendor/github.com/go-openapi/jsonreference/.travis.yml new file mode 100644 index 00000000..5b31a1b3 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/.travis.yml @@ -0,0 +1,14 @@ +language: go +go: +- 1.7 +install: +- go get -u github.com/stretchr/testify/assert +- go get -u github.com/PuerkitoBio/purell +- go get -u github.com/go-openapi/jsonpointer +script: +- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... +after_success: +- bash <(curl -s https://codecov.io/bash) +notifications: + slack: + secure: OpQG/36F7DSF00HLm9WZMhyqFCYYyYTsVDObW226cWiR8PWYiNfLZiSEvIzT1Gx4dDjhigKTIqcLhG34CkL5iNXDjm9Yyo2RYhQPlK8NErNqUEXuBqn4RqYHW48VGhEhOyDd4Ei0E2FN5ZbgpvHgtpkdZ6XDi64r3Ac89isP9aPHXQTuv2Jog6b4/OKKiUTftLcTIst0p4Cp3gqOJWf1wnoj+IadWiECNVQT6zb47IYjtyw6+uV8iUjTzdKcRB6Zc6b4Dq7JAg1Zd7Jfxkql3hlKp4PNlRf9Cy7y5iA3G7MLyg3FcPX5z2kmcyPt2jOTRMBWUJ5zIQpOxizAcN8WsT3WWBL5KbuYK6k0PzujrIDLqdxGpNmjkkMfDBT9cKmZpm2FdW+oZgPFJP+oKmAo4u4KJz/vjiPTXgQlN5bmrLuRMCp+AwC5wkIohTqWZVPE2TK6ZSnMYcg/W39s+RP/9mJoyryAvPSpBOLTI+biCgaUCTOAZxNTWpMFc3tPYntc41WWkdKcooZ9JA5DwfcaVFyTGQ3YXz+HvX6G1z/gW0Q/A4dBi9mj2iE1xm7tRTT+4VQ2AXFvSEI1HJpfPgYnwAtwOD1v3Qm2EUHk9sCdtEDR4wVGEPIVn44GnwFMnGKx9JWppMPYwFu3SVDdHt+E+LOlhZUply11Aa+IVrT2KUQ= diff --git a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..9322b065 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at ivan+abuse@flanders.co.nz. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonreference/LICENSE b/vendor/github.com/go-openapi/jsonreference/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-openapi/jsonreference/README.md b/vendor/github.com/go-openapi/jsonreference/README.md new file mode 100644 index 00000000..66345f4c --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/README.md @@ -0,0 +1,15 @@ +# gojsonreference [![Build Status](https://travis-ci.org/go-openapi/jsonreference.svg?branch=master)](https://travis-ci.org/go-openapi/jsonreference) [![codecov](https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonreference) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) + +[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonreference/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonreference?status.svg)](http://godoc.org/github.com/go-openapi/jsonreference) +An implementation of JSON Reference - Go language + +## Status +Work in progress ( 90% done ) + +## Dependencies +https://github.com/go-openapi/jsonpointer + +## References +http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 + +http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 diff --git a/vendor/github.com/go-openapi/jsonreference/reference.go b/vendor/github.com/go-openapi/jsonreference/reference.go new file mode 100644 index 00000000..3bc0a6e2 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/reference.go @@ -0,0 +1,156 @@ +// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// +// 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. + +// author sigu-399 +// author-github https://github.com/sigu-399 +// author-mail sigu.399@gmail.com +// +// repository-name jsonreference +// repository-desc An implementation of JSON Reference - Go language +// +// description Main and unique file. +// +// created 26-02-2013 + +package jsonreference + +import ( + "errors" + "net/url" + "strings" + + "github.com/PuerkitoBio/purell" + "github.com/go-openapi/jsonpointer" +) + +const ( + fragmentRune = `#` +) + +// New creates a new reference for the given string +func New(jsonReferenceString string) (Ref, error) { + + var r Ref + err := r.parse(jsonReferenceString) + return r, err + +} + +// MustCreateRef parses the ref string and panics when it's invalid. +// Use the New method for a version that returns an error +func MustCreateRef(ref string) Ref { + r, err := New(ref) + if err != nil { + panic(err) + } + return r +} + +// Ref represents a json reference object +type Ref struct { + referenceURL *url.URL + referencePointer jsonpointer.Pointer + + HasFullURL bool + HasURLPathOnly bool + HasFragmentOnly bool + HasFileScheme bool + HasFullFilePath bool +} + +// GetURL gets the URL for this reference +func (r *Ref) GetURL() *url.URL { + return r.referenceURL +} + +// GetPointer gets the json pointer for this reference +func (r *Ref) GetPointer() *jsonpointer.Pointer { + return &r.referencePointer +} + +// String returns the best version of the url for this reference +func (r *Ref) String() string { + + if r.referenceURL != nil { + return r.referenceURL.String() + } + + if r.HasFragmentOnly { + return fragmentRune + r.referencePointer.String() + } + + return r.referencePointer.String() +} + +// IsRoot returns true if this reference is a root document +func (r *Ref) IsRoot() bool { + return r.referenceURL != nil && + !r.IsCanonical() && + !r.HasURLPathOnly && + r.referenceURL.Fragment == "" +} + +// IsCanonical returns true when this pointer starts with http(s):// or file:// +func (r *Ref) IsCanonical() bool { + return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL) +} + +// "Constructor", parses the given string JSON reference +func (r *Ref) parse(jsonReferenceString string) error { + + parsed, err := url.Parse(jsonReferenceString) + if err != nil { + return err + } + + r.referenceURL, _ = url.Parse(purell.NormalizeURL(parsed, purell.FlagsSafe|purell.FlagRemoveDuplicateSlashes)) + refURL := r.referenceURL + + if refURL.Scheme != "" && refURL.Host != "" { + r.HasFullURL = true + } else { + if refURL.Path != "" { + r.HasURLPathOnly = true + } else if refURL.RawQuery == "" && refURL.Fragment != "" { + r.HasFragmentOnly = true + } + } + + r.HasFileScheme = refURL.Scheme == "file" + r.HasFullFilePath = strings.HasPrefix(refURL.Path, "/") + + // invalid json-pointer error means url has no json-pointer fragment. simply ignore error + r.referencePointer, _ = jsonpointer.New(refURL.Fragment) + + return nil +} + +// Inherits creates a new reference from a parent and a child +// If the child cannot inherit from the parent, an error is returned +func (r *Ref) Inherits(child Ref) (*Ref, error) { + childURL := child.GetURL() + parentURL := r.GetURL() + if childURL == nil { + return nil, errors.New("child url is nil") + } + if parentURL == nil { + return &child, nil + } + + ref, err := New(parentURL.ResolveReference(childURL).String()) + if err != nil { + return nil, err + } + return &ref, nil +} diff --git a/vendor/github.com/go-openapi/jsonreference/reference_test.go b/vendor/github.com/go-openapi/jsonreference/reference_test.go new file mode 100644 index 00000000..499c634c --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/reference_test.go @@ -0,0 +1,420 @@ +// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// +// 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. + +// author sigu-399 +// author-github https://github.com/sigu-399 +// author-mail sigu.399@gmail.com +// +// repository-name jsonreference +// repository-desc An implementation of JSON Reference - Go language +// +// description Automated tests on package. +// +// created 03-03-2013 + +package jsonreference + +import ( + "testing" + + "github.com/go-openapi/jsonpointer" + "github.com/stretchr/testify/assert" +) + +func TestIsRoot(t *testing.T) { + in := "#" + r1, err := New(in) + assert.NoError(t, err) + assert.True(t, r1.IsRoot()) + + in = "#/ok" + r1 = MustCreateRef(in) + assert.False(t, r1.IsRoot()) + + assert.Panics(t, assert.PanicTestFunc(func() { + MustCreateRef("%2") + })) +} + +func TestFull(t *testing.T) { + + in := "http://host/path/a/b/c#/f/a/b" + + r1, err := New(in) + if err != nil { + t.Errorf("New(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != false { + t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) + } + + if r1.HasFullURL != true { + t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true) + } + + if r1.HasURLPathOnly != false { + t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) + } + + if r1.HasFileScheme != false { + t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "/f/a/b" { + t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/f/a/b") + } +} + +func TestFullURL(t *testing.T) { + + in := "http://host/path/a/b/c" + + r1, err := New(in) + if err != nil { + t.Errorf("New(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != false { + t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) + } + + if r1.HasFullURL != true { + t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true) + } + + if r1.HasURLPathOnly != false { + t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) + } + + if r1.HasFileScheme != false { + t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "" { + t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") + } +} + +func TestFragmentOnly(t *testing.T) { + + in := "#/fragment/only" + + r1, err := New(in) + if err != nil { + t.Errorf("New(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != true { + t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, true) + } + + if r1.HasFullURL != false { + t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) + } + + if r1.HasURLPathOnly != false { + t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) + } + + if r1.HasFileScheme != false { + t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "/fragment/only" { + t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/fragment/only") + } + + p, _ := jsonpointer.New(r1.referenceURL.Fragment) + r2 := Ref{referencePointer: p, HasFragmentOnly: true} + assert.Equal(t, r2.String(), in) + + r3 := Ref{referencePointer: p, HasFragmentOnly: false} + assert.Equal(t, r3.String(), in[1:]) +} + +func TestURLPathOnly(t *testing.T) { + + in := "/documents/document.json" + + r1, err := New(in) + if err != nil { + t.Errorf("New(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != false { + t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) + } + + if r1.HasFullURL != false { + t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) + } + + if r1.HasURLPathOnly != true { + t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true) + } + + if r1.HasFileScheme != false { + t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "" { + t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") + } +} + +func TestURLRelativePathOnly(t *testing.T) { + + in := "document.json" + + r1, err := New(in) + if err != nil { + t.Errorf("New(%v) error %s", in, err.Error()) + } + + if in != r1.String() { + t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) + } + + if r1.HasFragmentOnly != false { + t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) + } + + if r1.HasFullURL != false { + t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) + } + + if r1.HasURLPathOnly != true { + t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true) + } + + if r1.HasFileScheme != false { + t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) + } + + if r1.GetPointer().String() != "" { + t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") + } +} + +func TestInheritsInValid(t *testing.T) { + in1 := "http://www.test.com/doc.json" + in2 := "#/a/b" + + r1, _ := New(in1) + r2 := Ref{} + result, err := r1.Inherits(r2) + assert.Error(t, err) + assert.Nil(t, result) + + r1 = Ref{} + r2, _ = New(in2) + result, err = r1.Inherits(r2) + assert.NoError(t, err) + assert.Equal(t, r2, *result) +} + +func TestInheritsValid(t *testing.T) { + + in1 := "http://www.test.com/doc.json" + in2 := "#/a/b" + out := in1 + in2 + + r1, _ := New(in1) + r2, _ := New(in2) + + result, err := r1.Inherits(r2) + if err != nil { + t.Errorf("Inherits(%s,%s) error %s", r1.String(), r2.String(), err.Error()) + } + + if result.String() != out { + t.Errorf("Inherits(%s,%s) = %s, expect %s", r1.String(), r2.String(), result.String(), out) + } + + if result.GetPointer().String() != "/a/b" { + t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "/a/b") + } +} + +func TestInheritsDifferentHost(t *testing.T) { + + in1 := "http://www.test.com/doc.json" + in2 := "http://www.test2.com/doc.json#bla" + + r1, _ := New(in1) + r2, _ := New(in2) + + result, err := r1.Inherits(r2) + + if err != nil { + t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) + } + + if result.String() != in2 { + t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) + } + + if result.GetPointer().String() != "" { + t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") + } +} + +func TestFileScheme(t *testing.T) { + + in1 := "file:///Users/mac/1.json#a" + in2 := "file:///Users/mac/2.json#b" + + r1, _ := New(in1) + r2, _ := New(in2) + + if r1.HasFragmentOnly != false { + t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in1, r1.HasFragmentOnly, false) + } + + if r1.HasFileScheme != true { + t.Errorf("New(%v)::HasFileScheme %v expect %v", in1, r1.HasFileScheme, true) + } + + if r1.HasFullFilePath != true { + t.Errorf("New(%v)::HasFullFilePath %v expect %v", in1, r1.HasFullFilePath, true) + } + + if r1.IsCanonical() != true { + t.Errorf("New(%v)::IsCanonical %v expect %v", in1, r1.IsCanonical, true) + } + + result, err := r1.Inherits(r2) + if err != nil { + t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) + } + if result.String() != in2 { + t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) + } + + if result.GetPointer().String() != "" { + t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") + } +} + +func TestReferenceResolution(t *testing.T) { + + // 5.4. Reference Resolution Examples + // http://tools.ietf.org/html/rfc3986#section-5.4 + + base := "http://a/b/c/d;p?q" + baseRef, err := New(base) + + if err != nil { + t.Errorf("New(%s) failed error: %s", base, err.Error()) + } + if baseRef.String() != base { + t.Errorf("New(%s) %s expected %s", base, baseRef.String(), base) + } + + checks := []string{ + // 5.4.1. Normal Examples + // http://tools.ietf.org/html/rfc3986#section-5.4.1 + + "g:h", "g:h", + "g", "http://a/b/c/g", + "./g", "http://a/b/c/g", + "g/", "http://a/b/c/g/", + "/g", "http://a/g", + "//g", "http://g", + "?y", "http://a/b/c/d;p?y", + "g?y", "http://a/b/c/g?y", + "#s", "http://a/b/c/d;p?q#s", + "g#s", "http://a/b/c/g#s", + "g?y#s", "http://a/b/c/g?y#s", + ";x", "http://a/b/c/;x", + "g;x", "http://a/b/c/g;x", + "g;x?y#s", "http://a/b/c/g;x?y#s", + "", "http://a/b/c/d;p?q", + ".", "http://a/b/c/", + "./", "http://a/b/c/", + "..", "http://a/b/", + "../", "http://a/b/", + "../g", "http://a/b/g", + "../..", "http://a/", + "../../", "http://a/", + "../../g", "http://a/g", + + // 5.4.2. Abnormal Examples + // http://tools.ietf.org/html/rfc3986#section-5.4.2 + + "../../../g", "http://a/g", + "../../../../g", "http://a/g", + + "/./g", "http://a/g", + "/../g", "http://a/g", + "g.", "http://a/b/c/g.", + ".g", "http://a/b/c/.g", + "g..", "http://a/b/c/g..", + "..g", "http://a/b/c/..g", + + "./../g", "http://a/b/g", + "./g/.", "http://a/b/c/g/", + "g/./h", "http://a/b/c/g/h", + "g/../h", "http://a/b/c/h", + "g;x=1/./y", "http://a/b/c/g;x=1/y", + "g;x=1/../y", "http://a/b/c/y", + + "g?y/./x", "http://a/b/c/g?y/./x", + "g?y/../x", "http://a/b/c/g?y/../x", + "g#s/./x", "http://a/b/c/g#s/./x", + "g#s/../x", "http://a/b/c/g#s/../x", + + "http:g", "http:g", // for strict parsers + //"http:g", "http://a/b/c/g", // for backward compatibility + + } + for i := 0; i < len(checks); i += 2 { + child := checks[i] + expected := checks[i+1] + // fmt.Printf("%d: %v -> %v\n", i/2, child, expected) + + childRef, e := New(child) + if e != nil { + t.Errorf("%d: New(%s) failed error: %s", i/2, child, e.Error()) + } + + res, e := baseRef.Inherits(childRef) + if res == nil { + t.Errorf("%d: Inherits(%s, %s) nil not expected", i/2, base, child) + } + if e != nil { + t.Errorf("%d: Inherits(%s) failed error: %s", i/2, child, e.Error()) + } + if res.String() != expected { + t.Errorf("%d: Inherits(%s, %s) %s expected %s", i/2, base, child, res.String(), expected) + } + } +} diff --git a/vendor/github.com/go-openapi/spec/.editorconfig b/vendor/github.com/go-openapi/spec/.editorconfig new file mode 100644 index 00000000..3152da69 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/.editorconfig @@ -0,0 +1,26 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +# Set default charset +[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] +charset = utf-8 + +# Tab indentation (no size specified) +[*.go] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false + +# Matches the exact files either package.json or .travis.yml +[{package.json,.travis.yml}] +indent_style = space +indent_size = 2 diff --git a/vendor/github.com/go-openapi/spec/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/spec/.github/CONTRIBUTING.md new file mode 100644 index 00000000..7dea4240 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/.github/CONTRIBUTING.md @@ -0,0 +1,117 @@ +## Contribution Guidelines + +### Pull requests are always welcome + +We are always thrilled to receive pull requests, and do our best to +process them as fast as possible. Not sure if that typo is worth a pull +request? Do it! We will appreciate it. + +If your pull request is not accepted on the first try, don't be +discouraged! If there's a problem with the implementation, hopefully you +received feedback on what to improve. + +We're trying very hard to keep go-swagger lean and focused. We don't want it +to do everything for everybody. This means that we might decide against +incorporating a new feature. However, there might be a way to implement +that feature *on top of* go-swagger. + + +### Conventions + +Fork the repo and make changes on your fork in a feature branch: + +- If it's a bugfix branch, name it XXX-something where XXX is the number of the + issue +- If it's a feature branch, create an enhancement issue to announce your + intentions, and name it XXX-something where XXX is the number of the issue. + +Submit unit tests for your changes. Go has a great test framework built in; use +it! Take a look at existing tests for inspiration. Run the full test suite on +your branch before submitting a pull request. + +Update the documentation when creating or modifying features. Test +your documentation changes for clarity, concision, and correctness, as +well as a clean documentation build. See ``docs/README.md`` for more +information on building the docs and how docs get released. + +Write clean code. Universally formatted code promotes ease of writing, reading, +and maintenance. Always run `gofmt -s -w file.go` on each changed file before +committing your changes. Most editors have plugins that do this automatically. + +Pull requests descriptions should be as clear as possible and include a +reference to all the issues that they address. + +Pull requests must not contain commits from other users or branches. + +Commit messages must start with a capitalized and short summary (max. 50 +chars) written in the imperative, followed by an optional, more detailed +explanatory text which is separated from the summary by an empty line. + +Code review comments may be added to your pull request. Discuss, then make the +suggested modifications and push additional commits to your feature branch. Be +sure to post a comment after pushing. The new commits will show up in the pull +request automatically, but the reviewers will not be notified unless you +comment. + +Before the pull request is merged, make sure that you squash your commits into +logical units of work using `git rebase -i` and `git push -f`. After every +commit the test suite should be passing. Include documentation changes in the +same commit so that a revert would remove all traces of the feature or fix. + +Commits that fix or close an issue should include a reference like `Closes #XXX` +or `Fixes #XXX`, which will automatically close the issue when merged. + +### Sign your work + +The sign-off is a simple line at the end of the explanation for the +patch, which certifies that you wrote it or otherwise have the right to +pass it on as an open-source patch. The rules are pretty simple: if you +can certify the below (from +[developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +660 York Street, Suite 102, +San Francisco, CA 94110 USA + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +using your real name (sorry, no pseudonyms or anonymous contributions.) + +You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/spec/.gitignore b/vendor/github.com/go-openapi/spec/.gitignore new file mode 100644 index 00000000..dd91ed6a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/.gitignore @@ -0,0 +1,2 @@ +secrets.yml +coverage.out diff --git a/vendor/github.com/go-openapi/spec/.travis.yml b/vendor/github.com/go-openapi/spec/.travis.yml new file mode 100644 index 00000000..ea80ef2a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/.travis.yml @@ -0,0 +1,16 @@ +language: go +go: +- 1.7 +install: +- go get -u github.com/stretchr/testify +- go get -u github.com/go-openapi/swag +- go get -u gopkg.in/yaml.v2 +- go get -u github.com/go-openapi/jsonpointer +- go get -u github.com/go-openapi/jsonreference +script: +- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... +after_success: +- bash <(curl -s https://codecov.io/bash) +notifications: + slack: + secure: QUWvCkBBK09GF7YtEvHHVt70JOkdlNBG0nIKu/5qc4/nW5HP8I2w0SEf/XR2je0eED1Qe3L/AfMCWwrEj+IUZc3l4v+ju8X8R3Lomhme0Eb0jd1MTMCuPcBT47YCj0M7RON7vXtbFfm1hFJ/jLe5+9FXz0hpXsR24PJc5ZIi/ogNwkaPqG4BmndzecpSh0vc2FJPZUD9LT0I09REY/vXR0oQAalLkW0asGD5taHZTUZq/kBpsNxaAFrLM23i4mUcf33M5fjLpvx5LRICrX/57XpBrDh2TooBU6Qj3CgoY0uPRYUmSNxbVx1czNzl2JtEpb5yjoxfVPQeg0BvQM00G8LJINISR+ohrjhkZmAqchDupAX+yFrxTtORa78CtnIL6z/aTNlgwwVD8kvL/1pFA/JWYmKDmz93mV/+6wubGzNSQCstzjkFA4/iZEKewKUoRIAi/fxyscP6L/rCpmY/4llZZvrnyTqVbt6URWpopUpH4rwYqreXAtJxJsfBJIeSmUIiDIOMGkCTvyTEW3fWGmGoqWtSHLoaWDyAIGb7azb+KvfpWtEcoPFWfSWU+LGee0A/YsUhBl7ADB9A0CJEuR8q4BPpKpfLwPKSiKSAXL7zDkyjExyhtgqbSl2jS+rKIHOZNL8JkCcTP2MKMVd563C5rC5FMKqu3S9m2b6380E= diff --git a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..9322b065 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at ivan+abuse@flanders.co.nz. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/spec/LICENSE b/vendor/github.com/go-openapi/spec/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-openapi/spec/README.md b/vendor/github.com/go-openapi/spec/README.md new file mode 100644 index 00000000..1d162208 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/README.md @@ -0,0 +1,5 @@ +# OAI object model [![Build Status](https://travis-ci.org/go-openapi/spec.svg?branch=master)](https://travis-ci.org/go-openapi/spec) [![codecov](https://codecov.io/gh/go-openapi/spec/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/spec) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) + +[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/spec/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/spec?status.svg)](http://godoc.org/github.com/go-openapi/spec) + +The object model for OpenAPI specification documents diff --git a/vendor/github.com/go-openapi/spec/auth_test.go b/vendor/github.com/go-openapi/spec/auth_test.go new file mode 100644 index 00000000..5449fdec --- /dev/null +++ b/vendor/github.com/go-openapi/spec/auth_test.go @@ -0,0 +1,128 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "testing" +) + +func TestSerialization_AuthSerialization(t *testing.T) { + assertSerializeJSON(t, BasicAuth(), `{"type":"basic"}`) + + assertSerializeJSON(t, APIKeyAuth("api-key", "header"), `{"type":"apiKey","name":"api-key","in":"header"}`) + + assertSerializeJSON( + t, + OAuth2Implicit("http://foo.com/authorization"), + `{"type":"oauth2","flow":"implicit","authorizationUrl":"http://foo.com/authorization"}`) + + assertSerializeJSON( + t, + OAuth2Password("http://foo.com/token"), + `{"type":"oauth2","flow":"password","tokenUrl":"http://foo.com/token"}`) + + assertSerializeJSON(t, + OAuth2Application("http://foo.com/token"), + `{"type":"oauth2","flow":"application","tokenUrl":"http://foo.com/token"}`) + + assertSerializeJSON( + t, + OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token"), + `{"type":"oauth2","flow":"accessCode","authorizationUrl":"http://foo.com/authorization","tokenUrl":"http://foo.com/token"}`) + + auth1 := OAuth2Implicit("http://foo.com/authorization") + auth1.AddScope("email", "read your email") + assertSerializeJSON( + t, + auth1, + `{"type":"oauth2","flow":"implicit","authorizationUrl":"http://foo.com/authorization","scopes":{"email":"read your email"}}`) + + auth2 := OAuth2Password("http://foo.com/authorization") + auth2.AddScope("email", "read your email") + assertSerializeJSON( + t, + auth2, + `{"type":"oauth2","flow":"password","tokenUrl":"http://foo.com/authorization","scopes":{"email":"read your email"}}`) + + auth3 := OAuth2Application("http://foo.com/token") + auth3.AddScope("email", "read your email") + assertSerializeJSON( + t, + auth3, + `{"type":"oauth2","flow":"application","tokenUrl":"http://foo.com/token","scopes":{"email":"read your email"}}`) + + auth4 := OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token") + auth4.AddScope("email", "read your email") + assertSerializeJSON( + t, + auth4, + `{"type":"oauth2","flow":"accessCode","authorizationUrl":"http://foo.com/authorization","tokenUrl":"http://foo.com/token","scopes":{"email":"read your email"}}`) +} + +func TestSerialization_AuthDeserialization(t *testing.T) { + + assertParsesJSON(t, `{"type":"basic"}`, BasicAuth()) + + assertParsesJSON( + t, + `{"in":"header","name":"api-key","type":"apiKey"}`, + APIKeyAuth("api-key", "header")) + + assertParsesJSON( + t, + `{"authorizationUrl":"http://foo.com/authorization","flow":"implicit","type":"oauth2"}`, + OAuth2Implicit("http://foo.com/authorization")) + + assertParsesJSON( + t, + `{"flow":"password","tokenUrl":"http://foo.com/token","type":"oauth2"}`, + OAuth2Password("http://foo.com/token")) + + assertParsesJSON( + t, + `{"flow":"application","tokenUrl":"http://foo.com/token","type":"oauth2"}`, + OAuth2Application("http://foo.com/token")) + + assertParsesJSON( + t, + `{"authorizationUrl":"http://foo.com/authorization","flow":"accessCode","tokenUrl":"http://foo.com/token","type":"oauth2"}`, + OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token")) + + auth1 := OAuth2Implicit("http://foo.com/authorization") + auth1.AddScope("email", "read your email") + assertParsesJSON(t, + `{"authorizationUrl":"http://foo.com/authorization","flow":"implicit","scopes":{"email":"read your email"},"type":"oauth2"}`, + auth1) + + auth2 := OAuth2Password("http://foo.com/token") + auth2.AddScope("email", "read your email") + assertParsesJSON(t, + `{"flow":"password","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, + auth2) + + auth3 := OAuth2Application("http://foo.com/token") + auth3.AddScope("email", "read your email") + assertParsesJSON(t, + `{"flow":"application","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, + auth3) + + auth4 := OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token") + auth4.AddScope("email", "read your email") + assertParsesJSON( + t, + `{"authorizationUrl":"http://foo.com/authorization","flow":"accessCode","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, + auth4) + +} diff --git a/vendor/github.com/go-openapi/spec/bindata.go b/vendor/github.com/go-openapi/spec/bindata.go new file mode 100644 index 00000000..9afb5df1 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/bindata.go @@ -0,0 +1,260 @@ +// Code generated by go-bindata. +// sources: +// schemas/jsonschema-draft-04.json +// schemas/v2/schema.json +// DO NOT EDIT! + +package spec + +import ( + "bytes" + "compress/gzip" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strings" + "time" +) + +func bindataRead(data []byte, name string) ([]byte, error) { + gz, err := gzip.NewReader(bytes.NewBuffer(data)) + if err != nil { + return nil, fmt.Errorf("Read %q: %v", name, err) + } + + var buf bytes.Buffer + _, err = io.Copy(&buf, gz) + clErr := gz.Close() + + if err != nil { + return nil, fmt.Errorf("Read %q: %v", name, err) + } + if clErr != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +type asset struct { + bytes []byte + info os.FileInfo +} + +type bindataFileInfo struct { + name string + size int64 + mode os.FileMode + modTime time.Time +} + +func (fi bindataFileInfo) Name() string { + return fi.name +} +func (fi bindataFileInfo) Size() int64 { + return fi.size +} +func (fi bindataFileInfo) Mode() os.FileMode { + return fi.mode +} +func (fi bindataFileInfo) ModTime() time.Time { + return fi.modTime +} +func (fi bindataFileInfo) IsDir() bool { + return false +} +func (fi bindataFileInfo) Sys() interface{} { + return nil +} + +var _jsonschemaDraft04JSON = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xc4\x57\x3b\x6f\xdb\x3e\x10\xdf\xf3\x29\x08\x26\x63\xf2\x97\xff\x40\x27\x6f\x45\xbb\x18\x68\xd1\x0c\xdd\x0c\x0f\xb4\x75\xb2\x19\x50\xa4\x42\x51\x81\x0d\x43\xdf\xbd\xa0\xa8\x07\x29\x91\x92\x2d\xbb\x8d\x97\x28\xbc\xd7\xef\x8e\xf7\xe2\xf9\x01\x21\x84\x30\x8d\xf1\x12\xe1\x83\x52\xd9\x32\x8a\xde\x72\xc1\x5f\xf2\xdd\x01\x52\xf2\x9f\x90\xfb\x28\x96\x24\x51\x2f\x8b\x2f\x91\x39\x7b\xc4\xcf\x46\xe8\xc9\xfc\x3f\x43\x32\x86\x7c\x27\x69\xa6\xa8\xe0\x5a\xfa\x9b\x90\x80\x0c\x0b\x4a\x41\x91\x5a\x45\xc7\x9d\x50\x4e\x35\x73\x8e\x97\xc8\x20\xae\x08\x86\xed\xab\x94\xe4\xe4\x10\x2a\xa2\x3a\x65\xa0\x95\x93\x8a\xfc\xec\x12\x53\xca\x57\x0a\x52\xad\xef\xff\x1e\x89\xd6\xe7\x67\x84\x9f\x24\x24\x5a\xc5\x23\x46\x65\xcb\x54\x76\xfc\x38\x13\x39\x55\xf4\x03\x56\x5c\xc1\x1e\x64\x18\x04\xad\x19\x86\x30\x68\x5a\xa4\x78\x89\x16\x97\xe8\xff\x0e\x09\x29\x98\x5a\x0c\xed\x10\xc6\x7e\x69\xa8\x6b\x07\x76\x64\x45\x2e\xea\x63\x45\xe5\xb3\x66\x8e\x8d\x4e\x0d\x01\x95\x68\xe3\x85\x91\xd3\x34\x63\xf0\xfb\x94\x41\x3e\x34\x0d\xbc\x72\x60\xdd\x46\x1a\xe1\xad\x10\x0c\x08\xd7\x9f\xad\xe3\x08\xf3\x82\x31\xf3\x37\xdd\x9a\x13\xb1\x7d\x83\x9d\xd2\x5f\xb9\x92\x94\xef\x71\xc8\x7e\x45\x9d\x73\xcf\xd6\x65\x36\x7c\x8d\xa9\xf2\xf2\x94\x28\x38\x7d\x2f\xa0\xa1\x2a\x59\x40\x07\xf3\xc1\x02\xdb\xda\x68\x1c\x33\xa7\x99\x14\x19\x48\x45\x7b\xd1\x33\x45\x17\xf0\xa6\x46\xd9\x03\x92\x08\x99\x12\x7d\x57\xb8\x90\x14\x7b\x63\xd5\x15\xe5\xbd\x35\x2b\xaa\x18\x4c\xea\xf5\x8a\xba\xf5\x3e\x4b\x41\x93\xa5\x67\xfb\x38\x2d\x98\xa2\x19\x83\x2a\xf7\x03\x6a\x9b\x74\x0b\x56\x5e\x8f\x02\xc7\x1d\x2b\x72\xfa\x01\x3f\x5b\x16\xf7\xc6\x6d\xfb\xe4\x58\xb3\x8c\x1b\xf7\x0a\x77\x86\xa6\xb4\xb4\xf5\xe4\x92\xbb\xa0\x24\x84\xe5\x01\x84\xad\x13\x37\x21\x9c\xd2\x72\x0b\x42\x72\xfc\x01\x7c\xaf\x0e\xbd\x9e\x3b\xd5\xbc\x1c\x1f\xaf\xd6\xd0\xb6\x52\xb7\xdf\x12\xa5\x40\x4e\xe7\x68\xb0\x78\x24\xec\xe1\xe8\x0f\x26\x89\xe3\x0a\x0a\x61\x4d\x23\xe9\xf7\x70\x7e\x32\x3d\xdc\x39\xd6\xbf\xf3\x30\xd0\xfd\xf6\x55\xb3\x79\x27\x96\xfe\x6d\x82\x37\x73\xf6\x8f\x36\x3a\x03\xa4\x6d\x7d\x1c\x9e\x73\x35\xf6\x18\xbf\x15\x76\x4a\x8e\x2b\xcf\x00\xbf\x2a\x99\xae\x55\xe0\xcf\x25\x77\x68\xfc\x95\xba\x79\x75\x06\xcb\x5c\x77\x67\x69\xf1\xfb\x2c\xe1\xbd\xa0\x12\xe2\x31\x45\xf6\x30\x0f\x14\xc8\xab\x7f\x60\x4e\x27\xe0\x3f\xaf\x92\xd0\x6a\x8a\x82\xdb\xc0\xa4\xbb\x63\x65\x34\x0d\x28\xb0\x6b\x7c\x1e\x1e\xd3\x51\xc7\x6e\xf4\x33\x60\xc5\x90\x01\x8f\x81\xef\xee\x88\x68\x90\x69\x23\xb9\x8a\x2e\x69\x98\x7d\xa6\x91\x32\x1a\xc8\x6e\x9c\x13\x7f\x10\xea\xcd\xfd\x4e\xef\xa6\xb1\x25\xd9\xde\x22\x8d\xfa\x59\x63\xc5\x0d\x80\xf5\x28\xf1\xd6\xb9\x37\x9e\xa3\xee\xb5\x4c\xbe\x37\xe0\x55\xc6\x27\x82\x75\x49\xd0\xda\xe0\xb9\x1d\xca\xbf\x5b\xd4\xcf\xbf\x0b\x47\xac\x2d\x59\x07\xfe\x7a\x49\xc1\x61\xa6\x24\x17\x2a\xf0\xbe\x2e\xdb\x17\x7f\xa0\x3c\x7d\x4b\xf3\xba\xdb\xc3\xed\x06\xee\xdb\x5e\xd7\xdd\x42\x5c\x47\xb2\xb3\x68\x75\x8c\xf2\xe1\x4f\x00\x00\x00\xff\xff\x4e\x9b\x8d\xdf\x17\x11\x00\x00") + +func jsonschemaDraft04JSONBytes() ([]byte, error) { + return bindataRead( + _jsonschemaDraft04JSON, + "jsonschema-draft-04.json", + ) +} + +func jsonschemaDraft04JSON() (*asset, error) { + bytes, err := jsonschemaDraft04JSONBytes() + if err != nil { + return nil, err + } + + info := bindataFileInfo{name: "jsonschema-draft-04.json", size: 4375, mode: os.FileMode(420), modTime: time.Unix(1482389892, 0)} + a := &asset{bytes: bytes, info: info} + return a, nil +} + +var _v2SchemaJSON = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xec\x5d\x4f\x93\xdb\x36\xb2\xbf\xfb\x53\xa0\x14\x57\xd9\xae\xd8\x92\xe3\xf7\x2e\xcf\x97\xd4\xbc\xd8\x49\x66\x37\x5e\x4f\x79\x26\xbb\x87\x78\x5c\x05\x91\x2d\x09\x09\x09\x30\x00\x38\x33\x5a\xef\x7c\xf7\x2d\xf0\x9f\x08\x02\x20\x41\x8a\xd2\xc8\x0e\x0f\xa9\x78\x28\xa0\xd1\xdd\x68\x34\x7e\xdd\xf8\xf7\xf9\x11\x42\x33\x49\x64\x04\xb3\xd7\x68\x76\x86\xfe\x76\xf9\xfe\x1f\xe8\x32\xd8\x40\x8c\xd1\x8a\x71\x74\x79\x8b\xd7\x6b\xe0\xe8\xd5\xfc\x25\x3a\xbb\x38\x9f\xcf\x9e\xab\x0a\x24\x54\xa5\x37\x52\x26\xaf\x17\x0b\x91\x17\x99\x13\xb6\xb8\x79\xb5\x10\x59\xdd\xf9\xef\x82\xd1\x6f\xf2\xc2\x8f\xf3\x4f\xb5\x1a\xea\xc7\x17\x45\x41\xc6\xd7\x8b\x90\xe3\x95\x7c\xf1\xf2\x7f\x8b\xca\x45\x3d\xb9\x4d\x32\xa6\xd8\xf2\x77\x08\x64\xfe\x8d\xc3\x9f\x29\xe1\xa0\x9a\xff\xed\x11\x42\x08\xcd\x8a\xd6\xb3\x9f\x15\x67\x74\xc5\xca\x7f\x27\x58\x6e\xc4\xec\x11\x42\xd7\x59\x5d\x1c\x86\x44\x12\x46\x71\x74\xc1\x59\x02\x5c\x12\x10\xb3\xd7\x68\x85\x23\x01\x59\x81\x04\x4b\x09\x9c\x6a\xbf\x7e\xce\x49\x7d\xba\x7b\x51\xfd\xa1\x44\xe2\xb0\x52\xac\x7d\xb3\x08\x61\x45\x68\x46\x56\x2c\x6e\x80\x86\x8c\xbf\xbd\x93\x40\x05\x61\x74\x96\x95\xbe\x7f\x84\xd0\x7d\x4e\xde\x42\xb7\xe4\xbe\x46\xbb\x14\x5b\x48\x4e\xe8\xba\x90\x05\xa1\x19\xd0\x34\xae\xc4\xce\xbe\xbc\x9a\xbf\x9c\x15\x7f\x5d\x57\xc5\x42\x10\x01\x27\x89\xe2\x48\x51\xb9\xda\x40\xd5\x87\x37\xc0\x15\x5f\x88\xad\x90\xdc\x10\x81\x42\x16\xa4\x31\x50\x39\x2f\x38\xad\xab\xb0\x53\xd8\xac\x94\x56\x6f\xc3\x84\xf4\x11\xa4\x50\xb3\xfa\xe9\xd3\x6f\x9f\x3e\xdf\x2f\xd0\xeb\x8f\x1f\x3f\x7e\xbc\xfe\xf6\xe9\xf7\xaf\x5f\x7f\xfc\x18\x7e\xfb\xec\xfb\xc7\xb3\x36\x79\x54\x43\xe8\x29\xc5\x31\x20\xc6\x11\x49\x9e\xe5\x12\x41\x66\xa0\xe8\xed\x1d\x8e\x93\x08\x5e\xa3\x27\x3b\xc3\x7c\xa2\x73\xba\xc4\x02\x2e\xb0\xdc\xf4\xe5\x76\xd1\xca\x96\xa2\x8a\x94\xcd\x21\xc9\x6c\xec\x2c\x70\x42\x9e\x34\x74\x9d\x19\x7c\xcd\x20\x9c\xea\x2e\x0a\xfe\x42\x84\xd4\x29\x04\x8c\x8a\xb4\x41\xa2\xc1\xdc\x19\x8a\x88\x90\x4a\x49\xef\xce\xdf\xbd\x45\x4a\x52\x81\x70\x10\x40\x22\x21\x44\xcb\x6d\xc5\xec\x4e\x3c\x1c\x45\xef\x57\x9a\xb5\x7d\xae\xfe\xe5\xe4\x31\x86\x90\xe0\xab\x6d\x02\x3b\x2e\xcb\x11\x90\xd9\xa8\xc6\x77\xc2\x59\x98\x06\xfd\xf9\x2e\x78\x45\x01\xa6\xa8\xa0\x71\x5c\xbe\x33\xa7\xd2\xd9\x5f\x95\xef\xd9\xd5\xac\xfd\xdc\x5d\xbf\x5e\xb8\xd1\x3e\xc7\x31\x48\xe0\x5e\x4c\x14\x65\xdf\xb8\xa8\x71\x10\x09\xa3\xc2\xc7\x02\xcb\xa2\x4e\x5a\x02\x82\x94\x13\xb9\xf5\x30\xe6\xb2\xa4\xb5\xfe\x9b\x3e\x7a\xb2\x55\xd2\xa8\x4a\xbc\x16\xb6\x71\x8e\x39\xc7\xdb\x9d\xe1\x10\x09\x71\xbd\x9c\xb3\x41\x89\xd7\xa5\x89\xdc\x57\xb5\x53\x4a\xfe\x4c\xe1\xbc\xa0\x21\x79\x0a\x1a\x0f\x70\xa7\x5c\x08\x8e\xde\xb0\xc0\x43\x24\xad\x74\x63\x0e\xb1\xd9\x90\xe1\xb0\x2d\x13\xa7\x6d\x78\xfd\x04\x14\x38\x8e\x90\xaa\xce\x63\xac\x3e\x23\xbc\x64\xa9\xb4\xf8\x03\x63\xde\xcd\xbe\x16\x13\x4a\x55\xac\x82\x12\xc6\xac\xd4\x35\xf7\x22\xd4\x3a\xff\x22\x73\x0e\x6e\x51\xa0\x75\x1e\xae\x8f\xe8\x5d\xc7\x59\xe6\xe4\x9a\x18\x8d\xd6\x1c\x53\x84\x4d\xb7\x67\x28\x37\x09\x84\x69\x88\x12\x0e\x01\x11\x80\x32\xa2\xf5\xb9\xaa\xc6\xd9\x73\x53\xab\xfb\xb4\x2e\x20\xc6\x54\x92\xa0\x9a\xf3\x69\x1a\x2f\x81\x77\x37\xae\x53\x1a\xce\x40\xc4\xa8\x82\x1c\xb5\xef\xda\x24\x7d\xb9\x61\x69\x14\xa2\x25\xa0\x90\xac\x56\xc0\x81\x4a\xb4\xe2\x2c\xce\x4a\x64\x7a\x9a\x23\xf4\x13\x91\x3f\xa7\x4b\xf4\x63\x84\x6f\x18\x87\x10\xbd\xc3\xfc\x8f\x90\xdd\x52\x44\x04\xc2\x51\xc4\x6e\x21\x74\x48\x21\x81\xc7\xe2\xfd\xea\x12\xf8\x0d\x09\xf6\xe9\x47\x35\xaf\x67\xc4\x14\xf7\x22\x27\x97\xe1\xe2\x76\x2d\x06\x8c\x4a\x1c\x48\x3f\x73\x2d\x0b\x5b\x29\x45\x24\x00\x2a\x0c\x11\xec\x94\xca\xc2\xa6\xc1\x37\x21\x43\x83\x3b\x5f\x97\xf1\x43\x5e\x53\x73\x19\xa5\x36\xd8\x2d\x05\x2e\x34\x0b\xeb\x39\xfc\x1d\x63\x51\x01\xbd\x3d\xbb\x90\x84\x40\x25\x59\x6d\x09\x5d\xa3\x1c\x37\xe6\x5c\x16\x9a\x40\x09\x70\xc1\xe8\x82\xf1\x35\xa6\xe4\xdf\x99\x5c\x8e\x9e\x4d\x79\xb4\x27\x2f\xbf\x7e\xf8\x05\x25\x8c\x50\xa9\x98\x29\x90\x62\x60\xea\x75\xae\x13\xca\xbf\x2b\x1a\x29\x27\x76\xd6\x20\xc6\x64\x5f\xe6\x32\x1a\x08\x87\x21\x07\x21\xbc\xb4\xe4\xe0\x32\x67\xa6\xcd\xf3\x1e\xcd\xd9\x6b\xb6\x6f\x8e\x27\xa7\xed\xdb\xe7\xbc\xcc\x1a\x07\xce\x6f\x87\x33\xf0\xba\x51\x17\x22\x66\x78\x79\x8e\xce\xe5\x13\x81\x80\x06\x2c\xe5\x78\x0d\xa1\xb2\xb8\x54\xa8\x79\x09\xbd\xbf\x3c\x47\x01\x8b\x13\x2c\xc9\x32\xaa\xaa\x1d\xd5\xee\xab\x36\xbd\x6c\xfd\x54\x6c\xc8\x08\x01\x3c\xbd\xe7\x07\x88\xb0\x24\x37\x79\x90\x28\x4a\x1d\x10\x1a\x92\x1b\x12\xa6\x38\x42\x40\xc3\x4c\x43\x62\x8e\xae\x36\xb0\x45\x71\x2a\xa4\x9a\x23\x79\x59\xb1\xa8\xf2\xa4\x0c\x60\x9f\xcc\x8d\x40\xf5\x80\xca\xa8\x99\xc3\xa7\x85\x1f\x31\x25\xa9\x82\xc5\x6d\xbd\xd8\x36\x76\x7c\x02\x28\x97\xf6\x1d\x74\x3b\x11\x7e\x91\xae\x32\xf8\x6c\xf4\xe6\x7b\x9a\xa5\x1f\x62\xc6\x21\xcf\x9a\xe5\xed\x8b\x02\xf3\x2c\x33\x33\xdf\x00\xca\xc9\x09\xb4\x04\xf5\xa5\x08\xd7\xc3\x02\x18\x66\xf1\xab\x1e\x83\x37\x4c\xcd\x12\xc1\x1d\x50\xf6\xaa\xbd\xfe\xe2\x73\x48\x38\x08\xa0\x32\x9b\x18\x44\x86\x0b\x6a\xc1\xaa\x26\x96\x2d\x96\x3c\xa0\x54\x65\x73\x87\x15\xca\x15\xe5\xf5\x94\x46\x9f\x33\x1a\x0c\x9a\xb1\x5a\xd9\x6a\x95\xcd\xcb\x7e\xec\x9a\xc5\x94\x3b\x37\x26\x31\xd7\xfc\xe4\x1f\x13\x8c\x31\x75\x9c\xba\xf7\x87\x3c\xa1\xb7\x4f\x17\x1b\x09\x82\x98\xc4\x70\x95\xd3\xe8\x4c\x48\x5a\xa6\xd6\x2a\x3d\x56\x42\x80\x9f\xaf\xae\x2e\x50\x0c\x42\xe0\x35\x34\x3c\x8a\x62\x03\x37\xba\xb2\x27\x04\xda\x25\x8d\x06\xe2\xa0\x13\x8a\xf3\xf5\xec\x10\x72\x67\x88\x90\x3d\x4b\x64\xeb\xaa\xda\x8f\xf7\x5a\x75\x47\x9a\xa8\x51\x70\x26\xd2\x38\xc6\x7c\xbb\x57\xfc\xbd\xe4\x04\x56\xa8\xa0\x54\x9a\x45\xd5\xf7\x0f\x16\xfc\x57\x1c\x3c\xdf\x23\xba\x77\x38\xda\x16\x4b\x31\x53\x6a\x4d\x9a\x15\x63\xe7\xe1\x18\x69\x9f\x22\xe0\x24\xbb\x94\x4b\x97\xee\x2d\xf9\x70\x87\x72\x7b\xe6\xc4\x33\x2a\x66\x5e\x1c\x35\x72\xe3\x2d\xda\x73\xe4\xc7\x51\x6d\xa4\xa1\x2a\x4f\xde\x94\xcb\xb2\x3e\x31\x48\xae\x82\xce\xc9\xc8\x65\xcd\xc3\xb7\x34\xb6\x2b\xdf\x58\x65\x78\x6e\x73\xac\x5e\x24\x0d\x3f\xdc\x70\x23\xc6\xda\x52\x0b\x2d\x63\x7d\xa9\x49\x2d\x54\x48\x28\xc0\x12\x9c\xe3\x63\xc9\x58\x04\x98\x36\x07\xc8\x0a\xa7\x91\xd4\xf0\xbc\xc1\xa8\xb9\x70\xd0\xc6\xa9\xb6\x78\x80\x5a\xa3\xb4\x2c\xf4\x18\x0b\x8a\x9d\xd0\xb4\x55\x10\xee\x0d\xc5\xd6\xe0\x99\x93\xdc\xa1\x04\xbb\xf1\xa7\x23\xd1\xd1\x97\x8c\x87\x13\x0a\x21\x02\xe9\x99\x25\xed\x20\xc5\x92\x66\x3c\x32\x9c\xd6\x06\xb0\x31\x5c\x86\x29\x0a\xcb\x60\x33\x12\xa5\x91\xfc\x96\x75\xd0\x59\xd7\x13\xbd\xd3\x23\x79\xdd\x2a\x90\xa6\x38\x06\x91\x39\x7f\x20\x72\x03\x1c\x2d\x01\x61\xba\x45\x37\x38\x22\x61\x8e\x71\x85\xc4\x32\x15\x28\x60\x61\x16\xb8\x3d\x29\xdc\x4d\x3d\x2f\x12\x13\x7d\xc8\x7e\x37\xee\xa8\x7f\xfa\xdb\xcb\x17\xff\x77\xfd\xf9\x7f\xee\x9f\x3d\xfe\xcf\xa7\xa7\x45\xfb\xcf\x1e\xf7\xf3\xe0\xff\xc4\x51\x0a\x8e\x4c\xcb\x01\xdc\x0a\x65\xb2\x01\x83\xed\x3d\xe4\xa9\xa3\x4e\x2d\x59\xc5\xe8\x2f\x48\x7d\x5a\x6e\x37\xbf\x5c\x9f\x35\x13\x64\x14\xfa\xef\x0b\x68\xa6\x0d\xb4\x8e\xf1\xa8\xff\xbb\x60\xf4\x03\x64\xab\x5b\x81\x65\x51\xe6\xda\xca\xfa\xf0\xb0\xac\x3e\x9c\xca\x26\x0e\x1d\xdb\x57\x5b\xbb\xb4\x9a\xa6\xb6\x9b\x1a\x6b\xd1\x9a\x9e\x7e\x33\x9a\xec\x41\x69\x45\x22\xb8\xb4\x51\xeb\x04\x77\xca\x6f\x7b\x7b\xc8\xb2\xb0\x95\x92\x25\x5b\xd0\x42\xaa\x2a\xdd\x32\x78\x4f\x0c\xab\x68\x46\x6c\xea\x6d\xf4\x5c\x5e\xde\xc4\xac\xa5\xf9\xd1\x00\x9f\x7d\x98\x65\x24\xbd\xc7\x97\xd4\xb3\x3a\xa8\x2b\xa0\x34\x76\xf9\x65\x5f\x2d\x25\x95\x1b\xcf\xd6\xf4\x9b\x5f\x09\x95\xb0\x36\x3f\xdb\xd0\x39\x2a\x93\x1c\x9d\x03\xa2\x4a\xca\xf5\xf6\x10\xb6\x94\x89\x0b\x6a\x70\x12\x13\x49\x6e\x40\xe4\x29\x12\x2b\xbd\x80\x45\x11\x04\xaa\xc2\x8f\x56\x9e\x5c\x6b\xec\x8d\x5a\x0e\x14\x59\x06\x2b\x1e\x24\xcb\xc2\x56\x4a\x31\xbe\x23\x71\x1a\xfb\x51\x2a\x0b\x3b\x1c\x48\x10\xa5\x82\xdc\xc0\xbb\x3e\x24\x8d\x5a\x76\x2e\x09\xed\xc1\x65\x51\xb8\x83\xcb\x3e\x24\x8d\x5a\x2e\x5d\xfe\x02\x74\x2d\x3d\xf1\xef\xae\xb8\x4b\xe6\x5e\xd4\xaa\xe2\x2e\x5c\x5e\xec\x0e\xf5\x5b\x0c\xcb\x0a\xbb\xa4\x3c\xf7\x1f\x2a\x55\x69\x97\x8c\x7d\x68\x95\xa5\xad\xb4\xf4\x9c\xa5\x07\xb9\x7a\x05\xbb\xad\x50\x6f\xfb\xa0\x4e\x9b\x48\x23\x49\x92\x28\x87\x19\x3e\x32\xee\xca\x3b\x46\x7e\x7f\x18\x64\xcc\xcc\x0f\x34\xe9\x36\x8b\xb7\x6c\xa8\xa5\x5b\x54\x4c\x54\x5b\x15\x3a\xf1\x6c\x2d\xfe\x96\xc8\x0d\xba\x7b\x81\x88\xc8\x23\xab\xee\x7d\x3b\x92\xa7\x60\x29\xe3\xdc\xff\xb8\x64\xe1\xf6\xa2\x5a\x59\xdc\x6f\xeb\x45\x7d\x6a\xd1\x76\x1e\xea\xb8\xf1\xfa\x14\xd3\x36\x63\xe5\xd7\xf3\xe4\xbe\x25\xbd\x5e\x05\xeb\x73\x74\xb5\x21\x2a\x2e\x4e\xa3\x30\xdf\xbf\x43\x28\x2a\xd1\xa5\x2a\x9d\x8a\xfd\x76\xd8\x8d\xbc\x67\x65\xc7\xb8\x03\x45\xec\xa3\xb0\x37\x8a\x70\x4c\x68\x91\x51\x8e\x58\x80\xed\x4a\xf3\x81\x62\xca\x96\xbb\xf1\x52\xcd\x80\xfb\xe4\x4a\x5d\x6c\xdf\x6e\x20\x4b\x80\x30\x8e\x28\x93\xf9\xe9\x8d\x8a\x6d\xd5\x59\x65\x7b\xaa\x44\x9e\xc0\xc2\xd1\x7c\x40\x26\xd6\x1a\xce\xf9\xc5\x69\x7b\x6c\xec\xc8\x71\x7b\xe5\x21\x2e\xd3\xe5\x65\x93\x91\x53\x0b\x7b\x3a\xc7\xfa\x17\x6a\x01\xa7\x33\xd0\xf4\x40\x0f\x39\x87\xda\xe4\x54\x87\x3a\xd5\xe3\xc7\xa6\x8e\x20\xd4\x11\xb2\x4e\xb1\xe9\x14\x9b\x4e\xb1\xe9\x14\x9b\xfe\x15\x63\xd3\x47\xf5\xff\x97\x38\xe9\xcf\x14\xf8\x76\x82\x49\x13\x4c\xaa\x7d\xcd\x6c\x62\x42\x49\x87\x43\x49\x19\x33\x6f\xe3\x44\x6e\x9b\xab\x8a\x3e\x86\xaa\x99\x52\x1b\x5b\x59\x33\x02\x09\xa0\x21\xa1\x6b\x84\x6b\x66\xbb\xdc\x16\x0c\xd3\x68\xab\xec\x36\x4b\xd8\x60\x8a\x40\x31\x85\x6e\x14\x57\x13\xc2\xfb\x92\x10\xde\xbf\x88\xdc\xbc\x53\x5e\x7f\x82\x7a\x13\xd4\x9b\xa0\xde\x04\xf5\x90\x01\xf5\x94\xcb\x7b\x83\x25\x9e\xd0\xde\x84\xf6\x6a\x5f\x4b\xb3\x98\x00\xdf\x04\xf8\x6c\xbc\x7f\x19\x80\xaf\xf1\x71\x45\x22\x98\x40\xe0\x04\x02\x27\x10\xd8\x29\xf5\x04\x02\xff\x4a\x20\x30\xc1\x72\xf3\x65\x02\x40\xd7\xc1\xd1\xe2\x6b\xf1\xa9\x7b\xfb\xe4\x20\xc0\x68\x9d\xd4\xb4\xd3\x96\xb5\xa6\xd1\x41\x20\xe6\x89\xc3\x48\x65\x58\x13\x84\x9c\x56\x56\x3b\x0c\xe0\x6b\x83\x5c\x13\xd2\x9a\x90\xd6\x84\xb4\x26\xa4\x85\x0c\xa4\x45\x19\xfd\xff\x63\x6c\x52\xb5\x1f\x1e\x19\x74\x3a\xcd\xb9\x69\xce\xa6\x3a\x0f\x7a\x2d\x19\xc7\x81\x14\x5d\xcb\xd5\x03\xc9\x39\xd0\xb0\xd1\xb3\xcd\xfb\x7a\x2d\x5d\x3a\x48\xe1\xfa\x2e\xe6\x81\x42\x18\x86\xd6\xc1\xbe\xb1\x23\xd3\xf7\x34\xed\x19\x0a\x0b\xc4\x48\x44\xfd\x22\x50\xb6\x42\x58\xbb\xe5\x3d\xa7\x73\xd4\x8b\xc4\x8c\x70\x61\xec\x73\xee\xc3\x81\x8b\xf5\xe2\xd7\x52\x3e\xcf\xeb\xeb\x17\x3b\x71\x16\xda\x7d\xb8\xde\xf0\x7a\x8f\x06\x2d\xa7\x40\x7b\xc1\x9d\x41\x4d\xb6\x61\xa2\x4e\x9f\x3d\xa0\xc5\xae\xe3\x1c\x1d\x40\x6c\x48\x8b\x63\xa0\xb5\x01\xed\x8e\x02\xe9\x86\xc8\x3b\x06\xee\xdb\x4b\xde\xbd\xc0\xa1\x6f\xcb\xda\xfc\xc2\x44\x16\x87\x9c\x17\x31\xd3\x30\x20\x39\x42\xcb\x6f\xf2\xf1\xf4\x72\x10\xf8\x1c\xa0\xf3\xbd\x10\xea\x21\x35\x7d\xe8\x86\xdb\x15\xed\x81\x81\x07\x28\xbb\x13\x28\xc7\xf8\xce\x7d\x8d\xc2\x31\xb4\x7e\x94\xd6\xdb\x55\xef\x4a\xfb\xed\xc3\x40\x3e\xeb\x9f\xe9\x99\x0f\xdf\x08\x65\x88\x27\x73\x86\x31\x9d\x47\xdf\x55\x19\xba\x3d\xee\x15\x0a\xcd\x8c\xaa\x5e\xb9\xf6\x57\x33\x73\x5a\xa1\x89\x7b\x3b\xa0\xb2\xa4\xc2\xf6\xc1\x53\xb5\x00\xca\x23\xe5\xf4\x60\x6a\xb4\x2d\x74\xea\x4e\xed\x3b\xe3\x47\xfb\xed\x82\x3d\x19\xd4\x3b\x6b\xaf\xae\x2b\x2f\x57\xb3\x82\x68\xcb\xed\x88\x2e\xe1\x5c\xd7\x26\xfa\x0a\x65\xe7\xce\x11\x33\xb4\xdd\x66\xe3\x37\xf6\xfa\x70\xd6\x4f\xa1\x21\x51\xd8\x3c\x26\x14\x4b\xc6\x87\x44\x27\x1c\x70\xf8\x9e\x46\xce\xab\x21\x07\x5f\xc1\x76\x17\x1b\x77\xb4\xda\x75\xa0\x0a\x3a\x30\xe1\xf8\x97\x32\x16\x2b\x00\x75\x85\xee\x62\x46\xef\xd3\x85\xb5\x6b\x60\xbe\xf2\x30\x7a\x8c\x0b\x4b\xa6\xd0\xf9\x64\x42\xe7\x07\x41\x41\xe3\x2c\x5d\xf9\x6d\xe9\x39\x98\x3b\x3b\x5d\x67\xd4\x5c\xed\xf2\xf0\x48\x7b\xbd\x2d\x31\xdd\x3f\x34\xad\x44\x76\x51\x9a\x56\x22\xa7\x95\xc8\x69\x25\xf2\xe1\x56\x22\x1f\x00\x32\x6a\x73\x92\xed\xe1\xc6\x7d\x9f\x49\x2c\x69\x7e\xc8\x31\x4c\x0c\xb4\xf2\x54\x3b\x79\x3b\x9e\x4d\xb4\xd1\x18\x3e\x5f\x9a\x93\xa2\x11\xc3\xda\x27\x0b\xaf\x37\x2e\x5c\x37\xfb\xeb\x9a\xd6\xc3\xac\xc3\xcc\xf8\x1e\x5b\x9d\xac\x22\x64\xb7\xed\x26\xb8\xf3\xb9\x3c\xbb\x1f\xe2\xb0\x22\x77\x43\x6a\x62\x29\x39\x59\xa6\xe6\xe5\xcd\x7b\x83\xc0\x5b\x8e\x93\x64\xac\xeb\xca\x4f\x65\xac\x4a\xbc\x1e\xcd\x82\xfa\x3c\x70\x36\xb6\xb5\xed\x79\xef\xec\x68\x00\xff\x54\xfa\xb5\xe3\xf1\xdb\xe1\xbe\xce\x76\x17\xaf\x57\xb6\x6b\x89\x05\x09\xce\x52\xb9\x01\x2a\x49\xbe\xd9\xf4\xd2\xb8\x7a\xbf\x91\x02\xf3\x22\x8c\x13\xf2\x77\xd8\x8e\x43\x8b\xe1\x54\x6e\x5e\x9d\xc7\x49\x44\x02\x22\xc7\xa4\x79\x81\x85\xb8\x65\x3c\x1c\x93\xe6\x59\xa2\xf8\x1c\x51\x95\x05\xd9\x20\x00\x21\x7e\x60\x21\x58\xa9\x56\xff\xbe\xb6\x5a\x5e\x5b\x3f\x1f\xd6\xd3\x3c\xc4\x4d\xba\x99\xb4\x63\x6e\x7d\x3e\x3d\x57\xd2\x18\x5f\x47\xe8\xc3\x06\x8a\x68\x6c\x7f\x3b\x72\x0f\xe7\xe2\x77\x77\xf1\xd0\x99\xab\xdf\x2e\xfe\xd6\xbb\xcd\x1a\xb9\x90\xd1\xaf\xf2\x38\x3d\xdb\x74\xf8\xeb\xe3\xda\xe8\x2a\x62\xb7\xda\x1b\x07\xa9\xdc\x30\x5e\xbc\x68\xfb\x6b\x9f\x97\xf1\xc6\xb1\xd8\x5c\x29\x1e\x49\x30\xc5\xf7\xde\xad\x91\x42\xf9\xdd\xed\x89\x80\x25\xbe\x37\xd7\xe7\x32\x5c\xe6\x35\xac\xd4\x0c\x2d\xf7\x90\xc4\xe3\xf5\xe3\x2f\x7f\x54\x18\x88\xe3\x61\x47\x85\x64\x7f\xc0\xd7\x3f\x1a\x92\x42\xe9\xc7\x1e\x0d\x95\x76\xa7\x51\xa0\x8f\x02\x1b\x46\x9e\x06\x42\xd1\xf2\x01\x07\x02\xde\xe9\x7d\x1a\x0b\xa7\x32\x16\xcc\xc0\xee\xc4\x90\xd2\x5f\x6f\x98\x54\x5d\xf2\x95\xe1\xa7\x69\x10\x3a\x06\xe1\x65\xb3\x17\x47\x58\x78\xd0\x45\xd6\x5b\xd5\x5f\x25\x1d\x71\x49\xa6\x7a\x64\xda\xd0\x6f\xc7\x3a\x4c\xe3\x09\xc0\x6e\x96\x2c\xa7\xa7\x77\x34\x10\x05\x08\x21\x44\x92\x65\x77\xdf\x20\x5c\xbc\xe7\x97\x3f\xf4\x1a\x45\xd6\xe7\x27\x4a\xde\x74\x27\x66\x11\x7d\x70\xba\xd3\x78\xf9\x1e\x0d\xca\xc8\x39\xde\x7c\xb3\xa6\xe1\xbc\xd7\xc1\x6a\x6f\xb3\x0e\x52\xbe\xe4\x98\x8a\x15\x70\x94\x70\x26\x59\xc0\xa2\xf2\x1c\xfb\xd9\xc5\xf9\xbc\xd5\x92\x9c\xa3\xdf\xe6\x1e\xb3\x0d\x49\xba\x87\x50\x5f\x84\xfe\xe9\xd6\xf8\xbb\xe6\xf0\x7a\xeb\xa6\x65\x3b\x86\x8b\x79\x93\xf5\x59\x20\x6e\xb4\xa7\x44\xf4\x3f\xa5\xfe\x67\x42\x12\xdb\xd3\xe7\xbb\xa5\xa3\x8c\x5c\x2b\x97\xbb\xbb\x7f\x8e\xc5\x6e\xed\x43\x5c\xbf\x74\xc8\x8f\xff\xe6\xd6\xbe\x91\xb6\xf5\x95\xe4\xed\x93\xc4\xa8\x5b\xf9\x76\x4d\x35\xb7\xd8\x8c\xb6\x7d\xaf\x72\xe0\xb6\xbd\x01\x63\x9e\x76\xab\x1a\x32\x76\xe4\x8c\x76\xc2\xad\x6c\xa2\x65\xf7\xcf\xf8\xa7\xda\x2a\xb9\x8c\x3d\x3c\xa3\x9d\x64\x33\xe5\x1a\xb5\x2d\xfb\x86\xa2\x5a\x7f\x19\x5b\x7f\xc6\x3f\xd1\x53\xd3\xe2\x41\x5b\xd3\x4f\xf0\xec\xb0\x42\x73\x43\xd2\x68\x27\xd3\x6a\x6a\x34\xf6\x4e\x1e\x52\x8b\x87\x6c\xcc\xae\x44\xfb\x9e\xa7\x51\x4f\x9d\x55\x03\x81\x8e\x67\xfc\xb4\x69\xf0\x3a\x18\xf2\x40\xd0\xf6\xa8\x34\xe3\xc9\x98\xaf\xf6\xda\x24\xd3\xeb\x60\xb9\x0e\xd3\x1f\xa9\xff\xee\x1f\xfd\x37\x00\x00\xff\xff\x69\x5d\x0a\x6a\x39\x9d\x00\x00") + +func v2SchemaJSONBytes() ([]byte, error) { + return bindataRead( + _v2SchemaJSON, + "v2/schema.json", + ) +} + +func v2SchemaJSON() (*asset, error) { + bytes, err := v2SchemaJSONBytes() + if err != nil { + return nil, err + } + + info := bindataFileInfo{name: "v2/schema.json", size: 40249, mode: os.FileMode(420), modTime: time.Unix(1482389892, 0)} + a := &asset{bytes: bytes, info: info} + return a, nil +} + +// Asset loads and returns the asset for the given name. +// It returns an error if the asset could not be found or +// could not be loaded. +func Asset(name string) ([]byte, error) { + cannonicalName := strings.Replace(name, "\\", "/", -1) + if f, ok := _bindata[cannonicalName]; ok { + a, err := f() + if err != nil { + return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) + } + return a.bytes, nil + } + return nil, fmt.Errorf("Asset %s not found", name) +} + +// MustAsset is like Asset but panics when Asset would return an error. +// It simplifies safe initialization of global variables. +func MustAsset(name string) []byte { + a, err := Asset(name) + if err != nil { + panic("asset: Asset(" + name + "): " + err.Error()) + } + + return a +} + +// AssetInfo loads and returns the asset info for the given name. +// It returns an error if the asset could not be found or +// could not be loaded. +func AssetInfo(name string) (os.FileInfo, error) { + cannonicalName := strings.Replace(name, "\\", "/", -1) + if f, ok := _bindata[cannonicalName]; ok { + a, err := f() + if err != nil { + return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) + } + return a.info, nil + } + return nil, fmt.Errorf("AssetInfo %s not found", name) +} + +// AssetNames returns the names of the assets. +func AssetNames() []string { + names := make([]string, 0, len(_bindata)) + for name := range _bindata { + names = append(names, name) + } + return names +} + +// _bindata is a table, holding each asset generator, mapped to its name. +var _bindata = map[string]func() (*asset, error){ + "jsonschema-draft-04.json": jsonschemaDraft04JSON, + "v2/schema.json": v2SchemaJSON, +} + +// AssetDir returns the file names below a certain +// directory embedded in the file by go-bindata. +// For example if you run go-bindata on data/... and data contains the +// following hierarchy: +// data/ +// foo.txt +// img/ +// a.png +// b.png +// then AssetDir("data") would return []string{"foo.txt", "img"} +// AssetDir("data/img") would return []string{"a.png", "b.png"} +// AssetDir("foo.txt") and AssetDir("notexist") would return an error +// AssetDir("") will return []string{"data"}. +func AssetDir(name string) ([]string, error) { + node := _bintree + if len(name) != 0 { + cannonicalName := strings.Replace(name, "\\", "/", -1) + pathList := strings.Split(cannonicalName, "/") + for _, p := range pathList { + node = node.Children[p] + if node == nil { + return nil, fmt.Errorf("Asset %s not found", name) + } + } + } + if node.Func != nil { + return nil, fmt.Errorf("Asset %s not found", name) + } + rv := make([]string, 0, len(node.Children)) + for childName := range node.Children { + rv = append(rv, childName) + } + return rv, nil +} + +type bintree struct { + Func func() (*asset, error) + Children map[string]*bintree +} +var _bintree = &bintree{nil, map[string]*bintree{ + "jsonschema-draft-04.json": &bintree{jsonschemaDraft04JSON, map[string]*bintree{}}, + "v2": &bintree{nil, map[string]*bintree{ + "schema.json": &bintree{v2SchemaJSON, map[string]*bintree{}}, + }}, +}} + +// RestoreAsset restores an asset under the given directory +func RestoreAsset(dir, name string) error { + data, err := Asset(name) + if err != nil { + return err + } + info, err := AssetInfo(name) + if err != nil { + return err + } + err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) + if err != nil { + return err + } + err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) + if err != nil { + return err + } + err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) + if err != nil { + return err + } + return nil +} + +// RestoreAssets restores an asset under the given directory recursively +func RestoreAssets(dir, name string) error { + children, err := AssetDir(name) + // File + if err != nil { + return RestoreAsset(dir, name) + } + // Dir + for _, child := range children { + err = RestoreAssets(dir, filepath.Join(name, child)) + if err != nil { + return err + } + } + return nil +} + +func _filePath(dir, name string) string { + cannonicalName := strings.Replace(name, "\\", "/", -1) + return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...) +} + diff --git a/vendor/github.com/go-openapi/spec/contact_info.go b/vendor/github.com/go-openapi/spec/contact_info.go new file mode 100644 index 00000000..f285970a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/contact_info.go @@ -0,0 +1,24 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +// ContactInfo contact information for the exposed API. +// +// For more information: http://goo.gl/8us55a#contactObject +type ContactInfo struct { + Name string `json:"name,omitempty"` + URL string `json:"url,omitempty"` + Email string `json:"email,omitempty"` +} diff --git a/vendor/github.com/go-openapi/spec/contact_info_test.go b/vendor/github.com/go-openapi/spec/contact_info_test.go new file mode 100644 index 00000000..5e644d0f --- /dev/null +++ b/vendor/github.com/go-openapi/spec/contact_info_test.go @@ -0,0 +1,37 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "testing" +) + +var contactInfoJSON = `{"name":"wordnik api team","url":"http://developer.wordnik.com","email":"some@mailayada.dkdkd"}` +var contactInfoYAML = `name: wordnik api team +url: http://developer.wordnik.com +email: some@mailayada.dkdkd +` +var contactInfo = ContactInfo{ + Name: "wordnik api team", + URL: "http://developer.wordnik.com", + Email: "some@mailayada.dkdkd", +} + +func TestIntegrationContactInfo(t *testing.T) { + assertSerializeJSON(t, contactInfo, contactInfoJSON) + assertSerializeYAML(t, contactInfo, contactInfoYAML) + assertParsesJSON(t, contactInfoJSON, contactInfo) + assertParsesYAML(t, contactInfoYAML, contactInfo) +} diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go new file mode 100644 index 00000000..172c937a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/expander.go @@ -0,0 +1,857 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "fmt" + "log" + "net/url" + "os" + "path" + "path/filepath" + "reflect" + "strings" + "sync" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +var ( + // Debug enables logging when SWAGGER_DEBUG env var is not empty + Debug = os.Getenv("SWAGGER_DEBUG") != "" +) + +// ExpandOptions provides options for expand. +type ExpandOptions struct { + RelativeBase string + SkipSchemas bool +} + +// ResolutionCache a cache for resolving urls +type ResolutionCache interface { + Get(string) (interface{}, bool) + Set(string, interface{}) +} + +type simpleCache struct { + lock sync.Mutex + store map[string]interface{} +} + +var resCache ResolutionCache + +func init() { + resCache = initResolutionCache() +} + +func initResolutionCache() ResolutionCache { + return &simpleCache{store: map[string]interface{}{ + "http://swagger.io/v2/schema.json": MustLoadSwagger20Schema(), + "http://json-schema.org/draft-04/schema": MustLoadJSONSchemaDraft04(), + }} +} + +func (s *simpleCache) Get(uri string) (interface{}, bool) { + debugLog("getting %q from resolution cache", uri) + s.lock.Lock() + v, ok := s.store[uri] + debugLog("got %q from resolution cache: %t", uri, ok) + + s.lock.Unlock() + return v, ok +} + +func (s *simpleCache) Set(uri string, data interface{}) { + s.lock.Lock() + s.store[uri] = data + s.lock.Unlock() +} + +// ResolveRefWithBase resolves a reference against a context root with preservation of base path +func ResolveRefWithBase(root interface{}, ref *Ref, opts *ExpandOptions) (*Schema, error) { + resolver, err := defaultSchemaLoader(root, nil, opts, nil) + if err != nil { + return nil, err + } + + result := new(Schema) + if err := resolver.Resolve(ref, result); err != nil { + return nil, err + } + return result, nil +} + +// ResolveRef resolves a reference against a context root +func ResolveRef(root interface{}, ref *Ref) (*Schema, error) { + return ResolveRefWithBase(root, ref, nil) +} + +// ResolveParameter resolves a paramter reference against a context root +func ResolveParameter(root interface{}, ref Ref) (*Parameter, error) { + return ResolveParameterWithBase(root, ref, nil) +} + +// ResolveParameterWithBase resolves a paramter reference against a context root and base path +func ResolveParameterWithBase(root interface{}, ref Ref, opts *ExpandOptions) (*Parameter, error) { + resolver, err := defaultSchemaLoader(root, nil, opts, nil) + if err != nil { + return nil, err + } + + result := new(Parameter) + if err := resolver.Resolve(&ref, result); err != nil { + return nil, err + } + return result, nil +} + +// ResolveResponse resolves response a reference against a context root +func ResolveResponse(root interface{}, ref Ref) (*Response, error) { + return ResolveResponseWithBase(root, ref, nil) +} + +// ResolveResponseWithBase resolves response a reference against a context root and base path +func ResolveResponseWithBase(root interface{}, ref Ref, opts *ExpandOptions) (*Response, error) { + resolver, err := defaultSchemaLoader(root, nil, opts, nil) + if err != nil { + return nil, err + } + + result := new(Response) + if err := resolver.Resolve(&ref, result); err != nil { + return nil, err + } + return result, nil +} + +// ResolveItems resolves header and parameter items reference against a context root and base path +func ResolveItems(root interface{}, ref Ref, opts *ExpandOptions) (*Items, error) { + resolver, err := defaultSchemaLoader(root, nil, opts, nil) + if err != nil { + return nil, err + } + + result := new(Items) + if err := resolver.Resolve(&ref, result); err != nil { + return nil, err + } + return result, nil +} + +// ResolvePathItem resolves response a path item against a context root and base path +func ResolvePathItem(root interface{}, ref Ref, opts *ExpandOptions) (*PathItem, error) { + resolver, err := defaultSchemaLoader(root, nil, opts, nil) + if err != nil { + return nil, err + } + + result := new(PathItem) + if err := resolver.Resolve(&ref, result); err != nil { + return nil, err + } + return result, nil +} + +type schemaLoader struct { + loadingRef *Ref + startingRef *Ref + currentRef *Ref + root interface{} + options *ExpandOptions + cache ResolutionCache + loadDoc func(string) (json.RawMessage, error) +} + +var idPtr, _ = jsonpointer.New("/id") +var refPtr, _ = jsonpointer.New("/$ref") + +// PathLoader function to use when loading remote refs +var PathLoader func(string) (json.RawMessage, error) + +func init() { + PathLoader = func(path string) (json.RawMessage, error) { + data, err := swag.LoadFromFileOrHTTP(path) + if err != nil { + return nil, err + } + return json.RawMessage(data), nil + } +} + +func defaultSchemaLoader( + root interface{}, + ref *Ref, + expandOptions *ExpandOptions, + cache ResolutionCache) (*schemaLoader, error) { + + if cache == nil { + cache = resCache + } + if expandOptions == nil { + expandOptions = &ExpandOptions{} + } + + var ptr *jsonpointer.Pointer + if ref != nil { + ptr = ref.GetPointer() + } + + currentRef := nextRef(root, ref, ptr) + + return &schemaLoader{ + loadingRef: ref, + startingRef: ref, + currentRef: currentRef, + root: root, + options: expandOptions, + cache: cache, + loadDoc: func(path string) (json.RawMessage, error) { + debugLog("fetching document at %q", path) + return PathLoader(path) + }, + }, nil +} + +func idFromNode(node interface{}) (*Ref, error) { + if idValue, _, err := idPtr.Get(node); err == nil { + if refStr, ok := idValue.(string); ok && refStr != "" { + idRef, err := NewRef(refStr) + if err != nil { + return nil, err + } + return &idRef, nil + } + } + return nil, nil +} + +func nextRef(startingNode interface{}, startingRef *Ref, ptr *jsonpointer.Pointer) *Ref { + if startingRef == nil { + return nil + } + + if ptr == nil { + return startingRef + } + + ret := startingRef + var idRef *Ref + node := startingNode + + for _, tok := range ptr.DecodedTokens() { + node, _, _ = jsonpointer.GetForToken(node, tok) + if node == nil { + break + } + + idRef, _ = idFromNode(node) + if idRef != nil { + nw, err := ret.Inherits(*idRef) + if err != nil { + break + } + ret = nw + } + + refRef, _, _ := refPtr.Get(node) + if refRef != nil { + var rf Ref + switch value := refRef.(type) { + case string: + rf, _ = NewRef(value) + } + nw, err := ret.Inherits(rf) + if err != nil { + break + } + nwURL := nw.GetURL() + if nwURL.Scheme == "file" || (nwURL.Scheme == "" && nwURL.Host == "") { + nwpt := filepath.ToSlash(nwURL.Path) + if filepath.IsAbs(nwpt) { + _, err := os.Stat(nwpt) + if err != nil { + nwURL.Path = filepath.Join(".", nwpt) + } + } + } + + ret = nw + } + + } + + return ret +} + +func debugLog(msg string, args ...interface{}) { + if Debug { + log.Printf(msg, args...) + } +} + +func normalizeFileRef(ref *Ref, relativeBase string) *Ref { + refURL := ref.GetURL() + debugLog("normalizing %s against %s (%s)", ref.String(), relativeBase, refURL.String()) + if strings.HasPrefix(refURL.String(), "#") { + return ref + } + + if refURL.Scheme == "file" || (refURL.Scheme == "" && refURL.Host == "") { + filePath := refURL.Path + debugLog("normalizing file path: %s", filePath) + + if !filepath.IsAbs(filepath.FromSlash(filePath)) && len(relativeBase) != 0 { + debugLog("joining %s with %s", relativeBase, filePath) + if fi, err := os.Stat(filepath.FromSlash(relativeBase)); err == nil { + if !fi.IsDir() { + relativeBase = path.Dir(relativeBase) + } + } + filePath = filepath.Join(filepath.FromSlash(relativeBase), filepath.FromSlash(filePath)) + } + if !filepath.IsAbs(filepath.FromSlash(filePath)) { + pwd, err := os.Getwd() + if err == nil { + debugLog("joining cwd %s with %s", pwd, filePath) + filePath = filepath.Join(pwd, filePath) + } + } + + debugLog("cleaning %s", filePath) + filePath = filepath.Clean(filePath) + _, err := os.Stat(filepath.FromSlash(filePath)) + if err == nil { + debugLog("rewriting url to scheme \"\" path %s", filePath) + refURL.Scheme = "" + refURL.Path = filepath.ToSlash(filePath) + debugLog("new url with joined filepath: %s", refURL.String()) + *ref = MustCreateRef(refURL.String()) + } + } + + debugLog("refurl: %s", ref.GetURL().String()) + return ref +} + +func (r *schemaLoader) resolveRef(currentRef, ref *Ref, node, target interface{}) error { + + tgt := reflect.ValueOf(target) + if tgt.Kind() != reflect.Ptr { + return fmt.Errorf("resolve ref: target needs to be a pointer") + } + + oldRef := currentRef + + if currentRef != nil { + debugLog("resolve ref current %s new %s", currentRef.String(), ref.String()) + nextRef := nextRef(node, ref, currentRef.GetPointer()) + if nextRef == nil || nextRef.GetURL() == nil { + return nil + } + var err error + currentRef, err = currentRef.Inherits(*nextRef) + debugLog("resolved ref current %s", currentRef.String()) + if err != nil { + return err + } + } + + if currentRef == nil { + currentRef = ref + } + + refURL := currentRef.GetURL() + if refURL == nil { + return nil + } + if currentRef.IsRoot() { + nv := reflect.ValueOf(node) + reflect.Indirect(tgt).Set(reflect.Indirect(nv)) + return nil + } + + if strings.HasPrefix(refURL.String(), "#") { + res, _, err := ref.GetPointer().Get(node) + if err != nil { + res, _, err = ref.GetPointer().Get(r.root) + if err != nil { + return err + } + } + rv := reflect.Indirect(reflect.ValueOf(res)) + tgtType := reflect.Indirect(tgt).Type() + if rv.Type().AssignableTo(tgtType) { + reflect.Indirect(tgt).Set(reflect.Indirect(reflect.ValueOf(res))) + } else { + if err := swag.DynamicJSONToStruct(rv.Interface(), target); err != nil { + return err + } + } + + return nil + } + + relativeBase := "" + if r.options != nil && r.options.RelativeBase != "" { + relativeBase = r.options.RelativeBase + } + normalizeFileRef(currentRef, relativeBase) + debugLog("current ref normalized file: %s", currentRef.String()) + normalizeFileRef(ref, relativeBase) + debugLog("ref normalized file: %s", currentRef.String()) + + data, _, _, err := r.load(currentRef.GetURL()) + if err != nil { + return err + } + + if ((oldRef == nil && currentRef != nil) || + (oldRef != nil && currentRef == nil) || + oldRef.String() != currentRef.String()) && + ((oldRef == nil && ref != nil) || + (oldRef != nil && ref == nil) || + (oldRef.String() != ref.String())) { + + return r.resolveRef(currentRef, ref, data, target) + } + + var res interface{} + if currentRef.String() != "" { + res, _, err = currentRef.GetPointer().Get(data) + if err != nil { + if strings.HasPrefix(ref.String(), "#") { + if r.loadingRef != nil { + rr, er := r.loadingRef.Inherits(*ref) + if er != nil { + return er + } + refURL = rr.GetURL() + + data, _, _, err = r.load(refURL) + if err != nil { + return err + } + } else { + data = r.root + } + } + + res, _, err = ref.GetPointer().Get(data) + if err != nil { + return err + } + } + } else { + res = data + } + + if err := swag.DynamicJSONToStruct(res, target); err != nil { + return err + } + + r.currentRef = currentRef + + return nil +} + +func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) { + debugLog("loading schema from url: %s", refURL) + toFetch := *refURL + toFetch.Fragment = "" + + data, fromCache := r.cache.Get(toFetch.String()) + if !fromCache { + b, err := r.loadDoc(toFetch.String()) + if err != nil { + return nil, url.URL{}, false, err + } + + if err := json.Unmarshal(b, &data); err != nil { + return nil, url.URL{}, false, err + } + r.cache.Set(toFetch.String(), data) + } + + return data, toFetch, fromCache, nil +} + +func (r *schemaLoader) Resolve(ref *Ref, target interface{}) error { + return r.resolveRef(r.currentRef, ref, r.root, target) +} + +func (r *schemaLoader) reset() { + ref := r.startingRef + + var ptr *jsonpointer.Pointer + if ref != nil { + ptr = ref.GetPointer() + } + + r.currentRef = nextRef(r.root, ref, ptr) +} + +// ExpandSpec expands the references in a swagger spec +func ExpandSpec(spec *Swagger, options *ExpandOptions) error { + resolver, err := defaultSchemaLoader(spec, nil, options, nil) + if err != nil { + return err + } + + if options == nil || !options.SkipSchemas { + for key, definition := range spec.Definitions { + var def *Schema + var err error + if def, err = expandSchema(definition, []string{"#/definitions/" + key}, resolver); err != nil { + return err + } + resolver.reset() + spec.Definitions[key] = *def + } + } + + for key, parameter := range spec.Parameters { + if err := expandParameter(¶meter, resolver); err != nil { + return err + } + spec.Parameters[key] = parameter + } + + for key, response := range spec.Responses { + if err := expandResponse(&response, resolver); err != nil { + return err + } + spec.Responses[key] = response + } + + if spec.Paths != nil { + for key, path := range spec.Paths.Paths { + if err := expandPathItem(&path, resolver); err != nil { + return err + } + spec.Paths.Paths[key] = path + } + } + + return nil +} + +// ExpandSchema expands the refs in the schema object +func ExpandSchema(schema *Schema, root interface{}, cache ResolutionCache) error { + return ExpandSchemaWithBasePath(schema, root, cache, nil) +} + +// ExpandSchemaWithBasePath expands the refs in the schema object, base path configured through expand options +func ExpandSchemaWithBasePath(schema *Schema, root interface{}, cache ResolutionCache, opts *ExpandOptions) error { + if schema == nil { + return nil + } + if root == nil { + root = schema + } + + nrr, _ := NewRef(schema.ID) + var rrr *Ref + if nrr.String() != "" { + switch rt := root.(type) { + case *Schema: + rid, _ := NewRef(rt.ID) + rrr, _ = rid.Inherits(nrr) + case *Swagger: + rid, _ := NewRef(rt.ID) + rrr, _ = rid.Inherits(nrr) + } + } + + resolver, err := defaultSchemaLoader(root, rrr, opts, cache) + if err != nil { + return err + } + + refs := []string{""} + if rrr != nil { + refs[0] = rrr.String() + } + var s *Schema + if s, err = expandSchema(*schema, refs, resolver); err != nil { + return err + } + *schema = *s + return nil +} + +func expandItems(target Schema, parentRefs []string, resolver *schemaLoader) (*Schema, error) { + if target.Items != nil { + if target.Items.Schema != nil { + t, err := expandSchema(*target.Items.Schema, parentRefs, resolver) + if err != nil { + if target.Items.Schema.ID == "" { + target.Items.Schema.ID = target.ID + if err != nil { + t, err = expandSchema(*target.Items.Schema, parentRefs, resolver) + if err != nil { + return nil, err + } + } + } + } + *target.Items.Schema = *t + } + for i := range target.Items.Schemas { + t, err := expandSchema(target.Items.Schemas[i], parentRefs, resolver) + if err != nil { + return nil, err + } + target.Items.Schemas[i] = *t + } + } + return &target, nil +} + +func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader) (*Schema, error) { + if target.Ref.String() == "" && target.Ref.IsRoot() { + debugLog("skipping expand schema for no ref and root: %v", resolver.root) + + return resolver.root.(*Schema), nil + } + + // t is the new expanded schema + var t *Schema + + for target.Ref.String() != "" { + if swag.ContainsStringsCI(parentRefs, target.Ref.String()) { + return &target, nil + } + + if err := resolver.Resolve(&target.Ref, &t); err != nil { + return &target, err + } + + if swag.ContainsStringsCI(parentRefs, target.Ref.String()) { + debugLog("ref already exists in parent") + return &target, nil + } + parentRefs = append(parentRefs, target.Ref.String()) + target = *t + } + + t, err := expandItems(target, parentRefs, resolver) + if err != nil { + return &target, err + } + target = *t + + for i := range target.AllOf { + t, err := expandSchema(target.AllOf[i], parentRefs, resolver) + if err != nil { + return &target, err + } + target.AllOf[i] = *t + } + for i := range target.AnyOf { + t, err := expandSchema(target.AnyOf[i], parentRefs, resolver) + if err != nil { + return &target, err + } + target.AnyOf[i] = *t + } + for i := range target.OneOf { + t, err := expandSchema(target.OneOf[i], parentRefs, resolver) + if err != nil { + return &target, err + } + target.OneOf[i] = *t + } + if target.Not != nil { + t, err := expandSchema(*target.Not, parentRefs, resolver) + if err != nil { + return &target, err + } + *target.Not = *t + } + for k := range target.Properties { + t, err := expandSchema(target.Properties[k], parentRefs, resolver) + if err != nil { + return &target, err + } + target.Properties[k] = *t + } + if target.AdditionalProperties != nil && target.AdditionalProperties.Schema != nil { + t, err := expandSchema(*target.AdditionalProperties.Schema, parentRefs, resolver) + if err != nil { + return &target, err + } + *target.AdditionalProperties.Schema = *t + } + for k := range target.PatternProperties { + t, err := expandSchema(target.PatternProperties[k], parentRefs, resolver) + if err != nil { + return &target, err + } + target.PatternProperties[k] = *t + } + for k := range target.Dependencies { + if target.Dependencies[k].Schema != nil { + t, err := expandSchema(*target.Dependencies[k].Schema, parentRefs, resolver) + if err != nil { + return &target, err + } + *target.Dependencies[k].Schema = *t + } + } + if target.AdditionalItems != nil && target.AdditionalItems.Schema != nil { + t, err := expandSchema(*target.AdditionalItems.Schema, parentRefs, resolver) + if err != nil { + return &target, err + } + *target.AdditionalItems.Schema = *t + } + for k := range target.Definitions { + t, err := expandSchema(target.Definitions[k], parentRefs, resolver) + if err != nil { + return &target, err + } + target.Definitions[k] = *t + } + return &target, nil +} + +func expandPathItem(pathItem *PathItem, resolver *schemaLoader) error { + if pathItem == nil { + return nil + } + if pathItem.Ref.String() != "" { + if err := resolver.Resolve(&pathItem.Ref, &pathItem); err != nil { + return err + } + resolver.reset() + pathItem.Ref = Ref{} + } + + for idx := range pathItem.Parameters { + if err := expandParameter(&(pathItem.Parameters[idx]), resolver); err != nil { + return err + } + } + if err := expandOperation(pathItem.Get, resolver); err != nil { + return err + } + if err := expandOperation(pathItem.Head, resolver); err != nil { + return err + } + if err := expandOperation(pathItem.Options, resolver); err != nil { + return err + } + if err := expandOperation(pathItem.Put, resolver); err != nil { + return err + } + if err := expandOperation(pathItem.Post, resolver); err != nil { + return err + } + if err := expandOperation(pathItem.Patch, resolver); err != nil { + return err + } + if err := expandOperation(pathItem.Delete, resolver); err != nil { + return err + } + return nil +} + +func expandOperation(op *Operation, resolver *schemaLoader) error { + if op == nil { + return nil + } + for i, param := range op.Parameters { + if err := expandParameter(¶m, resolver); err != nil { + return err + } + op.Parameters[i] = param + } + + if op.Responses != nil { + responses := op.Responses + if err := expandResponse(responses.Default, resolver); err != nil { + return err + } + for code, response := range responses.StatusCodeResponses { + if err := expandResponse(&response, resolver); err != nil { + return err + } + responses.StatusCodeResponses[code] = response + } + } + return nil +} + +func expandResponse(response *Response, resolver *schemaLoader) error { + if response == nil { + return nil + } + + var parentRefs []string + if response.Ref.String() != "" { + parentRefs = append(parentRefs, response.Ref.String()) + if err := resolver.Resolve(&response.Ref, response); err != nil { + return err + } + resolver.reset() + response.Ref = Ref{} + } + + if !resolver.options.SkipSchemas && response.Schema != nil { + parentRefs = append(parentRefs, response.Schema.Ref.String()) + debugLog("response ref: %s", response.Schema.Ref) + if err := resolver.Resolve(&response.Schema.Ref, &response.Schema); err != nil { + return err + } + s, err := expandSchema(*response.Schema, parentRefs, resolver) + if err != nil { + return err + } + resolver.reset() + *response.Schema = *s + } + return nil +} + +func expandParameter(parameter *Parameter, resolver *schemaLoader) error { + if parameter == nil { + return nil + } + + var parentRefs []string + if parameter.Ref.String() != "" { + parentRefs = append(parentRefs, parameter.Ref.String()) + if err := resolver.Resolve(¶meter.Ref, parameter); err != nil { + return err + } + resolver.reset() + parameter.Ref = Ref{} + } + if !resolver.options.SkipSchemas && parameter.Schema != nil { + parentRefs = append(parentRefs, parameter.Schema.Ref.String()) + if err := resolver.Resolve(¶meter.Schema.Ref, ¶meter.Schema); err != nil { + return err + } + s, err := expandSchema(*parameter.Schema, parentRefs, resolver) + if err != nil { + return err + } + resolver.reset() + *parameter.Schema = *s + } + return nil +} diff --git a/vendor/github.com/go-openapi/spec/expander_test.go b/vendor/github.com/go-openapi/spec/expander_test.go new file mode 100644 index 00000000..2cbffcab --- /dev/null +++ b/vendor/github.com/go-openapi/spec/expander_test.go @@ -0,0 +1,1133 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" + "github.com/stretchr/testify/assert" +) + +func jsonDoc(path string) (json.RawMessage, error) { + data, err := swag.LoadFromFileOrHTTP(path) + if err != nil { + return nil, err + } + return json.RawMessage(data), nil +} + +func TestExpandsKnownRef(t *testing.T) { + schema := RefProperty("http://json-schema.org/draft-04/schema#") + if assert.NoError(t, ExpandSchema(schema, nil, nil)) { + assert.Equal(t, "Core schema meta-schema", schema.Description) + } +} + +func TestExpandResponseSchema(t *testing.T) { + fp := "./fixtures/local_expansion/spec.json" + b, err := jsonDoc(fp) + if assert.NoError(t, err) { + var spec Swagger + if err := json.Unmarshal(b, &spec); assert.NoError(t, err) { + err := ExpandSpec(&spec, &ExpandOptions{RelativeBase: fp}) + if assert.NoError(t, err) { + sch := spec.Paths.Paths["/item"].Get.Responses.StatusCodeResponses[200].Schema + if assert.NotNil(t, sch) { + assert.Empty(t, sch.Ref.String()) + assert.Contains(t, sch.Type, "object") + assert.Len(t, sch.Properties, 2) + } + } + } + } +} + +func TestSpecExpansion(t *testing.T) { + spec := new(Swagger) + // resolver, err := defaultSchemaLoader(spec, nil, nil) + // assert.NoError(t, err) + + err := ExpandSpec(spec, nil) + assert.NoError(t, err) + + specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") + assert.NoError(t, err) + + spec = new(Swagger) + err = json.Unmarshal(specDoc, spec) + assert.NoError(t, err) + + pet := spec.Definitions["pet"] + errorModel := spec.Definitions["errorModel"] + petResponse := spec.Responses["petResponse"] + petResponse.Schema = &pet + stringResponse := spec.Responses["stringResponse"] + tagParam := spec.Parameters["tag"] + idParam := spec.Parameters["idParam"] + + err = ExpandSpec(spec, nil) + assert.NoError(t, err) + + assert.Equal(t, tagParam, spec.Parameters["query"]) + assert.Equal(t, petResponse, spec.Responses["petResponse"]) + assert.Equal(t, petResponse, spec.Responses["anotherPet"]) + assert.Equal(t, pet, *spec.Responses["petResponse"].Schema) + assert.Equal(t, stringResponse, *spec.Paths.Paths["/"].Get.Responses.Default) + assert.Equal(t, petResponse, spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200]) + assert.Equal(t, pet, *spec.Paths.Paths["/pets"].Get.Responses.StatusCodeResponses[200].Schema.Items.Schema) + assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Get.Responses.Default.Schema) + assert.Equal(t, pet, spec.Definitions["petInput"].AllOf[0]) + assert.Equal(t, spec.Definitions["petInput"], *spec.Paths.Paths["/pets"].Post.Parameters[0].Schema) + assert.Equal(t, petResponse, spec.Paths.Paths["/pets"].Post.Responses.StatusCodeResponses[200]) + assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Post.Responses.Default.Schema) + pi := spec.Paths.Paths["/pets/{id}"] + assert.Equal(t, idParam, pi.Get.Parameters[0]) + assert.Equal(t, petResponse, pi.Get.Responses.StatusCodeResponses[200]) + assert.Equal(t, errorModel, *pi.Get.Responses.Default.Schema) + assert.Equal(t, idParam, pi.Delete.Parameters[0]) + assert.Equal(t, errorModel, *pi.Delete.Responses.Default.Schema) +} + +func TestResponseExpansion(t *testing.T) { + specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") + assert.NoError(t, err) + + spec := new(Swagger) + err = json.Unmarshal(specDoc, spec) + assert.NoError(t, err) + + resolver, err := defaultSchemaLoader(spec, nil, nil, nil) + assert.NoError(t, err) + + resp := spec.Responses["anotherPet"] + expected := spec.Responses["petResponse"] + + err = expandResponse(&resp, resolver) + assert.NoError(t, err) + assert.Equal(t, expected, resp) + + resp2 := spec.Paths.Paths["/"].Get.Responses.Default + expected = spec.Responses["stringResponse"] + + err = expandResponse(resp2, resolver) + assert.NoError(t, err) + assert.Equal(t, expected, *resp2) + + resp = spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200] + expected = spec.Responses["petResponse"] + + err = expandResponse(&resp, resolver) + assert.NoError(t, err) + // assert.Equal(t, expected, resp) +} + +func TestIssue3(t *testing.T) { + spec := new(Swagger) + specDoc, err := jsonDoc("fixtures/expansion/overflow.json") + assert.NoError(t, err) + + err = json.Unmarshal(specDoc, spec) + assert.NoError(t, err) + + assert.NotPanics(t, func() { + err = ExpandSpec(spec, nil) + assert.NoError(t, err) + }, "Calling expand spec with circular refs, should not panic!") +} + +func TestParameterExpansion(t *testing.T) { + paramDoc, err := jsonDoc("fixtures/expansion/params.json") + assert.NoError(t, err) + + spec := new(Swagger) + err = json.Unmarshal(paramDoc, spec) + assert.NoError(t, err) + + resolver, err := defaultSchemaLoader(spec, nil, nil, nil) + assert.NoError(t, err) + + param := spec.Parameters["query"] + expected := spec.Parameters["tag"] + + err = expandParameter(¶m, resolver) + assert.NoError(t, err) + assert.Equal(t, expected, param) + + param = spec.Paths.Paths["/cars/{id}"].Parameters[0] + expected = spec.Parameters["id"] + + err = expandParameter(¶m, resolver) + assert.NoError(t, err) + assert.Equal(t, expected, param) +} + +func TestCircularRefsExpansion(t *testing.T) { + carsDoc, err := jsonDoc("fixtures/expansion/circularRefs.json") + assert.NoError(t, err) + + spec := new(Swagger) + err = json.Unmarshal(carsDoc, spec) + assert.NoError(t, err) + + resolver, err := defaultSchemaLoader(spec, nil, nil, nil) + assert.NoError(t, err) + schema := spec.Definitions["car"] + + assert.NotPanics(t, func() { + _, err = expandSchema(schema, []string{"#/definitions/car"}, resolver) + assert.NoError(t, err) + }, "Calling expand schema with circular refs, should not panic!") +} + +func TestIssue415(t *testing.T) { + doc, err := jsonDoc("fixtures/expansion/clickmeter.json") + assert.NoError(t, err) + + spec := new(Swagger) + err = json.Unmarshal(doc, spec) + assert.NoError(t, err) + + assert.NotPanics(t, func() { + err = ExpandSpec(spec, nil) + assert.NoError(t, err) + }, "Calling expand spec with response schemas that have circular refs, should not panic!") +} + +func TestCircularSpecExpansion(t *testing.T) { + doc, err := jsonDoc("fixtures/expansion/circularSpec.json") + assert.NoError(t, err) + + spec := new(Swagger) + err = json.Unmarshal(doc, spec) + assert.NoError(t, err) + + assert.NotPanics(t, func() { + err = ExpandSpec(spec, nil) + assert.NoError(t, err) + }, "Calling expand spec with circular refs, should not panic!") +} + +func TestItemsExpansion(t *testing.T) { + carsDoc, err := jsonDoc("fixtures/expansion/schemas2.json") + assert.NoError(t, err) + + spec := new(Swagger) + err = json.Unmarshal(carsDoc, spec) + assert.NoError(t, err) + + resolver, err := defaultSchemaLoader(spec, nil, nil, nil) + assert.NoError(t, err) + + schema := spec.Definitions["car"] + oldBrand := schema.Properties["brand"] + assert.NotEmpty(t, oldBrand.Items.Schema.Ref.String()) + assert.NotEqual(t, spec.Definitions["brand"], oldBrand) + + _, err = expandSchema(schema, []string{"#/definitions/car"}, resolver) + assert.NoError(t, err) + + newBrand := schema.Properties["brand"] + assert.Empty(t, newBrand.Items.Schema.Ref.String()) + assert.Equal(t, spec.Definitions["brand"], *newBrand.Items.Schema) + + schema = spec.Definitions["truck"] + assert.NotEmpty(t, schema.Items.Schema.Ref.String()) + + s, err := expandSchema(schema, []string{"#/definitions/truck"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.Items.Schema.Ref.String()) + assert.Equal(t, spec.Definitions["car"], *schema.Items.Schema) + + sch := new(Schema) + _, err = expandSchema(*sch, []string{""}, resolver) + assert.NoError(t, err) + + schema = spec.Definitions["batch"] + s, err = expandSchema(schema, []string{"#/definitions/batch"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.Items.Schema.Items.Schema.Ref.String()) + assert.Equal(t, *schema.Items.Schema.Items.Schema, spec.Definitions["brand"]) + + schema = spec.Definitions["batch2"] + s, err = expandSchema(schema, []string{"#/definitions/batch2"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.Items.Schemas[0].Items.Schema.Ref.String()) + assert.Empty(t, schema.Items.Schemas[1].Items.Schema.Ref.String()) + assert.Equal(t, *schema.Items.Schemas[0].Items.Schema, spec.Definitions["brand"]) + assert.Equal(t, *schema.Items.Schemas[1].Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["allofBoth"] + s, err = expandSchema(schema, []string{"#/definitions/allofBoth"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.AllOf[0].Items.Schema.Ref.String()) + assert.Empty(t, schema.AllOf[1].Items.Schema.Ref.String()) + assert.Equal(t, *schema.AllOf[0].Items.Schema, spec.Definitions["brand"]) + assert.Equal(t, *schema.AllOf[1].Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["anyofBoth"] + s, err = expandSchema(schema, []string{"#/definitions/anyofBoth"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.AnyOf[0].Items.Schema.Ref.String()) + assert.Empty(t, schema.AnyOf[1].Items.Schema.Ref.String()) + assert.Equal(t, *schema.AnyOf[0].Items.Schema, spec.Definitions["brand"]) + assert.Equal(t, *schema.AnyOf[1].Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["oneofBoth"] + s, err = expandSchema(schema, []string{"#/definitions/oneofBoth"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.OneOf[0].Items.Schema.Ref.String()) + assert.Empty(t, schema.OneOf[1].Items.Schema.Ref.String()) + assert.Equal(t, *schema.OneOf[0].Items.Schema, spec.Definitions["brand"]) + assert.Equal(t, *schema.OneOf[1].Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["notSomething"] + s, err = expandSchema(schema, []string{"#/definitions/notSomething"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.Not.Items.Schema.Ref.String()) + assert.Equal(t, *schema.Not.Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["withAdditional"] + s, err = expandSchema(schema, []string{"#/definitions/withAdditional"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.AdditionalProperties.Schema.Items.Schema.Ref.String()) + assert.Equal(t, *schema.AdditionalProperties.Schema.Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["withAdditionalItems"] + s, err = expandSchema(schema, []string{"#/definitions/withAdditionalItems"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.AdditionalItems.Schema.Items.Schema.Ref.String()) + assert.Equal(t, *schema.AdditionalItems.Schema.Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["withPattern"] + s, err = expandSchema(schema, []string{"#/definitions/withPattern"}, resolver) + schema = *s + assert.NoError(t, err) + prop := schema.PatternProperties["^x-ab"] + assert.Empty(t, prop.Items.Schema.Ref.String()) + assert.Equal(t, *prop.Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["deps"] + s, err = expandSchema(schema, []string{"#/definitions/deps"}, resolver) + schema = *s + assert.NoError(t, err) + prop2 := schema.Dependencies["something"] + assert.Empty(t, prop2.Schema.Items.Schema.Ref.String()) + assert.Equal(t, *prop2.Schema.Items.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["defined"] + s, err = expandSchema(schema, []string{"#/definitions/defined"}, resolver) + schema = *s + assert.NoError(t, err) + prop = schema.Definitions["something"] + assert.Empty(t, prop.Items.Schema.Ref.String()) + assert.Equal(t, *prop.Items.Schema, spec.Definitions["tag"]) +} + +func TestSchemaExpansion(t *testing.T) { + carsDoc, err := jsonDoc("fixtures/expansion/schemas1.json") + assert.NoError(t, err) + + spec := new(Swagger) + err = json.Unmarshal(carsDoc, spec) + assert.NoError(t, err) + + resolver, err := defaultSchemaLoader(spec, nil, nil, nil) + assert.NoError(t, err) + + schema := spec.Definitions["car"] + oldBrand := schema.Properties["brand"] + assert.NotEmpty(t, oldBrand.Ref.String()) + assert.NotEqual(t, spec.Definitions["brand"], oldBrand) + + s, err := expandSchema(schema, []string{"#/definitions/car"}, resolver) + schema = *s + assert.NoError(t, err) + + newBrand := schema.Properties["brand"] + assert.Empty(t, newBrand.Ref.String()) + assert.Equal(t, spec.Definitions["brand"], newBrand) + + schema = spec.Definitions["truck"] + assert.NotEmpty(t, schema.Ref.String()) + + s, err = expandSchema(schema, []string{"#/definitions/truck"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.Ref.String()) + assert.Equal(t, spec.Definitions["car"], schema) + + sch := new(Schema) + _, err = expandSchema(*sch, []string{""}, resolver) + assert.NoError(t, err) + + schema = spec.Definitions["batch"] + s, err = expandSchema(schema, []string{"#/definitions/batch"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.Items.Schema.Ref.String()) + assert.Equal(t, *schema.Items.Schema, spec.Definitions["brand"]) + + schema = spec.Definitions["batch2"] + s, err = expandSchema(schema, []string{"#/definitions/batch2"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.Items.Schemas[0].Ref.String()) + assert.Empty(t, schema.Items.Schemas[1].Ref.String()) + assert.Equal(t, schema.Items.Schemas[0], spec.Definitions["brand"]) + assert.Equal(t, schema.Items.Schemas[1], spec.Definitions["tag"]) + + schema = spec.Definitions["allofBoth"] + s, err = expandSchema(schema, []string{"#/definitions/allofBoth"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.AllOf[0].Ref.String()) + assert.Empty(t, schema.AllOf[1].Ref.String()) + assert.Equal(t, schema.AllOf[0], spec.Definitions["brand"]) + assert.Equal(t, schema.AllOf[1], spec.Definitions["tag"]) + + schema = spec.Definitions["anyofBoth"] + s, err = expandSchema(schema, []string{"#/definitions/anyofBoth"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.AnyOf[0].Ref.String()) + assert.Empty(t, schema.AnyOf[1].Ref.String()) + assert.Equal(t, schema.AnyOf[0], spec.Definitions["brand"]) + assert.Equal(t, schema.AnyOf[1], spec.Definitions["tag"]) + + schema = spec.Definitions["oneofBoth"] + s, err = expandSchema(schema, []string{"#/definitions/oneofBoth"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.OneOf[0].Ref.String()) + assert.Empty(t, schema.OneOf[1].Ref.String()) + assert.Equal(t, schema.OneOf[0], spec.Definitions["brand"]) + assert.Equal(t, schema.OneOf[1], spec.Definitions["tag"]) + + schema = spec.Definitions["notSomething"] + s, err = expandSchema(schema, []string{"#/definitions/notSomething"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.Not.Ref.String()) + assert.Equal(t, *schema.Not, spec.Definitions["tag"]) + + schema = spec.Definitions["withAdditional"] + s, err = expandSchema(schema, []string{"#/definitions/withAdditional"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.AdditionalProperties.Schema.Ref.String()) + assert.Equal(t, *schema.AdditionalProperties.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["withAdditionalItems"] + s, err = expandSchema(schema, []string{"#/definitions/withAdditionalItems"}, resolver) + schema = *s + assert.NoError(t, err) + assert.Empty(t, schema.AdditionalItems.Schema.Ref.String()) + assert.Equal(t, *schema.AdditionalItems.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["withPattern"] + s, err = expandSchema(schema, []string{"#/definitions/withPattern"}, resolver) + schema = *s + assert.NoError(t, err) + prop := schema.PatternProperties["^x-ab"] + assert.Empty(t, prop.Ref.String()) + assert.Equal(t, prop, spec.Definitions["tag"]) + + schema = spec.Definitions["deps"] + s, err = expandSchema(schema, []string{"#/definitions/deps"}, resolver) + schema = *s + assert.NoError(t, err) + prop2 := schema.Dependencies["something"] + assert.Empty(t, prop2.Schema.Ref.String()) + assert.Equal(t, *prop2.Schema, spec.Definitions["tag"]) + + schema = spec.Definitions["defined"] + s, err = expandSchema(schema, []string{"#/definitions/defined"}, resolver) + schema = *s + assert.NoError(t, err) + prop = schema.Definitions["something"] + assert.Empty(t, prop.Ref.String()) + assert.Equal(t, prop, spec.Definitions["tag"]) + +} + +func TestDefaultResolutionCache(t *testing.T) { + + cache := initResolutionCache() + + sch, ok := cache.Get("not there") + assert.False(t, ok) + assert.Nil(t, sch) + + sch, ok = cache.Get("http://swagger.io/v2/schema.json") + assert.True(t, ok) + assert.Equal(t, swaggerSchema, sch) + + sch, ok = cache.Get("http://json-schema.org/draft-04/schema") + assert.True(t, ok) + assert.Equal(t, jsonSchema, sch) + + cache.Set("something", "here") + sch, ok = cache.Get("something") + assert.True(t, ok) + assert.Equal(t, "here", sch) +} + +func resolutionContextServer() *httptest.Server { + var servedAt string + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + // fmt.Println("got a request for", req.URL.String()) + if req.URL.Path == "/resolution.json" { + + b, _ := ioutil.ReadFile("fixtures/specs/resolution.json") + var ctnt map[string]interface{} + json.Unmarshal(b, &ctnt) + ctnt["id"] = servedAt + + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(200) + bb, _ := json.Marshal(ctnt) + rw.Write(bb) + return + } + if req.URL.Path == "/resolution2.json" { + b, _ := ioutil.ReadFile("fixtures/specs/resolution2.json") + var ctnt map[string]interface{} + json.Unmarshal(b, &ctnt) + ctnt["id"] = servedAt + + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(200) + bb, _ := json.Marshal(ctnt) + rw.Write(bb) + return + } + + if req.URL.Path == "/boolProp.json" { + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(200) + b, _ := json.Marshal(map[string]interface{}{ + "type": "boolean", + }) + _, _ = rw.Write(b) + return + } + + if req.URL.Path == "/deeper/stringProp.json" { + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(200) + b, _ := json.Marshal(map[string]interface{}{ + "type": "string", + }) + rw.Write(b) + return + } + + if req.URL.Path == "/deeper/arrayProp.json" { + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(200) + b, _ := json.Marshal(map[string]interface{}{ + "type": "array", + "items": map[string]interface{}{ + "type": "file", + }, + }) + rw.Write(b) + return + } + + rw.WriteHeader(http.StatusNotFound) + })) + servedAt = server.URL + return server +} + +func TestResolveRemoteRef_RootSame(t *testing.T) { + specs := "fixtures/specs" + fileserver := http.FileServer(http.Dir(specs)) + server := httptest.NewServer(fileserver) + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var result_0 Swagger + ref_0, _ := NewRef(server.URL + "/refed.json#") + resolver_0, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver_0.Resolve(&ref_0, &result_0)) { + assertSpecs(t, result_0, *rootDoc) + } + + var result_1 Swagger + ref_1, _ := NewRef("./refed.json") + resolver_1, _ := defaultSchemaLoader(rootDoc, nil, &ExpandOptions{ + RelativeBase: (specs), + }, nil) + if assert.NoError(t, resolver_1.Resolve(&ref_1, &result_1)) { + assertSpecs(t, result_1, *rootDoc) + } + } +} + +func TestResolveRemoteRef_FromFragment(t *testing.T) { + specs := "fixtures/specs" + fileserver := http.FileServer(http.Dir(specs)) + server := httptest.NewServer(fileserver) + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Schema + ref, err := NewRef(server.URL + "/refed.json#/definitions/pet") + if assert.NoError(t, err) { + resolver := &schemaLoader{root: rootDoc, cache: initResolutionCache(), loadDoc: jsonDoc} + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, []string{"id", "name"}, tgt.Required) + } + } + } +} + +func TestResolveRemoteRef_FromInvalidFragment(t *testing.T) { + specs := "fixtures/specs" + fileserver := http.FileServer(http.Dir(specs)) + server := httptest.NewServer(fileserver) + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Schema + ref, err := NewRef(server.URL + "/refed.json#/definitions/NotThere") + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + assert.Error(t, resolver.Resolve(&ref, &tgt)) + } + } +} + +func TestResolveRemoteRef_WithResolutionContext(t *testing.T) { + server := resolutionContextServer() + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Schema + ref, err := NewRef(server.URL + "/resolution.json#/definitions/bool") + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, StringOrArray([]string{"boolean"}), tgt.Type) + } + } + } +} + +func TestResolveRemoteRef_WithNestedResolutionContext(t *testing.T) { + server := resolutionContextServer() + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Schema + ref, err := NewRef(server.URL + "/resolution.json#/items/items") + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, StringOrArray([]string{"string"}), tgt.Type) + } + } + } +} + +func TestResolveRemoteRef_WithNestedResolutionContextWithFragment(t *testing.T) { + server := resolutionContextServer() + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Schema + ref, err := NewRef(server.URL + "/resolution2.json#/items/items") + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, StringOrArray([]string{"file"}), tgt.Type) + } + } + } +} + +func TestResolveRemoteRef_ToParameter(t *testing.T) { + specs := "fixtures/specs" + fileserver := http.FileServer(http.Dir(specs)) + server := httptest.NewServer(fileserver) + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Parameter + ref, err := NewRef(server.URL + "/refed.json#/parameters/idParam") + if assert.NoError(t, err) { + + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, "id", tgt.Name) + assert.Equal(t, "path", tgt.In) + assert.Equal(t, "ID of pet to fetch", tgt.Description) + assert.True(t, tgt.Required) + assert.Equal(t, "integer", tgt.Type) + assert.Equal(t, "int64", tgt.Format) + } + } + } +} + +func TestResolveRemoteRef_ToPathItem(t *testing.T) { + specs := "fixtures/specs" + fileserver := http.FileServer(http.Dir(specs)) + server := httptest.NewServer(fileserver) + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt PathItem + ref, err := NewRef(server.URL + "/refed.json#/paths/" + jsonpointer.Escape("/pets/{id}")) + if assert.NoError(t, err) { + + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, rootDoc.Paths.Paths["/pets/{id}"].Get, tgt.Get) + } + } + } +} + +func TestResolveRemoteRef_ToResponse(t *testing.T) { + specs := "fixtures/specs" + fileserver := http.FileServer(http.Dir(specs)) + server := httptest.NewServer(fileserver) + defer server.Close() + + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Response + ref, err := NewRef(server.URL + "/refed.json#/responses/petResponse") + if assert.NoError(t, err) { + + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, rootDoc.Responses["petResponse"], tgt) + } + } + } +} + +func TestResolveLocalRef_SameRoot(t *testing.T) { + rootDoc := new(Swagger) + json.Unmarshal(PetStoreJSONMessage, rootDoc) + + result := new(Swagger) + ref, _ := NewRef("#") + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + err := resolver.Resolve(&ref, result) + if assert.NoError(t, err) { + assert.Equal(t, rootDoc, result) + } +} + +func TestResolveLocalRef_FromFragment(t *testing.T) { + rootDoc := new(Swagger) + json.Unmarshal(PetStoreJSONMessage, rootDoc) + + var tgt Schema + ref, err := NewRef("#/definitions/Category") + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + err := resolver.Resolve(&ref, &tgt) + if assert.NoError(t, err) { + assert.Equal(t, "Category", tgt.ID) + } + } +} + +func TestResolveLocalRef_FromInvalidFragment(t *testing.T) { + rootDoc := new(Swagger) + json.Unmarshal(PetStoreJSONMessage, rootDoc) + + var tgt Schema + ref, err := NewRef("#/definitions/NotThere") + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + err := resolver.Resolve(&ref, &tgt) + assert.Error(t, err) + } +} + +func TestResolveLocalRef_Parameter(t *testing.T) { + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Parameter + ref, err := NewRef("#/parameters/idParam") + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, "id", tgt.Name) + assert.Equal(t, "path", tgt.In) + assert.Equal(t, "ID of pet to fetch", tgt.Description) + assert.True(t, tgt.Required) + assert.Equal(t, "integer", tgt.Type) + assert.Equal(t, "int64", tgt.Format) + } + } + } +} + +func TestResolveLocalRef_PathItem(t *testing.T) { + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt PathItem + ref, err := NewRef("#/paths/" + jsonpointer.Escape("/pets/{id}")) + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, rootDoc.Paths.Paths["/pets/{id}"].Get, tgt.Get) + } + } + } +} + +func TestResolveLocalRef_Response(t *testing.T) { + rootDoc := new(Swagger) + b, err := ioutil.ReadFile("fixtures/specs/refed.json") + if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { + var tgt Response + ref, err := NewRef("#/responses/petResponse") + if assert.NoError(t, err) { + resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) + if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { + assert.Equal(t, rootDoc.Responses["petResponse"], tgt) + } + } + } +} + +// PetStoreJSONMessage json raw message for Petstore20 +var PetStoreJSONMessage = json.RawMessage([]byte(PetStore20)) + +// PetStore20 json doc for swagger 2.0 pet store +const PetStore20 = `{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "Swagger Petstore", + "contact": { + "name": "Wordnik API Team", + "url": "http://developer.wordnik.com" + }, + "license": { + "name": "Creative Commons 4.0 International", + "url": "http://creativecommons.org/licenses/by/4.0/" + } + }, + "host": "petstore.swagger.wordnik.com", + "basePath": "/api", + "schemes": [ + "http" + ], + "paths": { + "/pets": { + "get": { + "security": [ + { + "basic": [] + } + ], + "tags": [ "Pet Operations" ], + "operationId": "getAllPets", + "parameters": [ + { + "name": "status", + "in": "query", + "description": "The status to filter by", + "type": "string" + }, + { + "name": "limit", + "in": "query", + "description": "The maximum number of results to return", + "type": "integer", + "format": "int64" + } + ], + "summary": "Finds all pets in the system", + "responses": { + "200": { + "description": "Pet response", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "post": { + "security": [ + { + "basic": [] + } + ], + "tags": [ "Pet Operations" ], + "operationId": "createPet", + "summary": "Creates a new pet", + "consumes": ["application/x-yaml"], + "produces": ["application/x-yaml"], + "parameters": [ + { + "name": "pet", + "in": "body", + "description": "The Pet to create", + "required": true, + "schema": { + "$ref": "#/definitions/newPet" + } + } + ], + "responses": { + "200": { + "description": "Created Pet response", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/pets/{id}": { + "delete": { + "security": [ + { + "apiKey": [] + } + ], + "description": "Deletes the Pet by id", + "operationId": "deletePet", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "204": { + "description": "pet deleted" + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "get": { + "tags": [ "Pet Operations" ], + "operationId": "getPetById", + "summary": "Finds the pet by id", + "responses": { + "200": { + "description": "Pet response", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet", + "required": true, + "type": "integer", + "format": "int64" + } + ] + } + }, + "definitions": { + "Category": { + "id": "Category", + "properties": { + "id": { + "format": "int64", + "type": "integer" + }, + "name": { + "type": "string" + } + } + }, + "Pet": { + "id": "Pet", + "properties": { + "category": { + "$ref": "#/definitions/Category" + }, + "id": { + "description": "unique identifier for the pet", + "format": "int64", + "maximum": 100.0, + "minimum": 0.0, + "type": "integer" + }, + "name": { + "type": "string" + }, + "photoUrls": { + "items": { + "type": "string" + }, + "type": "array" + }, + "status": { + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ], + "type": "string" + }, + "tags": { + "items": { + "$ref": "#/definitions/Tag" + }, + "type": "array" + } + }, + "required": [ + "id", + "name" + ] + }, + "newPet": { + "anyOf": [ + { + "$ref": "#/definitions/Pet" + }, + { + "required": [ + "name" + ] + } + ] + }, + "Tag": { + "id": "Tag", + "properties": { + "id": { + "format": "int64", + "type": "integer" + }, + "name": { + "type": "string" + } + } + }, + "Error": { + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + }, + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml", + "text/plain", + "text/html" + ], + "securityDefinitions": { + "basic": { + "type": "basic" + }, + "apiKey": { + "type": "apiKey", + "in": "header", + "name": "X-API-KEY" + } + } +} +` diff --git a/vendor/github.com/go-openapi/spec/external_docs.go b/vendor/github.com/go-openapi/spec/external_docs.go new file mode 100644 index 00000000..88add91b --- /dev/null +++ b/vendor/github.com/go-openapi/spec/external_docs.go @@ -0,0 +1,24 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +// ExternalDocumentation allows referencing an external resource for +// extended documentation. +// +// For more information: http://goo.gl/8us55a#externalDocumentationObject +type ExternalDocumentation struct { + Description string `json:"description,omitempty"` + URL string `json:"url,omitempty"` +} diff --git a/vendor/github.com/go-openapi/spec/external_docs_test.go b/vendor/github.com/go-openapi/spec/external_docs_test.go new file mode 100644 index 00000000..14c5ef15 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/external_docs_test.go @@ -0,0 +1,29 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "testing" +) + +func TestIntegrationExternalDocs(t *testing.T) { + var extDocs = ExternalDocumentation{"the name", "the url"} + const extDocsYAML = "description: the name\nurl: the url\n" + const extDocsJSON = `{"description":"the name","url":"the url"}` + assertSerializeJSON(t, extDocs, extDocsJSON) + assertSerializeYAML(t, extDocs, extDocsYAML) + assertParsesJSON(t, extDocsJSON, extDocs) + assertParsesYAML(t, extDocsYAML, extDocs) +} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/all-the-things.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/all-the-things.json new file mode 100644 index 00000000..42e6f24e --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/all-the-things.json @@ -0,0 +1,254 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "Swagger Petstore", + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "name": "Wordnik API Team" + }, + "license": { + "name": "MIT" + } + }, + "host": "petstore.swagger.wordnik.com", + "basePath": "/api", + "schemes": [ + "http" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": { + "idParam": { + "name": "id", + "in": "path", + "description": "ID of pet to fetch", + "required": true, + "type": "integer", + "format": "int64" + }, + "tag": { + "type": "string", + "in": "query", + "required": false + }, + "query": { + "$ref": "#/parameters/tag" + } + }, + "responses": { + "petResponse": { + "description": "pet response", + "schema": { + "$ref": "#/definitions/pet" + } + }, + "stringResponse": { + "descripion": "string response", + "schema": { + "type": "string" + } + }, + "anotherPet": { + "$ref": "#/responses/petResponse" + } + }, + "paths": { + "/": { + "get": { + "operationId": "indexStuff", + "responses": { + "default": { + "$ref": "#/responses/stringResponse" + }, + "200": { + "$ref": "#/responses/anotherPet" + } + } + } + }, + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "operationId": "findPets", + "produces": [ + "application/json", + "application/xml", + "text/xml", + "text/html" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv" + }, + { + "name": "limit", + "in": "query", + "description": "maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/pet" + } + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/errorModel" + } + } + } + }, + "post": { + "description": "Creates a new pet in the store. Duplicates are allowed", + "operationId": "addPet", + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "pet", + "in": "body", + "description": "Pet to add to the store", + "required": true, + "schema": { + "$ref": "#/definitions/petInput" + } + } + ], + "responses": { + "200": { "$ref": "#/responses/petResponse" }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/errorModel" + } + } + } + } + }, + "/pets/{id}": { + "get": { + "description": "Returns a user based on a single ID, if the user does not have access to the pet", + "operationId": "findPetById", + "produces": [ + "application/json", + "application/xml", + "text/xml", + "text/html" + ], + "parameters": [ + { + "$ref": "#/parameters/idParam" + } + ], + "responses": { + "200": { + "$ref": "#/responses/petResponse" + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/errorModel" + } + } + } + }, + "delete": { + "description": "deletes a single pet based on the ID supplied", + "operationId": "deletePet", + "parameters": [ + { + "$ref": "#/parameters/idParam" + } + ], + "responses": { + "204": { + "description": "pet deleted" + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/errorModel" + } + } + } + } + } + }, + "definitions": { + "pet": { + "required": [ + "id", + "name" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "petInput": { + "allOf": [ + { + "$ref": "#/definitions/pet" + }, + { + "required": [ + "name" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + } + } + } + ] + }, + "errorModel": { + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } +} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularRefs.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularRefs.json new file mode 100644 index 00000000..f501aa14 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularRefs.json @@ -0,0 +1,54 @@ +{ + "definitions": { + "brand": { + "type": "object", + "properties": { + "name": { + "type": "string" + } + } + }, + "category": { + "type": "object", + "properties": { + "children": { + "type": "array", + "items": { + "$ref": "#/definitions/category" + } + } + } + }, + "car": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "make": { + "type": "string" + }, + "similar": { + "items": { + "$ref": "#/definitions/car" + } + }, + "notSimilar": { + "additionalProperties": { + "$ref": "#/definitions/car" + } + }, + "oneCar": { + "$ref": "#/definitions/car" + }, + "category": { + "$ref": "#/definitions/category" + }, + "brand": { + "$ref": "#/definitions/brand" + } + } + } + } +} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.json new file mode 100644 index 00000000..7b39b999 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.json @@ -0,0 +1 @@ +{"swagger":"2.0","info":{"title":"Swagger Sample","description":"Sample API Playground.","version":"1.0.0"},"basePath":"/v1","schemes":["http"],"consumes":["application/vdn.sample.v1+json"],"produces":["application/vdn.sample.v1+json"],"paths":{"/books":{"get":{"summary":"List all books","operationId":"listBooks","tags":["books"],"responses":{"200":{"headers":{"Link":{"type":"string"}},"description":"An array of books","schema":{"type":"array","items":{"$ref":"#/definitions/Book"}}},"default":{"description":"generic error response","schema":{"$ref":"#/definitions/Error"}}}}}},"definitions":{"Book":{"type":"object","required":["title","summary"],"properties":{"title":{"type":"string","example":"Winnie the Pooh"},"summary":{"type":"string","example":"Famous children's book"},"related_books":{"type":"array","items":{"$ref":"#/definitions/Book"}}}},"Error":{"type":"object","readOnly":true,"properties":{"code":{"type":"integer","format":"int64","example":400},"message":{"type":"string","example":"Unexpected error"}},"required":["message"]}}} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.yaml b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.yaml new file mode 100644 index 00000000..d43bd464 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.yaml @@ -0,0 +1,67 @@ +--- +swagger: "2.0" +info: + title: Swagger Sample + description: Sample API Playground. + version: 1.0.0 +basePath: /v1 +schemes: +- http +consumes: +- application/vdn.sample.v1+json +produces: +- application/vdn.sample.v1+json + +paths: + /books: + get: + summary: List all books + operationId: listBooks + tags: + - books + responses: + 200: + headers: + Link: + type: string + description: An array of books + schema: + type: array + items: + $ref: "#/definitions/Book" + default: + description: generic error response + schema: + $ref: "#/definitions/Error" + +definitions: + Book: + type: object + required: + - title + - summary + properties: + title: + type: string + example: Winnie the Pooh + summary: + type: string + example: Famous children's book + related_books: + type: array + items: + $ref: "#/definitions/Book" + + Error: + type: object + readOnly: true + properties: + code: + type: integer + format: int64 + example: 400 + message: + type: string + example: Unexpected error + required: + - message diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.json new file mode 100644 index 00000000..27e819aa --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.json @@ -0,0 +1 @@ +{"swagger":"2.0","schemes":["http","https"],"host":"apiv2.clickmeter.com:80","info":{"contact":{"email":"api@clickmeter.com","name":"Api Support","url":"http://www.clickmeter.com/api"},"description":"Api dashboard for ClickMeter API","title":"ClickMeter","version":"v2","x-logo":{"url":"https://s3.amazonaws.com/clickmeter.com/Web/static/cmlogo.svg"},"x-origin":{"format":"swagger","url":"http://api.v2.clickmeter.com.s3.amazonaws.com/docs/api-docs-v2.json","version":"2.0"},"x-providerName":"clickmeter.com"},"securityDefinitions":{"api_key":{"description":"API Key Authentication","in":"header","name":"X-Clickmeter-AuthKey","type":"apiKey"}},"security":[{"api_key":[]}],"paths":{"/account":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.User"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve current account data","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.User"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.User"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Update current account data","tags":["Account"]}},"/account/domainwhitelist":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.DomainWhitelistEntry]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve list of a domains allowed to redirect in DDU mode","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The entry to add","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Create an domain entry","tags":["Account"]}},"/account/domainwhitelist/{whitelistId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the domain to delete","in":"path","name":"whitelistId","required":true,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete an domain entry","tags":["Account"]}},"/account/guests":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve list of a guest","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Guest object to create","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Create a guest","tags":["Account"]}},"/account/guests/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve count of guests","tags":["Account"]}},"/account/guests/{guestId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete a guest","tags":["Account"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a guest","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Guest object with field updated","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Update a guest","tags":["Account"]}},"/account/guests/{guestId}/permissions":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Can be \"datapoint\" or \"group\"","enum":["datapoint","group"],"in":"query","name":"entityType","required":false,"type":"string"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Can be \"w\" or \"r\"","enum":["r","w"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Optional id of the datapoint/group entity to filter by","format":"int64","in":"query","name":"entityId","required":false,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Grants.Grant]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve permissions for a guest","tags":["Account"]}},"/account/guests/{guestId}/permissions/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Can be \"datapoint\" or \"group\"","enum":["datapoint","group"],"in":"query","name":"entityType","required":false,"type":"string"},{"description":"Can be \"w\" or \"r\"","enum":["r","w"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Optional id of the datapoint/group entity to filter by","format":"int64","in":"query","name":"entityId","required":false,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve count of the permissions for a guest","tags":["Account"]}},"/account/guests/{guestId}/{type}/permissions/patch":{"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Can be \"datapoint\" or \"group\"","enum":["datapoint","group"],"in":"path","name":"type","required":true,"type":"string"},{"description":"The patch permission request","in":"body","name":"body","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PermissionPatchRequest"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Change the permission on a shared object","tags":["Account"]},"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Can be \"datapoint\" or \"group\"","enum":["datapoint","group"],"in":"path","name":"type","required":true,"type":"string"},{"description":"The patch permission request","in":"body","name":"body","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PermissionPatchRequest"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Change the permission on a shared object","tags":["Account"]}},"/account/ipblacklist":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.IpBlacklistEntry]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve list of a ip to exclude from event tracking","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The entry to add","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Create an ip blacklist entry","tags":["Account"]}},"/account/ipblacklist/{blacklistId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the ip to delete","in":"path","name":"blacklistId","required":true,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete an ip blacklist entry","tags":["Account"]}},"/account/plan":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Plan"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve current account plan","tags":["Account"]}},"/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"},{"description":"","in":"query","name":"onlyFavorites","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe","tags":["Aggregated"]}},"/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe grouped by some temporal entity (day/week/month)","tags":["Aggregated"]}},"/aggregated/summary/conversions":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of conversion (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about a subset of conversions for a timeframe with conversions data","tags":["Aggregated"]}},"/aggregated/summary/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Filter by this group id","format":"int64","in":"query","name":"groupId","required":false,"type":"integer"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about a subset of datapoints for a timeframe with datapoints data","tags":["Aggregated"]}},"/aggregated/summary/groups":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of group (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the group marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about a subset of groups for a timeframe with groups data","tags":["Aggregated"]}},"/clickstream":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Filter by this group id (mutually exclusive with \"datapoint\" and \"conversion\")","format":"int64","in":"query","name":"group","required":false,"type":"integer"},{"description":"Filter by this datapoint id (mutually exclusive with \"group\" and \"conversion\")","format":"int64","in":"query","name":"datapoint","required":false,"type":"integer"},{"description":"Filter by this conversion id (mutually exclusive with \"datapoint\" and \"group\")","format":"int64","in":"query","name":"conversion","required":false,"type":"integer"},{"default":50,"description":"Limit results to this number","format":"int32","in":"query","name":"pageSize","required":false,"type":"integer"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["","spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.ClickStream.Hit]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the latest list of events of this account. Limited to last 100.","tags":["ClickStream"]}},"/conversions":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Status of conversion (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude conversions created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude conversions created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a list of conversions","tags":["Conversions"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the conversion","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Conversions.Conversion"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a conversion","tags":["Conversions"]}},"/conversions/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of conversion (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe related to a subset of conversions grouped by some temporal entity (day/week/month)","tags":["Conversions"]}},"/conversions/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Status of conversion (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude conversions created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude conversions created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a count of conversions","tags":["Conversions"]}},"/conversions/{conversionId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Delete conversion specified by id","tags":["Conversions"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Conversions.Conversion"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve conversion specified by id","tags":["Conversions"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Updated body of the conversion","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Conversions.Conversion"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Update conversion specified by id","tags":["Conversions"]}},"/conversions/{conversionId}/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter by this tag name","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this conversion for a timeframe","tags":["Conversions"]}},"/conversions/{conversionId}/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this conversion for a timeframe grouped by some temporal entity (day/week/month)","tags":["Conversions"]}},"/conversions/{conversionId}/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter by this tag name","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a list of datapoints connected to this conversion","tags":["Conversions"]}},"/conversions/{conversionId}/datapoints/batch/patch":{"put":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Patch requests","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PatchBodyBatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Modify the association between a conversion and multiple datapoints","tags":["Conversions"]}},"/conversions/{conversionId}/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Type of datapoint (\"tl\"/\"tp\")","in":"query","name":"type","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","in":"query","name":"status","required":false,"type":"string"},{"description":"Filter by this tag name","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a count of datapoints connected to this conversion","tags":["Conversions"]}},"/conversions/{conversionId}/datapoints/patch":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Patch request","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.ConversionPatchBody"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Modify the association between a conversion and a datapoint","tags":["Conversions"]}},"/conversions/{conversionId}/hits":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Offset where to start from (it's the lastKey field in the response object)","in":"query","name":"offset","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitListPage"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the list of events related to this conversion.","tags":["Conversions"]}},"/conversions/{conversionId}/notes":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Patch requests","in":"body","name":"note","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.GenericTextPatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast patch the \"notes\" field of a conversion","tags":["Conversions"]}},"/conversions/{conversionId}/reports":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Type of the report.","enum":["datapoints","groups","browsers","browsersfamilies","platforms","cities","countries","keywords","referrers","convparameters","destinations","languages","params"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","beginning","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Type of the event you want to filter this report with. By default no filter is applied.","enum":["clicks","views"],"in":"query","name":"hittype","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tops.Top"}},"401":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a top report connected to this conversion","tags":["Conversions"]}},"/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the datapoints associated to the user","tags":["DataPoints"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the datapoint","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a datapoint","tags":["DataPoints"]}},"/datapoints/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint is marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe by groups","tags":["DataPoints"]}},"/datapoints/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint is marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about all datapoints of this customer for a timeframe grouped by some temporal entity (day/week/month)","tags":["DataPoints"]}},"/datapoints/batch":{"delete":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"A json containing the datapoints to delete.","in":"body","name":"batch","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.DeleteBatch"}}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Delete multiple datapoints","tags":["DataPoints"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"A json containing the datapoints to update.","in":"body","name":"batch","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.DatapointsBatch"}}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Update multiple datapoints","tags":["DataPoints"]},"put":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"A json containing the datapoints to create.","in":"body","name":"batch","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.DatapointsBatch"}}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create multiple datapoints","tags":["DataPoints"]}},"/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the datapoints associated to the user","tags":["DataPoints"]}},"/datapoints/{id}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Delete a datapoint","tags":["DataPoints"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Get a datapoint","tags":["DataPoints"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The body of the datapoint","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Update a datapoint","tags":["DataPoints"]}},"/datapoints/{id}/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this datapoint for a timeframe","tags":["DataPoints"]}},"/datapoints/{id}/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this datapoint for a timeframe grouped by some temporal entity (day/week/month)","tags":["DataPoints"]}},"/datapoints/{id}/favourite":{"put":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast switch the \"favourite\" field of a datapoint","tags":["DataPoints"]}},"/datapoints/{id}/hits":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Offset where to start from (it's the lastKey field in the response object)","in":"query","name":"offset","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitListPage"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the list of events related to this datapoint.","tags":["DataPoints"]}},"/datapoints/{id}/notes":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Patch requests","in":"body","name":"note","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.GenericTextPatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast patch the \"notes\" field of a datapoint","tags":["DataPoints"]}},"/datapoints/{id}/reports":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Type of the report.","enum":["browsers","browsersfamilies","platforms","cities","countries","isps","ips","oss","ossfamilies","keywords","referrers","destinations","languages","params"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","beginning","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tops.Top"}},"401":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a top report connected to this datapoint","tags":["DataPoints"]}},"/domains":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"default":"system","description":"Type of domain (\"system\"/\"go\"/\"personal\"/\"dedicated\"). If not specified default is \"system\"","enum":["system","go","personal","dedicated"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Filter domains with this anmen","in":"query","name":"name","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a list of domains","tags":["Domains"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The domain to create","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Domains.Domain"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Create a domain","tags":["Domains"]}},"/domains/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":"system","description":"Type of domain (\"system\"/\"go\"/\"personal\"/\"dedicated\"). If not specified default is \"system\"","enum":["system","go","personal","dedicated"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Filter domains with this anmen","in":"query","name":"name","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve count of domains","tags":["Domains"]}},"/domains/{id}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of domain","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete a domain","tags":["Domains"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of domain","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Domains.Domain"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Get a domain","tags":["Domains"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of domain","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The domain to update","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Domains.Domain"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Update a domain","tags":["Domains"]}},"/groups":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Status of the group","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude groups created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude groups created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"},{"description":"Write permission","in":"query","name":"write","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the groups associated to the user.","tags":["Groups"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the group","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Groups.Group"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a group","tags":["Groups"]}},"/groups/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"},{"description":"Status of group (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the group is marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe by groups","tags":["Groups"]}},"/groups/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of group (\"deleted\"/\"active\")","in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the group is marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["deleted","active"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about all groups of this customer for a timeframe grouped by some temporal entity (day/week/month)","tags":["Groups"]}},"/groups/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Status of the datapoint","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude groups created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude groups created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"},{"description":"Write permission","in":"query","name":"write","required":false,"type":"boolean"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the groups associated to the user.","tags":["Groups"]}},"/groups/{id}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Delete group specified by id","tags":["Groups"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Groups.Group"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Get a group","tags":["Groups"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The body of the group","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Groups.Group"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Update a group","tags":["Groups"]}},"/groups/{id}/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this group for a timeframe","tags":["Groups"]}},"/groups/{id}/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this group for a timeframe grouped by some temporal entity (day/week/month)","tags":["Groups"]}},"/groups/{id}/aggregated/summary":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Filter by this group id","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"default":0,"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about a subset of datapoints for a timeframe with datapoints data","tags":["Groups"]}},"/groups/{id}/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the datapoints associated to the user in this group.","tags":["Groups"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The body of the datapoint","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a datapoint in this group","tags":["Groups"]}},"/groups/{id}/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the datapoints associated to the user in this group.","tags":["Groups"]}},"/groups/{id}/favourite":{"put":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast switch the \"favourite\" field of a group","tags":["Groups"]}},"/groups/{id}/hits":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Offset where to start from (it's the lastKey field in the response object)","in":"query","name":"offset","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitListPage"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the list of events related to this group.","tags":["Groups"]}},"/groups/{id}/notes":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Patch requests","in":"body","name":"note","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.GenericTextPatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast patch the \"notes\" field of a group","tags":["Groups"]}},"/groups/{id}/reports":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Type of the report.","enum":["browsers","browsersfamilies","platforms","cities","countries","isps","ips","oss","ossfamilies","keywords","referrers","destinations","languages","params"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","beginning","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Type of the event you want to filter this report with. By default no filter is applied.","enum":["clicks","views"],"in":"query","name":"hittype","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tops.Top"}},"401":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a top report connected to this group","tags":["Groups"]}},"/hits":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Limit results to this number","format":"int32","in":"query","name":"limit","required":false,"type":"integer"},{"description":"Offset where to start from (it's the lastKey field in the response object)","in":"query","name":"offset","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitListPage"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the list of events related to this account.","tags":["Hits"]}},"/me":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.User"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve current account data","tags":["Me"]}},"/me/plan":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Plan"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve current account plan","tags":["Me"]}},"/reports":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Type of the report.","enum":["browsers","browsersfamilies","platforms","cities","countries","isps","ips","oss","ossfamilies","keywords","referrers","destinations","languages","params"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","beginning","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Type of the event you want to filter this report with. By default no filter is applied.","in":"query","name":"hittype","required":false,"type":"string"},{"description":"Filter by this group id (mutually exclusive with \"datapoint\" and \"conversion\")","format":"int64","in":"query","name":"group","required":false,"type":"integer"},{"description":"Filter by this datapoint id (mutually exclusive with \"group\" and \"conversion\")","format":"int64","in":"query","name":"datapoint","required":false,"type":"integer"},{"description":"Filter by this conversion id (mutually exclusive with \"datapoint\" and \"group\")","format":"int64","in":"query","name":"conversion","required":false,"type":"integer"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tops.Top"}},"401":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a top report","tags":["Reports"]}},"/retargeting":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the retargeting scripts associated to the user","tags":["Retargeting"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the retargeting script","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Retargeting.RetargetingScript"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Creates a retargeting script","tags":["Retargeting"]}},"/retargeting/count":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve count of retargeting scripts","tags":["Retargeting"]}},"/retargeting/{id}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the retargeting script","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Deletes a retargeting script (and remove associations)","tags":["Retargeting"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the retargeting script","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Retargeting.RetargetingScript"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Get a retargeting script object","tags":["Retargeting"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The id of the retargeting script","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The body of the retargeting script","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Retargeting.RetargetingScript"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Updates a retargeting script","tags":["Retargeting"]}},"/retargeting/{id}/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the retargeting script","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the datapoints associated to the retargeting script.","tags":["Retargeting"]}},"/retargeting/{id}/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the datapoints associated to the retargeting script.","tags":["Retargeting"]}},"/tags":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Name of the tag","in":"query","name":"name","required":false,"type":"string"},{"description":"Comma separated list of datapoints id to filter by","in":"query","name":"datapoints","required":false,"type":"string"},{"description":"Comma separated list of groups id to filter by","in":"query","name":"groups","required":false,"type":"string"},{"description":"Type of entity related to the tag","enum":["tp","tl","dp","gr"],"in":"query","name":"type","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the groups associated to the user filtered by this tag.","tags":["Tags"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the tag","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a tag","tags":["Tags"]}},"/tags/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Name of the tag","in":"query","name":"name","required":false,"type":"string"},{"description":"Comma separated list of datapoints id to filter by","in":"query","name":"datapoints","required":false,"type":"string"},{"description":"Comma separated list of groups id to filter by","in":"query","name":"groups","required":false,"type":"string"},{"description":"Type of entity related to the tag","enum":["tp","tl","dp","gr"],"in":"query","name":"type","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/System.Object"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the groups associated to the user filtered by this tag.","tags":["Tags"]}},"/tags/{tagId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/System.Object"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete a tag","tags":["Tags"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a tag","tags":["Tags"]}},"/tags/{tagId}/datapoints":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete the association of this tag with all datapoints","tags":["Tags"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag.","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the datapoints associated to the user filtered by this tag","tags":["Tags"]}},"/tags/{tagId}/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag.","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the datapoints associated to the user filtered by this tag","tags":["Tags"]}},"/tags/{tagId}/datapoints/patch":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"The body patch","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PatchBody"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Associate/Deassociate a tag with a datapoint","tags":["Tags"]}},"/tags/{tagId}/groups":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete the association of this tag with all groups","tags":["Tags"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag.","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Status of the datapoint","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude groups created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude groups created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the groups associated to the user filtered by this tag.","tags":["Tags"]}},"/tags/{tagId}/groups/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag.","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"Status of the datapoint","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude groups created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude groups created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the groups associated to the user filtered by this tag","tags":["Tags"]}},"/tags/{tagId}/groups/patch":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"The body patch","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PatchBody"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Associate/Deassociate a tag with a group","tags":["Tags"]}},"/tags/{tagId}/name":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"The body patch","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.GenericTextPatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Fast patch a tag name","tags":["Tags"]}}},"definitions":{"Api.Core.Dto.Accounting.ConversionOptions":{"properties":{"hideComCost":{"type":"boolean"},"hideCost":{"type":"boolean"},"hideCount":{"type":"boolean"},"hideParams":{"type":"boolean"},"hideValue":{"type":"boolean"},"percentCommission":{"format":"int32","type":"integer"},"percentValue":{"format":"int32","type":"integer"}},"type":"object"},"Api.Core.Dto.Accounting.DomainWhitelistEntry":{"properties":{"id":{"type":"string"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.Accounting.ExtendedGrants":{"properties":{"allowAllGrants":{"type":"boolean"},"allowGroupCreation":{"type":"boolean"}},"type":"object"},"Api.Core.Dto.Accounting.Guest":{"properties":{"apiKey":{"type":"string"},"conversionOptions":{"$ref":"#/definitions/Api.Core.Dto.Accounting.ConversionOptions"},"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"currentGrant":{"$ref":"#/definitions/Api.Core.Dto.Grants.Grant"},"dateFormat":{"type":"string"},"decimalSeparator":{"type":"string"},"email":{"type":"string"},"extendedGrants":{"$ref":"#/definitions/Api.Core.Dto.Accounting.ExtendedGrants"},"groupGrants":{"format":"int64","type":"integer"},"hitOptions":{"$ref":"#/definitions/Api.Core.Dto.Accounting.HitOptions"},"id":{"format":"int64","type":"integer"},"key":{"type":"string"},"language":{"type":"string"},"loginCount":{"format":"int32","type":"integer"},"name":{"type":"string"},"notes":{"type":"string"},"numberGroupSeparator":{"type":"string"},"password":{"type":"string"},"timeFormat":{"enum":["AmPm","H24"],"type":"string"},"timeZone":{"format":"int32","type":"integer"},"timeframeMinDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"timezonename":{"type":"string"},"tlGrants":{"format":"int64","type":"integer"},"tpGrants":{"format":"int64","type":"integer"},"userName":{"type":"string"}},"type":"object"},"Api.Core.Dto.Accounting.HitOptions":{"properties":{"hideReferrer":{"type":"boolean"}},"type":"object"},"Api.Core.Dto.Accounting.IpBlacklistEntry":{"properties":{"id":{"type":"string"},"ip":{"type":"string"}},"type":"object"},"Api.Core.Dto.Accounting.Plan":{"properties":{"allowedPersonalDomains":{"format":"int32","type":"integer"},"allowedPersonalUrls":{"format":"int32","type":"integer"},"billingPeriodEnd":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"billingPeriodStart":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"bonusMonthlyEvents":{"format":"int64","type":"integer"},"maximumDatapoints":{"format":"int64","type":"integer"},"maximumGuests":{"format":"int64","type":"integer"},"monthlyEvents":{"format":"int64","type":"integer"},"name":{"type":"string"},"price":{"format":"double","type":"number"},"profileId":{"format":"int64","type":"integer"},"recurring":{"type":"boolean"},"recurringPeriod":{"format":"int32","type":"integer"},"usedDatapoints":{"format":"int64","type":"integer"},"usedMonthlyEvents":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Dto.Accounting.User":{"properties":{"boGoVal":{"type":"string"},"bonusClicks":{"format":"int64","type":"integer"},"companyName":{"type":"string"},"companyRole":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"phone":{"type":"string"},"redirectOnly":{"type":"boolean"},"registrationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"timeframeMinDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"timezone":{"format":"int32","type":"integer"},"timezonename":{"type":"string"}},"type":"object"},"Api.Core.Dto.Aggregated.AggregatedResult":{"properties":{"activityDay":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"commissionsCost":{"format":"double","type":"number"},"conversionsCost":{"format":"double","type":"number"},"conversionsValue":{"format":"double","type":"number"},"convertedClicks":{"format":"int64","type":"integer"},"entityData":{"$ref":"#/definitions/System.Object"},"entityId":{"type":"string"},"fromDay":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"hourlyBreakDown":{"additionalProperties":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"},"type":"object"},"lastHitDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"spiderHitsCount":{"format":"int64","type":"integer"},"toDay":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"totalClicks":{"format":"int64","type":"integer"},"totalViews":{"format":"int64","type":"integer"},"uniqueClicks":{"format":"int64","type":"integer"},"uniqueConversions":{"format":"int64","type":"integer"},"uniqueViews":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Dto.Aggregated.AggregatedSummaryResult":{"properties":{"count":{"format":"int64","type":"integer"},"limit":{"format":"int32","type":"integer"},"offset":{"format":"int64","type":"integer"},"result":{"items":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"},"type":"array"}},"type":"object"},"Api.Core.Dto.ClickStream.Hit":{"properties":{"accessTime":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"browser":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitBrowserInfo"},"clientLanguage":{"type":"string"},"conversion1":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversion2":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversion3":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversion4":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversion5":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversions":{"items":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"type":"array"},"entity":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitDatapointInfo"},"ip":{"type":"string"},"isProxy":{"type":"string"},"isSpider":{"type":"string"},"isUnique":{"type":"string"},"location":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitLocationInfo"},"org":{"type":"string"},"os":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitOsInfo"},"queryParams":{"type":"string"},"realDestinationUrl":{"type":"string"},"referer":{"type":"string"},"source":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitSource"},"type":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitBrowserInfo":{"properties":{"browserType":{"type":"string"},"familyId":{"format":"int64","type":"integer"},"familyName":{"type":"string"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitConversionInfo":{"properties":{"accessTime":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"comcost":{"format":"double","type":"number"},"cost":{"format":"double","type":"number"},"date":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"deleted":{"type":"boolean"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"parameter":{"type":"string"},"value":{"format":"double","type":"number"}},"type":"object"},"Api.Core.Dto.ClickStream.HitDatapointInfo":{"properties":{"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"datapointFavourite":{"type":"boolean"},"datapointId":{"format":"int64","type":"integer"},"datapointName":{"type":"string"},"datapointTitle":{"type":"string"},"datapointType":{"type":"string"},"destinationUrl":{"type":"string"},"groupId":{"format":"int64","type":"integer"},"groupName":{"type":"string"},"isABTest":{"type":"boolean"},"isPrivateShared":{"type":"boolean"},"isPublic":{"type":"boolean"},"notes":{"type":"string"},"status":{"enum":["Active","Paused","Abuse","Deleted"],"type":"string"},"tags":{"items":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"},"type":"array"},"trackingCode":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitListPage":{"properties":{"hits":{"items":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.Hit"},"type":"array"},"lastKey":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitLocationInfo":{"properties":{"areacode":{"type":"string"},"city":{"type":"string"},"country":{"type":"string"},"latitude":{"format":"double","type":"number"},"longitude":{"format":"double","type":"number"},"metrocode":{"type":"string"},"organization":{"type":"string"},"postalcode":{"type":"string"},"region":{"type":"string"},"regionName":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitOsInfo":{"properties":{"familyId":{"format":"int64","type":"integer"},"familyName":{"type":"string"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitSource":{"properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"param":{"type":"string"}},"type":"object"},"Api.Core.Dto.Conversions.Conversion":{"properties":{"code":{"type":"string"},"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"deleted":{"type":"boolean"},"description":{"type":"string"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"protocol":{"enum":["Http","Https"],"type":"string"},"value":{"format":"double","type":"number"}},"type":"object"},"Api.Core.Dto.Datapoints.BrowserBaseDestinationItem":{"properties":{"emailDestinationUrl":{"type":"string"},"mobileDestinationUrl":{"type":"string"},"spidersDestinationUrl":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.Datapoint":{"properties":{"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"encodeIp":{"type":"boolean"},"fifthConversionId":{"format":"int64","type":"integer"},"fifthConversionName":{"type":"string"},"firstConversionId":{"format":"int64","type":"integer"},"firstConversionName":{"type":"string"},"fourthConversionId":{"format":"int64","type":"integer"},"fourthConversionName":{"type":"string"},"groupId":{"format":"int64","type":"integer"},"groupName":{"type":"string"},"id":{"format":"int64","type":"integer"},"isPublic":{"type":"boolean"},"isSecured":{"type":"boolean"},"lightTracking":{"type":"boolean"},"name":{"type":"string"},"notes":{"type":"string"},"preferred":{"type":"boolean"},"redirectOnly":{"type":"boolean"},"secondConversionId":{"format":"int64","type":"integer"},"secondConversionName":{"type":"string"},"status":{"enum":["Active","Paused","Abuse","Deleted"],"type":"string"},"tags":{"items":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"},"type":"array"},"thirdConversionId":{"format":"int64","type":"integer"},"thirdConversionName":{"type":"string"},"title":{"type":"string"},"trackingCode":{"type":"string"},"type":{"enum":["TrackingLink","TrackingPixel"],"type":"string"},"typeTL":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.TrackingLinkSpecifics"},"typeTP":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.TrackingPixelSpecifics"},"writePermited":{"type":"boolean"}},"type":"object"},"Api.Core.Dto.Datapoints.DatapointRetargetingInfo":{"properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.MultipleDestinationItem":{"properties":{"url":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.TrackingLinkSpecifics":{"properties":{"appendQuery":{"type":"boolean"},"browserDestinationItem":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.BrowserBaseDestinationItem"},"destinationMode":{"enum":["Simple","RandomDestination","DestinationByLanguage","SpilloverDestination","DynamicUrl","BrowserDestination","DestinationByNation","UniqueDestination","SequentialDestination","WeightedDestination"],"type":"string"},"domainId":{"format":"int32","type":"integer"},"encodeUrl":{"type":"boolean"},"expirationClicks":{"format":"int64","type":"integer"},"expirationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"firstUrl":{"type":"string"},"goDomainId":{"format":"int32","type":"integer"},"hideUrl":{"type":"boolean"},"hideUrlTitle":{"type":"string"},"isABTest":{"type":"boolean"},"password":{"type":"string"},"pauseAfterClicksExpiration":{"type":"boolean"},"pauseAfterDateExpiration":{"type":"boolean"},"randomDestinationItems":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem"},"type":"array"},"redirectType":{"enum":["PermanentRedirect","TemporaryRedirect"],"type":"string"},"referrerClean":{"enum":["None","Clean","Myself"],"type":"string"},"scripts":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.DatapointRetargetingInfo"},"type":"array"},"sequentialDestinationItems":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem"},"type":"array"},"spilloverDestinationItems":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem"},"type":"array"},"uniqueDestinationItem":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.UniqueDestinationItem"},"url":{"type":"string"},"urlAfterClicksExpiration":{"type":"string"},"urlAfterDateExpiration":{"type":"string"},"urlsByLanguage":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.UrlByLanguageItem"},"type":"array"},"urlsByNation":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.UrlByNationItem"},"type":"array"},"weightedDestinationItems":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.WeightedDestinationItem"},"type":"array"}},"type":"object"},"Api.Core.Dto.Datapoints.TrackingPixelSpecifics":{"properties":{"parameterNote":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.UniqueDestinationItem":{"properties":{"firstDestinationUrl":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.UrlByLanguageItem":{"properties":{"languageCode":{"type":"string"},"url":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.UrlByNationItem":{"properties":{"nation":{"type":"string"},"url":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.WeightedDestinationItem":{"properties":{"url":{"type":"string"},"weight":{"format":"int32","type":"integer"}},"type":"object"},"Api.Core.Dto.Domains.Domain":{"properties":{"custom404":{"type":"string"},"customHomepage":{"type":"string"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"type":{"enum":["System","Go","Dedicated","Personal"],"type":"string"}},"type":"object"},"Api.Core.Dto.EntityUriLong":{"properties":{"id":{"format":"int64","type":"integer"},"uri":{"type":"string"}},"type":"object"},"Api.Core.Dto.Grants.Grant":{"properties":{"DatapointType":{"type":"string"},"Entity":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"},"EntityName":{"type":"string"},"EntityType":{"type":"string"},"Type":{"type":"string"}},"type":"object"},"Api.Core.Dto.Groups.Group":{"properties":{"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"deleted":{"type":"boolean"},"id":{"format":"int64","type":"integer"},"isPublic":{"type":"boolean"},"name":{"type":"string"},"notes":{"type":"string"},"preferred":{"type":"boolean"},"redirectOnly":{"type":"boolean"},"tags":{"items":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"},"type":"array"},"writePermited":{"type":"boolean"}},"type":"object"},"Api.Core.Dto.Retargeting.RetargetingScript":{"properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"script":{"type":"string"}},"type":"object"},"Api.Core.Dto.Tags.Tag":{"properties":{"datapoints":{"items":{"format":"int64","type":"integer"},"type":"array"},"groups":{"items":{"format":"int64","type":"integer"},"type":"array"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.Tops.Top":{"properties":{"createdAt":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"data":{"items":{"$ref":"#/definitions/Api.Core.Dto.Tops.TopItem"},"type":"array"},"key":{"type":"string"}},"type":"object"},"Api.Core.Dto.Tops.TopItem":{"properties":{"entityData":{"$ref":"#/definitions/System.Object"},"id":{"type":"string"},"lastHitDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"spiderClicks":{"format":"int64","type":"integer"},"spiderHits":{"format":"int64","type":"integer"},"spiderViews":{"format":"int64","type":"integer"},"totalClicks":{"format":"int64","type":"integer"},"totalCommissionsCost":{"format":"double","type":"number"},"totalConversions":{"format":"int64","type":"integer"},"totalConversionsCost":{"format":"double","type":"number"},"totalConversionsValue":{"format":"double","type":"number"},"totalHits":{"format":"int64","type":"integer"},"totalViews":{"format":"int64","type":"integer"},"uniqueClicks":{"format":"int64","type":"integer"},"uniqueHits":{"format":"int64","type":"integer"},"uniqueViews":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Requests.ConversionPatchBody":{"properties":{"Action":{"type":"string"},"Id":{"format":"int64","type":"integer"},"ReplaceId":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Requests.DatapointsBatch":{"properties":{"List":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"},"type":"array"}},"type":"object"},"Api.Core.Requests.DeleteBatch":{"properties":{"Entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.EntityUriLong"},"type":"array"}},"type":"object"},"Api.Core.Requests.GenericTextPatch":{"properties":{"Text":{"type":"string"}},"type":"object"},"Api.Core.Requests.PatchBody":{"properties":{"Action":{"type":"string"},"Id":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Requests.PatchBodyBatch":{"properties":{"PatchRequests":{"items":{"$ref":"#/definitions/Api.Core.Requests.PatchBody"},"type":"array"}},"type":"object"},"Api.Core.Requests.PermissionPatchRequest":{"properties":{"Action":{"type":"string"},"Id":{"format":"int64","type":"integer"},"Verb":{"type":"string"}},"type":"object"},"Api.Core.Responses.CountResponce":{"properties":{"count":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.DomainWhitelistEntry]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.IpBlacklistEntry]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.ClickStream.Hit]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.Hit"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Grants.Grant]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.Grants.Grant"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntityUri[System.Int64]":{"properties":{"id":{"format":"int64","type":"integer"},"uri":{"type":"string"}},"type":"object"},"Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]":{"properties":{"entityData":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"},"errors":{"items":{"$ref":"#/definitions/ClickMeter.Infrastructure.Validation.ValidationFailure"},"type":"array"},"result":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"},"status":{"type":"string"}},"type":"object"},"ClickMeter.Infrastructure.Validation.ValidationFailure":{"properties":{"code":{"$ref":"#/definitions/System.Object"},"errorMessage":{"type":"string"},"errorValue":{"$ref":"#/definitions/System.Object"},"property":{"type":"string"}},"type":"object"},"System.Object":{"properties":{},"type":"object"}}} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.yaml b/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.yaml new file mode 100644 index 00000000..0ce32b1a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.yaml @@ -0,0 +1,6461 @@ +swagger: '2.0' +schemes: + - http + - https +host: 'apiv2.clickmeter.com:80' +info: + contact: + email: api@clickmeter.com + name: Api Support + url: 'http://www.clickmeter.com/api' + description: Api dashboard for ClickMeter API + title: ClickMeter + version: v2 + x-logo: + url: 'https://s3.amazonaws.com/clickmeter.com/Web/static/cmlogo.svg' + x-origin: + format: swagger + url: 'http://api.v2.clickmeter.com.s3.amazonaws.com/docs/api-docs-v2.json' + version: '2.0' + x-providerName: clickmeter.com +securityDefinitions: + api_key: + description: API Key Authentication + in: header + name: X-Clickmeter-AuthKey + type: apiKey +security: + - api_key: [] +paths: + /account: + get: + consumes: [] + deprecated: false + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.User' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve current account data + tags: + - Account + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.User' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.User' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Update current account data + tags: + - Account + /account/domainwhitelist: + get: + consumes: [] + deprecated: false + parameters: + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.DomainWhitelistEntry]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve list of a domains allowed to redirect in DDU mode + tags: + - Account + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The entry to add + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Create an domain entry + tags: + - Account + '/account/domainwhitelist/{whitelistId}': + delete: + consumes: [] + deprecated: false + parameters: + - description: The id of the domain to delete + in: path + name: whitelistId + required: true + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Delete an domain entry + tags: + - Account + /account/guests: + get: + consumes: [] + deprecated: false + parameters: + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Field to sort by + in: query + name: sortBy + required: false + type: string + - description: 'Direction of sort "asc" or "desc"' + enum: + - asc + - desc + in: query + name: sortDirection + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve list of a guest + tags: + - Account + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Guest object to create + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Create a guest + tags: + - Account + /account/guests/count: + get: + consumes: [] + deprecated: false + parameters: + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve count of guests + tags: + - Account + '/account/guests/{guestId}': + delete: + consumes: [] + deprecated: false + parameters: + - description: Id of the guest + format: int64 + in: path + name: guestId + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Delete a guest + tags: + - Account + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the guest + format: int64 + in: path + name: guestId + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve a guest + tags: + - Account + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the guest + format: int64 + in: path + name: guestId + required: true + type: integer + - description: Guest object with field updated + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Update a guest + tags: + - Account + '/account/guests/{guestId}/permissions': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the guest + format: int64 + in: path + name: guestId + required: true + type: integer + - description: 'Can be "datapoint" or "group"' + enum: + - datapoint + - group + in: query + name: entityType + required: false + type: string + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: 'Can be "w" or "r"' + enum: + - r + - w + in: query + name: type + required: false + type: string + - description: Optional id of the datapoint/group entity to filter by + format: int64 + in: query + name: entityId + required: false + type: integer + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Grants.Grant]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve permissions for a guest + tags: + - Account + '/account/guests/{guestId}/permissions/count': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the guest + format: int64 + in: path + name: guestId + required: true + type: integer + - description: 'Can be "datapoint" or "group"' + enum: + - datapoint + - group + in: query + name: entityType + required: false + type: string + - description: 'Can be "w" or "r"' + enum: + - r + - w + in: query + name: type + required: false + type: string + - description: Optional id of the datapoint/group entity to filter by + format: int64 + in: query + name: entityId + required: false + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve count of the permissions for a guest + tags: + - Account + '/account/guests/{guestId}/{type}/permissions/patch': + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the guest + format: int64 + in: path + name: guestId + required: true + type: integer + - description: 'Can be "datapoint" or "group"' + enum: + - datapoint + - group + in: path + name: type + required: true + type: string + - description: The patch permission request + in: body + name: body + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.PermissionPatchRequest' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Change the permission on a shared object + tags: + - Account + put: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the guest + format: int64 + in: path + name: guestId + required: true + type: integer + - description: 'Can be "datapoint" or "group"' + enum: + - datapoint + - group + in: path + name: type + required: true + type: string + - description: The patch permission request + in: body + name: body + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.PermissionPatchRequest' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Change the permission on a shared object + tags: + - Account + /account/ipblacklist: + get: + consumes: [] + deprecated: false + parameters: + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.IpBlacklistEntry]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve list of a ip to exclude from event tracking + tags: + - Account + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The entry to add + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Create an ip blacklist entry + tags: + - Account + '/account/ipblacklist/{blacklistId}': + delete: + consumes: [] + deprecated: false + parameters: + - description: The id of the ip to delete + in: path + name: blacklistId + required: true + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Delete an ip blacklist entry + tags: + - Account + /account/plan: + get: + consumes: [] + deprecated: false + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.Plan' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve current account plan + tags: + - Account + /aggregated: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' + in: query + name: hourly + required: false + type: boolean + - description: '' + in: query + name: onlyFavorites + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this customer for a timeframe + tags: + - Aggregated + /aggregated/list: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' + enum: + - week + - month + in: query + name: groupBy + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this customer for a timeframe grouped by some temporal entity (day/week/month) + tags: + - Aggregated + /aggregated/summary/conversions: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Status of conversion ("deleted"/"active")' + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: Field to sort by + in: query + name: sortBy + required: false + type: string + - description: 'Direction of sort "asc" or "desc"' + enum: + - asc + - desc + in: query + name: sortDirection + required: false + type: string + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about a subset of conversions for a timeframe with conversions data + tags: + - Aggregated + /aggregated/summary/datapoints: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'Type of datapoint ("tl"/"tp")' + enum: + - tp + - tl + in: query + name: type + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tag + required: false + type: string + - description: Is the datapoint marked as favourite + in: query + name: favourite + required: false + type: boolean + - description: Field to sort by + in: query + name: sortBy + required: false + type: string + - description: 'Direction of sort "asc" or "desc"' + enum: + - asc + - desc + in: query + name: sortDirection + required: false + type: string + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Filter by this group id + format: int64 + in: query + name: groupId + required: false + type: integer + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about a subset of datapoints for a timeframe with datapoints data + tags: + - Aggregated + /aggregated/summary/groups: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Status of group ("deleted"/"active")' + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tag + required: false + type: string + - description: Is the group marked as favourite + in: query + name: favourite + required: false + type: boolean + - description: Field to sort by + in: query + name: sortBy + required: false + type: string + - description: 'Direction of sort "asc" or "desc"' + enum: + - asc + - desc + in: query + name: sortDirection + required: false + type: string + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about a subset of groups for a timeframe with groups data + tags: + - Aggregated + /clickstream: + get: + consumes: [] + deprecated: false + parameters: + - description: 'Filter by this group id (mutually exclusive with "datapoint" and "conversion")' + format: int64 + in: query + name: group + required: false + type: integer + - description: 'Filter by this datapoint id (mutually exclusive with "group" and "conversion")' + format: int64 + in: query + name: datapoint + required: false + type: integer + - description: 'Filter by this conversion id (mutually exclusive with "datapoint" and "group")' + format: int64 + in: query + name: conversion + required: false + type: integer + - default: 50 + description: Limit results to this number + format: int32 + in: query + name: pageSize + required: false + type: integer + - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' + enum: + - '' + - spiders + - uniques + - nonuniques + - conversions + in: query + name: filter + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.ClickStream.Hit]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve the latest list of events of this account. Limited to last 100. + tags: + - ClickStream + /conversions: + get: + consumes: [] + deprecated: false + parameters: + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: 'Status of conversion ("deleted"/"active")' + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude conversions created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude conversions created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve a list of conversions + tags: + - Conversions + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The body of the conversion + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Conversions.Conversion' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Create a conversion + tags: + - Conversions + /conversions/aggregated/list: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Status of conversion ("deleted"/"active")' + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' + enum: + - week + - month + in: query + name: groupBy + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this customer for a timeframe related to a subset of conversions grouped by some temporal entity (day/week/month) + tags: + - Conversions + /conversions/count: + get: + consumes: [] + deprecated: false + parameters: + - description: 'Status of conversion ("deleted"/"active")' + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude conversions created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude conversions created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve a count of conversions + tags: + - Conversions + '/conversions/{conversionId}': + delete: + consumes: [] + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Delete conversion specified by id + tags: + - Conversions + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Conversions.Conversion' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Retrieve conversion specified by id + tags: + - Conversions + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Updated body of the conversion + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Conversions.Conversion' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Update conversion specified by id + tags: + - Conversions + '/conversions/{conversionId}/aggregated': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: Filter by this tag name + in: query + name: tag + required: false + type: string + - description: Is the datapoint marked as favourite + in: query + name: favourite + required: false + type: boolean + - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' + in: query + name: hourly + required: false + type: boolean + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this conversion for a timeframe + tags: + - Conversions + '/conversions/{conversionId}/aggregated/list': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' + enum: + - week + - month + in: query + name: groupBy + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this conversion for a timeframe grouped by some temporal entity (day/week/month) + tags: + - Conversions + '/conversions/{conversionId}/datapoints': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: 'Type of datapoint ("tl"/"tp")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: Filter by this tag name + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve a list of datapoints connected to this conversion + tags: + - Conversions + '/conversions/{conversionId}/datapoints/batch/patch': + put: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Patch requests + in: body + name: data + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.PatchBodyBatch' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Modify the association between a conversion and multiple datapoints + tags: + - Conversions + '/conversions/{conversionId}/datapoints/count': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: 'Type of datapoint ("tl"/"tp")' + in: query + name: type + required: false + type: string + - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' + in: query + name: status + required: false + type: string + - description: Filter by this tag name + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve a count of datapoints connected to this conversion + tags: + - Conversions + '/conversions/{conversionId}/datapoints/patch': + put: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Patch request + in: body + name: data + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.ConversionPatchBody' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Modify the association between a conversion and a datapoint + tags: + - Conversions + '/conversions/{conversionId}/hits': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - custom + in: query + name: timeframe + required: true + type: string + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: "Offset where to start from (it's the lastKey field in the response object)" + in: query + name: offset + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' + enum: + - spiders + - uniques + - nonuniques + - conversions + in: query + name: filter + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitListPage' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve the list of events related to this conversion. + tags: + - Conversions + '/conversions/{conversionId}/notes': + put: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Patch requests + in: body + name: note + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.GenericTextPatch' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '403': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: 'Fast patch the "notes" field of a conversion' + tags: + - Conversions + '/conversions/{conversionId}/reports': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the conversion + format: int64 + in: path + name: conversionId + required: true + type: integer + - description: Type of the report. + enum: + - datapoints + - groups + - browsers + - browsersfamilies + - platforms + - cities + - countries + - keywords + - referrers + - convparameters + - destinations + - languages + - params + in: query + name: type + required: true + type: string + - description: Timeframe of the request. See list at $timeframeList + enum: + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - beginning + - custom + in: query + name: timeframe + required: true + type: string + - description: Type of the event you want to filter this report with. By default no filter is applied. + enum: + - clicks + - views + in: query + name: hittype + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Tops.Top' + '401': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: Retrieve a top report connected to this conversion + tags: + - Conversions + /datapoints: + get: + consumes: [] + deprecated: false + parameters: + - default: 0 + description: Where to start when retrieving elements. Default is 0 if not specified. + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Maximum elements to retrieve. Default to 20 if not specified. + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: 'Type of the datapoint ("tp"/"tl")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: Status of the datapoint + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Filter fields by favourite status + in: query + name: onlyFavorites + required: false + type: boolean + - description: Field to sort by + in: query + name: sortBy + required: false + type: string + - description: 'Direction of sort "asc" or "desc"' + enum: + - asc + - desc + in: query + name: sortDirection + required: false + type: string + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the datapoints associated to the user + tags: + - DataPoints + post: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The body of the datapoint + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Create a datapoint + tags: + - DataPoints + /datapoints/aggregated: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'Type of datapoint ("tl"/"tp")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' + in: query + name: hourly + required: false + type: boolean + - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tag + required: false + type: string + - description: Is the datapoint is marked as favourite + in: query + name: favourite + required: false + type: boolean + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this customer for a timeframe by groups + tags: + - DataPoints + /datapoints/aggregated/list: + get: + consumes: [] + deprecated: false + parameters: + - description: 'Type of datapoint ("tl"/"tp")' + enum: + - tp + - tl + in: query + name: type + required: true + type: string + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tag + required: false + type: string + - description: Is the datapoint is marked as favourite + in: query + name: favourite + required: false + type: boolean + - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' + enum: + - week + - month + in: query + name: groupBy + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about all datapoints of this customer for a timeframe grouped by some temporal entity (day/week/month) + tags: + - DataPoints + /datapoints/batch: + delete: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: A json containing the datapoints to delete. + in: body + name: batch + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.DeleteBatch' + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Delete multiple datapoints + tags: + - DataPoints + post: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: A json containing the datapoints to update. + in: body + name: batch + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.DatapointsBatch' + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Update multiple datapoints + tags: + - DataPoints + put: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: A json containing the datapoints to create. + in: body + name: batch + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.DatapointsBatch' + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Create multiple datapoints + tags: + - DataPoints + /datapoints/count: + get: + consumes: [] + deprecated: false + parameters: + - description: 'Type of the datapoint ("tp"/"tl")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: Status of the datapoint + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Filter fields by favourite status + in: query + name: onlyFavorites + required: false + type: boolean + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Count the datapoints associated to the user + tags: + - DataPoints + '/datapoints/{id}': + delete: + consumes: [] + deprecated: false + parameters: + - description: The id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Delete a datapoint + tags: + - DataPoints + get: + consumes: [] + deprecated: false + parameters: + - description: The id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Get a datapoint + tags: + - DataPoints + post: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + - description: The body of the datapoint + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Update a datapoint + tags: + - DataPoints + '/datapoints/{id}/aggregated': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' + in: query + name: hourly + required: false + type: boolean + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this datapoint for a timeframe + tags: + - DataPoints + '/datapoints/{id}/aggregated/list': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' + enum: + - week + - month + in: query + name: groupBy + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this datapoint for a timeframe grouped by some temporal entity (day/week/month) + tags: + - DataPoints + '/datapoints/{id}/favourite': + put: + consumes: [] + deprecated: false + parameters: + - description: Id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '403': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: 'Fast switch the "favourite" field of a datapoint' + tags: + - DataPoints + '/datapoints/{id}/hits': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - custom + in: query + name: timeframe + required: true + type: string + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: "Offset where to start from (it's the lastKey field in the response object)" + in: query + name: offset + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' + enum: + - spiders + - uniques + - nonuniques + - conversions + in: query + name: filter + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitListPage' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve the list of events related to this datapoint. + tags: + - DataPoints + '/datapoints/{id}/notes': + put: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + - description: Patch requests + in: body + name: note + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.GenericTextPatch' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '403': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: 'Fast patch the "notes" field of a datapoint' + tags: + - DataPoints + '/datapoints/{id}/reports': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the datapoint + format: int64 + in: path + name: id + required: true + type: integer + - description: Type of the report. + enum: + - browsers + - browsersfamilies + - platforms + - cities + - countries + - isps + - ips + - oss + - ossfamilies + - keywords + - referrers + - destinations + - languages + - params + in: query + name: type + required: true + type: string + - description: Timeframe of the request. See list at $timeframeList + enum: + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - beginning + - custom + in: query + name: timeframe + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Tops.Top' + '401': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: Retrieve a top report connected to this datapoint + tags: + - DataPoints + /domains: + get: + consumes: [] + deprecated: false + parameters: + - description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - default: system + description: 'Type of domain ("system"/"go"/"personal"/"dedicated"). If not specified default is "system"' + enum: + - system + - go + - personal + - dedicated + in: query + name: type + required: false + type: string + - description: Filter domains with this anmen + in: query + name: name + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve a list of domains + tags: + - Domains + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The domain to create + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Domains.Domain' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Create a domain + tags: + - Domains + /domains/count: + get: + consumes: [] + deprecated: false + parameters: + - default: system + description: 'Type of domain ("system"/"go"/"personal"/"dedicated"). If not specified default is "system"' + enum: + - system + - go + - personal + - dedicated + in: query + name: type + required: false + type: string + - description: Filter domains with this anmen + in: query + name: name + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve count of domains + tags: + - Domains + '/domains/{id}': + delete: + consumes: [] + deprecated: false + parameters: + - description: Id of domain + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Delete a domain + tags: + - Domains + get: + consumes: [] + deprecated: false + parameters: + - description: Id of domain + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Domains.Domain' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Get a domain + tags: + - Domains + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of domain + format: int64 + in: path + name: id + required: true + type: integer + - description: The domain to update + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Domains.Domain' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Update a domain + tags: + - Domains + /groups: + get: + consumes: [] + deprecated: false + parameters: + - default: 0 + description: Where to start when retrieving elements. Default is 0 if not specified. + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Maximum elements to retrieve. Default to 20 if not specified. + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Status of the group + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude groups created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude groups created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + - description: Write permission + in: query + name: write + required: false + type: boolean + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the groups associated to the user. + tags: + - Groups + post: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The body of the group + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Groups.Group' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Create a group + tags: + - Groups + /groups/aggregated: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' + in: query + name: hourly + required: false + type: boolean + - description: 'Status of group ("deleted"/"active")' + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tag + required: false + type: string + - description: Is the group is marked as favourite + in: query + name: favourite + required: false + type: boolean + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this customer for a timeframe by groups + tags: + - Groups + /groups/aggregated/list: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Status of group ("deleted"/"active")' + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tag + required: false + type: string + - description: Is the group is marked as favourite + in: query + name: favourite + required: false + type: boolean + - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' + enum: + - deleted + - active + in: query + name: groupBy + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about all groups of this customer for a timeframe grouped by some temporal entity (day/week/month) + tags: + - Groups + /groups/count: + get: + consumes: [] + deprecated: false + parameters: + - description: Status of the datapoint + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude groups created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude groups created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + - description: Write permission + in: query + name: write + required: false + type: boolean + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Count the groups associated to the user. + tags: + - Groups + '/groups/{id}': + delete: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Delete group specified by id + tags: + - Groups + get: + consumes: [] + deprecated: false + parameters: + - description: The id of the group + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Groups.Group' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Get a group + tags: + - Groups + post: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: The body of the group + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Groups.Group' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Update a group + tags: + - Groups + '/groups/{id}/aggregated': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' + in: query + name: hourly + required: false + type: boolean + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this group for a timeframe + tags: + - Groups + '/groups/{id}/aggregated/list': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' + enum: + - week + - month + in: query + name: groupBy + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about this group for a timeframe grouped by some temporal entity (day/week/month) + tags: + - Groups + '/groups/{id}/aggregated/summary': + get: + consumes: [] + deprecated: false + parameters: + - description: Filter by this group id + format: int64 + in: path + name: id + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - today + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - last12months + - lastyear + - currentyear + - beginning + - custom + in: query + name: timeFrame + required: true + type: string + - description: 'Type of datapoint ("tl"/"tp")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tag + required: false + type: string + - description: Is the datapoint marked as favourite + in: query + name: favourite + required: false + type: boolean + - description: Field to sort by + in: query + name: sortBy + required: false + type: string + - description: 'Direction of sort "asc" or "desc"' + enum: + - asc + - desc + in: query + name: sortDirection + required: false + type: string + - default: 0 + description: Offset where to start from + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve statistics about a subset of datapoints for a timeframe with datapoints data + tags: + - Groups + '/groups/{id}/datapoints': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + - default: 0 + description: Where to start when retrieving elements. Default is 0 if not specified. + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Maximum elements to retrieve. Default to 20 if not specified. + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: 'Type of the datapoint ("tp"/"tl")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: Status of the datapoint + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Filter fields by favourite status + in: query + name: onlyFavorites + required: false + type: boolean + - description: Field to sort by + in: query + name: sortBy + required: false + type: string + - description: 'Direction of sort "asc" or "desc"' + enum: + - asc + - desc + in: query + name: sortDirection + required: false + type: string + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the datapoints associated to the user in this group. + tags: + - Groups + post: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: The body of the datapoint + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Create a datapoint in this group + tags: + - Groups + '/groups/{id}/datapoints/count': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: 'Type of the datapoint ("tp"/"tl")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: Status of the datapoint + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Filter fields by favourite status + in: query + name: onlyFavorites + required: false + type: boolean + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Count the datapoints associated to the user in this group. + tags: + - Groups + '/groups/{id}/favourite': + put: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '403': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: 'Fast switch the "favourite" field of a group' + tags: + - Groups + '/groups/{id}/hits': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: Timeframe of the request. See list at $timeframeList + enum: + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - custom + in: query + name: timeframe + required: true + type: string + - description: Limit results to this number + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: "Offset where to start from (it's the lastKey field in the response object)" + in: query + name: offset + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' + enum: + - spiders + - uniques + - nonuniques + - conversions + in: query + name: filter + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitListPage' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve the list of events related to this group. + tags: + - Groups + '/groups/{id}/notes': + put: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: Patch requests + in: body + name: note + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.GenericTextPatch' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '403': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: 'Fast patch the "notes" field of a group' + tags: + - Groups + '/groups/{id}/reports': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: Type of the report. + enum: + - browsers + - browsersfamilies + - platforms + - cities + - countries + - isps + - ips + - oss + - ossfamilies + - keywords + - referrers + - destinations + - languages + - params + in: query + name: type + required: true + type: string + - description: Timeframe of the request. See list at $timeframeList + enum: + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - beginning + - custom + in: query + name: timeframe + required: true + type: string + - description: Type of the event you want to filter this report with. By default no filter is applied. + enum: + - clicks + - views + in: query + name: hittype + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Tops.Top' + '401': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: Retrieve a top report connected to this group + tags: + - Groups + /hits: + get: + consumes: [] + deprecated: false + parameters: + - description: Timeframe of the request. See list at $timeframeList + enum: + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - custom + in: query + name: timeframe + required: true + type: string + - description: Limit results to this number + format: int32 + in: query + name: limit + required: false + type: integer + - description: "Offset where to start from (it's the lastKey field in the response object)" + in: query + name: offset + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' + enum: + - spiders + - uniques + - nonuniques + - conversions + in: query + name: filter + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitListPage' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve the list of events related to this account. + tags: + - Hits + /me: + get: + consumes: [] + deprecated: false + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.User' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve current account data + tags: + - Me + /me/plan: + get: + consumes: [] + deprecated: false + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Accounting.Plan' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve current account plan + tags: + - Me + /reports: + get: + consumes: [] + deprecated: false + parameters: + - description: Type of the report. + enum: + - browsers + - browsersfamilies + - platforms + - cities + - countries + - isps + - ips + - oss + - ossfamilies + - keywords + - referrers + - destinations + - languages + - params + in: query + name: type + required: true + type: string + - description: Timeframe of the request. See list at $timeframeList + enum: + - yesterday + - last7 + - last30 + - lastmonth + - currentmonth + - previousmonth + - last90 + - last120 + - last180 + - beginning + - custom + in: query + name: timeframe + required: true + type: string + - description: Type of the event you want to filter this report with. By default no filter is applied. + in: query + name: hittype + required: false + type: string + - description: 'Filter by this group id (mutually exclusive with "datapoint" and "conversion")' + format: int64 + in: query + name: group + required: false + type: integer + - description: 'Filter by this datapoint id (mutually exclusive with "group" and "conversion")' + format: int64 + in: query + name: datapoint + required: false + type: integer + - description: 'Filter by this conversion id (mutually exclusive with "datapoint" and "group")' + format: int64 + in: query + name: conversion + required: false + type: integer + - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' + in: query + name: fromDay + required: false + type: string + - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' + in: query + name: toDay + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Tops.Top' + '401': + description: Forbidden + '404': + description: Not found + '500': + description: Internal Server Error + summary: Retrieve a top report + tags: + - Reports + /retargeting: + get: + consumes: [] + deprecated: false + parameters: + - default: 0 + description: Where to start when retrieving elements. Default is 0 if not specified. + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Maximum elements to retrieve. Default to 20 if not specified. + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the retargeting scripts associated to the user + tags: + - Retargeting + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The body of the retargeting script + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Retargeting.RetargetingScript' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Creates a retargeting script + tags: + - Retargeting + /retargeting/count: + get: + consumes: [] + deprecated: false + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve count of retargeting scripts + tags: + - Retargeting + '/retargeting/{id}': + delete: + consumes: [] + deprecated: false + parameters: + - description: The id of the retargeting script + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Deletes a retargeting script (and remove associations) + tags: + - Retargeting + get: + consumes: [] + deprecated: false + parameters: + - description: The id of the retargeting script + format: int64 + in: path + name: id + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Retargeting.RetargetingScript' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Get a retargeting script object + tags: + - Retargeting + post: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The id of the retargeting script + format: int64 + in: path + name: id + required: true + type: integer + - description: The body of the retargeting script + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Retargeting.RetargetingScript' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Updates a retargeting script + tags: + - Retargeting + '/retargeting/{id}/datapoints': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the retargeting script + format: int64 + in: path + name: id + required: true + type: integer + - default: 0 + description: Where to start when retrieving elements. Default is 0 if not specified. + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Maximum elements to retrieve. Default to 20 if not specified. + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Status of the datapoint + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Filter fields by favourite status + in: query + name: onlyFavorites + required: false + type: boolean + - description: Field to sort by + in: query + name: sortBy + required: false + type: string + - description: 'Direction of sort "asc" or "desc"' + enum: + - asc + - desc + in: query + name: sortDirection + required: false + type: string + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the datapoints associated to the retargeting script. + tags: + - Retargeting + '/retargeting/{id}/datapoints/count': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the group + format: int64 + in: path + name: id + required: true + type: integer + - description: Status of the datapoint + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: A comma separated list of tags you want to filter with. + in: query + name: tags + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Filter fields by favourite status + in: query + name: onlyFavorites + required: false + type: boolean + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Count the datapoints associated to the retargeting script. + tags: + - Retargeting + /tags: + get: + consumes: [] + deprecated: false + parameters: + - default: 0 + description: Where to start when retrieving elements. Default is 0 if not specified. + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Maximum elements to retrieve. Default to 20 if not specified. + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Name of the tag + in: query + name: name + required: false + type: string + - description: Comma separated list of datapoints id to filter by + in: query + name: datapoints + required: false + type: string + - description: Comma separated list of groups id to filter by + in: query + name: groups + required: false + type: string + - description: Type of entity related to the tag + enum: + - tp + - tl + - dp + - gr + in: query + name: type + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the groups associated to the user filtered by this tag. + tags: + - Tags + post: + consumes: + - application/json + - text/json + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: The body of the tag + in: body + name: value + required: true + schema: + $ref: '#/definitions/Api.Core.Dto.Tags.Tag' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Create a tag + tags: + - Tags + /tags/count: + get: + consumes: [] + deprecated: false + parameters: + - description: Name of the tag + in: query + name: name + required: false + type: string + - description: Comma separated list of datapoints id to filter by + in: query + name: datapoints + required: false + type: string + - description: Comma separated list of groups id to filter by + in: query + name: groups + required: false + type: string + - description: Type of entity related to the tag + enum: + - tp + - tl + - dp + - gr + in: query + name: type + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/System.Object' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the groups associated to the user filtered by this tag. + tags: + - Tags + '/tags/{tagId}': + delete: + consumes: [] + deprecated: false + parameters: + - description: Id of the tag + format: int64 + in: path + name: tagId + required: true + type: integer + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/System.Object' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Delete a tag + tags: + - Tags + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the tag + format: int64 + in: path + name: tagId + required: true + type: integer + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Dto.Tags.Tag' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Retrieve a tag + tags: + - Tags + '/tags/{tagId}/datapoints': + delete: + consumes: [] + deprecated: false + parameters: + - description: Id of the tag + format: int64 + in: path + name: tagId + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Delete the association of this tag with all datapoints + tags: + - Tags + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the tag. + format: int64 + in: path + name: tagId + required: true + type: integer + - default: 0 + description: Where to start when retrieving elements. Default is 0 if not specified. + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Maximum elements to retrieve. Default to 20 if not specified. + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: 'Type of the datapoint ("tp"/"tl")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: Status of the datapoint + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the datapoints associated to the user filtered by this tag + tags: + - Tags + '/tags/{tagId}/datapoints/count': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the tag. + format: int64 + in: path + name: tagId + required: true + type: integer + - description: 'Type of the datapoint ("tp"/"tl")' + enum: + - tp + - tl + in: query + name: type + required: false + type: string + - description: Status of the datapoint + enum: + - deleted + - active + - paused + - spam + in: query + name: status + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude datapoints created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude datapoints created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Count the datapoints associated to the user filtered by this tag + tags: + - Tags + '/tags/{tagId}/datapoints/patch': + put: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the tag + format: int64 + in: path + name: tagId + required: true + type: integer + - description: The body patch + in: body + name: data + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.PatchBody' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Associate/Deassociate a tag with a datapoint + tags: + - Tags + '/tags/{tagId}/groups': + delete: + consumes: [] + deprecated: false + parameters: + - description: Id of the tag + format: int64 + in: path + name: tagId + required: true + type: integer + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Delete the association of this tag with all groups + tags: + - Tags + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the tag. + format: int64 + in: path + name: tagId + required: true + type: integer + - default: 0 + description: Where to start when retrieving elements. Default is 0 if not specified. + format: int32 + in: query + minLength: 0 + name: offset + required: false + type: integer + - default: 20 + description: Maximum elements to retrieve. Default to 20 if not specified. + format: int32 + in: query + maxLength: 0 + minLength: 0 + name: limit + required: false + type: integer + - description: Status of the datapoint + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude groups created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude groups created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: List of all the groups associated to the user filtered by this tag. + tags: + - Tags + '/tags/{tagId}/groups/count': + get: + consumes: [] + deprecated: false + parameters: + - description: Id of the tag. + format: int64 + in: path + name: tagId + required: true + type: integer + - description: Status of the datapoint + enum: + - deleted + - active + in: query + name: status + required: false + type: string + - description: Filter fields by this pattern + in: query + name: textSearch + required: false + type: string + - description: Exclude groups created before this date (YYYYMMDD) + in: query + name: createdAfter + required: false + type: string + - description: Exclude groups created after this date (YYYYMMDD) + in: query + name: createdBefore + required: false + type: string + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.CountResponce' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Count the groups associated to the user filtered by this tag + tags: + - Tags + '/tags/{tagId}/groups/patch': + put: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the tag + format: int64 + in: path + name: tagId + required: true + type: integer + - description: The body patch + in: body + name: data + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.PatchBody' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '404': + description: Not found + '500': + description: Internal Server Error + summary: Associate/Deassociate a tag with a group + tags: + - Tags + '/tags/{tagId}/name': + put: + consumes: + - application/json + - text/json + - application/xml + - text/xml + - application/x-www-form-urlencoded + deprecated: false + parameters: + - description: Id of the tag + format: int64 + in: path + name: tagId + required: true + type: integer + - description: The body patch + in: body + name: data + required: true + schema: + $ref: '#/definitions/Api.Core.Requests.GenericTextPatch' + produces: + - application/json + - text/json + - application/xml + - text/xml + responses: + '200': + description: '' + schema: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + '401': + description: Unauthorized + '500': + description: Internal Server Error + summary: Fast patch a tag name + tags: + - Tags +definitions: + Api.Core.Dto.Accounting.ConversionOptions: + properties: + hideComCost: + type: boolean + hideCost: + type: boolean + hideCount: + type: boolean + hideParams: + type: boolean + hideValue: + type: boolean + percentCommission: + format: int32 + type: integer + percentValue: + format: int32 + type: integer + type: object + Api.Core.Dto.Accounting.DomainWhitelistEntry: + properties: + id: + type: string + name: + type: string + type: object + Api.Core.Dto.Accounting.ExtendedGrants: + properties: + allowAllGrants: + type: boolean + allowGroupCreation: + type: boolean + type: object + Api.Core.Dto.Accounting.Guest: + properties: + apiKey: + type: string + conversionOptions: + $ref: '#/definitions/Api.Core.Dto.Accounting.ConversionOptions' + creationDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + currentGrant: + $ref: '#/definitions/Api.Core.Dto.Grants.Grant' + dateFormat: + type: string + decimalSeparator: + type: string + email: + type: string + extendedGrants: + $ref: '#/definitions/Api.Core.Dto.Accounting.ExtendedGrants' + groupGrants: + format: int64 + type: integer + hitOptions: + $ref: '#/definitions/Api.Core.Dto.Accounting.HitOptions' + id: + format: int64 + type: integer + key: + type: string + language: + type: string + loginCount: + format: int32 + type: integer + name: + type: string + notes: + type: string + numberGroupSeparator: + type: string + password: + type: string + timeFormat: + enum: + - AmPm + - H24 + type: string + timeZone: + format: int32 + type: integer + timeframeMinDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + timezonename: + type: string + tlGrants: + format: int64 + type: integer + tpGrants: + format: int64 + type: integer + userName: + type: string + type: object + Api.Core.Dto.Accounting.HitOptions: + properties: + hideReferrer: + type: boolean + type: object + Api.Core.Dto.Accounting.IpBlacklistEntry: + properties: + id: + type: string + ip: + type: string + type: object + Api.Core.Dto.Accounting.Plan: + properties: + allowedPersonalDomains: + format: int32 + type: integer + allowedPersonalUrls: + format: int32 + type: integer + billingPeriodEnd: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + billingPeriodStart: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + bonusMonthlyEvents: + format: int64 + type: integer + maximumDatapoints: + format: int64 + type: integer + maximumGuests: + format: int64 + type: integer + monthlyEvents: + format: int64 + type: integer + name: + type: string + price: + format: double + type: number + profileId: + format: int64 + type: integer + recurring: + type: boolean + recurringPeriod: + format: int32 + type: integer + usedDatapoints: + format: int64 + type: integer + usedMonthlyEvents: + format: int64 + type: integer + type: object + Api.Core.Dto.Accounting.User: + properties: + boGoVal: + type: string + bonusClicks: + format: int64 + type: integer + companyName: + type: string + companyRole: + type: string + email: + type: string + firstName: + type: string + lastName: + type: string + phone: + type: string + redirectOnly: + type: boolean + registrationDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + timeframeMinDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + timezone: + format: int32 + type: integer + timezonename: + type: string + type: object + Api.Core.Dto.Aggregated.AggregatedResult: + properties: + activityDay: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + commissionsCost: + format: double + type: number + conversionsCost: + format: double + type: number + conversionsValue: + format: double + type: number + convertedClicks: + format: int64 + type: integer + entityData: + $ref: '#/definitions/System.Object' + entityId: + type: string + fromDay: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + hourlyBreakDown: + additionalProperties: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + type: object + lastHitDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + spiderHitsCount: + format: int64 + type: integer + toDay: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + totalClicks: + format: int64 + type: integer + totalViews: + format: int64 + type: integer + uniqueClicks: + format: int64 + type: integer + uniqueConversions: + format: int64 + type: integer + uniqueViews: + format: int64 + type: integer + type: object + Api.Core.Dto.Aggregated.AggregatedSummaryResult: + properties: + count: + format: int64 + type: integer + limit: + format: int32 + type: integer + offset: + format: int64 + type: integer + result: + items: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + type: array + type: object + Api.Core.Dto.ClickStream.Hit: + properties: + accessTime: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + browser: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitBrowserInfo' + clientLanguage: + type: string + conversion1: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' + conversion2: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' + conversion3: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' + conversion4: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' + conversion5: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' + conversions: + items: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' + type: array + entity: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitDatapointInfo' + ip: + type: string + isProxy: + type: string + isSpider: + type: string + isUnique: + type: string + location: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitLocationInfo' + org: + type: string + os: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitOsInfo' + queryParams: + type: string + realDestinationUrl: + type: string + referer: + type: string + source: + $ref: '#/definitions/Api.Core.Dto.ClickStream.HitSource' + type: + type: string + type: object + Api.Core.Dto.ClickStream.HitBrowserInfo: + properties: + browserType: + type: string + familyId: + format: int64 + type: integer + familyName: + type: string + id: + format: int64 + type: integer + name: + type: string + type: object + Api.Core.Dto.ClickStream.HitConversionInfo: + properties: + accessTime: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + comcost: + format: double + type: number + cost: + format: double + type: number + date: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + deleted: + type: boolean + id: + format: int64 + type: integer + name: + type: string + parameter: + type: string + value: + format: double + type: number + type: object + Api.Core.Dto.ClickStream.HitDatapointInfo: + properties: + creationDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + datapointFavourite: + type: boolean + datapointId: + format: int64 + type: integer + datapointName: + type: string + datapointTitle: + type: string + datapointType: + type: string + destinationUrl: + type: string + groupId: + format: int64 + type: integer + groupName: + type: string + isABTest: + type: boolean + isPrivateShared: + type: boolean + isPublic: + type: boolean + notes: + type: string + status: + enum: + - Active + - Paused + - Abuse + - Deleted + type: string + tags: + items: + $ref: '#/definitions/Api.Core.Dto.Tags.Tag' + type: array + trackingCode: + type: string + type: object + Api.Core.Dto.ClickStream.HitListPage: + properties: + hits: + items: + $ref: '#/definitions/Api.Core.Dto.ClickStream.Hit' + type: array + lastKey: + type: string + type: object + Api.Core.Dto.ClickStream.HitLocationInfo: + properties: + areacode: + type: string + city: + type: string + country: + type: string + latitude: + format: double + type: number + longitude: + format: double + type: number + metrocode: + type: string + organization: + type: string + postalcode: + type: string + region: + type: string + regionName: + type: string + type: object + Api.Core.Dto.ClickStream.HitOsInfo: + properties: + familyId: + format: int64 + type: integer + familyName: + type: string + id: + format: int64 + type: integer + name: + type: string + type: object + Api.Core.Dto.ClickStream.HitSource: + properties: + id: + format: int64 + type: integer + name: + type: string + param: + type: string + type: object + Api.Core.Dto.Conversions.Conversion: + properties: + code: + type: string + creationDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + deleted: + type: boolean + description: + type: string + id: + format: int64 + type: integer + name: + type: string + protocol: + enum: + - Http + - Https + type: string + value: + format: double + type: number + type: object + Api.Core.Dto.Datapoints.BrowserBaseDestinationItem: + properties: + emailDestinationUrl: + type: string + mobileDestinationUrl: + type: string + spidersDestinationUrl: + type: string + type: object + Api.Core.Dto.Datapoints.Datapoint: + properties: + creationDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + encodeIp: + type: boolean + fifthConversionId: + format: int64 + type: integer + fifthConversionName: + type: string + firstConversionId: + format: int64 + type: integer + firstConversionName: + type: string + fourthConversionId: + format: int64 + type: integer + fourthConversionName: + type: string + groupId: + format: int64 + type: integer + groupName: + type: string + id: + format: int64 + type: integer + isPublic: + type: boolean + isSecured: + type: boolean + lightTracking: + type: boolean + name: + type: string + notes: + type: string + preferred: + type: boolean + redirectOnly: + type: boolean + secondConversionId: + format: int64 + type: integer + secondConversionName: + type: string + status: + enum: + - Active + - Paused + - Abuse + - Deleted + type: string + tags: + items: + $ref: '#/definitions/Api.Core.Dto.Tags.Tag' + type: array + thirdConversionId: + format: int64 + type: integer + thirdConversionName: + type: string + title: + type: string + trackingCode: + type: string + type: + enum: + - TrackingLink + - TrackingPixel + type: string + typeTL: + $ref: '#/definitions/Api.Core.Dto.Datapoints.TrackingLinkSpecifics' + typeTP: + $ref: '#/definitions/Api.Core.Dto.Datapoints.TrackingPixelSpecifics' + writePermited: + type: boolean + type: object + Api.Core.Dto.Datapoints.DatapointRetargetingInfo: + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + Api.Core.Dto.Datapoints.MultipleDestinationItem: + properties: + url: + type: string + type: object + Api.Core.Dto.Datapoints.TrackingLinkSpecifics: + properties: + appendQuery: + type: boolean + browserDestinationItem: + $ref: '#/definitions/Api.Core.Dto.Datapoints.BrowserBaseDestinationItem' + destinationMode: + enum: + - Simple + - RandomDestination + - DestinationByLanguage + - SpilloverDestination + - DynamicUrl + - BrowserDestination + - DestinationByNation + - UniqueDestination + - SequentialDestination + - WeightedDestination + type: string + domainId: + format: int32 + type: integer + encodeUrl: + type: boolean + expirationClicks: + format: int64 + type: integer + expirationDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + firstUrl: + type: string + goDomainId: + format: int32 + type: integer + hideUrl: + type: boolean + hideUrlTitle: + type: string + isABTest: + type: boolean + password: + type: string + pauseAfterClicksExpiration: + type: boolean + pauseAfterDateExpiration: + type: boolean + randomDestinationItems: + items: + $ref: '#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem' + type: array + redirectType: + enum: + - PermanentRedirect + - TemporaryRedirect + type: string + referrerClean: + enum: + - None + - Clean + - Myself + type: string + scripts: + items: + $ref: '#/definitions/Api.Core.Dto.Datapoints.DatapointRetargetingInfo' + type: array + sequentialDestinationItems: + items: + $ref: '#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem' + type: array + spilloverDestinationItems: + items: + $ref: '#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem' + type: array + uniqueDestinationItem: + $ref: '#/definitions/Api.Core.Dto.Datapoints.UniqueDestinationItem' + url: + type: string + urlAfterClicksExpiration: + type: string + urlAfterDateExpiration: + type: string + urlsByLanguage: + items: + $ref: '#/definitions/Api.Core.Dto.Datapoints.UrlByLanguageItem' + type: array + urlsByNation: + items: + $ref: '#/definitions/Api.Core.Dto.Datapoints.UrlByNationItem' + type: array + weightedDestinationItems: + items: + $ref: '#/definitions/Api.Core.Dto.Datapoints.WeightedDestinationItem' + type: array + type: object + Api.Core.Dto.Datapoints.TrackingPixelSpecifics: + properties: + parameterNote: + type: string + type: object + Api.Core.Dto.Datapoints.UniqueDestinationItem: + properties: + firstDestinationUrl: + type: string + type: object + Api.Core.Dto.Datapoints.UrlByLanguageItem: + properties: + languageCode: + type: string + url: + type: string + type: object + Api.Core.Dto.Datapoints.UrlByNationItem: + properties: + nation: + type: string + url: + type: string + type: object + Api.Core.Dto.Datapoints.WeightedDestinationItem: + properties: + url: + type: string + weight: + format: int32 + type: integer + type: object + Api.Core.Dto.Domains.Domain: + properties: + custom404: + type: string + customHomepage: + type: string + id: + format: int64 + type: integer + name: + type: string + type: + enum: + - System + - Go + - Dedicated + - Personal + type: string + type: object + Api.Core.Dto.EntityUriLong: + properties: + id: + format: int64 + type: integer + uri: + type: string + type: object + Api.Core.Dto.Grants.Grant: + properties: + DatapointType: + type: string + Entity: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + EntityName: + type: string + EntityType: + type: string + Type: + type: string + type: object + Api.Core.Dto.Groups.Group: + properties: + creationDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + deleted: + type: boolean + id: + format: int64 + type: integer + isPublic: + type: boolean + name: + type: string + notes: + type: string + preferred: + type: boolean + redirectOnly: + type: boolean + tags: + items: + $ref: '#/definitions/Api.Core.Dto.Tags.Tag' + type: array + writePermited: + type: boolean + type: object + Api.Core.Dto.Retargeting.RetargetingScript: + properties: + id: + format: int64 + type: integer + name: + type: string + script: + type: string + type: object + Api.Core.Dto.Tags.Tag: + properties: + datapoints: + items: + format: int64 + type: integer + type: array + groups: + items: + format: int64 + type: integer + type: array + id: + format: int64 + type: integer + name: + type: string + type: object + Api.Core.Dto.Tops.Top: + properties: + createdAt: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + data: + items: + $ref: '#/definitions/Api.Core.Dto.Tops.TopItem' + type: array + key: + type: string + type: object + Api.Core.Dto.Tops.TopItem: + properties: + entityData: + $ref: '#/definitions/System.Object' + id: + type: string + lastHitDate: + description: ' (A date in "YmdHis" format)' + example: '20120203120530' + type: string + spiderClicks: + format: int64 + type: integer + spiderHits: + format: int64 + type: integer + spiderViews: + format: int64 + type: integer + totalClicks: + format: int64 + type: integer + totalCommissionsCost: + format: double + type: number + totalConversions: + format: int64 + type: integer + totalConversionsCost: + format: double + type: number + totalConversionsValue: + format: double + type: number + totalHits: + format: int64 + type: integer + totalViews: + format: int64 + type: integer + uniqueClicks: + format: int64 + type: integer + uniqueHits: + format: int64 + type: integer + uniqueViews: + format: int64 + type: integer + type: object + Api.Core.Requests.ConversionPatchBody: + properties: + Action: + type: string + Id: + format: int64 + type: integer + ReplaceId: + format: int64 + type: integer + type: object + Api.Core.Requests.DatapointsBatch: + properties: + List: + items: + $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' + type: array + type: object + Api.Core.Requests.DeleteBatch: + properties: + Entities: + items: + $ref: '#/definitions/Api.Core.Dto.EntityUriLong' + type: array + type: object + Api.Core.Requests.GenericTextPatch: + properties: + Text: + type: string + type: object + Api.Core.Requests.PatchBody: + properties: + Action: + type: string + Id: + format: int64 + type: integer + type: object + Api.Core.Requests.PatchBodyBatch: + properties: + PatchRequests: + items: + $ref: '#/definitions/Api.Core.Requests.PatchBody' + type: array + type: object + Api.Core.Requests.PermissionPatchRequest: + properties: + Action: + type: string + Id: + format: int64 + type: integer + Verb: + type: string + type: object + Api.Core.Responses.CountResponce: + properties: + count: + format: int64 + type: integer + type: object + 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.DomainWhitelistEntry]': + properties: + entities: + items: + $ref: '#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry' + type: array + type: object + 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.IpBlacklistEntry]': + properties: + entities: + items: + $ref: '#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry' + type: array + type: object + 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]': + properties: + entities: + items: + $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' + type: array + type: object + 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.ClickStream.Hit]': + properties: + entities: + items: + $ref: '#/definitions/Api.Core.Dto.ClickStream.Hit' + type: array + type: object + 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Grants.Grant]': + properties: + entities: + items: + $ref: '#/definitions/Api.Core.Dto.Grants.Grant' + type: array + type: object + 'Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]': + properties: + entities: + items: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + type: array + type: object + 'Api.Core.Responses.EntityUri[System.Int64]': + properties: + id: + format: int64 + type: integer + uri: + type: string + type: object + 'Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]': + properties: + entityData: + $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' + errors: + items: + $ref: '#/definitions/ClickMeter.Infrastructure.Validation.ValidationFailure' + type: array + result: + $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' + status: + type: string + type: object + ClickMeter.Infrastructure.Validation.ValidationFailure: + properties: + code: + $ref: '#/definitions/System.Object' + errorMessage: + type: string + errorValue: + $ref: '#/definitions/System.Object' + property: + type: string + type: object + System.Object: + properties: {} + type: object diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/invalid-refs.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/invalid-refs.json new file mode 100644 index 00000000..d636d458 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/invalid-refs.json @@ -0,0 +1,85 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "Swagger Petstore", + "contact": { + "name": "wordnik api team", + "url": "http://developer.wordnik.com" + }, + "license": { + "name": "Creative Commons 4.0 International", + "url": "http://creativecommons.org/licenses/by/4.0/" + } + }, + "host": "petstore.swagger.wordnik.com", + "basePath": "/api", + "schemes": [ + "http" + ], + "paths": { + "/pets": { + "get": { + "tags": [ "Pet Operations" ], + "summary": "finds pets in the system", + "responses": { + "200": { + "description": "pet response", + "schema": { + "type": "array", + "items": { + "$ref": "NotCorrectRef" + } + }, + "headers": { + "x-expires": { + "type": "string" + } + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "NotCorrectRef" + } + } + } + } + } + }, + "definitions": { + "Pet": { + "required": [ + "id", + "name" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "Error": { + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } +} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/overflow.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/overflow.json new file mode 100644 index 00000000..5a2a9f3d --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/overflow.json @@ -0,0 +1,124 @@ +{ + "swagger": "2.0", + "info": { + "title": "Swagger Sample", + "description": "Sample API Playground.", + "version": "1.0.0" + }, + "basePath": "/v1", + "schemes": [ + "http" + ], + "consumes": [ + "application/vdn.sample.v1+json" + ], + "produces": [ + "application/vdn.sample.v1+json" + ], + "paths": { + "/books": { + "get": { + "summary": "List all books", + "operationId": "listBooks", + "tags": [ + "books" + ], + "responses": { + "200": { + "headers": { + "Link": { + "type": "string" + } + }, + "description": "An array of books", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Book" + } + } + }, + "default": { + "description": "generic error response", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + } + }, + "definitions": { + "Store": { + "type": "object", + "properties": { + "title": { + "type": "string", + "example": "Book Shop" + }, + "categories": { + "type": "array", + "items": { + "$ref": "#/definitions/Category" + } + } + } + }, + "Category": { + "type": "object", + "properties": { + "title": { + "type": "string", + "example": "Drama" + }, + "books": { + "type": "array", + "items": { + "$ref": "#/definitions/Book" + } + } + } + }, + "Book": { + "type": "object", + "required": [ + "title", + "summary" + ], + "properties": { + "title": { + "type": "string", + "example": "Winnie the Pooh" + }, + "summary": { + "type": "string", + "example": "Famous children's book" + }, + "related_books": { + "type": "array", + "items": { + "$ref": "#/definitions/Book" + } + } + } + }, + "Error": { + "type": "object", + "readOnly": true, + "properties": { + "code": { + "type": "integer", + "format": "int64", + "example": 400 + }, + "message": { + "type": "string", + "example": "Unexpected error" + } + }, + "required": [ + "message" + ] + } + } +} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/params.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/params.json new file mode 100644 index 00000000..76e7b418 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/params.json @@ -0,0 +1,25 @@ +{ + "parameters": { + "id": { + "type": "integer", + "format": "int64", + "in": "path", + "required": true + }, + "tag": { + "type": "string", + "in": "query", + "required": false + }, + "query": { + "$ref": "#/parameters/tag" + } + }, + "paths": { + "/cars/{id}": { + "parameters": [ + { "$ref": "#/parameters/id"} + ] + } + } +} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas1.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas1.json new file mode 100644 index 00000000..e53a412e --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas1.json @@ -0,0 +1,127 @@ +{ + "definitions": { + "car": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "make": { + "type": "string" + }, + "brand": { + "$ref": "#/definitions/brand" + } + } + }, + "tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "value": { + "type": "string" + } + } + }, + "brand": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "truck": { + "$ref": "#/definitions/car" + }, + "batch": { + "items": { + "$ref": "#/definitions/brand" + } + }, + "batch2": { + "items": [ + { + "$ref": "#/definitions/brand" + }, + { + "$ref": "#/definitions/tag" + } + ] + }, + "allofBoth": { + "allOf": [ + { + "$ref": "#/definitions/brand" + }, + { + "$ref": "#/definitions/tag" + } + ] + }, + "anyofBoth": { + "anyOf": [ + { + "$ref": "#/definitions/brand" + }, + { + "$ref": "#/definitions/tag" + } + ] + }, + "oneofBoth": { + "oneOf": [ + { + "$ref": "#/definitions/brand" + }, + { + "$ref": "#/definitions/tag" + } + ] + }, + "notSomething": { + "not": { + "$ref": "#/definitions/tag" + } + }, + "withAdditional": { + "additionalProperties": { + "$ref": "#/definitions/tag" + } + }, + "withPattern": { + "patternProperties": { + "^x-ab": { + "$ref": "#/definitions/tag" + } + } + }, + "withAdditionalItems": { + "additionalItems": { + "$ref": "#/definitions/tag" + } + }, + "deps": { + "dependencies": { + "something": { + "$ref": "#/definitions/tag" + } + } + }, + "defined": { + "definitions": { + "something": { + "$ref": "#/definitions/tag" + } + } + } + } +} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas2.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas2.json new file mode 100644 index 00000000..fe885fd9 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas2.json @@ -0,0 +1,161 @@ +{ + "definitions": { + "car": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "make": { + "type": "string" + }, + "brand": { + "items": { + "$ref": "#/definitions/brand" + } + } + } + }, + "tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "value": { + "type": "string" + } + } + }, + "brand": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "truck": { + "items": { + "$ref": "#/definitions/car" + } + }, + "batch": { + "items": { + "items": { + "$ref": "#/definitions/brand" + } + } + }, + "batch2": { + "items": [ + { + "items": { + "$ref": "#/definitions/brand" + } + }, + { + "items": { + "$ref": "#/definitions/tag" + } + } + ] + }, + "allofBoth": { + "allOf": [ + { + "items": { + "$ref": "#/definitions/brand" + } + }, + { + "items": { + "$ref": "#/definitions/tag" + } + } + ] + }, + "anyofBoth": { + "anyOf": [ + { + "items": { + "$ref": "#/definitions/brand" + } + }, + { + "items": { + "$ref": "#/definitions/tag" + } + } + ] + }, + "oneofBoth": { + "oneOf": [ + { + "items": { + "$ref": "#/definitions/brand" + } + }, + { + "items": { + "$ref": "#/definitions/tag" + } + } + ] + }, + "notSomething": { + "not": { + "items": { + "$ref": "#/definitions/tag" + } + } + }, + "withAdditional": { + "additionalProperties": { + "items": { + "$ref": "#/definitions/tag" + } + } + }, + "withPattern": { + "patternProperties": { + "^x-ab": { + "items": { + "$ref": "#/definitions/tag" + } + } + } + }, + "withAdditionalItems": { + "additionalItems": { + "items": { + "$ref": "#/definitions/tag" + } + } + }, + "deps": { + "dependencies": { + "something": { + "items": { + "$ref": "#/definitions/tag" + } + } + } + }, + "defined": { + "definitions": { + "something": { + "items": { + "$ref": "#/definitions/tag" + } + } + } + } + } +} diff --git a/vendor/github.com/go-openapi/spec/fixtures/local_expansion/item.json b/vendor/github.com/go-openapi/spec/fixtures/local_expansion/item.json new file mode 100644 index 00000000..f042fdd7 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/local_expansion/item.json @@ -0,0 +1,18 @@ +{ + "properties": { + "id": { + "format": "int64", + "readOnly": true, + "type": "integer" + }, + "title": { + "maxLength": 80, + "minLength": 2, + "type": "string" + } + }, + "required": [ + "title" + ], + "type": "object" +} diff --git a/vendor/github.com/go-openapi/spec/fixtures/local_expansion/spec.json b/vendor/github.com/go-openapi/spec/fixtures/local_expansion/spec.json new file mode 100644 index 00000000..5c653bca --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/local_expansion/spec.json @@ -0,0 +1,46 @@ +{ + "basePath": "/v1", + "consumes": [ + "application/json" + ], + "host": "item.api.local", + "info": { + "description": "Item API", + "title": "Item API", + "version": "1.0.0" + }, + "paths": { + "/item": { + "get": { + "operationId": "GetItem", + "responses": { + "200": { + "description": "item detail response", + "schema": { + "$ref": "item.json" + } + } + } + } + } + }, + "produces": [ + "application/json" + ], + "schemes": [ + "http" + ], + "security": [ + { + "key": [] + } + ], + "securityDefinitions": { + "key": { + "in": "header", + "name": "x-item-token", + "type": "apiKey" + } + }, + "swagger": "2.0" +} diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/arrayProp.json b/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/arrayProp.json new file mode 100644 index 00000000..8f8dbf6b --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/arrayProp.json @@ -0,0 +1,6 @@ +{ + "type":"array", + "items": { + "type": "string" + } +} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/stringProp.json b/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/stringProp.json new file mode 100644 index 00000000..169a0d70 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/stringProp.json @@ -0,0 +1,3 @@ +{ + "type": "string" +} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/refed.json b/vendor/github.com/go-openapi/spec/fixtures/specs/refed.json new file mode 100644 index 00000000..142be8bb --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/specs/refed.json @@ -0,0 +1,224 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "Swagger Petstore", + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "name": "Wordnik API Team" + }, + "license": { + "name": "MIT" + } + }, + "host": "petstore.swagger.wordnik.com", + "basePath": "/api", + "schemes": [ + "http" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": { + "idParam": { + "name": "id", + "in": "path", + "description": "ID of pet to fetch", + "required": true, + "type": "integer", + "format": "int64" + } + }, + "responses": { + "petResponse": { + "description": "pet response", + "schema": { + "$ref": "#/definitions/pet" + } + } + }, + "paths": { + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "operationId": "findPets", + "produces": [ + "application/json", + "application/xml", + "text/xml", + "text/html" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv" + }, + { + "name": "limit", + "in": "query", + "description": "maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/pet" + } + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/errorModel" + } + } + } + }, + "post": { + "description": "Creates a new pet in the store. Duplicates are allowed", + "operationId": "addPet", + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "pet", + "in": "body", + "description": "Pet to add to the store", + "required": true, + "schema": { + "$ref": "#/definitions/petInput" + } + } + ], + "responses": { + "200": { "$ref": "#/responses/petResponse" }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/errorModel" + } + } + } + } + }, + "/pets/{id}": { + "get": { + "description": "Returns a user based on a single ID, if the user does not have access to the pet", + "operationId": "findPetById", + "produces": [ + "application/json", + "application/xml", + "text/xml", + "text/html" + ], + "parameters": [ + { + "$ref": "#/parameters/idParam" + } + ], + "responses": { + "200": { + "$ref": "#/responses/petResponse" + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/errorModel" + } + } + } + }, + "delete": { + "description": "deletes a single pet based on the ID supplied", + "operationId": "deletePet", + "parameters": [ + { + "$ref": "#/parameters/idParam" + } + ], + "responses": { + "204": { + "description": "pet deleted" + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/errorModel" + } + } + } + } + } + }, + "definitions": { + "pet": { + "required": [ + "id", + "name" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "petInput": { + "allOf": [ + { + "$ref": "pet" + }, + { + "required": [ + "name" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + } + } + } + ] + }, + "errorModel": { + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } +} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/resolution.json b/vendor/github.com/go-openapi/spec/fixtures/specs/resolution.json new file mode 100644 index 00000000..43cabe85 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/specs/resolution.json @@ -0,0 +1,14 @@ +{ + "id": "http://localhost:1234", + "items": { + "id": "deeper/", + "items": { + "$ref": "stringProp.json" + } + }, + "definitions": { + "bool": { + "$ref": "boolProp.json" + } + } +} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/resolution2.json b/vendor/github.com/go-openapi/spec/fixtures/specs/resolution2.json new file mode 100644 index 00000000..5d7a0056 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/fixtures/specs/resolution2.json @@ -0,0 +1,9 @@ +{ + "id": "http://localhost:1234", + "items": { + "id": "deeper/", + "items": { + "$ref": "arrayProp.json#/items" + } + } +} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/header.go b/vendor/github.com/go-openapi/spec/header.go new file mode 100644 index 00000000..85c4d454 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/header.go @@ -0,0 +1,195 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +type HeaderProps struct { + Description string `json:"description,omitempty"` +} + +// Header describes a header for a response of the API +// +// For more information: http://goo.gl/8us55a#headerObject +type Header struct { + CommonValidations + SimpleSchema + VendorExtensible + HeaderProps +} + +// ResponseHeader creates a new header instance for use in a response +func ResponseHeader() *Header { + return new(Header) +} + +// WithDescription sets the description on this response, allows for chaining +func (h *Header) WithDescription(description string) *Header { + h.Description = description + return h +} + +// Typed a fluent builder method for the type of parameter +func (h *Header) Typed(tpe, format string) *Header { + h.Type = tpe + h.Format = format + return h +} + +// CollectionOf a fluent builder method for an array item +func (h *Header) CollectionOf(items *Items, format string) *Header { + h.Type = "array" + h.Items = items + h.CollectionFormat = format + return h +} + +// WithDefault sets the default value on this item +func (h *Header) WithDefault(defaultValue interface{}) *Header { + h.Default = defaultValue + return h +} + +// WithMaxLength sets a max length value +func (h *Header) WithMaxLength(max int64) *Header { + h.MaxLength = &max + return h +} + +// WithMinLength sets a min length value +func (h *Header) WithMinLength(min int64) *Header { + h.MinLength = &min + return h +} + +// WithPattern sets a pattern value +func (h *Header) WithPattern(pattern string) *Header { + h.Pattern = pattern + return h +} + +// WithMultipleOf sets a multiple of value +func (h *Header) WithMultipleOf(number float64) *Header { + h.MultipleOf = &number + return h +} + +// WithMaximum sets a maximum number value +func (h *Header) WithMaximum(max float64, exclusive bool) *Header { + h.Maximum = &max + h.ExclusiveMaximum = exclusive + return h +} + +// WithMinimum sets a minimum number value +func (h *Header) WithMinimum(min float64, exclusive bool) *Header { + h.Minimum = &min + h.ExclusiveMinimum = exclusive + return h +} + +// WithEnum sets a the enum values (replace) +func (h *Header) WithEnum(values ...interface{}) *Header { + h.Enum = append([]interface{}{}, values...) + return h +} + +// WithMaxItems sets the max items +func (h *Header) WithMaxItems(size int64) *Header { + h.MaxItems = &size + return h +} + +// WithMinItems sets the min items +func (h *Header) WithMinItems(size int64) *Header { + h.MinItems = &size + return h +} + +// UniqueValues dictates that this array can only have unique items +func (h *Header) UniqueValues() *Header { + h.UniqueItems = true + return h +} + +// AllowDuplicates this array can have duplicates +func (h *Header) AllowDuplicates() *Header { + h.UniqueItems = false + return h +} + +// MarshalJSON marshal this to JSON +func (h Header) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(h.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(h.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(h.HeaderProps) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2, b3), nil +} + +// UnmarshalJSON marshal this from JSON +func (h *Header) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &h.CommonValidations); err != nil { + return err + } + if err := json.Unmarshal(data, &h.SimpleSchema); err != nil { + return err + } + if err := json.Unmarshal(data, &h.VendorExtensible); err != nil { + return err + } + if err := json.Unmarshal(data, &h.HeaderProps); err != nil { + return err + } + return nil +} + +// JSONLookup look up a value by the json property name +func (p Header) JSONLookup(token string) (interface{}, error) { + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + + r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.HeaderProps, token) + return r, err +} diff --git a/vendor/github.com/go-openapi/spec/header_test.go b/vendor/github.com/go-openapi/spec/header_test.go new file mode 100644 index 00000000..a07d174f --- /dev/null +++ b/vendor/github.com/go-openapi/spec/header_test.go @@ -0,0 +1,90 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +func float64Ptr(f float64) *float64 { + return &f +} +func int64Ptr(f int64) *int64 { + return &f +} + +var header = Header{ + VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{ + "x-framework": "swagger-go", + }}, + HeaderProps: HeaderProps{Description: "the description of this header"}, + SimpleSchema: SimpleSchema{ + Items: &Items{ + Refable: Refable{Ref: MustCreateRef("Cat")}, + }, + Type: "string", + Format: "date", + Default: "8", + }, + CommonValidations: CommonValidations{ + Maximum: float64Ptr(100), + ExclusiveMaximum: true, + ExclusiveMinimum: true, + Minimum: float64Ptr(5), + MaxLength: int64Ptr(100), + MinLength: int64Ptr(5), + Pattern: "\\w{1,5}\\w+", + MaxItems: int64Ptr(100), + MinItems: int64Ptr(5), + UniqueItems: true, + MultipleOf: float64Ptr(5), + Enum: []interface{}{"hello", "world"}, + }, +} + +var headerJSON = `{ + "items": { + "$ref": "Cat" + }, + "x-framework": "swagger-go", + "description": "the description of this header", + "maximum": 100, + "minimum": 5, + "exclusiveMaximum": true, + "exclusiveMinimum": true, + "maxLength": 100, + "minLength": 5, + "pattern": "\\w{1,5}\\w+", + "maxItems": 100, + "minItems": 5, + "uniqueItems": true, + "multipleOf": 5, + "enum": ["hello", "world"], + "type": "string", + "format": "date", + "default": "8" +}` + +func TestIntegrationHeader(t *testing.T) { + var actual Header + if assert.NoError(t, json.Unmarshal([]byte(headerJSON), &actual)) { + assert.EqualValues(t, actual, header) + } + + assertParsesJSON(t, headerJSON, header) +} diff --git a/vendor/github.com/go-openapi/spec/info.go b/vendor/github.com/go-openapi/spec/info.go new file mode 100644 index 00000000..fb8b7c4a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/info.go @@ -0,0 +1,168 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// Extensions vendor specific extensions +type Extensions map[string]interface{} + +// Add adds a value to these extensions +func (e Extensions) Add(key string, value interface{}) { + realKey := strings.ToLower(key) + e[realKey] = value +} + +// GetString gets a string value from the extensions +func (e Extensions) GetString(key string) (string, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + str, ok := v.(string) + return str, ok + } + return "", false +} + +// GetBool gets a string value from the extensions +func (e Extensions) GetBool(key string) (bool, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + str, ok := v.(bool) + return str, ok + } + return false, false +} + +// GetStringSlice gets a string value from the extensions +func (e Extensions) GetStringSlice(key string) ([]string, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + arr, ok := v.([]interface{}) + if !ok { + return nil, false + } + var strs []string + for _, iface := range arr { + str, ok := iface.(string) + if !ok { + return nil, false + } + strs = append(strs, str) + } + return strs, ok + } + return nil, false +} + +// VendorExtensible composition block. +type VendorExtensible struct { + Extensions Extensions +} + +// AddExtension adds an extension to this extensible object +func (v *VendorExtensible) AddExtension(key string, value interface{}) { + if value == nil { + return + } + if v.Extensions == nil { + v.Extensions = make(map[string]interface{}) + } + v.Extensions.Add(key, value) +} + +// MarshalJSON marshals the extensions to json +func (v VendorExtensible) MarshalJSON() ([]byte, error) { + toser := make(map[string]interface{}) + for k, v := range v.Extensions { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + toser[k] = v + } + } + return json.Marshal(toser) +} + +// UnmarshalJSON for this extensible object +func (v *VendorExtensible) UnmarshalJSON(data []byte) error { + var d map[string]interface{} + if err := json.Unmarshal(data, &d); err != nil { + return err + } + for k, vv := range d { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + if v.Extensions == nil { + v.Extensions = map[string]interface{}{} + } + v.Extensions[k] = vv + } + } + return nil +} + +// InfoProps the properties for an info definition +type InfoProps struct { + Description string `json:"description,omitempty"` + Title string `json:"title,omitempty"` + TermsOfService string `json:"termsOfService,omitempty"` + Contact *ContactInfo `json:"contact,omitempty"` + License *License `json:"license,omitempty"` + Version string `json:"version,omitempty"` +} + +// Info object provides metadata about the API. +// The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. +// +// For more information: http://goo.gl/8us55a#infoObject +type Info struct { + VendorExtensible + InfoProps +} + +// JSONLookup look up a value by the json property name +func (i Info) JSONLookup(token string) (interface{}, error) { + if ex, ok := i.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(i.InfoProps, token) + return r, err +} + +// MarshalJSON marshal this to JSON +func (i Info) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(i.InfoProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(i.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} + +// UnmarshalJSON marshal this from JSON +func (i *Info) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &i.InfoProps); err != nil { + return err + } + if err := json.Unmarshal(data, &i.VendorExtensible); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/go-openapi/spec/info_test.go b/vendor/github.com/go-openapi/spec/info_test.go new file mode 100644 index 00000000..fc40c163 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/info_test.go @@ -0,0 +1,65 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +var infoJSON = `{ + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "title": "Swagger Sample API", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "name": "wordnik api team", + "url": "http://developer.wordnik.com" + }, + "license": { + "name": "Creative Commons 4.0 International", + "url": "http://creativecommons.org/licenses/by/4.0/" + }, + "version": "1.0.9-abcd", + "x-framework": "go-swagger" +}` + +var info = Info{ + InfoProps: InfoProps{ + Version: "1.0.9-abcd", + Title: "Swagger Sample API", + Description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + TermsOfService: "http://helloreverb.com/terms/", + Contact: &ContactInfo{Name: "wordnik api team", URL: "http://developer.wordnik.com"}, + License: &License{Name: "Creative Commons 4.0 International", URL: "http://creativecommons.org/licenses/by/4.0/"}, + }, + VendorExtensible: VendorExtensible{map[string]interface{}{"x-framework": "go-swagger"}}, +} + +func TestIntegrationInfo_Serialize(t *testing.T) { + b, err := json.MarshalIndent(info, "", "\t") + if assert.NoError(t, err) { + assert.Equal(t, infoJSON, string(b)) + } +} + +func TestIntegrationInfo_Deserialize(t *testing.T) { + actual := Info{} + err := json.Unmarshal([]byte(infoJSON), &actual) + if assert.NoError(t, err) { + assert.EqualValues(t, info, actual) + } +} diff --git a/vendor/github.com/go-openapi/spec/items.go b/vendor/github.com/go-openapi/spec/items.go new file mode 100644 index 00000000..46944fb6 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/items.go @@ -0,0 +1,219 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +type SimpleSchema struct { + Type string `json:"type,omitempty"` + Format string `json:"format,omitempty"` + Items *Items `json:"items,omitempty"` + CollectionFormat string `json:"collectionFormat,omitempty"` + Default interface{} `json:"default,omitempty"` +} + +func (s *SimpleSchema) TypeName() string { + if s.Format != "" { + return s.Format + } + return s.Type +} + +func (s *SimpleSchema) ItemsTypeName() string { + if s.Items == nil { + return "" + } + return s.Items.TypeName() +} + +type CommonValidations struct { + Maximum *float64 `json:"maximum,omitempty"` + ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` + Minimum *float64 `json:"minimum,omitempty"` + ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` + MaxLength *int64 `json:"maxLength,omitempty"` + MinLength *int64 `json:"minLength,omitempty"` + Pattern string `json:"pattern,omitempty"` + MaxItems *int64 `json:"maxItems,omitempty"` + MinItems *int64 `json:"minItems,omitempty"` + UniqueItems bool `json:"uniqueItems,omitempty"` + MultipleOf *float64 `json:"multipleOf,omitempty"` + Enum []interface{} `json:"enum,omitempty"` +} + +// Items a limited subset of JSON-Schema's items object. +// It is used by parameter definitions that are not located in "body". +// +// For more information: http://goo.gl/8us55a#items-object +type Items struct { + Refable + CommonValidations + SimpleSchema + VendorExtensible +} + +// NewItems creates a new instance of items +func NewItems() *Items { + return &Items{} +} + +// Typed a fluent builder method for the type of item +func (i *Items) Typed(tpe, format string) *Items { + i.Type = tpe + i.Format = format + return i +} + +// CollectionOf a fluent builder method for an array item +func (i *Items) CollectionOf(items *Items, format string) *Items { + i.Type = "array" + i.Items = items + i.CollectionFormat = format + return i +} + +// WithDefault sets the default value on this item +func (i *Items) WithDefault(defaultValue interface{}) *Items { + i.Default = defaultValue + return i +} + +// WithMaxLength sets a max length value +func (i *Items) WithMaxLength(max int64) *Items { + i.MaxLength = &max + return i +} + +// WithMinLength sets a min length value +func (i *Items) WithMinLength(min int64) *Items { + i.MinLength = &min + return i +} + +// WithPattern sets a pattern value +func (i *Items) WithPattern(pattern string) *Items { + i.Pattern = pattern + return i +} + +// WithMultipleOf sets a multiple of value +func (i *Items) WithMultipleOf(number float64) *Items { + i.MultipleOf = &number + return i +} + +// WithMaximum sets a maximum number value +func (i *Items) WithMaximum(max float64, exclusive bool) *Items { + i.Maximum = &max + i.ExclusiveMaximum = exclusive + return i +} + +// WithMinimum sets a minimum number value +func (i *Items) WithMinimum(min float64, exclusive bool) *Items { + i.Minimum = &min + i.ExclusiveMinimum = exclusive + return i +} + +// WithEnum sets a the enum values (replace) +func (i *Items) WithEnum(values ...interface{}) *Items { + i.Enum = append([]interface{}{}, values...) + return i +} + +// WithMaxItems sets the max items +func (i *Items) WithMaxItems(size int64) *Items { + i.MaxItems = &size + return i +} + +// WithMinItems sets the min items +func (i *Items) WithMinItems(size int64) *Items { + i.MinItems = &size + return i +} + +// UniqueValues dictates that this array can only have unique items +func (i *Items) UniqueValues() *Items { + i.UniqueItems = true + return i +} + +// AllowDuplicates this array can have duplicates +func (i *Items) AllowDuplicates() *Items { + i.UniqueItems = false + return i +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (i *Items) UnmarshalJSON(data []byte) error { + var validations CommonValidations + if err := json.Unmarshal(data, &validations); err != nil { + return err + } + var ref Refable + if err := json.Unmarshal(data, &ref); err != nil { + return err + } + var simpleSchema SimpleSchema + if err := json.Unmarshal(data, &simpleSchema); err != nil { + return err + } + i.Refable = ref + i.CommonValidations = validations + i.SimpleSchema = simpleSchema + return nil +} + +// MarshalJSON converts this items object to JSON +func (i Items) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(i.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(i.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(i.Refable) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b3, b1, b2), nil +} + +// JSONLookup look up a value by the json property name +func (p Items) JSONLookup(token string) (interface{}, error) { + if token == "$ref" { + return &p.Ref, nil + } + + r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) + return r, err +} diff --git a/vendor/github.com/go-openapi/spec/items_test.go b/vendor/github.com/go-openapi/spec/items_test.go new file mode 100644 index 00000000..2f9ac11b --- /dev/null +++ b/vendor/github.com/go-openapi/spec/items_test.go @@ -0,0 +1,81 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +var items = Items{ + Refable: Refable{Ref: MustCreateRef("Dog")}, + CommonValidations: CommonValidations{ + Maximum: float64Ptr(100), + ExclusiveMaximum: true, + ExclusiveMinimum: true, + Minimum: float64Ptr(5), + MaxLength: int64Ptr(100), + MinLength: int64Ptr(5), + Pattern: "\\w{1,5}\\w+", + MaxItems: int64Ptr(100), + MinItems: int64Ptr(5), + UniqueItems: true, + MultipleOf: float64Ptr(5), + Enum: []interface{}{"hello", "world"}, + }, + SimpleSchema: SimpleSchema{ + Type: "string", + Format: "date", + Items: &Items{ + Refable: Refable{Ref: MustCreateRef("Cat")}, + }, + CollectionFormat: "csv", + Default: "8", + }, +} + +var itemsJSON = `{ + "items": { + "$ref": "Cat" + }, + "$ref": "Dog", + "maximum": 100, + "minimum": 5, + "exclusiveMaximum": true, + "exclusiveMinimum": true, + "maxLength": 100, + "minLength": 5, + "pattern": "\\w{1,5}\\w+", + "maxItems": 100, + "minItems": 5, + "uniqueItems": true, + "multipleOf": 5, + "enum": ["hello", "world"], + "type": "string", + "format": "date", + "collectionFormat": "csv", + "default": "8" +}` + +func TestIntegrationItems(t *testing.T) { + var actual Items + if assert.NoError(t, json.Unmarshal([]byte(itemsJSON), &actual)) { + assert.EqualValues(t, actual, items) + } + + assertParsesJSON(t, itemsJSON, items) +} diff --git a/vendor/github.com/go-openapi/spec/license.go b/vendor/github.com/go-openapi/spec/license.go new file mode 100644 index 00000000..f20961b4 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/license.go @@ -0,0 +1,23 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +// License information for the exposed API. +// +// For more information: http://goo.gl/8us55a#licenseObject +type License struct { + Name string `json:"name,omitempty"` + URL string `json:"url,omitempty"` +} diff --git a/vendor/github.com/go-openapi/spec/license_test.go b/vendor/github.com/go-openapi/spec/license_test.go new file mode 100644 index 00000000..8ed51a35 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/license_test.go @@ -0,0 +1,28 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import "testing" + +func TestIntegrationLicense(t *testing.T) { + license := License{"the name", "the url"} + const licenseJSON = `{"name":"the name","url":"the url"}` + const licenseYAML = "name: the name\nurl: the url\n" + + assertSerializeJSON(t, license, licenseJSON) + assertSerializeYAML(t, license, licenseYAML) + assertParsesJSON(t, licenseJSON, license) + assertParsesYAML(t, licenseYAML, license) +} diff --git a/vendor/github.com/go-openapi/spec/operation.go b/vendor/github.com/go-openapi/spec/operation.go new file mode 100644 index 00000000..de1db6f0 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/operation.go @@ -0,0 +1,233 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +type OperationProps struct { + Description string `json:"description,omitempty"` + Consumes []string `json:"consumes,omitempty"` + Produces []string `json:"produces,omitempty"` + Schemes []string `json:"schemes,omitempty"` // the scheme, when present must be from [http, https, ws, wss] + Tags []string `json:"tags,omitempty"` + Summary string `json:"summary,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` + ID string `json:"operationId,omitempty"` + Deprecated bool `json:"deprecated,omitempty"` + Security []map[string][]string `json:"security,omitempty"` + Parameters []Parameter `json:"parameters,omitempty"` + Responses *Responses `json:"responses,omitempty"` +} + +// Operation describes a single API operation on a path. +// +// For more information: http://goo.gl/8us55a#operationObject +type Operation struct { + VendorExtensible + OperationProps +} + +// SuccessResponse gets a success response model +func (o *Operation) SuccessResponse() (*Response, int, bool) { + if o.Responses == nil { + return nil, 0, false + } + + for k, v := range o.Responses.StatusCodeResponses { + if k/100 == 2 { + return &v, k, true + } + } + + return o.Responses.Default, 0, false +} + +// JSONLookup look up a value by the json property name +func (o Operation) JSONLookup(token string) (interface{}, error) { + if ex, ok := o.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(o.OperationProps, token) + return r, err +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (o *Operation) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &o.OperationProps); err != nil { + return err + } + if err := json.Unmarshal(data, &o.VendorExtensible); err != nil { + return err + } + return nil +} + +// MarshalJSON converts this items object to JSON +func (o Operation) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(o.OperationProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(o.VendorExtensible) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil +} + +// NewOperation creates a new operation instance. +// It expects an ID as parameter but not passing an ID is also valid. +func NewOperation(id string) *Operation { + op := new(Operation) + op.ID = id + return op +} + +// WithID sets the ID property on this operation, allows for chaining. +func (o *Operation) WithID(id string) *Operation { + o.ID = id + return o +} + +// WithDescription sets the description on this operation, allows for chaining +func (o *Operation) WithDescription(description string) *Operation { + o.Description = description + return o +} + +// WithSummary sets the summary on this operation, allows for chaining +func (o *Operation) WithSummary(summary string) *Operation { + o.Summary = summary + return o +} + +// WithExternalDocs sets/removes the external docs for/from this operation. +// When you pass empty strings as params the external documents will be removed. +// When you pass non-empty string as one value then those values will be used on the external docs object. +// So when you pass a non-empty description, you should also pass the url and vice versa. +func (o *Operation) WithExternalDocs(description, url string) *Operation { + if description == "" && url == "" { + o.ExternalDocs = nil + return o + } + + if o.ExternalDocs == nil { + o.ExternalDocs = &ExternalDocumentation{} + } + o.ExternalDocs.Description = description + o.ExternalDocs.URL = url + return o +} + +// Deprecate marks the operation as deprecated +func (o *Operation) Deprecate() *Operation { + o.Deprecated = true + return o +} + +// Undeprecate marks the operation as not deprected +func (o *Operation) Undeprecate() *Operation { + o.Deprecated = false + return o +} + +// WithConsumes adds media types for incoming body values +func (o *Operation) WithConsumes(mediaTypes ...string) *Operation { + o.Consumes = append(o.Consumes, mediaTypes...) + return o +} + +// WithProduces adds media types for outgoing body values +func (o *Operation) WithProduces(mediaTypes ...string) *Operation { + o.Produces = append(o.Produces, mediaTypes...) + return o +} + +// WithTags adds tags for this operation +func (o *Operation) WithTags(tags ...string) *Operation { + o.Tags = append(o.Tags, tags...) + return o +} + +// AddParam adds a parameter to this operation, when a parameter for that location +// and with that name already exists it will be replaced +func (o *Operation) AddParam(param *Parameter) *Operation { + if param == nil { + return o + } + + for i, p := range o.Parameters { + if p.Name == param.Name && p.In == param.In { + params := append(o.Parameters[:i], *param) + params = append(params, o.Parameters[i+1:]...) + o.Parameters = params + return o + } + } + + o.Parameters = append(o.Parameters, *param) + return o +} + +// RemoveParam removes a parameter from the operation +func (o *Operation) RemoveParam(name, in string) *Operation { + for i, p := range o.Parameters { + if p.Name == name && p.In == name { + o.Parameters = append(o.Parameters[:i], o.Parameters[i+1:]...) + return o + } + } + return o +} + +// SecuredWith adds a security scope to this operation. +func (o *Operation) SecuredWith(name string, scopes ...string) *Operation { + o.Security = append(o.Security, map[string][]string{name: scopes}) + return o +} + +// WithDefaultResponse adds a default response to the operation. +// Passing a nil value will remove the response +func (o *Operation) WithDefaultResponse(response *Response) *Operation { + return o.RespondsWith(0, response) +} + +// RespondsWith adds a status code response to the operation. +// When the code is 0 the value of the response will be used as default response value. +// When the value of the response is nil it will be removed from the operation +func (o *Operation) RespondsWith(code int, response *Response) *Operation { + if o.Responses == nil { + o.Responses = new(Responses) + } + if code == 0 { + o.Responses.Default = response + return o + } + if response == nil { + delete(o.Responses.StatusCodeResponses, code) + return o + } + if o.Responses.StatusCodeResponses == nil { + o.Responses.StatusCodeResponses = make(map[int]Response) + } + o.Responses.StatusCodeResponses[code] = *response + return o +} diff --git a/vendor/github.com/go-openapi/spec/operation_test.go b/vendor/github.com/go-openapi/spec/operation_test.go new file mode 100644 index 00000000..113bf6c0 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/operation_test.go @@ -0,0 +1,85 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +var operation = Operation{ + VendorExtensible: VendorExtensible{ + Extensions: map[string]interface{}{ + "x-framework": "go-swagger", + }, + }, + OperationProps: OperationProps{ + Description: "operation description", + Consumes: []string{"application/json", "application/x-yaml"}, + Produces: []string{"application/json", "application/x-yaml"}, + Schemes: []string{"http", "https"}, + Tags: []string{"dogs"}, + Summary: "the summary of the operation", + ID: "sendCat", + Deprecated: true, + Security: []map[string][]string{ + map[string][]string{ + "apiKey": []string{}, + }, + }, + Parameters: []Parameter{ + Parameter{Refable: Refable{Ref: MustCreateRef("Cat")}}, + }, + Responses: &Responses{ + ResponsesProps: ResponsesProps{ + Default: &Response{ + ResponseProps: ResponseProps{ + Description: "void response", + }, + }, + }, + }, + }, +} + +var operationJSON = `{ + "description": "operation description", + "x-framework": "go-swagger", + "consumes": [ "application/json", "application/x-yaml" ], + "produces": [ "application/json", "application/x-yaml" ], + "schemes": ["http", "https"], + "tags": ["dogs"], + "summary": "the summary of the operation", + "operationId": "sendCat", + "deprecated": true, + "security": [ { "apiKey": [] } ], + "parameters": [{"$ref":"Cat"}], + "responses": { + "default": { + "description": "void response" + } + } +}` + +func TestIntegrationOperation(t *testing.T) { + var actual Operation + if assert.NoError(t, json.Unmarshal([]byte(operationJSON), &actual)) { + assert.EqualValues(t, actual, operation) + } + + assertParsesJSON(t, operationJSON, operation) +} diff --git a/vendor/github.com/go-openapi/spec/parameter.go b/vendor/github.com/go-openapi/spec/parameter.go new file mode 100644 index 00000000..71aee1e8 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/parameter.go @@ -0,0 +1,301 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// QueryParam creates a query parameter +func QueryParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "query"}} +} + +// HeaderParam creates a header parameter, this is always required by default +func HeaderParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "header", Required: true}} +} + +// PathParam creates a path parameter, this is always required +func PathParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "path", Required: true}} +} + +// BodyParam creates a body parameter +func BodyParam(name string, schema *Schema) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "body", Schema: schema}, SimpleSchema: SimpleSchema{Type: "object"}} +} + +// FormDataParam creates a body parameter +func FormDataParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}} +} + +// FileParam creates a body parameter +func FileParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}, SimpleSchema: SimpleSchema{Type: "file"}} +} + +// SimpleArrayParam creates a param for a simple array (string, int, date etc) +func SimpleArrayParam(name, tpe, fmt string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name}, SimpleSchema: SimpleSchema{Type: "array", CollectionFormat: "csv", Items: &Items{SimpleSchema: SimpleSchema{Type: "string", Format: fmt}}}} +} + +// ParamRef creates a parameter that's a json reference +func ParamRef(uri string) *Parameter { + p := new(Parameter) + p.Ref = MustCreateRef(uri) + return p +} + +type ParamProps struct { + Description string `json:"description,omitempty"` + Name string `json:"name,omitempty"` + In string `json:"in,omitempty"` + Required bool `json:"required,omitempty"` + Schema *Schema `json:"schema,omitempty"` // when in == "body" + AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` // when in == "query" || "formData" +} + +// Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). +// +// There are five possible parameter types. +// * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. +// * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +// * Header - Custom headers that are expected as part of the request. +// * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be *one* body parameter. The name of the body parameter has no effect on the parameter itself and is used for documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist together for the same operation. +// * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or `multipart/form-data` are used as the content type of the request (in Swagger's definition, the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4): +// * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple parameters that are being transferred. +// * `multipart/form-data` - each parameter takes a section in the payload with an internal header. For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is `submit-name`. This type of form parameters is more commonly used for file transfers. +// +// For more information: http://goo.gl/8us55a#parameterObject +type Parameter struct { + Refable + CommonValidations + SimpleSchema + VendorExtensible + ParamProps +} + +// JSONLookup look up a value by the json property name +func (p Parameter) JSONLookup(token string) (interface{}, error) { + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + if token == "$ref" { + return &p.Ref, nil + } + + r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.ParamProps, token) + return r, err +} + +// WithDescription a fluent builder method for the description of the parameter +func (p *Parameter) WithDescription(description string) *Parameter { + p.Description = description + return p +} + +// Named a fluent builder method to override the name of the parameter +func (p *Parameter) Named(name string) *Parameter { + p.Name = name + return p +} + +// WithLocation a fluent builder method to override the location of the parameter +func (p *Parameter) WithLocation(in string) *Parameter { + p.In = in + return p +} + +// Typed a fluent builder method for the type of the parameter value +func (p *Parameter) Typed(tpe, format string) *Parameter { + p.Type = tpe + p.Format = format + return p +} + +// CollectionOf a fluent builder method for an array parameter +func (p *Parameter) CollectionOf(items *Items, format string) *Parameter { + p.Type = "array" + p.Items = items + p.CollectionFormat = format + return p +} + +// WithDefault sets the default value on this parameter +func (p *Parameter) WithDefault(defaultValue interface{}) *Parameter { + p.AsOptional() // with default implies optional + p.Default = defaultValue + return p +} + +// AllowsEmptyValues flags this parameter as being ok with empty values +func (p *Parameter) AllowsEmptyValues() *Parameter { + p.AllowEmptyValue = true + return p +} + +// NoEmptyValues flags this parameter as not liking empty values +func (p *Parameter) NoEmptyValues() *Parameter { + p.AllowEmptyValue = false + return p +} + +// AsOptional flags this parameter as optional +func (p *Parameter) AsOptional() *Parameter { + p.Required = false + return p +} + +// AsRequired flags this parameter as required +func (p *Parameter) AsRequired() *Parameter { + if p.Default != nil { // with a default required makes no sense + return p + } + p.Required = true + return p +} + +// WithMaxLength sets a max length value +func (p *Parameter) WithMaxLength(max int64) *Parameter { + p.MaxLength = &max + return p +} + +// WithMinLength sets a min length value +func (p *Parameter) WithMinLength(min int64) *Parameter { + p.MinLength = &min + return p +} + +// WithPattern sets a pattern value +func (p *Parameter) WithPattern(pattern string) *Parameter { + p.Pattern = pattern + return p +} + +// WithMultipleOf sets a multiple of value +func (p *Parameter) WithMultipleOf(number float64) *Parameter { + p.MultipleOf = &number + return p +} + +// WithMaximum sets a maximum number value +func (p *Parameter) WithMaximum(max float64, exclusive bool) *Parameter { + p.Maximum = &max + p.ExclusiveMaximum = exclusive + return p +} + +// WithMinimum sets a minimum number value +func (p *Parameter) WithMinimum(min float64, exclusive bool) *Parameter { + p.Minimum = &min + p.ExclusiveMinimum = exclusive + return p +} + +// WithEnum sets a the enum values (replace) +func (p *Parameter) WithEnum(values ...interface{}) *Parameter { + p.Enum = append([]interface{}{}, values...) + return p +} + +// WithMaxItems sets the max items +func (p *Parameter) WithMaxItems(size int64) *Parameter { + p.MaxItems = &size + return p +} + +// WithMinItems sets the min items +func (p *Parameter) WithMinItems(size int64) *Parameter { + p.MinItems = &size + return p +} + +// UniqueValues dictates that this array can only have unique items +func (p *Parameter) UniqueValues() *Parameter { + p.UniqueItems = true + return p +} + +// AllowDuplicates this array can have duplicates +func (p *Parameter) AllowDuplicates() *Parameter { + p.UniqueItems = false + return p +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (p *Parameter) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &p.CommonValidations); err != nil { + return err + } + if err := json.Unmarshal(data, &p.Refable); err != nil { + return err + } + if err := json.Unmarshal(data, &p.SimpleSchema); err != nil { + return err + } + if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { + return err + } + if err := json.Unmarshal(data, &p.ParamProps); err != nil { + return err + } + return nil +} + +// MarshalJSON converts this items object to JSON +func (p Parameter) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(p.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(p.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(p.Refable) + if err != nil { + return nil, err + } + b4, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } + b5, err := json.Marshal(p.ParamProps) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b3, b1, b2, b4, b5), nil +} diff --git a/vendor/github.com/go-openapi/spec/parameters_test.go b/vendor/github.com/go-openapi/spec/parameters_test.go new file mode 100644 index 00000000..424f6633 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/parameters_test.go @@ -0,0 +1,156 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +var parameter = Parameter{ + VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{ + "x-framework": "swagger-go", + }}, + Refable: Refable{Ref: MustCreateRef("Dog")}, + CommonValidations: CommonValidations{ + Maximum: float64Ptr(100), + ExclusiveMaximum: true, + ExclusiveMinimum: true, + Minimum: float64Ptr(5), + MaxLength: int64Ptr(100), + MinLength: int64Ptr(5), + Pattern: "\\w{1,5}\\w+", + MaxItems: int64Ptr(100), + MinItems: int64Ptr(5), + UniqueItems: true, + MultipleOf: float64Ptr(5), + Enum: []interface{}{"hello", "world"}, + }, + SimpleSchema: SimpleSchema{ + Type: "string", + Format: "date", + CollectionFormat: "csv", + Items: &Items{ + Refable: Refable{Ref: MustCreateRef("Cat")}, + }, + Default: "8", + }, + ParamProps: ParamProps{ + Name: "param-name", + In: "header", + Required: true, + Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + Description: "the description of this parameter", + }, +} + +var parameterJSON = `{ + "items": { + "$ref": "Cat" + }, + "x-framework": "swagger-go", + "$ref": "Dog", + "description": "the description of this parameter", + "maximum": 100, + "minimum": 5, + "exclusiveMaximum": true, + "exclusiveMinimum": true, + "maxLength": 100, + "minLength": 5, + "pattern": "\\w{1,5}\\w+", + "maxItems": 100, + "minItems": 5, + "uniqueItems": true, + "multipleOf": 5, + "enum": ["hello", "world"], + "type": "string", + "format": "date", + "name": "param-name", + "in": "header", + "required": true, + "schema": { + "type": "string" + }, + "collectionFormat": "csv", + "default": "8" +}` + +func TestIntegrationParameter(t *testing.T) { + var actual Parameter + if assert.NoError(t, json.Unmarshal([]byte(parameterJSON), &actual)) { + assert.EqualValues(t, actual, parameter) + } + + assertParsesJSON(t, parameterJSON, parameter) +} + +func TestParameterSerialization(t *testing.T) { + items := &Items{ + SimpleSchema: SimpleSchema{Type: "string"}, + } + + intItems := &Items{ + SimpleSchema: SimpleSchema{Type: "int", Format: "int32"}, + } + + assertSerializeJSON(t, QueryParam("").Typed("string", ""), `{"type":"string","in":"query"}`) + + assertSerializeJSON(t, + QueryParam("").CollectionOf(items, "multi"), + `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"query"}`) + + assertSerializeJSON(t, PathParam("").Typed("string", ""), `{"type":"string","in":"path","required":true}`) + + assertSerializeJSON(t, + PathParam("").CollectionOf(items, "multi"), + `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"path","required":true}`) + + assertSerializeJSON(t, + PathParam("").CollectionOf(intItems, "multi"), + `{"type":"array","items":{"type":"int","format":"int32"},"collectionFormat":"multi","in":"path","required":true}`) + + assertSerializeJSON(t, HeaderParam("").Typed("string", ""), `{"type":"string","in":"header","required":true}`) + + assertSerializeJSON(t, + HeaderParam("").CollectionOf(items, "multi"), + `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"header","required":true}`) + schema := &Schema{SchemaProps: SchemaProps{ + Properties: map[string]Schema{ + "name": Schema{SchemaProps: SchemaProps{ + Type: []string{"string"}, + }}, + }, + }} + + refSchema := &Schema{ + SchemaProps: SchemaProps{Ref: MustCreateRef("Cat")}, + } + + assertSerializeJSON(t, + BodyParam("", schema), + `{"type":"object","in":"body","schema":{"properties":{"name":{"type":"string"}}}}`) + + assertSerializeJSON(t, + BodyParam("", refSchema), + `{"type":"object","in":"body","schema":{"$ref":"Cat"}}`) + + // array body param + assertSerializeJSON(t, + BodyParam("", ArrayProperty(RefProperty("Cat"))), + `{"type":"object","in":"body","schema":{"type":"array","items":{"$ref":"Cat"}}}`) + +} diff --git a/vendor/github.com/go-openapi/spec/path_item.go b/vendor/github.com/go-openapi/spec/path_item.go new file mode 100644 index 00000000..9ab3ec53 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/path_item.go @@ -0,0 +1,90 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// pathItemProps the path item specific properties +type PathItemProps struct { + Get *Operation `json:"get,omitempty"` + Put *Operation `json:"put,omitempty"` + Post *Operation `json:"post,omitempty"` + Delete *Operation `json:"delete,omitempty"` + Options *Operation `json:"options,omitempty"` + Head *Operation `json:"head,omitempty"` + Patch *Operation `json:"patch,omitempty"` + Parameters []Parameter `json:"parameters,omitempty"` +} + +// PathItem describes the operations available on a single path. +// A Path Item may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). +// The path itself is still exposed to the documentation viewer but they will +// not know which operations and parameters are available. +// +// For more information: http://goo.gl/8us55a#pathItemObject +type PathItem struct { + Refable + VendorExtensible + PathItemProps +} + +// JSONLookup look up a value by the json property name +func (p PathItem) JSONLookup(token string) (interface{}, error) { + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + if token == "$ref" { + return &p.Ref, nil + } + r, _, err := jsonpointer.GetForToken(p.PathItemProps, token) + return r, err +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (p *PathItem) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &p.Refable); err != nil { + return err + } + if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { + return err + } + if err := json.Unmarshal(data, &p.PathItemProps); err != nil { + return err + } + return nil +} + +// MarshalJSON converts this items object to JSON +func (p PathItem) MarshalJSON() ([]byte, error) { + b3, err := json.Marshal(p.Refable) + if err != nil { + return nil, err + } + b4, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } + b5, err := json.Marshal(p.PathItemProps) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b3, b4, b5) + return concated, nil +} diff --git a/vendor/github.com/go-openapi/spec/path_item_test.go b/vendor/github.com/go-openapi/spec/path_item_test.go new file mode 100644 index 00000000..ea77e6a9 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/path_item_test.go @@ -0,0 +1,81 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +var pathItem = PathItem{ + Refable: Refable{Ref: MustCreateRef("Dog")}, + VendorExtensible: VendorExtensible{ + Extensions: map[string]interface{}{ + "x-framework": "go-swagger", + }, + }, + PathItemProps: PathItemProps{ + Get: &Operation{ + OperationProps: OperationProps{Description: "get operation description"}, + }, + Put: &Operation{ + OperationProps: OperationProps{Description: "put operation description"}, + }, + Post: &Operation{ + OperationProps: OperationProps{Description: "post operation description"}, + }, + Delete: &Operation{ + OperationProps: OperationProps{Description: "delete operation description"}, + }, + Options: &Operation{ + OperationProps: OperationProps{Description: "options operation description"}, + }, + Head: &Operation{ + OperationProps: OperationProps{Description: "head operation description"}, + }, + Patch: &Operation{ + OperationProps: OperationProps{Description: "patch operation description"}, + }, + Parameters: []Parameter{ + Parameter{ + ParamProps: ParamProps{In: "path"}, + }, + }, + }, +} + +var pathItemJSON = `{ + "$ref": "Dog", + "x-framework": "go-swagger", + "get": { "description": "get operation description" }, + "put": { "description": "put operation description" }, + "post": { "description": "post operation description" }, + "delete": { "description": "delete operation description" }, + "options": { "description": "options operation description" }, + "head": { "description": "head operation description" }, + "patch": { "description": "patch operation description" }, + "parameters": [{"in":"path"}] +}` + +func TestIntegrationPathItem(t *testing.T) { + var actual PathItem + if assert.NoError(t, json.Unmarshal([]byte(pathItemJSON), &actual)) { + assert.EqualValues(t, actual, pathItem) + } + + assertParsesJSON(t, pathItemJSON, pathItem) +} diff --git a/vendor/github.com/go-openapi/spec/paths.go b/vendor/github.com/go-openapi/spec/paths.go new file mode 100644 index 00000000..9dc82a29 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/paths.go @@ -0,0 +1,97 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/go-openapi/swag" +) + +// Paths holds the relative paths to the individual endpoints. +// The path is appended to the [`basePath`](http://goo.gl/8us55a#swaggerBasePath) in order +// to construct the full URL. +// The Paths may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). +// +// For more information: http://goo.gl/8us55a#pathsObject +type Paths struct { + VendorExtensible + Paths map[string]PathItem `json:"-"` // custom serializer to flatten this, each entry must start with "/" +} + +// JSONLookup look up a value by the json property name +func (p Paths) JSONLookup(token string) (interface{}, error) { + if pi, ok := p.Paths[token]; ok { + return &pi, nil + } + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + return nil, fmt.Errorf("object has no field %q", token) +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (p *Paths) UnmarshalJSON(data []byte) error { + var res map[string]json.RawMessage + if err := json.Unmarshal(data, &res); err != nil { + return err + } + for k, v := range res { + if strings.HasPrefix(strings.ToLower(k), "x-") { + if p.Extensions == nil { + p.Extensions = make(map[string]interface{}) + } + var d interface{} + if err := json.Unmarshal(v, &d); err != nil { + return err + } + p.Extensions[k] = d + } + if strings.HasPrefix(k, "/") { + if p.Paths == nil { + p.Paths = make(map[string]PathItem) + } + var pi PathItem + if err := json.Unmarshal(v, &pi); err != nil { + return err + } + p.Paths[k] = pi + } + } + return nil +} + +// MarshalJSON converts this items object to JSON +func (p Paths) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } + + pths := make(map[string]PathItem) + for k, v := range p.Paths { + if strings.HasPrefix(k, "/") { + pths[k] = v + } + } + b2, err := json.Marshal(pths) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil +} diff --git a/vendor/github.com/go-openapi/spec/paths_test.go b/vendor/github.com/go-openapi/spec/paths_test.go new file mode 100644 index 00000000..5ccfd4a0 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/paths_test.go @@ -0,0 +1,43 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +var paths = Paths{ + VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{"x-framework": "go-swagger"}}, + Paths: map[string]PathItem{ + "/": PathItem{ + Refable: Refable{Ref: MustCreateRef("cats")}, + }, + }, +} + +var pathsJSON = `{"x-framework":"go-swagger","/":{"$ref":"cats"}}` + +func TestIntegrationPaths(t *testing.T) { + var actual Paths + if assert.NoError(t, json.Unmarshal([]byte(pathsJSON), &actual)) { + assert.EqualValues(t, actual, paths) + } + + assertParsesJSON(t, pathsJSON, paths) + +} diff --git a/vendor/github.com/go-openapi/spec/properties_test.go b/vendor/github.com/go-openapi/spec/properties_test.go new file mode 100644 index 00000000..90bd32c9 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/properties_test.go @@ -0,0 +1,58 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "testing" +) + +func TestPropertySerialization(t *testing.T) { + strProp := StringProperty() + strProp.Enum = append(strProp.Enum, "a", "b") + + prop := &Schema{SchemaProps: SchemaProps{ + Items: &SchemaOrArray{Schemas: []Schema{ + Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + }}, + }} + + var propSerData = []struct { + Schema *Schema + JSON string + }{ + {BooleanProperty(), `{"type":"boolean"}`}, + {DateProperty(), `{"type":"string","format":"date"}`}, + {DateTimeProperty(), `{"type":"string","format":"date-time"}`}, + {Float64Property(), `{"type":"number","format":"double"}`}, + {Float32Property(), `{"type":"number","format":"float"}`}, + {Int32Property(), `{"type":"integer","format":"int32"}`}, + {Int64Property(), `{"type":"integer","format":"int64"}`}, + {MapProperty(StringProperty()), `{"type":"object","additionalProperties":{"type":"string"}}`}, + {MapProperty(Int32Property()), `{"type":"object","additionalProperties":{"type":"integer","format":"int32"}}`}, + {RefProperty("Dog"), `{"$ref":"Dog"}`}, + {StringProperty(), `{"type":"string"}`}, + {strProp, `{"type":"string","enum":["a","b"]}`}, + {ArrayProperty(StringProperty()), `{"type":"array","items":{"type":"string"}}`}, + {prop, `{"items":[{"type":"string"},{"type":"string"}]}`}, + } + + for _, v := range propSerData { + t.Log("roundtripping for", v.JSON) + assertSerializeJSON(t, v.Schema, v.JSON) + assertParsesJSON(t, v.JSON, v.Schema) + } + +} diff --git a/vendor/github.com/go-openapi/spec/ref.go b/vendor/github.com/go-openapi/spec/ref.go new file mode 100644 index 00000000..f6bfbfb5 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/ref.go @@ -0,0 +1,171 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "net/http" + "os" + "path/filepath" + + "github.com/go-openapi/jsonreference" +) + +// Refable is a struct for things that accept a $ref property +type Refable struct { + Ref Ref +} + +// MarshalJSON marshals the ref to json +func (r Refable) MarshalJSON() ([]byte, error) { + return r.Ref.MarshalJSON() +} + +// UnmarshalJSON unmarshalss the ref from json +func (r *Refable) UnmarshalJSON(d []byte) error { + return json.Unmarshal(d, &r.Ref) +} + +// Ref represents a json reference that is potentially resolved +type Ref struct { + jsonreference.Ref +} + +// RemoteURI gets the remote uri part of the ref +func (r *Ref) RemoteURI() string { + if r.String() == "" { + return r.String() + } + + u := *r.GetURL() + u.Fragment = "" + return u.String() +} + +// IsValidURI returns true when the url the ref points to can be found +func (r *Ref) IsValidURI(basepaths ...string) bool { + if r.String() == "" { + return true + } + + v := r.RemoteURI() + if v == "" { + return true + } + + if r.HasFullURL { + rr, err := http.Get(v) + if err != nil { + return false + } + + return rr.StatusCode/100 == 2 + } + + if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) { + return false + } + + // check for local file + pth := v + if r.HasURLPathOnly { + base := "." + if len(basepaths) > 0 { + base = filepath.Dir(filepath.Join(basepaths...)) + } + p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth))) + if e != nil { + return false + } + pth = p + } + + fi, err := os.Stat(filepath.ToSlash(pth)) + if err != nil { + return false + } + + return !fi.IsDir() +} + +// Inherits creates a new reference from a parent and a child +// If the child cannot inherit from the parent, an error is returned +func (r *Ref) Inherits(child Ref) (*Ref, error) { + ref, err := r.Ref.Inherits(child.Ref) + if err != nil { + return nil, err + } + return &Ref{Ref: *ref}, nil +} + +// NewRef creates a new instance of a ref object +// returns an error when the reference uri is an invalid uri +func NewRef(refURI string) (Ref, error) { + ref, err := jsonreference.New(refURI) + if err != nil { + return Ref{}, err + } + return Ref{Ref: ref}, nil +} + +// MustCreateRef creates a ref object but +func MustCreateRef(refURI string) Ref { + return Ref{Ref: jsonreference.MustCreateRef(refURI)} +} + +// // NewResolvedRef creates a resolved ref +// func NewResolvedRef(refURI string, data interface{}) Ref { +// return Ref{ +// Ref: jsonreference.MustCreateRef(refURI), +// Resolved: data, +// } +// } + +// MarshalJSON marshals this ref into a JSON object +func (r Ref) MarshalJSON() ([]byte, error) { + str := r.String() + if str == "" { + if r.IsRoot() { + return []byte(`{"$ref":"#"}`), nil + } + return []byte("{}"), nil + } + v := map[string]interface{}{"$ref": str} + return json.Marshal(v) +} + +// UnmarshalJSON unmarshals this ref from a JSON object +func (r *Ref) UnmarshalJSON(d []byte) error { + var v map[string]interface{} + if err := json.Unmarshal(d, &v); err != nil { + return err + } + + if v == nil { + return nil + } + + if vv, ok := v["$ref"]; ok { + if str, ok := vv.(string); ok { + ref, err := jsonreference.New(str) + if err != nil { + return err + } + *r = Ref{Ref: ref} + } + } + + return nil +} diff --git a/vendor/github.com/go-openapi/spec/response.go b/vendor/github.com/go-openapi/spec/response.go new file mode 100644 index 00000000..a32b039e --- /dev/null +++ b/vendor/github.com/go-openapi/spec/response.go @@ -0,0 +1,134 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// ResponseProps properties specific to a response +type ResponseProps struct { + Description string `json:"description,omitempty"` + Schema *Schema `json:"schema,omitempty"` + Headers map[string]Header `json:"headers,omitempty"` + Examples map[string]interface{} `json:"examples,omitempty"` +} + +// Response describes a single response from an API Operation. +// +// For more information: http://goo.gl/8us55a#responseObject +type Response struct { + Refable + ResponseProps + VendorExtensible +} + +// JSONLookup look up a value by the json property name +func (p Response) JSONLookup(token string) (interface{}, error) { + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + if token == "$ref" { + return &p.Ref, nil + } + r, _, err := jsonpointer.GetForToken(p.ResponseProps, token) + return r, err +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (r *Response) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &r.ResponseProps); err != nil { + return err + } + if err := json.Unmarshal(data, &r.Refable); err != nil { + return err + } + if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { + return err + } + return nil +} + +// MarshalJSON converts this items object to JSON +func (r Response) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(r.ResponseProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(r.Refable) + if err != nil { + return nil, err + } + b3, err := json.Marshal(r.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2, b3), nil +} + +// NewResponse creates a new response instance +func NewResponse() *Response { + return new(Response) +} + +// ResponseRef creates a response as a json reference +func ResponseRef(url string) *Response { + resp := NewResponse() + resp.Ref = MustCreateRef(url) + return resp +} + +// WithDescription sets the description on this response, allows for chaining +func (r *Response) WithDescription(description string) *Response { + r.Description = description + return r +} + +// WithSchema sets the schema on this response, allows for chaining. +// Passing a nil argument removes the schema from this response +func (r *Response) WithSchema(schema *Schema) *Response { + r.Schema = schema + return r +} + +// AddHeader adds a header to this response +func (r *Response) AddHeader(name string, header *Header) *Response { + if header == nil { + return r.RemoveHeader(name) + } + if r.Headers == nil { + r.Headers = make(map[string]Header) + } + r.Headers[name] = *header + return r +} + +// RemoveHeader removes a header from this response +func (r *Response) RemoveHeader(name string) *Response { + delete(r.Headers, name) + return r +} + +// AddExample adds an example to this response +func (r *Response) AddExample(mediaType string, example interface{}) *Response { + if r.Examples == nil { + r.Examples = make(map[string]interface{}) + } + r.Examples[mediaType] = example + return r +} diff --git a/vendor/github.com/go-openapi/spec/response_test.go b/vendor/github.com/go-openapi/spec/response_test.go new file mode 100644 index 00000000..2a3ca409 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/response_test.go @@ -0,0 +1,53 @@ +// Copyright 2017 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +var response = Response{ + Refable: Refable{Ref: MustCreateRef("Dog")}, + VendorExtensible: VendorExtensible{ + Extensions: map[string]interface{}{ + "x-go-name": "PutDogExists", + }, + }, + ResponseProps: ResponseProps{ + Description: "Dog exists", + Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + }, +} + +var responseJSON = `{ + "$ref": "Dog", + "x-go-name": "PutDogExists", + "description": "Dog exists", + "schema": { + "type": "string" + } +}` + +func TestIntegrationResponse(t *testing.T) { + var actual Response + if assert.NoError(t, json.Unmarshal([]byte(responseJSON), &actual)) { + assert.EqualValues(t, actual, response) + } + + assertParsesJSON(t, responseJSON, response) +} diff --git a/vendor/github.com/go-openapi/spec/responses.go b/vendor/github.com/go-openapi/spec/responses.go new file mode 100644 index 00000000..3ab06697 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/responses.go @@ -0,0 +1,122 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "fmt" + "reflect" + "strconv" + + "github.com/go-openapi/swag" +) + +// Responses is a container for the expected responses of an operation. +// The container maps a HTTP response code to the expected response. +// It is not expected from the documentation to necessarily cover all possible HTTP response codes, +// since they may not be known in advance. However, it is expected from the documentation to cover +// a successful operation response and any known errors. +// +// The `default` can be used a default response object for all HTTP codes that are not covered +// individually by the specification. +// +// The `Responses Object` MUST contain at least one response code, and it SHOULD be the response +// for a successful operation call. +// +// For more information: http://goo.gl/8us55a#responsesObject +type Responses struct { + VendorExtensible + ResponsesProps +} + +// JSONLookup implements an interface to customize json pointer lookup +func (r Responses) JSONLookup(token string) (interface{}, error) { + if token == "default" { + return r.Default, nil + } + if ex, ok := r.Extensions[token]; ok { + return &ex, nil + } + if i, err := strconv.Atoi(token); err == nil { + if scr, ok := r.StatusCodeResponses[i]; ok { + return scr, nil + } + } + return nil, fmt.Errorf("object has no field %q", token) +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (r *Responses) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { + return err + } + if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { + return err + } + if reflect.DeepEqual(ResponsesProps{}, r.ResponsesProps) { + r.ResponsesProps = ResponsesProps{} + } + return nil +} + +// MarshalJSON converts this items object to JSON +func (r Responses) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(r.ResponsesProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(r.VendorExtensible) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil +} + +type ResponsesProps struct { + Default *Response + StatusCodeResponses map[int]Response +} + +func (r ResponsesProps) MarshalJSON() ([]byte, error) { + toser := map[string]Response{} + if r.Default != nil { + toser["default"] = *r.Default + } + for k, v := range r.StatusCodeResponses { + toser[strconv.Itoa(k)] = v + } + return json.Marshal(toser) +} + +func (r *ResponsesProps) UnmarshalJSON(data []byte) error { + var res map[string]Response + if err := json.Unmarshal(data, &res); err != nil { + return nil + } + if v, ok := res["default"]; ok { + r.Default = &v + delete(res, "default") + } + for k, v := range res { + if nk, err := strconv.Atoi(k); err == nil { + if r.StatusCodeResponses == nil { + r.StatusCodeResponses = map[int]Response{} + } + r.StatusCodeResponses[nk] = v + } + } + return nil +} diff --git a/vendor/github.com/go-openapi/spec/schema.go b/vendor/github.com/go-openapi/spec/schema.go new file mode 100644 index 00000000..04aafcc7 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/schema.go @@ -0,0 +1,628 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "fmt" + "net/url" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// BooleanProperty creates a boolean property +func BooleanProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}} +} + +// BoolProperty creates a boolean property +func BoolProperty() *Schema { return BooleanProperty() } + +// StringProperty creates a string property +func StringProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} +} + +// CharProperty creates a string property +func CharProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} +} + +// Float64Property creates a float64/double property +func Float64Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}} +} + +// Float32Property creates a float32/float property +func Float32Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}} +} + +// Int8Property creates an int8 property +func Int8Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}} +} + +// Int16Property creates an int16 property +func Int16Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}} +} + +// Int32Property creates an int32 property +func Int32Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}} +} + +// Int64Property creates an int64 property +func Int64Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}} +} + +// StrFmtProperty creates a property for the named string format +func StrFmtProperty(format string) *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}} +} + +// DateProperty creates a date property +func DateProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}} +} + +// DateTimeProperty creates a date time property +func DateTimeProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}} +} + +// MapProperty creates a map property +func MapProperty(property *Schema) *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"object"}, AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}} +} + +// RefProperty creates a ref property +func RefProperty(name string) *Schema { + return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} +} + +// RefSchema creates a ref property +func RefSchema(name string) *Schema { + return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} +} + +// ArrayProperty creates an array property +func ArrayProperty(items *Schema) *Schema { + if items == nil { + return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}} + } + return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}} +} + +// ComposedSchema creates a schema with allOf +func ComposedSchema(schemas ...Schema) *Schema { + s := new(Schema) + s.AllOf = schemas + return s +} + +// SchemaURL represents a schema url +type SchemaURL string + +// MarshalJSON marshal this to JSON +func (r SchemaURL) MarshalJSON() ([]byte, error) { + if r == "" { + return []byte("{}"), nil + } + v := map[string]interface{}{"$schema": string(r)} + return json.Marshal(v) +} + +// UnmarshalJSON unmarshal this from JSON +func (r *SchemaURL) UnmarshalJSON(data []byte) error { + var v map[string]interface{} + if err := json.Unmarshal(data, &v); err != nil { + return err + } + if v == nil { + return nil + } + if vv, ok := v["$schema"]; ok { + if str, ok := vv.(string); ok { + u, err := url.Parse(str) + if err != nil { + return err + } + + *r = SchemaURL(u.String()) + } + } + return nil +} + +// type ExtraSchemaProps map[string]interface{} + +// // JSONSchema represents a structure that is a json schema draft 04 +// type JSONSchema struct { +// SchemaProps +// ExtraSchemaProps +// } + +// // MarshalJSON marshal this to JSON +// func (s JSONSchema) MarshalJSON() ([]byte, error) { +// b1, err := json.Marshal(s.SchemaProps) +// if err != nil { +// return nil, err +// } +// b2, err := s.Ref.MarshalJSON() +// if err != nil { +// return nil, err +// } +// b3, err := s.Schema.MarshalJSON() +// if err != nil { +// return nil, err +// } +// b4, err := json.Marshal(s.ExtraSchemaProps) +// if err != nil { +// return nil, err +// } +// return swag.ConcatJSON(b1, b2, b3, b4), nil +// } + +// // UnmarshalJSON marshal this from JSON +// func (s *JSONSchema) UnmarshalJSON(data []byte) error { +// var sch JSONSchema +// if err := json.Unmarshal(data, &sch.SchemaProps); err != nil { +// return err +// } +// if err := json.Unmarshal(data, &sch.Ref); err != nil { +// return err +// } +// if err := json.Unmarshal(data, &sch.Schema); err != nil { +// return err +// } +// if err := json.Unmarshal(data, &sch.ExtraSchemaProps); err != nil { +// return err +// } +// *s = sch +// return nil +// } + +type SchemaProps struct { + ID string `json:"id,omitempty"` + Ref Ref `json:"-,omitempty"` + Schema SchemaURL `json:"-,omitempty"` + Description string `json:"description,omitempty"` + Type StringOrArray `json:"type,omitempty"` + Format string `json:"format,omitempty"` + Title string `json:"title,omitempty"` + Default interface{} `json:"default,omitempty"` + Maximum *float64 `json:"maximum,omitempty"` + ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` + Minimum *float64 `json:"minimum,omitempty"` + ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` + MaxLength *int64 `json:"maxLength,omitempty"` + MinLength *int64 `json:"minLength,omitempty"` + Pattern string `json:"pattern,omitempty"` + MaxItems *int64 `json:"maxItems,omitempty"` + MinItems *int64 `json:"minItems,omitempty"` + UniqueItems bool `json:"uniqueItems,omitempty"` + MultipleOf *float64 `json:"multipleOf,omitempty"` + Enum []interface{} `json:"enum,omitempty"` + MaxProperties *int64 `json:"maxProperties,omitempty"` + MinProperties *int64 `json:"minProperties,omitempty"` + Required []string `json:"required,omitempty"` + Items *SchemaOrArray `json:"items,omitempty"` + AllOf []Schema `json:"allOf,omitempty"` + OneOf []Schema `json:"oneOf,omitempty"` + AnyOf []Schema `json:"anyOf,omitempty"` + Not *Schema `json:"not,omitempty"` + Properties map[string]Schema `json:"properties,omitempty"` + AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"` + PatternProperties map[string]Schema `json:"patternProperties,omitempty"` + Dependencies Dependencies `json:"dependencies,omitempty"` + AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"` + Definitions Definitions `json:"definitions,omitempty"` +} + +type SwaggerSchemaProps struct { + Discriminator string `json:"discriminator,omitempty"` + ReadOnly bool `json:"readOnly,omitempty"` + XML *XMLObject `json:"xml,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` + Example interface{} `json:"example,omitempty"` +} + +// Schema the schema object allows the definition of input and output data types. +// These types can be objects, but also primitives and arrays. +// This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) +// and uses a predefined subset of it. +// On top of this subset, there are extensions provided by this specification to allow for more complete documentation. +// +// For more information: http://goo.gl/8us55a#schemaObject +type Schema struct { + VendorExtensible + SchemaProps + SwaggerSchemaProps + ExtraProps map[string]interface{} `json:"-"` +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s Schema) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } + + if ex, ok := s.ExtraProps[token]; ok { + return &ex, nil + } + + r, _, err := jsonpointer.GetForToken(s.SchemaProps, token) + if r != nil || (err != nil && !strings.HasPrefix(err.Error(), "object has no field")) { + return r, err + } + r, _, err = jsonpointer.GetForToken(s.SwaggerSchemaProps, token) + return r, err +} + +// WithID sets the id for this schema, allows for chaining +func (s *Schema) WithID(id string) *Schema { + s.ID = id + return s +} + +// WithTitle sets the title for this schema, allows for chaining +func (s *Schema) WithTitle(title string) *Schema { + s.Title = title + return s +} + +// WithDescription sets the description for this schema, allows for chaining +func (s *Schema) WithDescription(description string) *Schema { + s.Description = description + return s +} + +// WithProperties sets the properties for this schema +func (s *Schema) WithProperties(schemas map[string]Schema) *Schema { + s.Properties = schemas + return s +} + +// SetProperty sets a property on this schema +func (s *Schema) SetProperty(name string, schema Schema) *Schema { + if s.Properties == nil { + s.Properties = make(map[string]Schema) + } + s.Properties[name] = schema + return s +} + +// WithAllOf sets the all of property +func (s *Schema) WithAllOf(schemas ...Schema) *Schema { + s.AllOf = schemas + return s +} + +// WithMaxProperties sets the max number of properties an object can have +func (s *Schema) WithMaxProperties(max int64) *Schema { + s.MaxProperties = &max + return s +} + +// WithMinProperties sets the min number of properties an object must have +func (s *Schema) WithMinProperties(min int64) *Schema { + s.MinProperties = &min + return s +} + +// Typed sets the type of this schema for a single value item +func (s *Schema) Typed(tpe, format string) *Schema { + s.Type = []string{tpe} + s.Format = format + return s +} + +// AddType adds a type with potential format to the types for this schema +func (s *Schema) AddType(tpe, format string) *Schema { + s.Type = append(s.Type, tpe) + if format != "" { + s.Format = format + } + return s +} + +// CollectionOf a fluent builder method for an array parameter +func (s *Schema) CollectionOf(items Schema) *Schema { + s.Type = []string{"array"} + s.Items = &SchemaOrArray{Schema: &items} + return s +} + +// WithDefault sets the default value on this parameter +func (s *Schema) WithDefault(defaultValue interface{}) *Schema { + s.Default = defaultValue + return s +} + +// WithRequired flags this parameter as required +func (s *Schema) WithRequired(items ...string) *Schema { + s.Required = items + return s +} + +// AddRequired adds field names to the required properties array +func (s *Schema) AddRequired(items ...string) *Schema { + s.Required = append(s.Required, items...) + return s +} + +// WithMaxLength sets a max length value +func (s *Schema) WithMaxLength(max int64) *Schema { + s.MaxLength = &max + return s +} + +// WithMinLength sets a min length value +func (s *Schema) WithMinLength(min int64) *Schema { + s.MinLength = &min + return s +} + +// WithPattern sets a pattern value +func (s *Schema) WithPattern(pattern string) *Schema { + s.Pattern = pattern + return s +} + +// WithMultipleOf sets a multiple of value +func (s *Schema) WithMultipleOf(number float64) *Schema { + s.MultipleOf = &number + return s +} + +// WithMaximum sets a maximum number value +func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema { + s.Maximum = &max + s.ExclusiveMaximum = exclusive + return s +} + +// WithMinimum sets a minimum number value +func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema { + s.Minimum = &min + s.ExclusiveMinimum = exclusive + return s +} + +// WithEnum sets a the enum values (replace) +func (s *Schema) WithEnum(values ...interface{}) *Schema { + s.Enum = append([]interface{}{}, values...) + return s +} + +// WithMaxItems sets the max items +func (s *Schema) WithMaxItems(size int64) *Schema { + s.MaxItems = &size + return s +} + +// WithMinItems sets the min items +func (s *Schema) WithMinItems(size int64) *Schema { + s.MinItems = &size + return s +} + +// UniqueValues dictates that this array can only have unique items +func (s *Schema) UniqueValues() *Schema { + s.UniqueItems = true + return s +} + +// AllowDuplicates this array can have duplicates +func (s *Schema) AllowDuplicates() *Schema { + s.UniqueItems = false + return s +} + +// AddToAllOf adds a schema to the allOf property +func (s *Schema) AddToAllOf(schemas ...Schema) *Schema { + s.AllOf = append(s.AllOf, schemas...) + return s +} + +// WithDiscriminator sets the name of the discriminator field +func (s *Schema) WithDiscriminator(discriminator string) *Schema { + s.Discriminator = discriminator + return s +} + +// AsReadOnly flags this schema as readonly +func (s *Schema) AsReadOnly() *Schema { + s.ReadOnly = true + return s +} + +// AsWritable flags this schema as writeable (not read-only) +func (s *Schema) AsWritable() *Schema { + s.ReadOnly = false + return s +} + +// WithExample sets the example for this schema +func (s *Schema) WithExample(example interface{}) *Schema { + s.Example = example + return s +} + +// WithExternalDocs sets/removes the external docs for/from this schema. +// When you pass empty strings as params the external documents will be removed. +// When you pass non-empty string as one value then those values will be used on the external docs object. +// So when you pass a non-empty description, you should also pass the url and vice versa. +func (s *Schema) WithExternalDocs(description, url string) *Schema { + if description == "" && url == "" { + s.ExternalDocs = nil + return s + } + + if s.ExternalDocs == nil { + s.ExternalDocs = &ExternalDocumentation{} + } + s.ExternalDocs.Description = description + s.ExternalDocs.URL = url + return s +} + +// WithXMLName sets the xml name for the object +func (s *Schema) WithXMLName(name string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Name = name + return s +} + +// WithXMLNamespace sets the xml namespace for the object +func (s *Schema) WithXMLNamespace(namespace string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Namespace = namespace + return s +} + +// WithXMLPrefix sets the xml prefix for the object +func (s *Schema) WithXMLPrefix(prefix string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Prefix = prefix + return s +} + +// AsXMLAttribute flags this object as xml attribute +func (s *Schema) AsXMLAttribute() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Attribute = true + return s +} + +// AsXMLElement flags this object as an xml node +func (s *Schema) AsXMLElement() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Attribute = false + return s +} + +// AsWrappedXML flags this object as wrapped, this is mostly useful for array types +func (s *Schema) AsWrappedXML() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Wrapped = true + return s +} + +// AsUnwrappedXML flags this object as an xml node +func (s *Schema) AsUnwrappedXML() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Wrapped = false + return s +} + +// MarshalJSON marshal this to JSON +func (s Schema) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(s.SchemaProps) + if err != nil { + return nil, fmt.Errorf("schema props %v", err) + } + b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, fmt.Errorf("vendor props %v", err) + } + b3, err := s.Ref.MarshalJSON() + if err != nil { + return nil, fmt.Errorf("ref prop %v", err) + } + b4, err := s.Schema.MarshalJSON() + if err != nil { + return nil, fmt.Errorf("schema prop %v", err) + } + b5, err := json.Marshal(s.SwaggerSchemaProps) + if err != nil { + return nil, fmt.Errorf("common validations %v", err) + } + var b6 []byte + if s.ExtraProps != nil { + jj, err := json.Marshal(s.ExtraProps) + if err != nil { + return nil, fmt.Errorf("extra props %v", err) + } + b6 = jj + } + return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil +} + +// UnmarshalJSON marshal this from JSON +func (s *Schema) UnmarshalJSON(data []byte) error { + var sch Schema + if err := json.Unmarshal(data, &sch.SchemaProps); err != nil { + return err + } + if err := json.Unmarshal(data, &sch.Ref); err != nil { + return err + } + if err := json.Unmarshal(data, &sch.Schema); err != nil { + return err + } + if err := json.Unmarshal(data, &sch.SwaggerSchemaProps); err != nil { + return err + } + + var d map[string]interface{} + if err := json.Unmarshal(data, &d); err != nil { + return err + } + + delete(d, "$ref") + delete(d, "$schema") + for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) { + delete(d, pn) + } + + for k, vv := range d { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + if sch.Extensions == nil { + sch.Extensions = map[string]interface{}{} + } + sch.Extensions[k] = vv + continue + } + if sch.ExtraProps == nil { + sch.ExtraProps = map[string]interface{}{} + } + sch.ExtraProps[k] = vv + } + + *s = sch + + return nil +} diff --git a/vendor/github.com/go-openapi/spec/schema_test.go b/vendor/github.com/go-openapi/spec/schema_test.go new file mode 100644 index 00000000..2e49fbc1 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/schema_test.go @@ -0,0 +1,205 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +var schema = Schema{ + VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{"x-framework": "go-swagger"}}, + SchemaProps: SchemaProps{ + Ref: MustCreateRef("Cat"), + Type: []string{"string"}, + Format: "date", + Description: "the description of this schema", + Title: "the title", + Default: "blah", + Maximum: float64Ptr(100), + ExclusiveMaximum: true, + ExclusiveMinimum: true, + Minimum: float64Ptr(5), + MaxLength: int64Ptr(100), + MinLength: int64Ptr(5), + Pattern: "\\w{1,5}\\w+", + MaxItems: int64Ptr(100), + MinItems: int64Ptr(5), + UniqueItems: true, + MultipleOf: float64Ptr(5), + Enum: []interface{}{"hello", "world"}, + MaxProperties: int64Ptr(5), + MinProperties: int64Ptr(1), + Required: []string{"id", "name"}, + Items: &SchemaOrArray{Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}, + AllOf: []Schema{Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}, + Properties: map[string]Schema{ + "id": Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}}, + "name": Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + }, + AdditionalProperties: &SchemaOrBool{Allows: true, Schema: &Schema{SchemaProps: SchemaProps{ + Type: []string{"integer"}, + Format: "int32", + }}}, + }, + SwaggerSchemaProps: SwaggerSchemaProps{ + Discriminator: "not this", + ReadOnly: true, + XML: &XMLObject{"sch", "io", "sw", true, true}, + ExternalDocs: &ExternalDocumentation{ + Description: "the documentation etc", + URL: "http://readthedocs.org/swagger", + }, + Example: []interface{}{ + map[string]interface{}{ + "id": 1, + "name": "a book", + }, + map[string]interface{}{ + "id": 2, + "name": "the thing", + }, + }, + }, +} + +var schemaJSON = `{ + "x-framework": "go-swagger", + "$ref": "Cat", + "description": "the description of this schema", + "maximum": 100, + "minimum": 5, + "exclusiveMaximum": true, + "exclusiveMinimum": true, + "maxLength": 100, + "minLength": 5, + "pattern": "\\w{1,5}\\w+", + "maxItems": 100, + "minItems": 5, + "uniqueItems": true, + "multipleOf": 5, + "enum": ["hello", "world"], + "type": "string", + "format": "date", + "title": "the title", + "default": "blah", + "maxProperties": 5, + "minProperties": 1, + "required": ["id", "name"], + "items": { + "type": "string" + }, + "allOf": [ + { + "type": "string" + } + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "discriminator": "not this", + "readOnly": true, + "xml": { + "name": "sch", + "namespace": "io", + "prefix": "sw", + "wrapped": true, + "attribute": true + }, + "externalDocs": { + "description": "the documentation etc", + "url": "http://readthedocs.org/swagger" + }, + "example": [ + { + "id": 1, + "name": "a book" + }, + { + "id": 2, + "name": "the thing" + } + ], + "additionalProperties": { + "type": "integer", + "format": "int32" + } +} +` + +func TestSchema(t *testing.T) { + + expected := map[string]interface{}{} + json.Unmarshal([]byte(schemaJSON), &expected) + b, err := json.Marshal(schema) + if assert.NoError(t, err) { + var actual map[string]interface{} + json.Unmarshal(b, &actual) + assert.Equal(t, expected, actual) + } + + actual2 := Schema{} + if assert.NoError(t, json.Unmarshal([]byte(schemaJSON), &actual2)) { + assert.Equal(t, schema.Ref, actual2.Ref) + assert.Equal(t, schema.Description, actual2.Description) + assert.Equal(t, schema.Maximum, actual2.Maximum) + assert.Equal(t, schema.Minimum, actual2.Minimum) + assert.Equal(t, schema.ExclusiveMinimum, actual2.ExclusiveMinimum) + assert.Equal(t, schema.ExclusiveMaximum, actual2.ExclusiveMaximum) + assert.Equal(t, schema.MaxLength, actual2.MaxLength) + assert.Equal(t, schema.MinLength, actual2.MinLength) + assert.Equal(t, schema.Pattern, actual2.Pattern) + assert.Equal(t, schema.MaxItems, actual2.MaxItems) + assert.Equal(t, schema.MinItems, actual2.MinItems) + assert.True(t, actual2.UniqueItems) + assert.Equal(t, schema.MultipleOf, actual2.MultipleOf) + assert.Equal(t, schema.Enum, actual2.Enum) + assert.Equal(t, schema.Type, actual2.Type) + assert.Equal(t, schema.Format, actual2.Format) + assert.Equal(t, schema.Title, actual2.Title) + assert.Equal(t, schema.MaxProperties, actual2.MaxProperties) + assert.Equal(t, schema.MinProperties, actual2.MinProperties) + assert.Equal(t, schema.Required, actual2.Required) + assert.Equal(t, schema.Items, actual2.Items) + assert.Equal(t, schema.AllOf, actual2.AllOf) + assert.Equal(t, schema.Properties, actual2.Properties) + assert.Equal(t, schema.Discriminator, actual2.Discriminator) + assert.Equal(t, schema.ReadOnly, actual2.ReadOnly) + assert.Equal(t, schema.XML, actual2.XML) + assert.Equal(t, schema.ExternalDocs, actual2.ExternalDocs) + assert.Equal(t, schema.AdditionalProperties, actual2.AdditionalProperties) + assert.Equal(t, schema.Extensions, actual2.Extensions) + examples := actual2.Example.([]interface{}) + expEx := schema.Example.([]interface{}) + ex1 := examples[0].(map[string]interface{}) + ex2 := examples[1].(map[string]interface{}) + exp1 := expEx[0].(map[string]interface{}) + exp2 := expEx[1].(map[string]interface{}) + + assert.EqualValues(t, exp1["id"], ex1["id"]) + assert.Equal(t, exp1["name"], ex1["name"]) + assert.EqualValues(t, exp2["id"], ex2["id"]) + assert.Equal(t, exp2["name"], ex2["name"]) + } + +} diff --git a/vendor/github.com/go-openapi/spec/schemas/jsonschema-draft-04.json b/vendor/github.com/go-openapi/spec/schemas/jsonschema-draft-04.json new file mode 100644 index 00000000..85eb502a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/schemas/jsonschema-draft-04.json @@ -0,0 +1,150 @@ +{ + "id": "http://json-schema.org/draft-04/schema#", + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "positiveInteger": { + "type": "integer", + "minimum": 0 + }, + "positiveIntegerDefault0": { + "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ] + }, + "simpleTypes": { + "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "minItems": 1, + "uniqueItems": true + } + }, + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uri" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "boolean", + "default": false + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "boolean", + "default": false + }, + "maxLength": { "$ref": "#/definitions/positiveInteger" }, + "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { + "anyOf": [ + { "type": "boolean" }, + { "$ref": "#" } + ], + "default": {} + }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": {} + }, + "maxItems": { "$ref": "#/definitions/positiveInteger" }, + "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxProperties": { "$ref": "#/definitions/positiveInteger" }, + "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { + "anyOf": [ + { "type": "boolean" }, + { "$ref": "#" } + ], + "default": {} + }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "dependencies": { + "exclusiveMaximum": [ "maximum" ], + "exclusiveMinimum": [ "minimum" ] + }, + "default": {} +} diff --git a/vendor/github.com/go-openapi/spec/schemas/v2/README.md b/vendor/github.com/go-openapi/spec/schemas/v2/README.md new file mode 100644 index 00000000..32c1b929 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/schemas/v2/README.md @@ -0,0 +1,5 @@ +# Swagger 2.0 specification schema + +This folder contains the Swagger 2.0 specification schema files maintained here: + +https://github.com/reverb/swagger-spec/blob/master/schemas/v2.0 \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/schemas/v2/schema.json b/vendor/github.com/go-openapi/spec/schemas/v2/schema.json new file mode 100644 index 00000000..4dfccd07 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/schemas/v2/schema.json @@ -0,0 +1,1607 @@ +{ + "title": "A JSON Schema for Swagger 2.0 API.", + "id": "http://swagger.io/v2/schema.json#", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "required": [ + "swagger", + "info", + "paths" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "swagger": { + "type": "string", + "enum": [ + "2.0" + ], + "description": "The Swagger version of this document." + }, + "info": { + "$ref": "#/definitions/info" + }, + "host": { + "type": "string", + "pattern": "^[^{}/ :\\\\]+(?::\\d+)?$", + "description": "The host (name or ip) of the API. Example: 'swagger.io'" + }, + "basePath": { + "type": "string", + "pattern": "^/", + "description": "The base path to the API. Example: '/api'." + }, + "schemes": { + "$ref": "#/definitions/schemesList" + }, + "consumes": { + "description": "A list of MIME types accepted by the API.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "produces": { + "description": "A list of MIME types the API can produce.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "paths": { + "$ref": "#/definitions/paths" + }, + "definitions": { + "$ref": "#/definitions/definitions" + }, + "parameters": { + "$ref": "#/definitions/parameterDefinitions" + }, + "responses": { + "$ref": "#/definitions/responseDefinitions" + }, + "security": { + "$ref": "#/definitions/security" + }, + "securityDefinitions": { + "$ref": "#/definitions/securityDefinitions" + }, + "tags": { + "type": "array", + "items": { + "$ref": "#/definitions/tag" + }, + "uniqueItems": true + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + } + }, + "definitions": { + "info": { + "type": "object", + "description": "General information about the API.", + "required": [ + "version", + "title" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "title": { + "type": "string", + "description": "A unique and precise title of the API." + }, + "version": { + "type": "string", + "description": "A semantic version number of the API." + }, + "description": { + "type": "string", + "description": "A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed." + }, + "termsOfService": { + "type": "string", + "description": "The terms of service for the API." + }, + "contact": { + "$ref": "#/definitions/contact" + }, + "license": { + "$ref": "#/definitions/license" + } + } + }, + "contact": { + "type": "object", + "description": "Contact information for the owners of the API.", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "The identifying name of the contact person/organization." + }, + "url": { + "type": "string", + "description": "The URL pointing to the contact information.", + "format": "uri" + }, + "email": { + "type": "string", + "description": "The email address of the contact person/organization.", + "format": "email" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "license": { + "type": "object", + "required": [ + "name" + ], + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "The name of the license type. It's encouraged to use an OSI compatible license." + }, + "url": { + "type": "string", + "description": "The URL pointing to the license.", + "format": "uri" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "paths": { + "type": "object", + "description": "Relative paths to the individual endpoints. They must be relative to the 'basePath'.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + }, + "^/": { + "$ref": "#/definitions/pathItem" + } + }, + "additionalProperties": false + }, + "definitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/schema" + }, + "description": "One or more JSON objects describing the schemas being consumed and produced by the API." + }, + "parameterDefinitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/parameter" + }, + "description": "One or more JSON representations for parameters" + }, + "responseDefinitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/response" + }, + "description": "One or more JSON representations for parameters" + }, + "externalDocs": { + "type": "object", + "additionalProperties": false, + "description": "information about external documentation", + "required": [ + "url" + ], + "properties": { + "description": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "examples": { + "type": "object", + "additionalProperties": true + }, + "mimeType": { + "type": "string", + "description": "The MIME type of the HTTP message." + }, + "operation": { + "type": "object", + "required": [ + "responses" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "summary": { + "type": "string", + "description": "A brief summary of the operation." + }, + "description": { + "type": "string", + "description": "A longer description of the operation, GitHub Flavored Markdown is allowed." + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "operationId": { + "type": "string", + "description": "A unique identifier of the operation." + }, + "produces": { + "description": "A list of MIME types the API can produce.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "consumes": { + "description": "A list of MIME types the API can consume.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "parameters": { + "$ref": "#/definitions/parametersList" + }, + "responses": { + "$ref": "#/definitions/responses" + }, + "schemes": { + "$ref": "#/definitions/schemesList" + }, + "deprecated": { + "type": "boolean", + "default": false + }, + "security": { + "$ref": "#/definitions/security" + } + } + }, + "pathItem": { + "type": "object", + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "$ref": { + "type": "string" + }, + "get": { + "$ref": "#/definitions/operation" + }, + "put": { + "$ref": "#/definitions/operation" + }, + "post": { + "$ref": "#/definitions/operation" + }, + "delete": { + "$ref": "#/definitions/operation" + }, + "options": { + "$ref": "#/definitions/operation" + }, + "head": { + "$ref": "#/definitions/operation" + }, + "patch": { + "$ref": "#/definitions/operation" + }, + "parameters": { + "$ref": "#/definitions/parametersList" + } + } + }, + "responses": { + "type": "object", + "description": "Response objects names can either be any valid HTTP status code or 'default'.", + "minProperties": 1, + "additionalProperties": false, + "patternProperties": { + "^([0-9]{3})$|^(default)$": { + "$ref": "#/definitions/responseValue" + }, + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "not": { + "type": "object", + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + } + }, + "responseValue": { + "oneOf": [ + { + "$ref": "#/definitions/response" + }, + { + "$ref": "#/definitions/jsonReference" + } + ] + }, + "response": { + "type": "object", + "required": [ + "description" + ], + "properties": { + "description": { + "type": "string" + }, + "schema": { + "oneOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "$ref": "#/definitions/fileSchema" + } + ] + }, + "headers": { + "$ref": "#/definitions/headers" + }, + "examples": { + "$ref": "#/definitions/examples" + } + }, + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "headers": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/header" + } + }, + "header": { + "type": "object", + "additionalProperties": false, + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "integer", + "boolean", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "vendorExtension": { + "description": "Any property starting with x- is valid.", + "additionalProperties": true, + "additionalItems": true + }, + "bodyParameter": { + "type": "object", + "required": [ + "name", + "in", + "schema" + ], + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "body" + ] + }, + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "schema": { + "$ref": "#/definitions/schema" + } + }, + "additionalProperties": false + }, + "headerParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "header" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "queryParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "query" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "allowEmptyValue": { + "type": "boolean", + "default": false, + "description": "allows sending a parameter by name only or with an empty value." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormatWithMulti" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "formDataParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "formData" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "allowEmptyValue": { + "type": "boolean", + "default": false, + "description": "allows sending a parameter by name only or with an empty value." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array", + "file" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormatWithMulti" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "pathParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "required": [ + "required" + ], + "properties": { + "required": { + "type": "boolean", + "enum": [ + true + ], + "description": "Determines whether or not this parameter is required or optional." + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "path" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "nonBodyParameter": { + "type": "object", + "required": [ + "name", + "in", + "type" + ], + "oneOf": [ + { + "$ref": "#/definitions/headerParameterSubSchema" + }, + { + "$ref": "#/definitions/formDataParameterSubSchema" + }, + { + "$ref": "#/definitions/queryParameterSubSchema" + }, + { + "$ref": "#/definitions/pathParameterSubSchema" + } + ] + }, + "parameter": { + "oneOf": [ + { + "$ref": "#/definitions/bodyParameter" + }, + { + "$ref": "#/definitions/nonBodyParameter" + } + ] + }, + "schema": { + "type": "object", + "description": "A deterministic version of a JSON Schema object.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "$ref": { + "type": "string" + }, + "format": { + "type": "string" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "multipleOf": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" + }, + "maximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" + }, + "exclusiveMaximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" + }, + "minimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" + }, + "exclusiveMinimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" + }, + "maxLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "pattern": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" + }, + "maxItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "uniqueItems": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" + }, + "maxProperties": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minProperties": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "required": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" + }, + "enum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" + }, + "additionalProperties": { + "anyOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "type": "boolean" + } + ], + "default": {} + }, + "type": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/type" + }, + "items": { + "anyOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/definitions/schema" + } + } + ], + "default": {} + }, + "allOf": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/definitions/schema" + } + }, + "properties": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/schema" + }, + "default": {} + }, + "discriminator": { + "type": "string" + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "xml": { + "$ref": "#/definitions/xml" + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "example": {} + }, + "additionalProperties": false + }, + "fileSchema": { + "type": "object", + "description": "A deterministic version of a JSON Schema object.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "required": [ + "type" + ], + "properties": { + "format": { + "type": "string" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "required": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" + }, + "type": { + "type": "string", + "enum": [ + "file" + ] + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "example": {} + }, + "additionalProperties": false + }, + "primitivesItems": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "integer", + "boolean", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "security": { + "type": "array", + "items": { + "$ref": "#/definitions/securityRequirement" + }, + "uniqueItems": true + }, + "securityRequirement": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + } + }, + "xml": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "namespace": { + "type": "string" + }, + "prefix": { + "type": "string" + }, + "attribute": { + "type": "boolean", + "default": false + }, + "wrapped": { + "type": "boolean", + "default": false + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "tag": { + "type": "object", + "additionalProperties": false, + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "securityDefinitions": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "$ref": "#/definitions/basicAuthenticationSecurity" + }, + { + "$ref": "#/definitions/apiKeySecurity" + }, + { + "$ref": "#/definitions/oauth2ImplicitSecurity" + }, + { + "$ref": "#/definitions/oauth2PasswordSecurity" + }, + { + "$ref": "#/definitions/oauth2ApplicationSecurity" + }, + { + "$ref": "#/definitions/oauth2AccessCodeSecurity" + } + ] + } + }, + "basicAuthenticationSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "basic" + ] + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "apiKeySecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "name", + "in" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "apiKey" + ] + }, + "name": { + "type": "string" + }, + "in": { + "type": "string", + "enum": [ + "header", + "query" + ] + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2ImplicitSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "authorizationUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "implicit" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "authorizationUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2PasswordSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "password" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2ApplicationSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "application" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2AccessCodeSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "authorizationUrl", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "accessCode" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "authorizationUrl": { + "type": "string", + "format": "uri" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2Scopes": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "mediaTypeList": { + "type": "array", + "items": { + "$ref": "#/definitions/mimeType" + }, + "uniqueItems": true + }, + "parametersList": { + "type": "array", + "description": "The parameters needed to send a valid API call.", + "additionalItems": false, + "items": { + "oneOf": [ + { + "$ref": "#/definitions/parameter" + }, + { + "$ref": "#/definitions/jsonReference" + } + ] + }, + "uniqueItems": true + }, + "schemesList": { + "type": "array", + "description": "The transfer protocol of the API.", + "items": { + "type": "string", + "enum": [ + "http", + "https", + "ws", + "wss" + ] + }, + "uniqueItems": true + }, + "collectionFormat": { + "type": "string", + "enum": [ + "csv", + "ssv", + "tsv", + "pipes" + ], + "default": "csv" + }, + "collectionFormatWithMulti": { + "type": "string", + "enum": [ + "csv", + "ssv", + "tsv", + "pipes", + "multi" + ], + "default": "csv" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "multipleOf": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" + }, + "maximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" + }, + "exclusiveMaximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" + }, + "minimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" + }, + "exclusiveMinimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" + }, + "maxLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "pattern": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" + }, + "maxItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "uniqueItems": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" + }, + "enum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" + }, + "jsonReference": { + "type": "object", + "required": [ + "$ref" + ], + "additionalProperties": false, + "properties": { + "$ref": { + "type": "string" + } + } + } + } +} diff --git a/vendor/github.com/go-openapi/spec/security_scheme.go b/vendor/github.com/go-openapi/spec/security_scheme.go new file mode 100644 index 00000000..22d4f10a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/security_scheme.go @@ -0,0 +1,142 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +const ( + basic = "basic" + apiKey = "apiKey" + oauth2 = "oauth2" + implicit = "implicit" + password = "password" + application = "application" + accessCode = "accessCode" +) + +// BasicAuth creates a basic auth security scheme +func BasicAuth() *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: basic}} +} + +// APIKeyAuth creates an api key auth security scheme +func APIKeyAuth(fieldName, valueSource string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: apiKey, Name: fieldName, In: valueSource}} +} + +// OAuth2Implicit creates an implicit flow oauth2 security scheme +func OAuth2Implicit(authorizationURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ + Type: oauth2, + Flow: implicit, + AuthorizationURL: authorizationURL, + }} +} + +// OAuth2Password creates a password flow oauth2 security scheme +func OAuth2Password(tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ + Type: oauth2, + Flow: password, + TokenURL: tokenURL, + }} +} + +// OAuth2Application creates an application flow oauth2 security scheme +func OAuth2Application(tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ + Type: oauth2, + Flow: application, + TokenURL: tokenURL, + }} +} + +// OAuth2AccessToken creates an access token flow oauth2 security scheme +func OAuth2AccessToken(authorizationURL, tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ + Type: oauth2, + Flow: accessCode, + AuthorizationURL: authorizationURL, + TokenURL: tokenURL, + }} +} + +type SecuritySchemeProps struct { + Description string `json:"description,omitempty"` + Type string `json:"type"` + Name string `json:"name,omitempty"` // api key + In string `json:"in,omitempty"` // api key + Flow string `json:"flow,omitempty"` // oauth2 + AuthorizationURL string `json:"authorizationUrl,omitempty"` // oauth2 + TokenURL string `json:"tokenUrl,omitempty"` // oauth2 + Scopes map[string]string `json:"scopes,omitempty"` // oauth2 +} + +// AddScope adds a scope to this security scheme +func (s *SecuritySchemeProps) AddScope(scope, description string) { + if s.Scopes == nil { + s.Scopes = make(map[string]string) + } + s.Scopes[scope] = description +} + +// SecurityScheme allows the definition of a security scheme that can be used by the operations. +// Supported schemes are basic authentication, an API key (either as a header or as a query parameter) +// and OAuth2's common flows (implicit, password, application and access code). +// +// For more information: http://goo.gl/8us55a#securitySchemeObject +type SecurityScheme struct { + VendorExtensible + SecuritySchemeProps +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s SecurityScheme) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } + + r, _, err := jsonpointer.GetForToken(s.SecuritySchemeProps, token) + return r, err +} + +// MarshalJSON marshal this to JSON +func (s SecurityScheme) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(s.SecuritySchemeProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} + +// UnmarshalJSON marshal this from JSON +func (s *SecurityScheme) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &s.SecuritySchemeProps); err != nil { + return err + } + if err := json.Unmarshal(data, &s.VendorExtensible); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/go-openapi/spec/spec.go b/vendor/github.com/go-openapi/spec/spec.go new file mode 100644 index 00000000..0bb045bc --- /dev/null +++ b/vendor/github.com/go-openapi/spec/spec.go @@ -0,0 +1,86 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import "encoding/json" + +//go:generate curl -L --progress -o ./schemas/v2/schema.json http://swagger.io/v2/schema.json +//go:generate curl -L --progress -o ./schemas/jsonschema-draft-04.json http://json-schema.org/draft-04/schema +//go:generate go-bindata -pkg=spec -prefix=./schemas -ignore=.*\.md ./schemas/... +//go:generate perl -pi -e s,Json,JSON,g bindata.go + +const ( + // SwaggerSchemaURL the url for the swagger 2.0 schema to validate specs + SwaggerSchemaURL = "http://swagger.io/v2/schema.json#" + // JSONSchemaURL the url for the json schema schema + JSONSchemaURL = "http://json-schema.org/draft-04/schema#" +) + +var ( + jsonSchema *Schema + swaggerSchema *Schema +) + +func init() { + jsonSchema = MustLoadJSONSchemaDraft04() + swaggerSchema = MustLoadSwagger20Schema() +} + +// MustLoadJSONSchemaDraft04 panics when Swagger20Schema returns an error +func MustLoadJSONSchemaDraft04() *Schema { + d, e := JSONSchemaDraft04() + if e != nil { + panic(e) + } + return d +} + +// JSONSchemaDraft04 loads the json schema document for json shema draft04 +func JSONSchemaDraft04() (*Schema, error) { + b, err := Asset("jsonschema-draft-04.json") + if err != nil { + return nil, err + } + + schema := new(Schema) + if err := json.Unmarshal(b, schema); err != nil { + return nil, err + } + return schema, nil +} + +// MustLoadSwagger20Schema panics when Swagger20Schema returns an error +func MustLoadSwagger20Schema() *Schema { + d, e := Swagger20Schema() + if e != nil { + panic(e) + } + return d +} + +// Swagger20Schema loads the swagger 2.0 schema from the embedded assets +func Swagger20Schema() (*Schema, error) { + + b, err := Asset("v2/schema.json") + if err != nil { + return nil, err + } + + schema := new(Schema) + if err := json.Unmarshal(b, schema); err != nil { + return nil, err + } + return schema, nil +} diff --git a/vendor/github.com/go-openapi/spec/structs_test.go b/vendor/github.com/go-openapi/spec/structs_test.go new file mode 100644 index 00000000..bfa59ee0 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/structs_test.go @@ -0,0 +1,110 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + "gopkg.in/yaml.v2" +) + +func assertSerializeJSON(t testing.TB, actual interface{}, expected string) bool { + ser, err := json.Marshal(actual) + if err != nil { + return assert.Fail(t, "unable to marshal to json (%s): %#v", err, actual) + } + return assert.Equal(t, string(ser), expected) +} + +func assertParsesJSON(t testing.TB, actual string, expected interface{}) bool { + tpe := reflect.TypeOf(expected) + var pointed bool + if tpe.Kind() == reflect.Ptr { + tpe = tpe.Elem() + pointed = true + } + + parsed := reflect.New(tpe) + err := json.Unmarshal([]byte(actual), parsed.Interface()) + if err != nil { + return assert.Fail(t, "unable to unmarshal from json (%s): %s", err, actual) + } + act := parsed.Interface() + if !pointed { + act = reflect.Indirect(parsed).Interface() + } + return assert.Equal(t, act, expected) +} + +func assertSerializeYAML(t testing.TB, actual interface{}, expected string) bool { + ser, err := yaml.Marshal(actual) + if err != nil { + return assert.Fail(t, "unable to marshal to yaml (%s): %#v", err, actual) + } + return assert.Equal(t, string(ser), expected) +} + +func assertParsesYAML(t testing.TB, actual string, expected interface{}) bool { + tpe := reflect.TypeOf(expected) + var pointed bool + if tpe.Kind() == reflect.Ptr { + tpe = tpe.Elem() + pointed = true + } + parsed := reflect.New(tpe) + err := yaml.Unmarshal([]byte(actual), parsed.Interface()) + if err != nil { + return assert.Fail(t, "unable to unmarshal from yaml (%s): %s", err, actual) + } + act := parsed.Interface() + if !pointed { + act = reflect.Indirect(parsed).Interface() + } + return assert.EqualValues(t, act, expected) +} + +func TestSerialization_SerializeJSON(t *testing.T) { + assertSerializeJSON(t, []string{"hello"}, "[\"hello\"]") + assertSerializeJSON(t, []string{"hello", "world", "and", "stuff"}, "[\"hello\",\"world\",\"and\",\"stuff\"]") + assertSerializeJSON(t, StringOrArray(nil), "null") + assertSerializeJSON(t, SchemaOrArray{Schemas: []Schema{Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}}, "[{\"type\":\"string\"}]") + assertSerializeJSON(t, SchemaOrArray{ + Schemas: []Schema{ + Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + }}, "[{\"type\":\"string\"},{\"type\":\"string\"}]") + assertSerializeJSON(t, SchemaOrArray{}, "null") +} + +func TestSerialization_DeserializeJSON(t *testing.T) { + // String + assertParsesJSON(t, "\"hello\"", StringOrArray([]string{"hello"})) + assertParsesJSON(t, "[\"hello\",\"world\",\"and\",\"stuff\"]", StringOrArray([]string{"hello", "world", "and", "stuff"})) + assertParsesJSON(t, "[\"hello\",\"world\",null,\"stuff\"]", StringOrArray([]string{"hello", "world", "", "stuff"})) + assertParsesJSON(t, "null", StringOrArray(nil)) + + // Schema + assertParsesJSON(t, "{\"type\":\"string\"}", SchemaOrArray{Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}) + assertParsesJSON(t, "[{\"type\":\"string\"},{\"type\":\"string\"}]", &SchemaOrArray{ + Schemas: []Schema{ + Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, + }, + }) + assertParsesJSON(t, "null", SchemaOrArray{}) +} diff --git a/vendor/github.com/go-openapi/spec/swagger.go b/vendor/github.com/go-openapi/spec/swagger.go new file mode 100644 index 00000000..393a3167 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/swagger.go @@ -0,0 +1,317 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// Swagger this is the root document object for the API specification. +// It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) together into one document. +// +// For more information: http://goo.gl/8us55a#swagger-object- +type Swagger struct { + VendorExtensible + SwaggerProps +} + +// JSONLookup look up a value by the json property name +func (s Swagger) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(s.SwaggerProps, token) + return r, err +} + +// MarshalJSON marshals this swagger structure to json +func (s Swagger) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(s.SwaggerProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} + +// UnmarshalJSON unmarshals a swagger spec from json +func (s *Swagger) UnmarshalJSON(data []byte) error { + var sw Swagger + if err := json.Unmarshal(data, &sw.SwaggerProps); err != nil { + return err + } + if err := json.Unmarshal(data, &sw.VendorExtensible); err != nil { + return err + } + *s = sw + return nil +} + +type SwaggerProps struct { + ID string `json:"id,omitempty"` + Consumes []string `json:"consumes,omitempty"` + Produces []string `json:"produces,omitempty"` + Schemes []string `json:"schemes,omitempty"` // the scheme, when present must be from [http, https, ws, wss] + Swagger string `json:"swagger,omitempty"` + Info *Info `json:"info,omitempty"` + Host string `json:"host,omitempty"` + BasePath string `json:"basePath,omitempty"` // must start with a leading "/" + Paths *Paths `json:"paths"` // required + Definitions Definitions `json:"definitions,omitempty"` + Parameters map[string]Parameter `json:"parameters,omitempty"` + Responses map[string]Response `json:"responses,omitempty"` + SecurityDefinitions SecurityDefinitions `json:"securityDefinitions,omitempty"` + Security []map[string][]string `json:"security,omitempty"` + Tags []Tag `json:"tags,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` +} + +// Dependencies represent a dependencies property +type Dependencies map[string]SchemaOrStringArray + +// SchemaOrBool represents a schema or boolean value, is biased towards true for the boolean property +type SchemaOrBool struct { + Allows bool + Schema *Schema +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s SchemaOrBool) JSONLookup(token string) (interface{}, error) { + if token == "allows" { + return s.Allows, nil + } + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err +} + +var jsTrue = []byte("true") +var jsFalse = []byte("false") + +// MarshalJSON convert this object to JSON +func (s SchemaOrBool) MarshalJSON() ([]byte, error) { + if s.Schema != nil { + return json.Marshal(s.Schema) + } + + if s.Schema == nil && !s.Allows { + return jsFalse, nil + } + return jsTrue, nil +} + +// UnmarshalJSON converts this bool or schema object from a JSON structure +func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { + var nw SchemaOrBool + if len(data) >= 4 { + if data[0] == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + nw.Allows = !(data[0] == 'f' && data[1] == 'a' && data[2] == 'l' && data[3] == 's' && data[4] == 'e') + } + *s = nw + return nil +} + +// SchemaOrStringArray represents a schema or a string array +type SchemaOrStringArray struct { + Schema *Schema + Property []string +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s SchemaOrStringArray) JSONLookup(token string) (interface{}, error) { + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err +} + +// MarshalJSON converts this schema object or array into JSON structure +func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { + if len(s.Property) > 0 { + return json.Marshal(s.Property) + } + if s.Schema != nil { + return json.Marshal(s.Schema) + } + return nil, nil +} + +// UnmarshalJSON converts this schema object or array from a JSON structure +func (s *SchemaOrStringArray) UnmarshalJSON(data []byte) error { + var first byte + if len(data) > 1 { + first = data[0] + } + var nw SchemaOrStringArray + if first == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + if first == '[' { + if err := json.Unmarshal(data, &nw.Property); err != nil { + return err + } + } + *s = nw + return nil +} + +// Definitions contains the models explicitly defined in this spec +// An object to hold data types that can be consumed and produced by operations. +// These data types can be primitives, arrays or models. +// +// For more information: http://goo.gl/8us55a#definitionsObject +type Definitions map[string]Schema + +// SecurityDefinitions a declaration of the security schemes available to be used in the specification. +// This does not enforce the security schemes on the operations and only serves to provide +// the relevant details for each scheme. +// +// For more information: http://goo.gl/8us55a#securityDefinitionsObject +type SecurityDefinitions map[string]*SecurityScheme + +// StringOrArray represents a value that can either be a string +// or an array of strings. Mainly here for serialization purposes +type StringOrArray []string + +// Contains returns true when the value is contained in the slice +func (s StringOrArray) Contains(value string) bool { + for _, str := range s { + if str == value { + return true + } + } + return false +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s SchemaOrArray) JSONLookup(token string) (interface{}, error) { + if _, err := strconv.Atoi(token); err == nil { + r, _, err := jsonpointer.GetForToken(s.Schemas, token) + return r, err + } + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err +} + +// UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string +func (s *StringOrArray) UnmarshalJSON(data []byte) error { + var first byte + if len(data) > 1 { + first = data[0] + } + + if first == '[' { + var parsed []string + if err := json.Unmarshal(data, &parsed); err != nil { + return err + } + *s = StringOrArray(parsed) + return nil + } + + var single interface{} + if err := json.Unmarshal(data, &single); err != nil { + return err + } + if single == nil { + return nil + } + switch single.(type) { + case string: + *s = StringOrArray([]string{single.(string)}) + return nil + default: + return fmt.Errorf("only string or array is allowed, not %T", single) + } +} + +// MarshalJSON converts this string or array to a JSON array or JSON string +func (s StringOrArray) MarshalJSON() ([]byte, error) { + if len(s) == 1 { + return json.Marshal([]string(s)[0]) + } + return json.Marshal([]string(s)) +} + +// SchemaOrArray represents a value that can either be a Schema +// or an array of Schema. Mainly here for serialization purposes +type SchemaOrArray struct { + Schema *Schema + Schemas []Schema +} + +// Len returns the number of schemas in this property +func (s SchemaOrArray) Len() int { + if s.Schema != nil { + return 1 + } + return len(s.Schemas) +} + +// ContainsType returns true when one of the schemas is of the specified type +func (s *SchemaOrArray) ContainsType(name string) bool { + if s.Schema != nil { + return s.Schema.Type != nil && s.Schema.Type.Contains(name) + } + return false +} + +// MarshalJSON converts this schema object or array into JSON structure +func (s SchemaOrArray) MarshalJSON() ([]byte, error) { + if len(s.Schemas) > 0 { + return json.Marshal(s.Schemas) + } + return json.Marshal(s.Schema) +} + +// UnmarshalJSON converts this schema object or array from a JSON structure +func (s *SchemaOrArray) UnmarshalJSON(data []byte) error { + var nw SchemaOrArray + var first byte + if len(data) > 1 { + first = data[0] + } + if first == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + if first == '[' { + if err := json.Unmarshal(data, &nw.Schemas); err != nil { + return err + } + } + *s = nw + return nil +} + +// vim:set ft=go noet sts=2 sw=2 ts=2: diff --git a/vendor/github.com/go-openapi/spec/swagger_test.go b/vendor/github.com/go-openapi/spec/swagger_test.go new file mode 100644 index 00000000..f7b3d902 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/swagger_test.go @@ -0,0 +1,365 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/go-openapi/swag" + "github.com/stretchr/testify/assert" +) + +var spec = Swagger{ + SwaggerProps: SwaggerProps{ + ID: "http://localhost:3849/api-docs", + Swagger: "2.0", + Consumes: []string{"application/json", "application/x-yaml"}, + Produces: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Info: &info, + Host: "some.api.out.there", + BasePath: "/", + Paths: &paths, + Definitions: map[string]Schema{"Category": {SchemaProps: SchemaProps{Type: []string{"string"}}}}, + Parameters: map[string]Parameter{ + "categoryParam": {ParamProps: ParamProps{Name: "category", In: "query"}, SimpleSchema: SimpleSchema{Type: "string"}}, + }, + Responses: map[string]Response{ + "EmptyAnswer": { + ResponseProps: ResponseProps{ + Description: "no data to return for this operation", + }, + }, + }, + SecurityDefinitions: map[string]*SecurityScheme{ + "internalApiKey": APIKeyAuth("api_key", "header"), + }, + Security: []map[string][]string{ + {"internalApiKey": {}}, + }, + Tags: []Tag{NewTag("pets", "", nil)}, + ExternalDocs: &ExternalDocumentation{"the name", "the url"}, + }, + VendorExtensible: VendorExtensible{map[string]interface{}{ + "x-some-extension": "vendor", + "x-schemes": []interface{}{"unix", "amqp"}, + }}, +} + +var specJSON = `{ + "id": "http://localhost:3849/api-docs", + "consumes": ["application/json", "application/x-yaml"], + "produces": ["application/json"], + "schemes": ["http", "https"], + "swagger": "2.0", + "info": { + "contact": { + "name": "wordnik api team", + "url": "http://developer.wordnik.com" + }, + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "license": { + "name": "Creative Commons 4.0 International", + "url": "http://creativecommons.org/licenses/by/4.0/" + }, + "termsOfService": "http://helloreverb.com/terms/", + "title": "Swagger Sample API", + "version": "1.0.9-abcd", + "x-framework": "go-swagger" + }, + "host": "some.api.out.there", + "basePath": "/", + "paths": {"x-framework":"go-swagger","/":{"$ref":"cats"}}, + "definitions": { "Category": { "type": "string"} }, + "parameters": { + "categoryParam": { + "name": "category", + "in": "query", + "type": "string" + } + }, + "responses": { "EmptyAnswer": { "description": "no data to return for this operation" } }, + "securityDefinitions": { + "internalApiKey": { + "type": "apiKey", + "in": "header", + "name": "api_key" + } + }, + "security": [{"internalApiKey":[]}], + "tags": [{"name":"pets"}], + "externalDocs": {"description":"the name","url":"the url"}, + "x-some-extension": "vendor", + "x-schemes": ["unix","amqp"] +}` + +// +// func verifySpecSerialize(specJSON []byte, spec Swagger) { +// expected := map[string]interface{}{} +// json.Unmarshal(specJSON, &expected) +// b, err := json.MarshalIndent(spec, "", " ") +// So(err, ShouldBeNil) +// var actual map[string]interface{} +// err = json.Unmarshal(b, &actual) +// So(err, ShouldBeNil) +// compareSpecMaps(actual, expected) +// } + +func assertEquivalent(t testing.TB, actual, expected interface{}) bool { + if actual == nil || expected == nil || reflect.DeepEqual(actual, expected) { + return true + } + + actualType := reflect.TypeOf(actual) + expectedType := reflect.TypeOf(expected) + if reflect.TypeOf(actual).ConvertibleTo(expectedType) { + expectedValue := reflect.ValueOf(expected) + if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { + return true + } + + // Attempt comparison after type conversion + if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { + return true + } + } + + // Last ditch effort + if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { + return true + } + errFmt := "Expected: '%T(%#v)'\nActual: '%T(%#v)'\n(Should be equivalent)!" + return assert.Fail(t, errFmt, expected, expected, actual, actual) +} + +func ShouldBeEquivalentTo(actual interface{}, expecteds ...interface{}) string { + expected := expecteds[0] + if actual == nil || expected == nil { + return "" + } + + if reflect.DeepEqual(expected, actual) { + return "" + } + + actualType := reflect.TypeOf(actual) + expectedType := reflect.TypeOf(expected) + if reflect.TypeOf(actual).ConvertibleTo(expectedType) { + expectedValue := reflect.ValueOf(expected) + if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { + return "" + } + + // Attempt comparison after type conversion + if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { + return "" + } + } + + // Last ditch effort + if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { + return "" + } + errFmt := "Expected: '%T(%#v)'\nActual: '%T(%#v)'\n(Should be equivalent)!" + return fmt.Sprintf(errFmt, expected, expected, actual, actual) + +} + +func assertSpecMaps(t testing.TB, actual, expected map[string]interface{}) bool { + res := true + if id, ok := expected["id"]; ok { + res = assert.Equal(t, id, actual["id"]) + } + res = res && assert.Equal(t, expected["consumes"], actual["consumes"]) + res = res && assert.Equal(t, expected["produces"], actual["produces"]) + res = res && assert.Equal(t, expected["schemes"], actual["schemes"]) + res = res && assert.Equal(t, expected["swagger"], actual["swagger"]) + res = res && assert.Equal(t, expected["info"], actual["info"]) + res = res && assert.Equal(t, expected["host"], actual["host"]) + res = res && assert.Equal(t, expected["basePath"], actual["basePath"]) + res = res && assert.Equal(t, expected["paths"], actual["paths"]) + res = res && assert.Equal(t, expected["definitions"], actual["definitions"]) + res = res && assert.Equal(t, expected["responses"], actual["responses"]) + res = res && assert.Equal(t, expected["securityDefinitions"], actual["securityDefinitions"]) + res = res && assert.Equal(t, expected["tags"], actual["tags"]) + res = res && assert.Equal(t, expected["externalDocs"], actual["externalDocs"]) + res = res && assert.Equal(t, expected["x-some-extension"], actual["x-some-extension"]) + res = res && assert.Equal(t, expected["x-schemes"], actual["x-schemes"]) + + return res +} + +// +// func compareSpecMaps(actual, expected map[string]interface{}) { +// if id, ok := expected["id"]; ok { +// So(actual["id"], ShouldEqual, id) +// } +// //So(actual["$schema"], ShouldEqual, SwaggerSchemaURL) +// So(actual["consumes"], ShouldResemble, expected["consumes"]) +// So(actual["produces"], ShouldResemble, expected["produces"]) +// So(actual["schemes"], ShouldResemble, expected["schemes"]) +// So(actual["swagger"], ShouldEqual, expected["swagger"]) +// So(actual["info"], ShouldResemble, expected["info"]) +// So(actual["host"], ShouldEqual, expected["host"]) +// So(actual["basePath"], ShouldEqual, expected["basePath"]) +// So(actual["paths"], ShouldBeEquivalentTo, expected["paths"]) +// So(actual["definitions"], ShouldBeEquivalentTo, expected["definitions"]) +// So(actual["responses"], ShouldBeEquivalentTo, expected["responses"]) +// So(actual["securityDefinitions"], ShouldResemble, expected["securityDefinitions"]) +// So(actual["tags"], ShouldResemble, expected["tags"]) +// So(actual["externalDocs"], ShouldResemble, expected["externalDocs"]) +// So(actual["x-some-extension"], ShouldResemble, expected["x-some-extension"]) +// So(actual["x-schemes"], ShouldResemble, expected["x-schemes"]) +// } + +func assertSpecs(t testing.TB, actual, expected Swagger) bool { + expected.Swagger = "2.0" + return assert.Equal(t, actual, expected) +} + +// +// func compareSpecs(actual Swagger, spec Swagger) { +// spec.Swagger = "2.0" +// So(actual, ShouldBeEquivalentTo, spec) +// } + +func assertSpecJSON(t testing.TB, specJSON []byte) bool { + var expected map[string]interface{} + if !assert.NoError(t, json.Unmarshal(specJSON, &expected)) { + return false + } + + obj := Swagger{} + if !assert.NoError(t, json.Unmarshal(specJSON, &obj)) { + return false + } + + cb, err := json.MarshalIndent(obj, "", " ") + if assert.NoError(t, err) { + return false + } + var actual map[string]interface{} + if !assert.NoError(t, json.Unmarshal(cb, &actual)) { + return false + } + return assertSpecMaps(t, actual, expected) +} + +// func verifySpecJSON(specJSON []byte) { +// //Println() +// //Println("json to verify", string(specJson)) +// var expected map[string]interface{} +// err := json.Unmarshal(specJSON, &expected) +// So(err, ShouldBeNil) +// +// obj := Swagger{} +// err = json.Unmarshal(specJSON, &obj) +// So(err, ShouldBeNil) +// +// //spew.Dump(obj) +// +// cb, err := json.MarshalIndent(obj, "", " ") +// So(err, ShouldBeNil) +// //Println() +// //Println("Marshalling to json returned", string(cb)) +// +// var actual map[string]interface{} +// err = json.Unmarshal(cb, &actual) +// So(err, ShouldBeNil) +// //Println() +// //spew.Dump(expected) +// //spew.Dump(actual) +// //fmt.Printf("comparing %s\n\t%#v\nto\n\t%#+v\n", fileName, expected, actual) +// compareSpecMaps(actual, expected) +// } + +func TestSwaggerSpec_Serialize(t *testing.T) { + expected := make(map[string]interface{}) + json.Unmarshal([]byte(specJSON), &expected) + b, err := json.MarshalIndent(spec, "", " ") + if assert.NoError(t, err) { + var actual map[string]interface{} + err := json.Unmarshal(b, &actual) + if assert.NoError(t, err) { + assert.EqualValues(t, actual, expected) + } + } +} + +func TestSwaggerSpec_Deserialize(t *testing.T) { + var actual Swagger + err := json.Unmarshal([]byte(specJSON), &actual) + if assert.NoError(t, err) { + assert.EqualValues(t, actual, spec) + } +} + +func TestVendorExtensionStringSlice(t *testing.T) { + var actual Swagger + err := json.Unmarshal([]byte(specJSON), &actual) + if assert.NoError(t, err) { + schemes, ok := actual.Extensions.GetStringSlice("x-schemes") + if assert.True(t, ok) { + assert.EqualValues(t, []string{"unix", "amqp"}, schemes) + } + } +} + +func TestOptionalSwaggerProps_Serialize(t *testing.T) { + minimalJsonSpec := []byte(`{ + "swagger": "2.0", + "info": { + "version": "0.0.0", + "title": "Simple API" + }, + "paths": { + "/": { + "get": { + "responses": { + "200": { + "description": "OK" + } + } + } + } + } +}`) + + var minimalSpec Swagger + err := json.Unmarshal(minimalJsonSpec, &minimalSpec) + if assert.NoError(t, err) { + bytes, err := json.Marshal(&minimalSpec) + if assert.NoError(t, err) { + var ms map[string]interface{} + if err := json.Unmarshal(bytes, &ms); assert.NoError(t, err) { + assert.NotContains(t, ms, "consumes") + assert.NotContains(t, ms, "produces") + assert.NotContains(t, ms, "schemes") + assert.NotContains(t, ms, "host") + assert.NotContains(t, ms, "basePath") + assert.NotContains(t, ms, "definitions") + assert.NotContains(t, ms, "parameters") + assert.NotContains(t, ms, "responses") + assert.NotContains(t, ms, "securityDefinitions") + assert.NotContains(t, ms, "security") + assert.NotContains(t, ms, "tags") + assert.NotContains(t, ms, "externalDocs") + } + } + } +} diff --git a/vendor/github.com/go-openapi/spec/tag.go b/vendor/github.com/go-openapi/spec/tag.go new file mode 100644 index 00000000..97f55584 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/tag.go @@ -0,0 +1,73 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +type TagProps struct { + Description string `json:"description,omitempty"` + Name string `json:"name,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` +} + +// NewTag creates a new tag +func NewTag(name, description string, externalDocs *ExternalDocumentation) Tag { + return Tag{TagProps: TagProps{description, name, externalDocs}} +} + +// Tag allows adding meta data to a single tag that is used by the [Operation Object](http://goo.gl/8us55a#operationObject). +// It is not mandatory to have a Tag Object per tag used there. +// +// For more information: http://goo.gl/8us55a#tagObject +type Tag struct { + VendorExtensible + TagProps +} + +// JSONLookup implements an interface to customize json pointer lookup +func (t Tag) JSONLookup(token string) (interface{}, error) { + if ex, ok := t.Extensions[token]; ok { + return &ex, nil + } + + r, _, err := jsonpointer.GetForToken(t.TagProps, token) + return r, err +} + +// MarshalJSON marshal this to JSON +func (t Tag) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(t.TagProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(t.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} + +// UnmarshalJSON marshal this from JSON +func (t *Tag) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &t.TagProps); err != nil { + return err + } + return json.Unmarshal(data, &t.VendorExtensible) +} diff --git a/vendor/github.com/go-openapi/spec/xml_object.go b/vendor/github.com/go-openapi/spec/xml_object.go new file mode 100644 index 00000000..945a4670 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/xml_object.go @@ -0,0 +1,68 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +// XMLObject a metadata object that allows for more fine-tuned XML model definitions. +// +// For more information: http://goo.gl/8us55a#xmlObject +type XMLObject struct { + Name string `json:"name,omitempty"` + Namespace string `json:"namespace,omitempty"` + Prefix string `json:"prefix,omitempty"` + Attribute bool `json:"attribute,omitempty"` + Wrapped bool `json:"wrapped,omitempty"` +} + +// WithName sets the xml name for the object +func (x *XMLObject) WithName(name string) *XMLObject { + x.Name = name + return x +} + +// WithNamespace sets the xml namespace for the object +func (x *XMLObject) WithNamespace(namespace string) *XMLObject { + x.Namespace = namespace + return x +} + +// WithPrefix sets the xml prefix for the object +func (x *XMLObject) WithPrefix(prefix string) *XMLObject { + x.Prefix = prefix + return x +} + +// AsAttribute flags this object as xml attribute +func (x *XMLObject) AsAttribute() *XMLObject { + x.Attribute = true + return x +} + +// AsElement flags this object as an xml node +func (x *XMLObject) AsElement() *XMLObject { + x.Attribute = false + return x +} + +// AsWrapped flags this object as wrapped, this is mostly useful for array types +func (x *XMLObject) AsWrapped() *XMLObject { + x.Wrapped = true + return x +} + +// AsUnwrapped flags this object as an xml node +func (x *XMLObject) AsUnwrapped() *XMLObject { + x.Wrapped = false + return x +} diff --git a/vendor/github.com/go-openapi/spec/xml_object_test.go b/vendor/github.com/go-openapi/spec/xml_object_test.go new file mode 100644 index 00000000..fda3b108 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/xml_object_test.go @@ -0,0 +1,65 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestXmlObject_Serialize(t *testing.T) { + obj1 := XMLObject{} + actual, err := json.Marshal(obj1) + if assert.NoError(t, err) { + assert.Equal(t, "{}", string(actual)) + } + + obj2 := XMLObject{ + Name: "the name", + Namespace: "the namespace", + Prefix: "the prefix", + Attribute: true, + Wrapped: true, + } + + actual, err = json.Marshal(obj2) + if assert.NoError(t, err) { + var ad map[string]interface{} + if assert.NoError(t, json.Unmarshal(actual, &ad)) { + assert.Equal(t, obj2.Name, ad["name"]) + assert.Equal(t, obj2.Namespace, ad["namespace"]) + assert.Equal(t, obj2.Prefix, ad["prefix"]) + assert.True(t, ad["attribute"].(bool)) + assert.True(t, ad["wrapped"].(bool)) + } + } +} + +func TestXmlObject_Deserialize(t *testing.T) { + expected := XMLObject{} + actual := XMLObject{} + if assert.NoError(t, json.Unmarshal([]byte("{}"), &actual)) { + assert.Equal(t, expected, actual) + } + + completed := `{"name":"the name","namespace":"the namespace","prefix":"the prefix","attribute":true,"wrapped":true}` + expected = XMLObject{"the name", "the namespace", "the prefix", true, true} + actual = XMLObject{} + if assert.NoError(t, json.Unmarshal([]byte(completed), &actual)) { + assert.Equal(t, expected, actual) + } +} diff --git a/vendor/github.com/go-openapi/swag/.editorconfig b/vendor/github.com/go-openapi/swag/.editorconfig new file mode 100644 index 00000000..3152da69 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.editorconfig @@ -0,0 +1,26 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +# Set default charset +[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] +charset = utf-8 + +# Tab indentation (no size specified) +[*.go] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false + +# Matches the exact files either package.json or .travis.yml +[{package.json,.travis.yml}] +indent_style = space +indent_size = 2 diff --git a/vendor/github.com/go-openapi/swag/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/swag/.github/CONTRIBUTING.md new file mode 100644 index 00000000..7dea4240 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.github/CONTRIBUTING.md @@ -0,0 +1,117 @@ +## Contribution Guidelines + +### Pull requests are always welcome + +We are always thrilled to receive pull requests, and do our best to +process them as fast as possible. Not sure if that typo is worth a pull +request? Do it! We will appreciate it. + +If your pull request is not accepted on the first try, don't be +discouraged! If there's a problem with the implementation, hopefully you +received feedback on what to improve. + +We're trying very hard to keep go-swagger lean and focused. We don't want it +to do everything for everybody. This means that we might decide against +incorporating a new feature. However, there might be a way to implement +that feature *on top of* go-swagger. + + +### Conventions + +Fork the repo and make changes on your fork in a feature branch: + +- If it's a bugfix branch, name it XXX-something where XXX is the number of the + issue +- If it's a feature branch, create an enhancement issue to announce your + intentions, and name it XXX-something where XXX is the number of the issue. + +Submit unit tests for your changes. Go has a great test framework built in; use +it! Take a look at existing tests for inspiration. Run the full test suite on +your branch before submitting a pull request. + +Update the documentation when creating or modifying features. Test +your documentation changes for clarity, concision, and correctness, as +well as a clean documentation build. See ``docs/README.md`` for more +information on building the docs and how docs get released. + +Write clean code. Universally formatted code promotes ease of writing, reading, +and maintenance. Always run `gofmt -s -w file.go` on each changed file before +committing your changes. Most editors have plugins that do this automatically. + +Pull requests descriptions should be as clear as possible and include a +reference to all the issues that they address. + +Pull requests must not contain commits from other users or branches. + +Commit messages must start with a capitalized and short summary (max. 50 +chars) written in the imperative, followed by an optional, more detailed +explanatory text which is separated from the summary by an empty line. + +Code review comments may be added to your pull request. Discuss, then make the +suggested modifications and push additional commits to your feature branch. Be +sure to post a comment after pushing. The new commits will show up in the pull +request automatically, but the reviewers will not be notified unless you +comment. + +Before the pull request is merged, make sure that you squash your commits into +logical units of work using `git rebase -i` and `git push -f`. After every +commit the test suite should be passing. Include documentation changes in the +same commit so that a revert would remove all traces of the feature or fix. + +Commits that fix or close an issue should include a reference like `Closes #XXX` +or `Fixes #XXX`, which will automatically close the issue when merged. + +### Sign your work + +The sign-off is a simple line at the end of the explanation for the +patch, which certifies that you wrote it or otherwise have the right to +pass it on as an open-source patch. The rules are pretty simple: if you +can certify the below (from +[developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +660 York Street, Suite 102, +San Francisco, CA 94110 USA + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +using your real name (sorry, no pseudonyms or anonymous contributions.) + +You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/swag/.gitignore b/vendor/github.com/go-openapi/swag/.gitignore new file mode 100644 index 00000000..769c2440 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.gitignore @@ -0,0 +1 @@ +secrets.yml diff --git a/vendor/github.com/go-openapi/swag/.travis.yml b/vendor/github.com/go-openapi/swag/.travis.yml new file mode 100644 index 00000000..8b75a3b7 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.travis.yml @@ -0,0 +1,13 @@ +language: go +go: +- 1.7 +install: +- go get -u github.com/stretchr/testify +- go get -u github.com/mailru/easyjson +script: +- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... +after_success: +- bash <(curl -s https://codecov.io/bash) +notifications: + slack: + secure: QUWvCkBBK09GF7YtEvHHVt70JOkdlNBG0nIKu/5qc4/nW5HP8I2w0SEf/XR2je0eED1Qe3L/AfMCWwrEj+IUZc3l4v+ju8X8R3Lomhme0Eb0jd1MTMCuPcBT47YCj0M7RON7vXtbFfm1hFJ/jLe5+9FXz0hpXsR24PJc5ZIi/ogNwkaPqG4BmndzecpSh0vc2FJPZUD9LT0I09REY/vXR0oQAalLkW0asGD5taHZTUZq/kBpsNxaAFrLM23i4mUcf33M5fjLpvx5LRICrX/57XpBrDh2TooBU6Qj3CgoY0uPRYUmSNxbVx1czNzl2JtEpb5yjoxfVPQeg0BvQM00G8LJINISR+ohrjhkZmAqchDupAX+yFrxTtORa78CtnIL6z/aTNlgwwVD8kvL/1pFA/JWYmKDmz93mV/+6wubGzNSQCstzjkFA4/iZEKewKUoRIAi/fxyscP6L/rCpmY/4llZZvrnyTqVbt6URWpopUpH4rwYqreXAtJxJsfBJIeSmUIiDIOMGkCTvyTEW3fWGmGoqWtSHLoaWDyAIGb7azb+KvfpWtEcoPFWfSWU+LGee0A/YsUhBl7ADB9A0CJEuR8q4BPpKpfLwPKSiKSAXL7zDkyjExyhtgqbSl2jS+rKIHOZNL8JkCcTP2MKMVd563C5rC5FMKqu3S9m2b6380E= diff --git a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..9322b065 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at ivan+abuse@flanders.co.nz. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/swag/LICENSE b/vendor/github.com/go-openapi/swag/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md new file mode 100644 index 00000000..5d43728e --- /dev/null +++ b/vendor/github.com/go-openapi/swag/README.md @@ -0,0 +1,12 @@ +# Swag [![Build Status](https://travis-ci.org/go-openapi/swag.svg?branch=master)](https://travis-ci.org/go-openapi/swag) [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) + +[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/swag?status.svg)](http://godoc.org/github.com/go-openapi/swag) + +Contains a bunch of helper functions: + +* convert between value and pointers for builtins +* convert from string to builtin +* fast json concatenation +* search in path +* load from file or http +* name manglin \ No newline at end of file diff --git a/vendor/github.com/go-openapi/swag/convert.go b/vendor/github.com/go-openapi/swag/convert.go new file mode 100644 index 00000000..2bf5ecbb --- /dev/null +++ b/vendor/github.com/go-openapi/swag/convert.go @@ -0,0 +1,188 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "math" + "strconv" + "strings" +) + +// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER +const ( + maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 + minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 +) + +// IsFloat64AJSONInteger allow for integers [-2^53, 2^53-1] inclusive +func IsFloat64AJSONInteger(f float64) bool { + if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { + return false + } + + return f == float64(int64(f)) || f == float64(uint64(f)) +} + +var evaluatesAsTrue = map[string]struct{}{ + "true": struct{}{}, + "1": struct{}{}, + "yes": struct{}{}, + "ok": struct{}{}, + "y": struct{}{}, + "on": struct{}{}, + "selected": struct{}{}, + "checked": struct{}{}, + "t": struct{}{}, + "enabled": struct{}{}, +} + +// ConvertBool turn a string into a boolean +func ConvertBool(str string) (bool, error) { + _, ok := evaluatesAsTrue[strings.ToLower(str)] + return ok, nil +} + +// ConvertFloat32 turn a string into a float32 +func ConvertFloat32(str string) (float32, error) { + f, err := strconv.ParseFloat(str, 32) + if err != nil { + return 0, err + } + return float32(f), nil +} + +// ConvertFloat64 turn a string into a float64 +func ConvertFloat64(str string) (float64, error) { + return strconv.ParseFloat(str, 64) +} + +// ConvertInt8 turn a string into int8 boolean +func ConvertInt8(str string) (int8, error) { + i, err := strconv.ParseInt(str, 10, 8) + if err != nil { + return 0, err + } + return int8(i), nil +} + +// ConvertInt16 turn a string into a int16 +func ConvertInt16(str string) (int16, error) { + i, err := strconv.ParseInt(str, 10, 16) + if err != nil { + return 0, err + } + return int16(i), nil +} + +// ConvertInt32 turn a string into a int32 +func ConvertInt32(str string) (int32, error) { + i, err := strconv.ParseInt(str, 10, 32) + if err != nil { + return 0, err + } + return int32(i), nil +} + +// ConvertInt64 turn a string into a int64 +func ConvertInt64(str string) (int64, error) { + return strconv.ParseInt(str, 10, 64) +} + +// ConvertUint8 turn a string into a uint8 +func ConvertUint8(str string) (uint8, error) { + i, err := strconv.ParseUint(str, 10, 8) + if err != nil { + return 0, err + } + return uint8(i), nil +} + +// ConvertUint16 turn a string into a uint16 +func ConvertUint16(str string) (uint16, error) { + i, err := strconv.ParseUint(str, 10, 16) + if err != nil { + return 0, err + } + return uint16(i), nil +} + +// ConvertUint32 turn a string into a uint32 +func ConvertUint32(str string) (uint32, error) { + i, err := strconv.ParseUint(str, 10, 32) + if err != nil { + return 0, err + } + return uint32(i), nil +} + +// ConvertUint64 turn a string into a uint64 +func ConvertUint64(str string) (uint64, error) { + return strconv.ParseUint(str, 10, 64) +} + +// FormatBool turns a boolean into a string +func FormatBool(value bool) string { + return strconv.FormatBool(value) +} + +// FormatFloat32 turns a float32 into a string +func FormatFloat32(value float32) string { + return strconv.FormatFloat(float64(value), 'f', -1, 32) +} + +// FormatFloat64 turns a float64 into a string +func FormatFloat64(value float64) string { + return strconv.FormatFloat(value, 'f', -1, 64) +} + +// FormatInt8 turns an int8 into a string +func FormatInt8(value int8) string { + return strconv.FormatInt(int64(value), 10) +} + +// FormatInt16 turns an int16 into a string +func FormatInt16(value int16) string { + return strconv.FormatInt(int64(value), 10) +} + +// FormatInt32 turns an int32 into a string +func FormatInt32(value int32) string { + return strconv.Itoa(int(value)) +} + +// FormatInt64 turns an int64 into a string +func FormatInt64(value int64) string { + return strconv.FormatInt(value, 10) +} + +// FormatUint8 turns an uint8 into a string +func FormatUint8(value uint8) string { + return strconv.FormatUint(uint64(value), 10) +} + +// FormatUint16 turns an uint16 into a string +func FormatUint16(value uint16) string { + return strconv.FormatUint(uint64(value), 10) +} + +// FormatUint32 turns an uint32 into a string +func FormatUint32(value uint32) string { + return strconv.FormatUint(uint64(value), 10) +} + +// FormatUint64 turns an uint64 into a string +func FormatUint64(value uint64) string { + return strconv.FormatUint(value, 10) +} diff --git a/vendor/github.com/go-openapi/swag/convert_test.go b/vendor/github.com/go-openapi/swag/convert_test.go new file mode 100644 index 00000000..2f007323 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/convert_test.go @@ -0,0 +1,215 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "math" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" +) + +// These are really dumb tests + +func TestConvertBool(t *testing.T) { + for k := range evaluatesAsTrue { + r, err := ConvertBool(k) + if assert.NoError(t, err) { + assert.True(t, r) + } + } + for _, k := range []string{"a", "", "0", "false", "unchecked"} { + r, err := ConvertBool(k) + if assert.NoError(t, err) { + assert.False(t, r) + } + } +} + +func TestConvertFloat32(t *testing.T) { + validFloats := []float32{1.0, -1, math.MaxFloat32, math.SmallestNonzeroFloat32, 0, 5.494430303} + invalidFloats := []string{"a", strconv.FormatFloat(math.MaxFloat64, 'f', -1, 64), "true"} + + for _, f := range validFloats { + c, err := ConvertFloat32(FormatFloat32(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidFloats { + _, err := ConvertFloat32(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertFloat64(t *testing.T) { + validFloats := []float64{1.0, -1, float64(math.MaxFloat32), float64(math.SmallestNonzeroFloat32), math.MaxFloat64, math.SmallestNonzeroFloat64, 0, 5.494430303} + invalidFloats := []string{"a", "true"} + + for _, f := range validFloats { + c, err := ConvertFloat64(FormatFloat64(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidFloats { + _, err := ConvertFloat64(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertInt8(t *testing.T) { + validInts := []int8{0, 1, -1, math.MaxInt8, math.MinInt8} + invalidInts := []string{"1.233", "a", "false", strconv.Itoa(int(math.MaxInt64))} + + for _, f := range validInts { + c, err := ConvertInt8(FormatInt8(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidInts { + _, err := ConvertInt8(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertInt16(t *testing.T) { + validInts := []int16{0, 1, -1, math.MaxInt8, math.MinInt8, math.MaxInt16, math.MinInt16} + invalidInts := []string{"1.233", "a", "false", strconv.Itoa(int(math.MaxInt64))} + + for _, f := range validInts { + c, err := ConvertInt16(FormatInt16(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidInts { + _, err := ConvertInt16(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertInt32(t *testing.T) { + validInts := []int32{0, 1, -1, math.MaxInt8, math.MinInt8, math.MaxInt16, math.MinInt16, math.MinInt32, math.MaxInt32} + invalidInts := []string{"1.233", "a", "false", strconv.Itoa(int(math.MaxInt64))} + + for _, f := range validInts { + c, err := ConvertInt32(FormatInt32(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidInts { + _, err := ConvertInt32(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertInt64(t *testing.T) { + validInts := []int64{0, 1, -1, math.MaxInt8, math.MinInt8, math.MaxInt16, math.MinInt16, math.MinInt32, math.MaxInt32, math.MaxInt64, math.MinInt64} + invalidInts := []string{"1.233", "a", "false"} + + for _, f := range validInts { + c, err := ConvertInt64(FormatInt64(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidInts { + _, err := ConvertInt64(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertUint8(t *testing.T) { + validInts := []uint8{0, 1, math.MaxUint8} + invalidInts := []string{"1.233", "a", "false", strconv.FormatUint(math.MaxUint64, 10)} + + for _, f := range validInts { + c, err := ConvertUint8(FormatUint8(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidInts { + _, err := ConvertUint8(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertUint16(t *testing.T) { + validUints := []uint16{0, 1, math.MaxUint8, math.MaxUint16} + invalidUints := []string{"1.233", "a", "false", strconv.FormatUint(math.MaxUint64, 10)} + + for _, f := range validUints { + c, err := ConvertUint16(FormatUint16(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidUints { + _, err := ConvertUint16(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertUint32(t *testing.T) { + validUints := []uint32{0, 1, math.MaxUint8, math.MaxUint16, math.MaxUint32} + invalidUints := []string{"1.233", "a", "false", strconv.FormatUint(math.MaxUint64, 10)} + + for _, f := range validUints { + c, err := ConvertUint32(FormatUint32(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidUints { + _, err := ConvertUint32(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestConvertUint64(t *testing.T) { + validUints := []uint64{0, 1, math.MaxUint8, math.MaxUint16, math.MaxUint32, math.MaxUint64} + invalidUints := []string{"1.233", "a", "false"} + + for _, f := range validUints { + c, err := ConvertUint64(FormatUint64(f)) + if assert.NoError(t, err) { + assert.EqualValues(t, f, c) + } + } + for _, f := range invalidUints { + _, err := ConvertUint64(f) + assert.Error(t, err, "expected '"+f+"' to generate an error") + } +} + +func TestIsFloat64AJSONInteger(t *testing.T) { + assert.False(t, IsFloat64AJSONInteger(math.Inf(1))) + assert.False(t, IsFloat64AJSONInteger(maxJSONFloat+1)) + + assert.False(t, IsFloat64AJSONInteger(minJSONFloat-1)) + assert.True(t, IsFloat64AJSONInteger(1.0)) + assert.True(t, IsFloat64AJSONInteger(maxJSONFloat)) + assert.True(t, IsFloat64AJSONInteger(minJSONFloat)) +} + +func TestFormatBool(t *testing.T) { + assert.Equal(t, "true", FormatBool(true)) + assert.Equal(t, "false", FormatBool(false)) +} diff --git a/vendor/github.com/go-openapi/swag/convert_types.go b/vendor/github.com/go-openapi/swag/convert_types.go new file mode 100644 index 00000000..c95e4e78 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/convert_types.go @@ -0,0 +1,595 @@ +package swag + +import "time" + +// This file was taken from the aws go sdk + +// String returns a pointer to of the string value passed in. +func String(v string) *string { + return &v +} + +// StringValue returns the value of the string pointer passed in or +// "" if the pointer is nil. +func StringValue(v *string) string { + if v != nil { + return *v + } + return "" +} + +// StringSlice converts a slice of string values into a slice of +// string pointers +func StringSlice(src []string) []*string { + dst := make([]*string, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// StringValueSlice converts a slice of string pointers into a slice of +// string values +func StringValueSlice(src []*string) []string { + dst := make([]string, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// StringMap converts a string map of string values into a string +// map of string pointers +func StringMap(src map[string]string) map[string]*string { + dst := make(map[string]*string) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// StringValueMap converts a string map of string pointers into a string +// map of string values +func StringValueMap(src map[string]*string) map[string]string { + dst := make(map[string]string) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Bool returns a pointer to of the bool value passed in. +func Bool(v bool) *bool { + return &v +} + +// BoolValue returns the value of the bool pointer passed in or +// false if the pointer is nil. +func BoolValue(v *bool) bool { + if v != nil { + return *v + } + return false +} + +// BoolSlice converts a slice of bool values into a slice of +// bool pointers +func BoolSlice(src []bool) []*bool { + dst := make([]*bool, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// BoolValueSlice converts a slice of bool pointers into a slice of +// bool values +func BoolValueSlice(src []*bool) []bool { + dst := make([]bool, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// BoolMap converts a string map of bool values into a string +// map of bool pointers +func BoolMap(src map[string]bool) map[string]*bool { + dst := make(map[string]*bool) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// BoolValueMap converts a string map of bool pointers into a string +// map of bool values +func BoolValueMap(src map[string]*bool) map[string]bool { + dst := make(map[string]bool) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Int returns a pointer to of the int value passed in. +func Int(v int) *int { + return &v +} + +// IntValue returns the value of the int pointer passed in or +// 0 if the pointer is nil. +func IntValue(v *int) int { + if v != nil { + return *v + } + return 0 +} + +// IntSlice converts a slice of int values into a slice of +// int pointers +func IntSlice(src []int) []*int { + dst := make([]*int, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// IntValueSlice converts a slice of int pointers into a slice of +// int values +func IntValueSlice(src []*int) []int { + dst := make([]int, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// IntMap converts a string map of int values into a string +// map of int pointers +func IntMap(src map[string]int) map[string]*int { + dst := make(map[string]*int) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// IntValueMap converts a string map of int pointers into a string +// map of int values +func IntValueMap(src map[string]*int) map[string]int { + dst := make(map[string]int) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Int32 returns a pointer to of the int64 value passed in. +func Int32(v int32) *int32 { + return &v +} + +// Int32Value returns the value of the int64 pointer passed in or +// 0 if the pointer is nil. +func Int32Value(v *int32) int32 { + if v != nil { + return *v + } + return 0 +} + +// Int32Slice converts a slice of int64 values into a slice of +// int32 pointers +func Int32Slice(src []int32) []*int32 { + dst := make([]*int32, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Int32ValueSlice converts a slice of int32 pointers into a slice of +// int32 values +func Int32ValueSlice(src []*int32) []int32 { + dst := make([]int32, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Int32Map converts a string map of int32 values into a string +// map of int32 pointers +func Int32Map(src map[string]int32) map[string]*int32 { + dst := make(map[string]*int32) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Int32ValueMap converts a string map of int32 pointers into a string +// map of int32 values +func Int32ValueMap(src map[string]*int32) map[string]int32 { + dst := make(map[string]int32) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Int64 returns a pointer to of the int64 value passed in. +func Int64(v int64) *int64 { + return &v +} + +// Int64Value returns the value of the int64 pointer passed in or +// 0 if the pointer is nil. +func Int64Value(v *int64) int64 { + if v != nil { + return *v + } + return 0 +} + +// Int64Slice converts a slice of int64 values into a slice of +// int64 pointers +func Int64Slice(src []int64) []*int64 { + dst := make([]*int64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Int64ValueSlice converts a slice of int64 pointers into a slice of +// int64 values +func Int64ValueSlice(src []*int64) []int64 { + dst := make([]int64, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Int64Map converts a string map of int64 values into a string +// map of int64 pointers +func Int64Map(src map[string]int64) map[string]*int64 { + dst := make(map[string]*int64) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Int64ValueMap converts a string map of int64 pointers into a string +// map of int64 values +func Int64ValueMap(src map[string]*int64) map[string]int64 { + dst := make(map[string]int64) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Uint returns a pouinter to of the uint value passed in. +func Uint(v uint) *uint { + return &v +} + +// UintValue returns the value of the uint pouinter passed in or +// 0 if the pouinter is nil. +func UintValue(v *uint) uint { + if v != nil { + return *v + } + return 0 +} + +// UintSlice converts a slice of uint values uinto a slice of +// uint pouinters +func UintSlice(src []uint) []*uint { + dst := make([]*uint, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// UintValueSlice converts a slice of uint pouinters uinto a slice of +// uint values +func UintValueSlice(src []*uint) []uint { + dst := make([]uint, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// UintMap converts a string map of uint values uinto a string +// map of uint pouinters +func UintMap(src map[string]uint) map[string]*uint { + dst := make(map[string]*uint) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// UintValueMap converts a string map of uint pouinters uinto a string +// map of uint values +func UintValueMap(src map[string]*uint) map[string]uint { + dst := make(map[string]uint) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Uint32 returns a pouinter to of the uint64 value passed in. +func Uint32(v uint32) *uint32 { + return &v +} + +// Uint32Value returns the value of the uint64 pouinter passed in or +// 0 if the pouinter is nil. +func Uint32Value(v *uint32) uint32 { + if v != nil { + return *v + } + return 0 +} + +// Uint32Slice converts a slice of uint64 values uinto a slice of +// uint32 pouinters +func Uint32Slice(src []uint32) []*uint32 { + dst := make([]*uint32, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Uint32ValueSlice converts a slice of uint32 pouinters uinto a slice of +// uint32 values +func Uint32ValueSlice(src []*uint32) []uint32 { + dst := make([]uint32, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Uint32Map converts a string map of uint32 values uinto a string +// map of uint32 pouinters +func Uint32Map(src map[string]uint32) map[string]*uint32 { + dst := make(map[string]*uint32) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Uint32ValueMap converts a string map of uint32 pouinters uinto a string +// map of uint32 values +func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { + dst := make(map[string]uint32) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Uint64 returns a pouinter to of the uint64 value passed in. +func Uint64(v uint64) *uint64 { + return &v +} + +// Uint64Value returns the value of the uint64 pouinter passed in or +// 0 if the pouinter is nil. +func Uint64Value(v *uint64) uint64 { + if v != nil { + return *v + } + return 0 +} + +// Uint64Slice converts a slice of uint64 values uinto a slice of +// uint64 pouinters +func Uint64Slice(src []uint64) []*uint64 { + dst := make([]*uint64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Uint64ValueSlice converts a slice of uint64 pouinters uinto a slice of +// uint64 values +func Uint64ValueSlice(src []*uint64) []uint64 { + dst := make([]uint64, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Uint64Map converts a string map of uint64 values uinto a string +// map of uint64 pouinters +func Uint64Map(src map[string]uint64) map[string]*uint64 { + dst := make(map[string]*uint64) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Uint64ValueMap converts a string map of uint64 pouinters uinto a string +// map of uint64 values +func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { + dst := make(map[string]uint64) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Float64 returns a pointer to of the float64 value passed in. +func Float64(v float64) *float64 { + return &v +} + +// Float64Value returns the value of the float64 pointer passed in or +// 0 if the pointer is nil. +func Float64Value(v *float64) float64 { + if v != nil { + return *v + } + return 0 +} + +// Float64Slice converts a slice of float64 values into a slice of +// float64 pointers +func Float64Slice(src []float64) []*float64 { + dst := make([]*float64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Float64ValueSlice converts a slice of float64 pointers into a slice of +// float64 values +func Float64ValueSlice(src []*float64) []float64 { + dst := make([]float64, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Float64Map converts a string map of float64 values into a string +// map of float64 pointers +func Float64Map(src map[string]float64) map[string]*float64 { + dst := make(map[string]*float64) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Float64ValueMap converts a string map of float64 pointers into a string +// map of float64 values +func Float64ValueMap(src map[string]*float64) map[string]float64 { + dst := make(map[string]float64) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Time returns a pointer to of the time.Time value passed in. +func Time(v time.Time) *time.Time { + return &v +} + +// TimeValue returns the value of the time.Time pointer passed in or +// time.Time{} if the pointer is nil. +func TimeValue(v *time.Time) time.Time { + if v != nil { + return *v + } + return time.Time{} +} + +// TimeSlice converts a slice of time.Time values into a slice of +// time.Time pointers +func TimeSlice(src []time.Time) []*time.Time { + dst := make([]*time.Time, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// TimeValueSlice converts a slice of time.Time pointers into a slice of +// time.Time values +func TimeValueSlice(src []*time.Time) []time.Time { + dst := make([]time.Time, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// TimeMap converts a string map of time.Time values into a string +// map of time.Time pointers +func TimeMap(src map[string]time.Time) map[string]*time.Time { + dst := make(map[string]*time.Time) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// TimeValueMap converts a string map of time.Time pointers into a string +// map of time.Time values +func TimeValueMap(src map[string]*time.Time) map[string]time.Time { + dst := make(map[string]time.Time) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} diff --git a/vendor/github.com/go-openapi/swag/convert_types_test.go b/vendor/github.com/go-openapi/swag/convert_types_test.go new file mode 100644 index 00000000..978cf3a1 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/convert_types_test.go @@ -0,0 +1,579 @@ +package swag + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +var testCasesStringSlice = [][]string{ + {"a", "b", "c", "d", "e"}, + {"a", "b", "", "", "e"}, +} + +func TestStringSlice(t *testing.T) { + for idx, in := range testCasesStringSlice { + if in == nil { + continue + } + out := StringSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := StringValueSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesStringValueSlice = [][]*string{ + {String("a"), String("b"), nil, String("c")}, +} + +func TestStringValueSlice(t *testing.T) { + for idx, in := range testCasesStringValueSlice { + if in == nil { + continue + } + out := StringValueSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + if in[i] == nil { + assert.Empty(t, out[i], "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) + } + } + + out2 := StringSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + for i := range out2 { + if in[i] == nil { + assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) + } + } + } +} + +var testCasesStringMap = []map[string]string{ + {"a": "1", "b": "2", "c": "3"}, +} + +func TestStringMap(t *testing.T) { + for idx, in := range testCasesStringMap { + if in == nil { + continue + } + out := StringMap(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := StringValueMap(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesBoolSlice = [][]bool{ + {true, true, false, false}, +} + +func TestBoolSlice(t *testing.T) { + for idx, in := range testCasesBoolSlice { + if in == nil { + continue + } + out := BoolSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := BoolValueSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesBoolValueSlice = [][]*bool{} + +func TestBoolValueSlice(t *testing.T) { + for idx, in := range testCasesBoolValueSlice { + if in == nil { + continue + } + out := BoolValueSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + if in[i] == nil { + assert.Empty(t, out[i], "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) + } + } + + out2 := BoolSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + for i := range out2 { + if in[i] == nil { + assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) + } + } + } +} + +var testCasesBoolMap = []map[string]bool{ + {"a": true, "b": false, "c": true}, +} + +func TestBoolMap(t *testing.T) { + for idx, in := range testCasesBoolMap { + if in == nil { + continue + } + out := BoolMap(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := BoolValueMap(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesIntSlice = [][]int{ + {1, 2, 3, 4}, +} + +func TestIntSlice(t *testing.T) { + for idx, in := range testCasesIntSlice { + if in == nil { + continue + } + out := IntSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := IntValueSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesIntValueSlice = [][]*int{} + +func TestIntValueSlice(t *testing.T) { + for idx, in := range testCasesIntValueSlice { + if in == nil { + continue + } + out := IntValueSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + if in[i] == nil { + assert.Empty(t, out[i], "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) + } + } + + out2 := IntSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + for i := range out2 { + if in[i] == nil { + assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) + } + } + } +} + +var testCasesIntMap = []map[string]int{ + {"a": 3, "b": 2, "c": 1}, +} + +func TestIntMap(t *testing.T) { + for idx, in := range testCasesIntMap { + if in == nil { + continue + } + out := IntMap(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := IntValueMap(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesInt64Slice = [][]int64{ + {1, 2, 3, 4}, +} + +func TestInt64Slice(t *testing.T) { + for idx, in := range testCasesInt64Slice { + if in == nil { + continue + } + out := Int64Slice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := Int64ValueSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesInt64ValueSlice = [][]*int64{} + +func TestInt64ValueSlice(t *testing.T) { + for idx, in := range testCasesInt64ValueSlice { + if in == nil { + continue + } + out := Int64ValueSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + if in[i] == nil { + assert.Empty(t, out[i], "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) + } + } + + out2 := Int64Slice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + for i := range out2 { + if in[i] == nil { + assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) + } + } + } +} + +var testCasesInt64Map = []map[string]int64{ + {"a": 3, "b": 2, "c": 1}, +} + +func TestInt64Map(t *testing.T) { + for idx, in := range testCasesInt64Map { + if in == nil { + continue + } + out := Int64Map(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := Int64ValueMap(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesFloat64Slice = [][]float64{ + {1, 2, 3, 4}, +} + +func TestFloat64Slice(t *testing.T) { + for idx, in := range testCasesFloat64Slice { + if in == nil { + continue + } + out := Float64Slice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := Float64ValueSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesUintSlice = [][]uint{ + {1, 2, 3, 4}, +} + +func TestUintSlice(t *testing.T) { + for idx, in := range testCasesUintSlice { + if in == nil { + continue + } + out := UintSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := UintValueSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesUintValueSlice = [][]*uint{} + +func TestUintValueSlice(t *testing.T) { + for idx, in := range testCasesUintValueSlice { + if in == nil { + continue + } + out := UintValueSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + if in[i] == nil { + assert.Empty(t, out[i], "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) + } + } + + out2 := UintSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + for i := range out2 { + if in[i] == nil { + assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) + } + } + } +} + +var testCasesUintMap = []map[string]uint{ + {"a": 3, "b": 2, "c": 1}, +} + +func TestUintMap(t *testing.T) { + for idx, in := range testCasesUintMap { + if in == nil { + continue + } + out := UintMap(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := UintValueMap(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesUint64Slice = [][]uint64{ + {1, 2, 3, 4}, +} + +func TestUint64Slice(t *testing.T) { + for idx, in := range testCasesUint64Slice { + if in == nil { + continue + } + out := Uint64Slice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := Uint64ValueSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesUint64ValueSlice = [][]*uint64{} + +func TestUint64ValueSlice(t *testing.T) { + for idx, in := range testCasesUint64ValueSlice { + if in == nil { + continue + } + out := Uint64ValueSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + if in[i] == nil { + assert.Empty(t, out[i], "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) + } + } + + out2 := Uint64Slice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + for i := range out2 { + if in[i] == nil { + assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) + } + } + } +} + +var testCasesUint64Map = []map[string]uint64{ + {"a": 3, "b": 2, "c": 1}, +} + +func TestUint64Map(t *testing.T) { + for idx, in := range testCasesUint64Map { + if in == nil { + continue + } + out := Uint64Map(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := Uint64ValueMap(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesFloat64ValueSlice = [][]*float64{} + +func TestFloat64ValueSlice(t *testing.T) { + for idx, in := range testCasesFloat64ValueSlice { + if in == nil { + continue + } + out := Float64ValueSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + if in[i] == nil { + assert.Empty(t, out[i], "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) + } + } + + out2 := Float64Slice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + for i := range out2 { + if in[i] == nil { + assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) + } + } + } +} + +var testCasesFloat64Map = []map[string]float64{ + {"a": 3, "b": 2, "c": 1}, +} + +func TestFloat64Map(t *testing.T) { + for idx, in := range testCasesFloat64Map { + if in == nil { + continue + } + out := Float64Map(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := Float64ValueMap(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesTimeSlice = [][]time.Time{ + {time.Now(), time.Now().AddDate(100, 0, 0)}, +} + +func TestTimeSlice(t *testing.T) { + for idx, in := range testCasesTimeSlice { + if in == nil { + continue + } + out := TimeSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := TimeValueSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} + +var testCasesTimeValueSlice = [][]*time.Time{} + +func TestTimeValueSlice(t *testing.T) { + for idx, in := range testCasesTimeValueSlice { + if in == nil { + continue + } + out := TimeValueSlice(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + if in[i] == nil { + assert.Empty(t, out[i], "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) + } + } + + out2 := TimeSlice(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + for i := range out2 { + if in[i] == nil { + assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) + } else { + assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) + } + } + } +} + +var testCasesTimeMap = []map[string]time.Time{ + {"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()}, +} + +func TestTimeMap(t *testing.T) { + for idx, in := range testCasesTimeMap { + if in == nil { + continue + } + out := TimeMap(in) + assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) + for i := range out { + assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) + } + + out2 := TimeValueMap(out) + assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) + assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) + } +} diff --git a/vendor/github.com/go-openapi/swag/json.go b/vendor/github.com/go-openapi/swag/json.go new file mode 100644 index 00000000..0eb37446 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/json.go @@ -0,0 +1,291 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "bytes" + "encoding/json" + "log" + "reflect" + "strings" + "sync" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// DefaultJSONNameProvider the default cache for types +var DefaultJSONNameProvider = NewNameProvider() + +const comma = byte(',') + +var closers = map[byte]byte{ + '{': '}', + '[': ']', +} + +type ejMarshaler interface { + MarshalEasyJSON(w *jwriter.Writer) +} + +type ejUnmarshaler interface { + UnmarshalEasyJSON(w *jlexer.Lexer) +} + +// WriteJSON writes json data, prefers finding an appropriate interface to short-circuit the marshaller +// so it takes the fastest option available. +func WriteJSON(data interface{}) ([]byte, error) { + if d, ok := data.(ejMarshaler); ok { + jw := new(jwriter.Writer) + d.MarshalEasyJSON(jw) + return jw.BuildBytes() + } + if d, ok := data.(json.Marshaler); ok { + return d.MarshalJSON() + } + return json.Marshal(data) +} + +// ReadJSON reads json data, prefers finding an appropriate interface to short-circuit the unmarshaller +// so it takes the fastes option available +func ReadJSON(data []byte, value interface{}) error { + if d, ok := value.(ejUnmarshaler); ok { + jl := &jlexer.Lexer{Data: data} + d.UnmarshalEasyJSON(jl) + return jl.Error() + } + if d, ok := value.(json.Unmarshaler); ok { + return d.UnmarshalJSON(data) + } + return json.Unmarshal(data, value) +} + +// DynamicJSONToStruct converts an untyped json structure into a struct +func DynamicJSONToStruct(data interface{}, target interface{}) error { + // TODO: convert straight to a json typed map (mergo + iterate?) + b, err := WriteJSON(data) + if err != nil { + return err + } + if err := ReadJSON(b, target); err != nil { + return err + } + return nil +} + +// ConcatJSON concatenates multiple json objects efficiently +func ConcatJSON(blobs ...[]byte) []byte { + if len(blobs) == 0 { + return nil + } + if len(blobs) == 1 { + return blobs[0] + } + + last := len(blobs) - 1 + var opening, closing byte + a := 0 + idx := 0 + buf := bytes.NewBuffer(nil) + + for i, b := range blobs { + if len(b) > 0 && opening == 0 { // is this an array or an object? + opening, closing = b[0], closers[b[0]] + } + + if opening != '{' && opening != '[' { + continue // don't know how to concatenate non container objects + } + + if len(b) < 3 { // yep empty but also the last one, so closing this thing + if i == last && a > 0 { + if err := buf.WriteByte(closing); err != nil { + log.Println(err) + } + } + continue + } + + idx = 0 + if a > 0 { // we need to join with a comma for everything beyond the first non-empty item + if err := buf.WriteByte(comma); err != nil { + log.Println(err) + } + idx = 1 // this is not the first or the last so we want to drop the leading bracket + } + + if i != last { // not the last one, strip brackets + if _, err := buf.Write(b[idx : len(b)-1]); err != nil { + log.Println(err) + } + } else { // last one, strip only the leading bracket + if _, err := buf.Write(b[idx:]); err != nil { + log.Println(err) + } + } + a++ + } + // somehow it ended up being empty, so provide a default value + if buf.Len() == 0 { + if err := buf.WriteByte(opening); err != nil { + log.Println(err) + } + if err := buf.WriteByte(closing); err != nil { + log.Println(err) + } + } + return buf.Bytes() +} + +// ToDynamicJSON turns an object into a properly JSON typed structure +func ToDynamicJSON(data interface{}) interface{} { + // TODO: convert straight to a json typed map (mergo + iterate?) + b, err := json.Marshal(data) + if err != nil { + log.Println(err) + } + var res interface{} + if err := json.Unmarshal(b, &res); err != nil { + log.Println(err) + } + return res +} + +// FromDynamicJSON turns an object into a properly JSON typed structure +func FromDynamicJSON(data, target interface{}) error { + b, err := json.Marshal(data) + if err != nil { + log.Println(err) + } + return json.Unmarshal(b, target) +} + +// NameProvider represents an object capabale of translating from go property names +// to json property names +// This type is thread-safe. +type NameProvider struct { + lock *sync.Mutex + index map[reflect.Type]nameIndex +} + +type nameIndex struct { + jsonNames map[string]string + goNames map[string]string +} + +// NewNameProvider creates a new name provider +func NewNameProvider() *NameProvider { + return &NameProvider{ + lock: &sync.Mutex{}, + index: make(map[reflect.Type]nameIndex), + } +} + +func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { + for i := 0; i < tpe.NumField(); i++ { + targetDes := tpe.Field(i) + + if targetDes.PkgPath != "" { // unexported + continue + } + + if targetDes.Anonymous { // walk embedded structures tree down first + buildnameIndex(targetDes.Type, idx, reverseIdx) + continue + } + + if tag := targetDes.Tag.Get("json"); tag != "" { + + parts := strings.Split(tag, ",") + if len(parts) == 0 { + continue + } + + nm := parts[0] + if nm == "-" { + continue + } + if nm == "" { // empty string means we want to use the Go name + nm = targetDes.Name + } + + idx[nm] = targetDes.Name + reverseIdx[targetDes.Name] = nm + } + } +} + +func newNameIndex(tpe reflect.Type) nameIndex { + var idx = make(map[string]string, tpe.NumField()) + var reverseIdx = make(map[string]string, tpe.NumField()) + + buildnameIndex(tpe, idx, reverseIdx) + return nameIndex{jsonNames: idx, goNames: reverseIdx} +} + +// GetJSONNames gets all the json property names for a type +func (n *NameProvider) GetJSONNames(subject interface{}) []string { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + + var res []string + for k := range names.jsonNames { + res = append(res, k) + } + return res +} + +// GetJSONName gets the json name for a go property name +func (n *NameProvider) GetJSONName(subject interface{}, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetJSONNameForType(tpe, name) +} + +// GetJSONNameForType gets the json name for a go property name on a given type +func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.goNames[name] + return nme, ok +} + +func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { + n.lock.Lock() + defer n.lock.Unlock() + names := newNameIndex(tpe) + n.index[tpe] = names + return names +} + +// GetGoName gets the go name for a json property name +func (n *NameProvider) GetGoName(subject interface{}, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetGoNameForType(tpe, name) +} + +// GetGoNameForType gets the go name for a given type for a json property name +func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.jsonNames[name] + return nme, ok +} diff --git a/vendor/github.com/go-openapi/swag/json_test.go b/vendor/github.com/go-openapi/swag/json_test.go new file mode 100644 index 00000000..a7d0d982 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/json_test.go @@ -0,0 +1,163 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" +) + +type testNameStruct struct { + Name string `json:"name"` + NotTheSame int64 `json:"plain"` + Ignored string `json:"-"` +} + +func TestNameProvider(t *testing.T) { + + provider := NewNameProvider() + + var obj = testNameStruct{} + + nm, ok := provider.GetGoName(obj, "name") + assert.True(t, ok) + assert.Equal(t, "Name", nm) + + nm, ok = provider.GetGoName(obj, "plain") + assert.True(t, ok) + assert.Equal(t, "NotTheSame", nm) + + nm, ok = provider.GetGoName(obj, "doesNotExist") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetGoName(obj, "ignored") + assert.False(t, ok) + assert.Empty(t, nm) + + tpe := reflect.TypeOf(obj) + nm, ok = provider.GetGoNameForType(tpe, "name") + assert.True(t, ok) + assert.Equal(t, "Name", nm) + + nm, ok = provider.GetGoNameForType(tpe, "plain") + assert.True(t, ok) + assert.Equal(t, "NotTheSame", nm) + + nm, ok = provider.GetGoNameForType(tpe, "doesNotExist") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetGoNameForType(tpe, "ignored") + assert.False(t, ok) + assert.Empty(t, nm) + + ptr := &obj + nm, ok = provider.GetGoName(ptr, "name") + assert.True(t, ok) + assert.Equal(t, "Name", nm) + + nm, ok = provider.GetGoName(ptr, "plain") + assert.True(t, ok) + assert.Equal(t, "NotTheSame", nm) + + nm, ok = provider.GetGoName(ptr, "doesNotExist") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetGoName(ptr, "ignored") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetJSONName(obj, "Name") + assert.True(t, ok) + assert.Equal(t, "name", nm) + + nm, ok = provider.GetJSONName(obj, "NotTheSame") + assert.True(t, ok) + assert.Equal(t, "plain", nm) + + nm, ok = provider.GetJSONName(obj, "DoesNotExist") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetJSONName(obj, "Ignored") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetJSONNameForType(tpe, "Name") + assert.True(t, ok) + assert.Equal(t, "name", nm) + + nm, ok = provider.GetJSONNameForType(tpe, "NotTheSame") + assert.True(t, ok) + assert.Equal(t, "plain", nm) + + nm, ok = provider.GetJSONNameForType(tpe, "doesNotExist") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetJSONNameForType(tpe, "Ignored") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetJSONName(ptr, "Name") + assert.True(t, ok) + assert.Equal(t, "name", nm) + + nm, ok = provider.GetJSONName(ptr, "NotTheSame") + assert.True(t, ok) + assert.Equal(t, "plain", nm) + + nm, ok = provider.GetJSONName(ptr, "doesNotExist") + assert.False(t, ok) + assert.Empty(t, nm) + + nm, ok = provider.GetJSONName(ptr, "Ignored") + assert.False(t, ok) + assert.Empty(t, nm) + + nms := provider.GetJSONNames(ptr) + assert.Len(t, nms, 2) + + assert.Len(t, provider.index, 1) + +} + +func TestJSONConcatenation(t *testing.T) { + assert.Nil(t, ConcatJSON()) + assert.Equal(t, ConcatJSON([]byte(`{"id":1}`)), []byte(`{"id":1}`)) + assert.Equal(t, ConcatJSON([]byte(`{}`), []byte(`{}`)), []byte(`{}`)) + assert.Equal(t, ConcatJSON([]byte(`[]`), []byte(`[]`)), []byte(`[]`)) + assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{"name":"Rachel"}`)), []byte(`{"id":1,"name":"Rachel"}`)) + assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[{"name":"Rachel"}]`)), []byte(`[{"id":1},{"name":"Rachel"}]`)) + assert.Equal(t, ConcatJSON([]byte(`{}`), []byte(`{"name":"Rachel"}`)), []byte(`{"name":"Rachel"}`)) + assert.Equal(t, ConcatJSON([]byte(`[]`), []byte(`[{"name":"Rachel"}]`)), []byte(`[{"name":"Rachel"}]`)) + assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{}`)), []byte(`{"id":1}`)) + assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[]`)), []byte(`[{"id":1}]`)) + assert.Equal(t, ConcatJSON([]byte(`{}`), []byte(`{}`), []byte(`{}`)), []byte(`{}`)) + assert.Equal(t, ConcatJSON([]byte(`[]`), []byte(`[]`), []byte(`[]`)), []byte(`[]`)) + assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{"name":"Rachel"}`), []byte(`{"age":32}`)), []byte(`{"id":1,"name":"Rachel","age":32}`)) + assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[{"name":"Rachel"}]`), []byte(`[{"age":32}]`)), []byte(`[{"id":1},{"name":"Rachel"},{"age":32}]`)) + assert.Equal(t, ConcatJSON([]byte(`{}`), []byte(`{"name":"Rachel"}`), []byte(`{"age":32}`)), []byte(`{"name":"Rachel","age":32}`)) + assert.Equal(t, ConcatJSON([]byte(`[]`), []byte(`[{"name":"Rachel"}]`), []byte(`[{"age":32}]`)), []byte(`[{"name":"Rachel"},{"age":32}]`)) + assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{}`), []byte(`{"age":32}`)), []byte(`{"id":1,"age":32}`)) + assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[]`), []byte(`[{"age":32}]`)), []byte(`[{"id":1},{"age":32}]`)) + assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{"name":"Rachel"}`), []byte(`{}`)), []byte(`{"id":1,"name":"Rachel"}`)) + assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[{"name":"Rachel"}]`), []byte(`[]`)), []byte(`[{"id":1},{"name":"Rachel"}]`)) + +} diff --git a/vendor/github.com/go-openapi/swag/loading.go b/vendor/github.com/go-openapi/swag/loading.go new file mode 100644 index 00000000..62ed1e80 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading.go @@ -0,0 +1,74 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "fmt" + "io/ioutil" + "log" + "net/http" + "path/filepath" + "strings" + "time" +) + +// LoadHTTPTimeout the default timeout for load requests +var LoadHTTPTimeout = 30 * time.Second + +// LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in +func LoadFromFileOrHTTP(path string) ([]byte, error) { + return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(path) +} + +// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in +// timeout arg allows for per request overriding of the request timeout +func LoadFromFileOrHTTPWithTimeout(path string, timeout time.Duration) ([]byte, error) { + return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(timeout))(path) +} + +// LoadStrategy returns a loader function for a given path or uri +func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) { + if strings.HasPrefix(path, "http") { + return remote + } + return func(pth string) ([]byte, error) { return local(filepath.FromSlash(pth)) } +} + +func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { + return func(path string) ([]byte, error) { + client := &http.Client{Timeout: timeout} + req, err := http.NewRequest("GET", path, nil) + if err != nil { + return nil, err + } + resp, err := client.Do(req) + defer func() { + if resp != nil { + if e := resp.Body.Close(); e != nil { + log.Println(e) + } + } + }() + if err != nil { + return nil, err + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status) + } + + return ioutil.ReadAll(resp.Body) + } +} diff --git a/vendor/github.com/go-openapi/swag/loading_test.go b/vendor/github.com/go-openapi/swag/loading_test.go new file mode 100644 index 00000000..7b8bdf48 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading_test.go @@ -0,0 +1,47 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestLoadFromHTTP(t *testing.T) { + + _, err := LoadFromFileOrHTTP("httx://12394:abd") + assert.Error(t, err) + + serv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + rw.WriteHeader(http.StatusNotFound) + })) + defer serv.Close() + + _, err = LoadFromFileOrHTTP(serv.URL) + assert.Error(t, err) + + ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + rw.WriteHeader(http.StatusOK) + rw.Write([]byte("the content")) + })) + defer ts2.Close() + + d, err := LoadFromFileOrHTTP(ts2.URL) + assert.NoError(t, err) + assert.Equal(t, []byte("the content"), d) +} diff --git a/vendor/github.com/go-openapi/swag/net.go b/vendor/github.com/go-openapi/swag/net.go new file mode 100644 index 00000000..8323fa37 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/net.go @@ -0,0 +1,24 @@ +package swag + +import ( + "net" + "strconv" +) + +// SplitHostPort splits a network address into a host and a port. +// The port is -1 when there is no port to be found +func SplitHostPort(addr string) (host string, port int, err error) { + h, p, err := net.SplitHostPort(addr) + if err != nil { + return "", -1, err + } + if p == "" { + return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} + } + + pi, err := strconv.Atoi(p) + if err != nil { + return "", -1, err + } + return h, pi, nil +} diff --git a/vendor/github.com/go-openapi/swag/net_test.go b/vendor/github.com/go-openapi/swag/net_test.go new file mode 100644 index 00000000..041db60a --- /dev/null +++ b/vendor/github.com/go-openapi/swag/net_test.go @@ -0,0 +1,30 @@ +package swag + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSplitHostPort(t *testing.T) { + data := []struct { + Input string + Host string + Port int + Err bool + }{ + {"localhost:3933", "localhost", 3933, false}, + {"localhost:yellow", "", -1, true}, + {"localhost", "", -1, true}, + {"localhost:", "", -1, true}, + {"localhost:3933", "localhost", 3933, false}, + } + + for _, e := range data { + h, p, err := SplitHostPort(e.Input) + if (!e.Err && assert.NoError(t, err)) || (e.Err && assert.Error(t, err)) { + assert.Equal(t, e.Host, h) + assert.Equal(t, e.Port, p) + } + } +} diff --git a/vendor/github.com/go-openapi/swag/path.go b/vendor/github.com/go-openapi/swag/path.go new file mode 100644 index 00000000..273e9fbe --- /dev/null +++ b/vendor/github.com/go-openapi/swag/path.go @@ -0,0 +1,56 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "os" + "path/filepath" + "runtime" + "strings" +) + +const ( + // GOPATHKey represents the env key for gopath + GOPATHKey = "GOPATH" +) + +// FindInSearchPath finds a package in a provided lists of paths +func FindInSearchPath(searchPath, pkg string) string { + pathsList := filepath.SplitList(searchPath) + for _, path := range pathsList { + if evaluatedPath, err := filepath.EvalSymlinks(filepath.Join(path, "src", pkg)); err == nil { + if _, err := os.Stat(evaluatedPath); err == nil { + return evaluatedPath + } + } + } + return "" +} + +// FindInGoSearchPath finds a package in the $GOPATH:$GOROOT +func FindInGoSearchPath(pkg string) string { + return FindInSearchPath(FullGoSearchPath(), pkg) +} + +// FullGoSearchPath gets the search paths for finding packages +func FullGoSearchPath() string { + allPaths := os.Getenv(GOPATHKey) + if allPaths != "" { + allPaths = strings.Join([]string{allPaths, runtime.GOROOT()}, ":") + } else { + allPaths = runtime.GOROOT() + } + return allPaths +} diff --git a/vendor/github.com/go-openapi/swag/path_test.go b/vendor/github.com/go-openapi/swag/path_test.go new file mode 100644 index 00000000..743bba53 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/path_test.go @@ -0,0 +1,118 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "io/ioutil" + "os" + "path/filepath" + "path" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" +) + +func makeDirStructure(t *testing.T, tgt string) (string, string, error) { + if tgt == "" { + tgt = "pkgpaths" + } + td, err := ioutil.TempDir("", tgt) + if err != nil { + return "", "", err + } + td2, err := ioutil.TempDir("", tgt+"-2") + if err != nil { + return "", "", err + } + realPath := filepath.Join(td, "src", "foo", "bar") + if err := os.MkdirAll(realPath, os.ModePerm); err != nil { + return "", "", err + } + linkPathBase := filepath.Join(td, "src", "baz") + if err := os.MkdirAll(linkPathBase, os.ModePerm); err != nil { + return "", "", err + } + linkPath := filepath.Join(linkPathBase, "das") + if err := os.Symlink(realPath, linkPath); err != nil { + return "", "", err + } + + realPath = filepath.Join(td2, "src", "fuu", "bir") + if err := os.MkdirAll(realPath, os.ModePerm); err != nil { + return "", "", err + } + linkPathBase = filepath.Join(td2, "src", "biz") + if err := os.MkdirAll(linkPathBase, os.ModePerm); err != nil { + return "", "", err + } + linkPath = filepath.Join(linkPathBase, "dis") + if err := os.Symlink(realPath, linkPath); err != nil { + return "", "", err + } + return td, td2, nil +} + +func TestFindPackage(t *testing.T) { + pth, pth2, err := makeDirStructure(t, "") + if err != nil { + t.Fatal(err) + } + defer func() { + os.RemoveAll(pth) + os.RemoveAll(pth2) + }() + + searchPath := pth + string(filepath.ListSeparator) + pth2 + // finds package when real name mentioned + pkg := FindInSearchPath(searchPath, "foo/bar") + assert.NotEmpty(t, pkg) + assertPath(t, path.Join(pth, "src", "foo", "bar"), pkg) + // finds package when real name is mentioned in secondary + pkg = FindInSearchPath(searchPath, "fuu/bir") + assert.NotEmpty(t, pkg) + assertPath(t, path.Join(pth2, "src", "fuu", "bir"), pkg) + // finds package when symlinked + pkg = FindInSearchPath(searchPath, "baz/das") + assert.NotEmpty(t, pkg) + assertPath(t, path.Join(pth, "src", "foo", "bar"), pkg) + // finds package when symlinked in secondary + pkg = FindInSearchPath(searchPath, "biz/dis") + assert.NotEmpty(t, pkg) + assertPath(t, path.Join(pth2, "src", "fuu", "bir"), pkg) + // return empty string when nothing is found + pkg = FindInSearchPath(searchPath, "not/there") + assert.Empty(t, pkg) +} + +func assertPath(t testing.TB, expected, actual string) bool { + fp, err := filepath.EvalSymlinks(expected) + if assert.NoError(t, err) { + return assert.Equal(t, fp, actual) + } + return true +} + +func TestFullGOPATH(t *testing.T) { + os.Unsetenv(GOPATHKey) + ngp := "/some/where:/other/place" + os.Setenv(GOPATHKey, ngp) + + ogp := os.Getenv(GOPATHKey) + defer os.Setenv(GOPATHKey, ogp) + + expected := ngp + ":" + runtime.GOROOT() + assert.Equal(t, expected, FullGoSearchPath()) +} diff --git a/vendor/github.com/go-openapi/swag/util.go b/vendor/github.com/go-openapi/swag/util.go new file mode 100644 index 00000000..40751aab --- /dev/null +++ b/vendor/github.com/go-openapi/swag/util.go @@ -0,0 +1,336 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "math" + "reflect" + "regexp" + "sort" + "strings" + "unicode" +) + +// Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769 +var commonInitialisms = map[string]bool{ + "ACL": true, + "API": true, + "ASCII": true, + "CPU": true, + "CSS": true, + "DNS": true, + "EOF": true, + "GUID": true, + "HTML": true, + "HTTPS": true, + "HTTP": true, + "ID": true, + "IP": true, + "JSON": true, + "LHS": true, + "QPS": true, + "RAM": true, + "RHS": true, + "RPC": true, + "SLA": true, + "SMTP": true, + "SQL": true, + "SSH": true, + "TCP": true, + "TLS": true, + "TTL": true, + "UDP": true, + "UI": true, + "UID": true, + "UUID": true, + "URI": true, + "URL": true, + "UTF8": true, + "VM": true, + "XML": true, + "XMPP": true, + "XSRF": true, + "XSS": true, +} +var initialisms []string + +func init() { + for k := range commonInitialisms { + initialisms = append(initialisms, k) + } + sort.Sort(sort.Reverse(byLength(initialisms))) +} + +// JoinByFormat joins a string array by a known format: +// ssv: space separated value +// tsv: tab separated value +// pipes: pipe (|) separated value +// csv: comma separated value (default) +func JoinByFormat(data []string, format string) []string { + if len(data) == 0 { + return data + } + var sep string + switch format { + case "ssv": + sep = " " + case "tsv": + sep = "\t" + case "pipes": + sep = "|" + case "multi": + return data + default: + sep = "," + } + return []string{strings.Join(data, sep)} +} + +// SplitByFormat splits a string by a known format: +// ssv: space separated value +// tsv: tab separated value +// pipes: pipe (|) separated value +// csv: comma separated value (default) +func SplitByFormat(data, format string) []string { + if data == "" { + return nil + } + var sep string + switch format { + case "ssv": + sep = " " + case "tsv": + sep = "\t" + case "pipes": + sep = "|" + case "multi": + return nil + default: + sep = "," + } + var result []string + for _, s := range strings.Split(data, sep) { + if ts := strings.TrimSpace(s); ts != "" { + result = append(result, ts) + } + } + return result +} + +type byLength []string + +func (s byLength) Len() int { + return len(s) +} +func (s byLength) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} +func (s byLength) Less(i, j int) bool { + return len(s[i]) < len(s[j]) +} + +// Prepares strings by splitting by caps, spaces, dashes, and underscore +func split(str string) (words []string) { + repl := strings.NewReplacer( + "@", "At ", + "&", "And ", + "|", "Pipe ", + "$", "Dollar ", + "!", "Bang ", + "-", " ", + "_", " ", + ) + + rex1 := regexp.MustCompile(`(\p{Lu})`) + rex2 := regexp.MustCompile(`(\pL|\pM|\pN|\p{Pc})+`) + + str = trim(str) + + // Convert dash and underscore to spaces + str = repl.Replace(str) + + // Split when uppercase is found (needed for Snake) + str = rex1.ReplaceAllString(str, " $1") + // check if consecutive single char things make up an initialism + + for _, k := range initialisms { + str = strings.Replace(str, rex1.ReplaceAllString(k, " $1"), " "+k, -1) + } + // Get the final list of words + words = rex2.FindAllString(str, -1) + + return +} + +// Removes leading whitespaces +func trim(str string) string { + return strings.Trim(str, " ") +} + +// Shortcut to strings.ToUpper() +func upper(str string) string { + return strings.ToUpper(trim(str)) +} + +// Shortcut to strings.ToLower() +func lower(str string) string { + return strings.ToLower(trim(str)) +} + +// ToFileName lowercases and underscores a go type name +func ToFileName(name string) string { + var out []string + for _, w := range split(name) { + out = append(out, lower(w)) + } + return strings.Join(out, "_") +} + +// ToCommandName lowercases and underscores a go type name +func ToCommandName(name string) string { + var out []string + for _, w := range split(name) { + out = append(out, lower(w)) + } + return strings.Join(out, "-") +} + +// ToHumanNameLower represents a code name as a human series of words +func ToHumanNameLower(name string) string { + var out []string + for _, w := range split(name) { + if !commonInitialisms[upper(w)] { + out = append(out, lower(w)) + } else { + out = append(out, w) + } + } + return strings.Join(out, " ") +} + +// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized +func ToHumanNameTitle(name string) string { + var out []string + for _, w := range split(name) { + uw := upper(w) + if !commonInitialisms[uw] { + out = append(out, upper(w[:1])+lower(w[1:])) + } else { + out = append(out, w) + } + } + return strings.Join(out, " ") +} + +// ToJSONName camelcases a name which can be underscored or pascal cased +func ToJSONName(name string) string { + var out []string + for i, w := range split(name) { + if i == 0 { + out = append(out, lower(w)) + continue + } + out = append(out, upper(w[:1])+lower(w[1:])) + } + return strings.Join(out, "") +} + +// ToVarName camelcases a name which can be underscored or pascal cased +func ToVarName(name string) string { + res := ToGoName(name) + if _, ok := commonInitialisms[res]; ok { + return lower(res) + } + if len(res) <= 1 { + return lower(res) + } + return lower(res[:1]) + res[1:] +} + +// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes +func ToGoName(name string) string { + var out []string + for _, w := range split(name) { + uw := upper(w) + mod := int(math.Min(float64(len(uw)), 2)) + if !commonInitialisms[uw] && !commonInitialisms[uw[:len(uw)-mod]] { + uw = upper(w[:1]) + lower(w[1:]) + } + out = append(out, uw) + } + + result := strings.Join(out, "") + if len(result) > 0 { + ud := upper(result[:1]) + ru := []rune(ud) + if unicode.IsUpper(ru[0]) { + result = ud + result[1:] + } else { + result = "X" + ud + result[1:] + } + } + return result +} + +// ContainsStringsCI searches a slice of strings for a case-insensitive match +func ContainsStringsCI(coll []string, item string) bool { + for _, a := range coll { + if strings.EqualFold(a, item) { + return true + } + } + return false +} + +type zeroable interface { + IsZero() bool +} + +// IsZero returns true when the value passed into the function is a zero value. +// This allows for safer checking of interface values. +func IsZero(data interface{}) bool { + // check for things that have an IsZero method instead + if vv, ok := data.(zeroable); ok { + return vv.IsZero() + } + // continue with slightly more complex reflection + v := reflect.ValueOf(data) + switch v.Kind() { + case 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 reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return v.IsNil() + case reflect.Struct, reflect.Array: + return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) + case reflect.Invalid: + return true + } + return false +} + +// CommandLineOptionsGroup represents a group of user-defined command line options +type CommandLineOptionsGroup struct { + ShortDescription string + LongDescription string + Options interface{} +} diff --git a/vendor/github.com/go-openapi/swag/util_test.go b/vendor/github.com/go-openapi/swag/util_test.go new file mode 100644 index 00000000..5db20b90 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/util_test.go @@ -0,0 +1,277 @@ +// Copyright 2015 go-swagger maintainers +// +// 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 swag + +import ( + "fmt" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +type translationSample struct { + str, out string +} + +func titleize(s string) string { return strings.ToTitle(s[:1]) + lower(s[1:]) } + +func TestToGoName(t *testing.T) { + samples := []translationSample{ + {"sample text", "SampleText"}, + {"sample-text", "SampleText"}, + {"sample_text", "SampleText"}, + {"sampleText", "SampleText"}, + {"sample 2 Text", "Sample2Text"}, + {"findThingById", "FindThingByID"}, + {"日本語sample 2 Text", "X日本語sample2Text"}, + {"日本語findThingById", "X日本語findThingByID"}, + } + + for k := range commonInitialisms { + samples = append(samples, + translationSample{"sample " + lower(k) + " text", "Sample" + k + "Text"}, + translationSample{"sample-" + lower(k) + "-text", "Sample" + k + "Text"}, + translationSample{"sample_" + lower(k) + "_text", "Sample" + k + "Text"}, + translationSample{"sample" + titleize(k) + "Text", "Sample" + k + "Text"}, + translationSample{"sample " + lower(k), "Sample" + k}, + translationSample{"sample-" + lower(k), "Sample" + k}, + translationSample{"sample_" + lower(k), "Sample" + k}, + translationSample{"sample" + titleize(k), "Sample" + k}, + translationSample{"sample " + titleize(k) + " text", "Sample" + k + "Text"}, + translationSample{"sample-" + titleize(k) + "-text", "Sample" + k + "Text"}, + translationSample{"sample_" + titleize(k) + "_text", "Sample" + k + "Text"}, + ) + } + + for _, sample := range samples { + assert.Equal(t, sample.out, ToGoName(sample.str)) + } +} + +func TestContainsStringsCI(t *testing.T) { + list := []string{"hello", "world", "and", "such"} + + assert.True(t, ContainsStringsCI(list, "hELLo")) + assert.True(t, ContainsStringsCI(list, "world")) + assert.True(t, ContainsStringsCI(list, "AND")) + assert.False(t, ContainsStringsCI(list, "nuts")) +} + +func TestSplitByFormat(t *testing.T) { + expected := []string{"one", "two", "three"} + for _, fmt := range []string{"csv", "pipes", "tsv", "ssv", "multi"} { + + var actual []string + switch fmt { + case "multi": + assert.Nil(t, SplitByFormat("", fmt)) + assert.Nil(t, SplitByFormat("blah", fmt)) + case "ssv": + actual = SplitByFormat(strings.Join(expected, " "), fmt) + assert.EqualValues(t, expected, actual) + case "pipes": + actual = SplitByFormat(strings.Join(expected, "|"), fmt) + assert.EqualValues(t, expected, actual) + case "tsv": + actual = SplitByFormat(strings.Join(expected, "\t"), fmt) + assert.EqualValues(t, expected, actual) + default: + actual = SplitByFormat(strings.Join(expected, ","), fmt) + assert.EqualValues(t, expected, actual) + } + } +} + +func TestJoinByFormat(t *testing.T) { + for _, fmt := range []string{"csv", "pipes", "tsv", "ssv", "multi"} { + + lval := []string{"one", "two", "three"} + var expected []string + switch fmt { + case "multi": + expected = lval + case "ssv": + expected = []string{strings.Join(lval, " ")} + case "pipes": + expected = []string{strings.Join(lval, "|")} + case "tsv": + expected = []string{strings.Join(lval, "\t")} + default: + expected = []string{strings.Join(lval, ",")} + } + assert.Nil(t, JoinByFormat(nil, fmt)) + assert.EqualValues(t, expected, JoinByFormat(lval, fmt)) + } +} + +func TestToFileName(t *testing.T) { + samples := []translationSample{ + {"SampleText", "sample_text"}, + {"FindThingByID", "find_thing_by_id"}, + } + + for k := range commonInitialisms { + samples = append(samples, + translationSample{"Sample" + k + "Text", "sample_" + lower(k) + "_text"}, + ) + } + + for _, sample := range samples { + assert.Equal(t, sample.out, ToFileName(sample.str)) + } +} + +func TestToCommandName(t *testing.T) { + samples := []translationSample{ + {"SampleText", "sample-text"}, + {"FindThingByID", "find-thing-by-id"}, + } + + for k := range commonInitialisms { + samples = append(samples, + translationSample{"Sample" + k + "Text", "sample-" + lower(k) + "-text"}, + ) + } + + for _, sample := range samples { + assert.Equal(t, sample.out, ToCommandName(sample.str)) + } +} + +func TestToHumanName(t *testing.T) { + samples := []translationSample{ + {"SampleText", "sample text"}, + {"FindThingByID", "find thing by ID"}, + } + + for k := range commonInitialisms { + samples = append(samples, + translationSample{"Sample" + k + "Text", "sample " + k + " text"}, + ) + } + + for _, sample := range samples { + assert.Equal(t, sample.out, ToHumanNameLower(sample.str)) + } +} + +func TestToJSONName(t *testing.T) { + samples := []translationSample{ + {"SampleText", "sampleText"}, + {"FindThingByID", "findThingById"}, + } + + for k := range commonInitialisms { + samples = append(samples, + translationSample{"Sample" + k + "Text", "sample" + titleize(k) + "Text"}, + ) + } + + for _, sample := range samples { + assert.Equal(t, sample.out, ToJSONName(sample.str)) + } +} + +type SimpleZeroes struct { + ID string + Name string +} +type ZeroesWithTime struct { + Time time.Time +} + +func TestIsZero(t *testing.T) { + var strs [5]string + var strss []string + var a int + var b int8 + var c int16 + var d int32 + var e int64 + var f uint + var g uint8 + var h uint16 + var i uint32 + var j uint64 + var k map[string]string + var l interface{} + var m *SimpleZeroes + var n string + var o SimpleZeroes + var p ZeroesWithTime + var q time.Time + data := []struct { + Data interface{} + Expected bool + }{ + {a, true}, + {b, true}, + {c, true}, + {d, true}, + {e, true}, + {f, true}, + {g, true}, + {h, true}, + {i, true}, + {j, true}, + {k, true}, + {l, true}, + {m, true}, + {n, true}, + {o, true}, + {p, true}, + {q, true}, + {strss, true}, + {strs, true}, + {"", true}, + {nil, true}, + {1, false}, + {0, true}, + {int8(1), false}, + {int8(0), true}, + {int16(1), false}, + {int16(0), true}, + {int32(1), false}, + {int32(0), true}, + {int64(1), false}, + {int64(0), true}, + {uint(1), false}, + {uint(0), true}, + {uint8(1), false}, + {uint8(0), true}, + {uint16(1), false}, + {uint16(0), true}, + {uint32(1), false}, + {uint32(0), true}, + {uint64(1), false}, + {uint64(0), true}, + {0.0, true}, + {0.1, false}, + {float32(0.0), true}, + {float32(0.1), false}, + {float64(0.0), true}, + {float64(0.1), false}, + {[...]string{}, true}, + {[...]string{"hello"}, false}, + {[]string(nil), true}, + {[]string{"a"}, false}, + } + + for _, it := range data { + assert.Equal(t, it.Expected, IsZero(it.Data), fmt.Sprintf("%#v", it.Data)) + } +} diff --git a/vendor/github.com/google/gofuzz/.travis.yml b/vendor/github.com/google/gofuzz/.travis.yml new file mode 100644 index 00000000..f8684d99 --- /dev/null +++ b/vendor/github.com/google/gofuzz/.travis.yml @@ -0,0 +1,13 @@ +language: go + +go: + - 1.4 + - 1.3 + - 1.2 + - tip + +install: + - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi + +script: + - go test -cover diff --git a/vendor/github.com/google/gofuzz/CONTRIBUTING.md b/vendor/github.com/google/gofuzz/CONTRIBUTING.md new file mode 100644 index 00000000..51cf5cd1 --- /dev/null +++ b/vendor/github.com/google/gofuzz/CONTRIBUTING.md @@ -0,0 +1,67 @@ +# How to contribute # + +We'd love to accept your patches and contributions to this project. There are +a just a few small guidelines you need to follow. + + +## Contributor License Agreement ## + +Contributions to any Google project must be accompanied by a Contributor +License Agreement. This is not a copyright **assignment**, it simply gives +Google permission to use and redistribute your contributions as part of the +project. + + * If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an [individual + CLA][]. + + * If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a [corporate CLA][]. + +You generally only need to submit a CLA once, so if you've already submitted +one (even if it was for a different project), you probably don't need to do it +again. + +[individual CLA]: https://developers.google.com/open-source/cla/individual +[corporate CLA]: https://developers.google.com/open-source/cla/corporate + + +## Submitting a patch ## + + 1. It's generally best to start by opening a new issue describing the bug or + feature you're intending to fix. Even if you think it's relatively minor, + it's helpful to know what people are working on. Mention in the initial + issue that you are planning to work on that bug or feature so that it can + be assigned to you. + + 1. Follow the normal process of [forking][] the project, and setup a new + branch to work in. It's important that each group of changes be done in + separate branches in order to ensure that a pull request only includes the + commits related to that bug or feature. + + 1. Go makes it very simple to ensure properly formatted code, so always run + `go fmt` on your code before committing it. You should also run + [golint][] over your code. As noted in the [golint readme][], it's not + strictly necessary that your code be completely "lint-free", but this will + help you find common style issues. + + 1. Any significant changes should almost always be accompanied by tests. The + project already has good test coverage, so look at some of the existing + tests if you're unsure how to go about it. [gocov][] and [gocov-html][] + are invaluable tools for seeing which parts of your code aren't being + exercised by your tests. + + 1. Do your best to have [well-formed commit messages][] for each change. + This provides consistency throughout the project, and ensures that commit + messages are able to be formatted properly by various git tools. + + 1. Finally, push the commits to your fork and submit a [pull request][]. + +[forking]: https://help.github.com/articles/fork-a-repo +[golint]: https://github.com/golang/lint +[golint readme]: https://github.com/golang/lint/blob/master/README +[gocov]: https://github.com/axw/gocov +[gocov-html]: https://github.com/matm/gocov-html +[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html +[squash]: http://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits +[pull request]: https://help.github.com/articles/creating-a-pull-request diff --git a/vendor/github.com/google/gofuzz/LICENSE b/vendor/github.com/google/gofuzz/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/google/gofuzz/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/google/gofuzz/README.md b/vendor/github.com/google/gofuzz/README.md new file mode 100644 index 00000000..64869af3 --- /dev/null +++ b/vendor/github.com/google/gofuzz/README.md @@ -0,0 +1,71 @@ +gofuzz +====== + +gofuzz is a library for populating go objects with random values. + +[![GoDoc](https://godoc.org/github.com/google/gofuzz?status.png)](https://godoc.org/github.com/google/gofuzz) +[![Travis](https://travis-ci.org/google/gofuzz.svg?branch=master)](https://travis-ci.org/google/gofuzz) + +This is useful for testing: + +* Do your project's objects really serialize/unserialize correctly in all cases? +* Is there an incorrectly formatted object that will cause your project to panic? + +Import with ```import "github.com/google/gofuzz"``` + +You can use it on single variables: +```go +f := fuzz.New() +var myInt int +f.Fuzz(&myInt) // myInt gets a random value. +``` + +You can use it on maps: +```go +f := fuzz.New().NilChance(0).NumElements(1, 1) +var myMap map[ComplexKeyType]string +f.Fuzz(&myMap) // myMap will have exactly one element. +``` + +Customize the chance of getting a nil pointer: +```go +f := fuzz.New().NilChance(.5) +var fancyStruct struct { + A, B, C, D *string +} +f.Fuzz(&fancyStruct) // About half the pointers should be set. +``` + +You can even customize the randomization completely if needed: +```go +type MyEnum string +const ( + A MyEnum = "A" + B MyEnum = "B" +) +type MyInfo struct { + Type MyEnum + AInfo *string + BInfo *string +} + +f := fuzz.New().NilChance(0).Funcs( + func(e *MyInfo, c fuzz.Continue) { + switch c.Intn(2) { + case 0: + e.Type = A + c.Fuzz(&e.AInfo) + case 1: + e.Type = B + c.Fuzz(&e.BInfo) + } + }, +) + +var myObject MyInfo +f.Fuzz(&myObject) // Type will correspond to whether A or B info is set. +``` + +See more examples in ```example_test.go```. + +Happy testing! diff --git a/vendor/github.com/google/gofuzz/doc.go b/vendor/github.com/google/gofuzz/doc.go new file mode 100644 index 00000000..9f9956d4 --- /dev/null +++ b/vendor/github.com/google/gofuzz/doc.go @@ -0,0 +1,18 @@ +/* +Copyright 2014 Google Inc. All rights reserved. + +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 fuzz is a library for populating go objects with random values. +package fuzz diff --git a/vendor/github.com/google/gofuzz/example_test.go b/vendor/github.com/google/gofuzz/example_test.go new file mode 100644 index 00000000..792707a3 --- /dev/null +++ b/vendor/github.com/google/gofuzz/example_test.go @@ -0,0 +1,225 @@ +/* +Copyright 2014 Google Inc. All rights reserved. + +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 fuzz_test + +import ( + "encoding/json" + "fmt" + "math/rand" + + "github.com/google/gofuzz" +) + +func ExampleSimple() { + type MyType struct { + A string + B string + C int + D struct { + E float64 + } + } + + f := fuzz.New() + object := MyType{} + + uniqueObjects := map[MyType]int{} + + for i := 0; i < 1000; i++ { + f.Fuzz(&object) + uniqueObjects[object]++ + } + fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) + // Output: + // Got 1000 unique objects. +} + +func ExampleCustom() { + type MyType struct { + A int + B string + } + + counter := 0 + f := fuzz.New().Funcs( + func(i *int, c fuzz.Continue) { + *i = counter + counter++ + }, + ) + object := MyType{} + + uniqueObjects := map[MyType]int{} + + for i := 0; i < 100; i++ { + f.Fuzz(&object) + if object.A != i { + fmt.Printf("Unexpected value: %#v\n", object) + } + uniqueObjects[object]++ + } + fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) + // Output: + // Got 100 unique objects. +} + +func ExampleComplex() { + type OtherType struct { + A string + B string + } + type MyType struct { + Pointer *OtherType + Map map[string]OtherType + PointerMap *map[string]OtherType + Slice []OtherType + SlicePointer []*OtherType + PointerSlicePointer *[]*OtherType + } + + f := fuzz.New().RandSource(rand.NewSource(0)).NilChance(0).NumElements(1, 1).Funcs( + func(o *OtherType, c fuzz.Continue) { + o.A = "Foo" + o.B = "Bar" + }, + func(op **OtherType, c fuzz.Continue) { + *op = &OtherType{"A", "B"} + }, + func(m map[string]OtherType, c fuzz.Continue) { + m["Works Because"] = OtherType{ + "Fuzzer", + "Preallocated", + } + }, + ) + object := MyType{} + f.Fuzz(&object) + bytes, err := json.MarshalIndent(&object, "", " ") + if err != nil { + fmt.Printf("error: %v\n", err) + } + fmt.Printf("%s\n", string(bytes)) + // Output: + // { + // "Pointer": { + // "A": "A", + // "B": "B" + // }, + // "Map": { + // "Works Because": { + // "A": "Fuzzer", + // "B": "Preallocated" + // } + // }, + // "PointerMap": { + // "Works Because": { + // "A": "Fuzzer", + // "B": "Preallocated" + // } + // }, + // "Slice": [ + // { + // "A": "Foo", + // "B": "Bar" + // } + // ], + // "SlicePointer": [ + // { + // "A": "A", + // "B": "B" + // } + // ], + // "PointerSlicePointer": [ + // { + // "A": "A", + // "B": "B" + // } + // ] + // } +} + +func ExampleMap() { + f := fuzz.New().NilChance(0).NumElements(1, 1) + var myMap map[struct{ A, B, C int }]string + f.Fuzz(&myMap) + fmt.Printf("myMap has %v element(s).\n", len(myMap)) + // Output: + // myMap has 1 element(s). +} + +func ExampleSingle() { + f := fuzz.New() + var i int + f.Fuzz(&i) + + // Technically, we'd expect this to fail one out of 2 billion attempts... + fmt.Printf("(i == 0) == %v", i == 0) + // Output: + // (i == 0) == false +} + +func ExampleEnum() { + type MyEnum string + const ( + A MyEnum = "A" + B MyEnum = "B" + ) + type MyInfo struct { + Type MyEnum + AInfo *string + BInfo *string + } + + f := fuzz.New().NilChance(0).Funcs( + func(e *MyInfo, c fuzz.Continue) { + // Note c's embedded Rand allows for direct use. + // We could also use c.RandBool() here. + switch c.Intn(2) { + case 0: + e.Type = A + c.Fuzz(&e.AInfo) + case 1: + e.Type = B + c.Fuzz(&e.BInfo) + } + }, + ) + + for i := 0; i < 100; i++ { + var myObject MyInfo + f.Fuzz(&myObject) + switch myObject.Type { + case A: + if myObject.AInfo == nil { + fmt.Println("AInfo should have been set!") + } + if myObject.BInfo != nil { + fmt.Println("BInfo should NOT have been set!") + } + case B: + if myObject.BInfo == nil { + fmt.Println("BInfo should have been set!") + } + if myObject.AInfo != nil { + fmt.Println("AInfo should NOT have been set!") + } + default: + fmt.Println("Invalid enum value!") + } + } + // Output: +} diff --git a/vendor/github.com/google/gofuzz/fuzz.go b/vendor/github.com/google/gofuzz/fuzz.go new file mode 100644 index 00000000..4f888fbc --- /dev/null +++ b/vendor/github.com/google/gofuzz/fuzz.go @@ -0,0 +1,453 @@ +/* +Copyright 2014 Google Inc. All rights reserved. + +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 fuzz + +import ( + "fmt" + "math/rand" + "reflect" + "time" +) + +// fuzzFuncMap is a map from a type to a fuzzFunc that handles that type. +type fuzzFuncMap map[reflect.Type]reflect.Value + +// Fuzzer knows how to fill any object with random fields. +type Fuzzer struct { + fuzzFuncs fuzzFuncMap + defaultFuzzFuncs fuzzFuncMap + r *rand.Rand + nilChance float64 + minElements int + maxElements int +} + +// New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs, +// RandSource, NilChance, or NumElements in any order. +func New() *Fuzzer { + f := &Fuzzer{ + defaultFuzzFuncs: fuzzFuncMap{ + reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime), + }, + + fuzzFuncs: fuzzFuncMap{}, + r: rand.New(rand.NewSource(time.Now().UnixNano())), + nilChance: .2, + minElements: 1, + maxElements: 10, + } + return f +} + +// Funcs adds each entry in fuzzFuncs as a custom fuzzing function. +// +// Each entry in fuzzFuncs must be a function taking two parameters. +// The first parameter must be a pointer or map. It is the variable that +// function will fill with random data. The second parameter must be a +// fuzz.Continue, which will provide a source of randomness and a way +// to automatically continue fuzzing smaller pieces of the first parameter. +// +// These functions are called sensibly, e.g., if you wanted custom string +// fuzzing, the function `func(s *string, c fuzz.Continue)` would get +// called and passed the address of strings. Maps and pointers will always +// be made/new'd for you, ignoring the NilChange option. For slices, it +// doesn't make much sense to pre-create them--Fuzzer doesn't know how +// long you want your slice--so take a pointer to a slice, and make it +// yourself. (If you don't want your map/pointer type pre-made, take a +// pointer to it, and make it yourself.) See the examples for a range of +// custom functions. +func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer { + for i := range fuzzFuncs { + v := reflect.ValueOf(fuzzFuncs[i]) + if v.Kind() != reflect.Func { + panic("Need only funcs!") + } + t := v.Type() + if t.NumIn() != 2 || t.NumOut() != 0 { + panic("Need 2 in and 0 out params!") + } + argT := t.In(0) + switch argT.Kind() { + case reflect.Ptr, reflect.Map: + default: + panic("fuzzFunc must take pointer or map type") + } + if t.In(1) != reflect.TypeOf(Continue{}) { + panic("fuzzFunc's second parameter must be type fuzz.Continue") + } + f.fuzzFuncs[argT] = v + } + return f +} + +// RandSource causes f to get values from the given source of randomness. +// Use if you want deterministic fuzzing. +func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer { + f.r = rand.New(s) + return f +} + +// NilChance sets the probability of creating a nil pointer, map, or slice to +// 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive. +func (f *Fuzzer) NilChance(p float64) *Fuzzer { + if p < 0 || p > 1 { + panic("p should be between 0 and 1, inclusive.") + } + f.nilChance = p + return f +} + +// NumElements sets the minimum and maximum number of elements that will be +// added to a non-nil map or slice. +func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer { + if atLeast > atMost { + panic("atLeast must be <= atMost") + } + if atLeast < 0 { + panic("atLeast must be >= 0") + } + f.minElements = atLeast + f.maxElements = atMost + return f +} + +func (f *Fuzzer) genElementCount() int { + if f.minElements == f.maxElements { + return f.minElements + } + return f.minElements + f.r.Intn(f.maxElements-f.minElements+1) +} + +func (f *Fuzzer) genShouldFill() bool { + return f.r.Float64() > f.nilChance +} + +// Fuzz recursively fills all of obj's fields with something random. First +// this tries to find a custom fuzz function (see Funcs). If there is no +// custom function this tests whether the object implements fuzz.Interface and, +// if so, calls Fuzz on it to fuzz itself. If that fails, this will see if +// there is a default fuzz function provided by this package. If all of that +// fails, this will generate random values for all primitive fields and then +// recurse for all non-primitives. +// +// Not safe for cyclic or tree-like structs! +// +// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) +// Intended for tests, so will panic on bad input or unimplemented fields. +func (f *Fuzzer) Fuzz(obj interface{}) { + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("needed ptr!") + } + v = v.Elem() + f.doFuzz(v, 0) +} + +// FuzzNoCustom is just like Fuzz, except that any custom fuzz function for +// obj's type will not be called and obj will not be tested for fuzz.Interface +// conformance. This applies only to obj and not other instances of obj's +// type. +// Not safe for cyclic or tree-like structs! +// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) +// Intended for tests, so will panic on bad input or unimplemented fields. +func (f *Fuzzer) FuzzNoCustom(obj interface{}) { + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("needed ptr!") + } + v = v.Elem() + f.doFuzz(v, flagNoCustomFuzz) +} + +const ( + // Do not try to find a custom fuzz function. Does not apply recursively. + flagNoCustomFuzz uint64 = 1 << iota +) + +func (f *Fuzzer) doFuzz(v reflect.Value, flags uint64) { + if !v.CanSet() { + return + } + + if flags&flagNoCustomFuzz == 0 { + // Check for both pointer and non-pointer custom functions. + if v.CanAddr() && f.tryCustom(v.Addr()) { + return + } + if f.tryCustom(v) { + return + } + } + + if fn, ok := fillFuncMap[v.Kind()]; ok { + fn(v, f.r) + return + } + switch v.Kind() { + case reflect.Map: + if f.genShouldFill() { + v.Set(reflect.MakeMap(v.Type())) + n := f.genElementCount() + for i := 0; i < n; i++ { + key := reflect.New(v.Type().Key()).Elem() + f.doFuzz(key, 0) + val := reflect.New(v.Type().Elem()).Elem() + f.doFuzz(val, 0) + v.SetMapIndex(key, val) + } + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Ptr: + if f.genShouldFill() { + v.Set(reflect.New(v.Type().Elem())) + f.doFuzz(v.Elem(), 0) + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Slice: + if f.genShouldFill() { + n := f.genElementCount() + v.Set(reflect.MakeSlice(v.Type(), n, n)) + for i := 0; i < n; i++ { + f.doFuzz(v.Index(i), 0) + } + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Array: + if f.genShouldFill() { + n := v.Len() + for i := 0; i < n; i++ { + f.doFuzz(v.Index(i), 0) + } + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + f.doFuzz(v.Field(i), 0) + } + case reflect.Chan: + fallthrough + case reflect.Func: + fallthrough + case reflect.Interface: + fallthrough + default: + panic(fmt.Sprintf("Can't handle %#v", v.Interface())) + } +} + +// tryCustom searches for custom handlers, and returns true iff it finds a match +// and successfully randomizes v. +func (f *Fuzzer) tryCustom(v reflect.Value) bool { + // First: see if we have a fuzz function for it. + doCustom, ok := f.fuzzFuncs[v.Type()] + if !ok { + // Second: see if it can fuzz itself. + if v.CanInterface() { + intf := v.Interface() + if fuzzable, ok := intf.(Interface); ok { + fuzzable.Fuzz(Continue{f: f, Rand: f.r}) + return true + } + } + // Finally: see if there is a default fuzz function. + doCustom, ok = f.defaultFuzzFuncs[v.Type()] + if !ok { + return false + } + } + + switch v.Kind() { + case reflect.Ptr: + if v.IsNil() { + if !v.CanSet() { + return false + } + v.Set(reflect.New(v.Type().Elem())) + } + case reflect.Map: + if v.IsNil() { + if !v.CanSet() { + return false + } + v.Set(reflect.MakeMap(v.Type())) + } + default: + return false + } + + doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{ + f: f, + Rand: f.r, + })}) + return true +} + +// Interface represents an object that knows how to fuzz itself. Any time we +// find a type that implements this interface we will delegate the act of +// fuzzing itself. +type Interface interface { + Fuzz(c Continue) +} + +// Continue can be passed to custom fuzzing functions to allow them to use +// the correct source of randomness and to continue fuzzing their members. +type Continue struct { + f *Fuzzer + + // For convenience, Continue implements rand.Rand via embedding. + // Use this for generating any randomness if you want your fuzzing + // to be repeatable for a given seed. + *rand.Rand +} + +// Fuzz continues fuzzing obj. obj must be a pointer. +func (c Continue) Fuzz(obj interface{}) { + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("needed ptr!") + } + v = v.Elem() + c.f.doFuzz(v, 0) +} + +// FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for +// obj's type will not be called and obj will not be tested for fuzz.Interface +// conformance. This applies only to obj and not other instances of obj's +// type. +func (c Continue) FuzzNoCustom(obj interface{}) { + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("needed ptr!") + } + v = v.Elem() + c.f.doFuzz(v, flagNoCustomFuzz) +} + +// RandString makes a random string up to 20 characters long. The returned string +// may include a variety of (valid) UTF-8 encodings. +func (c Continue) RandString() string { + return randString(c.Rand) +} + +// RandUint64 makes random 64 bit numbers. +// Weirdly, rand doesn't have a function that gives you 64 random bits. +func (c Continue) RandUint64() uint64 { + return randUint64(c.Rand) +} + +// RandBool returns true or false randomly. +func (c Continue) RandBool() bool { + return randBool(c.Rand) +} + +func fuzzInt(v reflect.Value, r *rand.Rand) { + v.SetInt(int64(randUint64(r))) +} + +func fuzzUint(v reflect.Value, r *rand.Rand) { + v.SetUint(randUint64(r)) +} + +func fuzzTime(t *time.Time, c Continue) { + var sec, nsec int64 + // Allow for about 1000 years of random time values, which keeps things + // like JSON parsing reasonably happy. + sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60) + c.Fuzz(&nsec) + *t = time.Unix(sec, nsec) +} + +var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){ + reflect.Bool: func(v reflect.Value, r *rand.Rand) { + v.SetBool(randBool(r)) + }, + reflect.Int: fuzzInt, + reflect.Int8: fuzzInt, + reflect.Int16: fuzzInt, + reflect.Int32: fuzzInt, + reflect.Int64: fuzzInt, + reflect.Uint: fuzzUint, + reflect.Uint8: fuzzUint, + reflect.Uint16: fuzzUint, + reflect.Uint32: fuzzUint, + reflect.Uint64: fuzzUint, + reflect.Uintptr: fuzzUint, + reflect.Float32: func(v reflect.Value, r *rand.Rand) { + v.SetFloat(float64(r.Float32())) + }, + reflect.Float64: func(v reflect.Value, r *rand.Rand) { + v.SetFloat(r.Float64()) + }, + reflect.Complex64: func(v reflect.Value, r *rand.Rand) { + panic("unimplemented") + }, + reflect.Complex128: func(v reflect.Value, r *rand.Rand) { + panic("unimplemented") + }, + reflect.String: func(v reflect.Value, r *rand.Rand) { + v.SetString(randString(r)) + }, + reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) { + panic("unimplemented") + }, +} + +// randBool returns true or false randomly. +func randBool(r *rand.Rand) bool { + if r.Int()&1 == 1 { + return true + } + return false +} + +type charRange struct { + first, last rune +} + +// choose returns a random unicode character from the given range, using the +// given randomness source. +func (r *charRange) choose(rand *rand.Rand) rune { + count := int64(r.last - r.first) + return r.first + rune(rand.Int63n(count)) +} + +var unicodeRanges = []charRange{ + {' ', '~'}, // ASCII characters + {'\u00a0', '\u02af'}, // Multi-byte encoded characters + {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings) +} + +// randString makes a random string up to 20 characters long. The returned string +// may include a variety of (valid) UTF-8 encodings. +func randString(r *rand.Rand) string { + n := r.Intn(20) + runes := make([]rune, n) + for i := range runes { + runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r) + } + return string(runes) +} + +// randUint64 makes random 64 bit numbers. +// Weirdly, rand doesn't have a function that gives you 64 random bits. +func randUint64(r *rand.Rand) uint64 { + return uint64(r.Uint32())<<32 | uint64(r.Uint32()) +} diff --git a/vendor/github.com/google/gofuzz/fuzz_test.go b/vendor/github.com/google/gofuzz/fuzz_test.go new file mode 100644 index 00000000..65cbd822 --- /dev/null +++ b/vendor/github.com/google/gofuzz/fuzz_test.go @@ -0,0 +1,428 @@ +/* +Copyright 2014 Google Inc. All rights reserved. + +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 fuzz + +import ( + "reflect" + "testing" + "time" +) + +func TestFuzz_basic(t *testing.T) { + obj := &struct { + I int + I8 int8 + I16 int16 + I32 int32 + I64 int64 + U uint + U8 uint8 + U16 uint16 + U32 uint32 + U64 uint64 + Uptr uintptr + S string + B bool + T time.Time + }{} + + failed := map[string]int{} + for i := 0; i < 10; i++ { + New().Fuzz(obj) + + if n, v := "i", obj.I; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "i8", obj.I8; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "i16", obj.I16; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "i32", obj.I32; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "i64", obj.I64; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "u", obj.U; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "u8", obj.U8; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "u16", obj.U16; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "u32", obj.U32; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "u64", obj.U64; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "uptr", obj.Uptr; v == 0 { + failed[n] = failed[n] + 1 + } + if n, v := "s", obj.S; v == "" { + failed[n] = failed[n] + 1 + } + if n, v := "b", obj.B; v == false { + failed[n] = failed[n] + 1 + } + if n, v := "t", obj.T; v.IsZero() { + failed[n] = failed[n] + 1 + } + } + checkFailed(t, failed) +} + +func checkFailed(t *testing.T, failed map[string]int) { + for k, v := range failed { + if v > 8 { + t.Errorf("%v seems to not be getting set, was zero value %v times", k, v) + } + } +} + +func TestFuzz_structptr(t *testing.T) { + obj := &struct { + A *struct { + S string + } + }{} + + f := New().NilChance(.5) + failed := map[string]int{} + for i := 0; i < 10; i++ { + f.Fuzz(obj) + + if n, v := "a not nil", obj.A; v == nil { + failed[n] = failed[n] + 1 + } + if n, v := "a nil", obj.A; v != nil { + failed[n] = failed[n] + 1 + } + if n, v := "as", obj.A; v == nil || v.S == "" { + failed[n] = failed[n] + 1 + } + } + checkFailed(t, failed) +} + +// tryFuzz tries fuzzing up to 20 times. Fail if check() never passes, report the highest +// stage it ever got to. +func tryFuzz(t *testing.T, f *Fuzzer, obj interface{}, check func() (stage int, passed bool)) { + maxStage := 0 + for i := 0; i < 20; i++ { + f.Fuzz(obj) + stage, passed := check() + if stage > maxStage { + maxStage = stage + } + if passed { + return + } + } + t.Errorf("Only ever got to stage %v", maxStage) +} + +func TestFuzz_structmap(t *testing.T) { + obj := &struct { + A map[struct { + S string + }]struct { + S2 string + } + B map[string]string + }{} + + tryFuzz(t, New(), obj, func() (int, bool) { + if obj.A == nil { + return 1, false + } + if len(obj.A) == 0 { + return 2, false + } + for k, v := range obj.A { + if k.S == "" { + return 3, false + } + if v.S2 == "" { + return 4, false + } + } + + if obj.B == nil { + return 5, false + } + if len(obj.B) == 0 { + return 6, false + } + for k, v := range obj.B { + if k == "" { + return 7, false + } + if v == "" { + return 8, false + } + } + return 9, true + }) +} + +func TestFuzz_structslice(t *testing.T) { + obj := &struct { + A []struct { + S string + } + B []string + }{} + + tryFuzz(t, New(), obj, func() (int, bool) { + if obj.A == nil { + return 1, false + } + if len(obj.A) == 0 { + return 2, false + } + for _, v := range obj.A { + if v.S == "" { + return 3, false + } + } + + if obj.B == nil { + return 4, false + } + if len(obj.B) == 0 { + return 5, false + } + for _, v := range obj.B { + if v == "" { + return 6, false + } + } + return 7, true + }) +} + +func TestFuzz_structarray(t *testing.T) { + obj := &struct { + A [3]struct { + S string + } + B [2]int + }{} + + tryFuzz(t, New(), obj, func() (int, bool) { + for _, v := range obj.A { + if v.S == "" { + return 1, false + } + } + + for _, v := range obj.B { + if v == 0 { + return 2, false + } + } + return 3, true + }) +} + +func TestFuzz_custom(t *testing.T) { + obj := &struct { + A string + B *string + C map[string]string + D *map[string]string + }{} + + testPhrase := "gotcalled" + testMap := map[string]string{"C": "D"} + f := New().Funcs( + func(s *string, c Continue) { + *s = testPhrase + }, + func(m map[string]string, c Continue) { + m["C"] = "D" + }, + ) + + tryFuzz(t, f, obj, func() (int, bool) { + if obj.A != testPhrase { + return 1, false + } + if obj.B == nil { + return 2, false + } + if *obj.B != testPhrase { + return 3, false + } + if e, a := testMap, obj.C; !reflect.DeepEqual(e, a) { + return 4, false + } + if obj.D == nil { + return 5, false + } + if e, a := testMap, *obj.D; !reflect.DeepEqual(e, a) { + return 6, false + } + return 7, true + }) +} + +type SelfFuzzer string + +// Implement fuzz.Interface. +func (sf *SelfFuzzer) Fuzz(c Continue) { + *sf = selfFuzzerTestPhrase +} + +const selfFuzzerTestPhrase = "was fuzzed" + +func TestFuzz_interface(t *testing.T) { + f := New() + + var obj1 SelfFuzzer + tryFuzz(t, f, &obj1, func() (int, bool) { + if obj1 != selfFuzzerTestPhrase { + return 1, false + } + return 1, true + }) + + var obj2 map[int]SelfFuzzer + tryFuzz(t, f, &obj2, func() (int, bool) { + for _, v := range obj2 { + if v != selfFuzzerTestPhrase { + return 1, false + } + } + return 1, true + }) +} + +func TestFuzz_interfaceAndFunc(t *testing.T) { + const privateTestPhrase = "private phrase" + f := New().Funcs( + // This should take precedence over SelfFuzzer.Fuzz(). + func(s *SelfFuzzer, c Continue) { + *s = privateTestPhrase + }, + ) + + var obj1 SelfFuzzer + tryFuzz(t, f, &obj1, func() (int, bool) { + if obj1 != privateTestPhrase { + return 1, false + } + return 1, true + }) + + var obj2 map[int]SelfFuzzer + tryFuzz(t, f, &obj2, func() (int, bool) { + for _, v := range obj2 { + if v != privateTestPhrase { + return 1, false + } + } + return 1, true + }) +} + +func TestFuzz_noCustom(t *testing.T) { + type Inner struct { + Str string + } + type Outer struct { + Str string + In Inner + } + + testPhrase := "gotcalled" + f := New().Funcs( + func(outer *Outer, c Continue) { + outer.Str = testPhrase + c.Fuzz(&outer.In) + }, + func(inner *Inner, c Continue) { + inner.Str = testPhrase + }, + ) + c := Continue{f: f, Rand: f.r} + + // Fuzzer.Fuzz() + obj1 := Outer{} + f.Fuzz(&obj1) + if obj1.Str != testPhrase { + t.Errorf("expected Outer custom function to have been called") + } + if obj1.In.Str != testPhrase { + t.Errorf("expected Inner custom function to have been called") + } + + // Continue.Fuzz() + obj2 := Outer{} + c.Fuzz(&obj2) + if obj2.Str != testPhrase { + t.Errorf("expected Outer custom function to have been called") + } + if obj2.In.Str != testPhrase { + t.Errorf("expected Inner custom function to have been called") + } + + // Fuzzer.FuzzNoCustom() + obj3 := Outer{} + f.FuzzNoCustom(&obj3) + if obj3.Str == testPhrase { + t.Errorf("expected Outer custom function to not have been called") + } + if obj3.In.Str != testPhrase { + t.Errorf("expected Inner custom function to have been called") + } + + // Continue.FuzzNoCustom() + obj4 := Outer{} + c.FuzzNoCustom(&obj4) + if obj4.Str == testPhrase { + t.Errorf("expected Outer custom function to not have been called") + } + if obj4.In.Str != testPhrase { + t.Errorf("expected Inner custom function to have been called") + } +} + +func TestFuzz_NumElements(t *testing.T) { + f := New().NilChance(0).NumElements(0, 1) + obj := &struct { + A []int + }{} + + tryFuzz(t, f, obj, func() (int, bool) { + if obj.A == nil { + return 1, false + } + return 2, len(obj.A) == 0 + }) + tryFuzz(t, f, obj, func() (int, bool) { + if obj.A == nil { + return 3, false + } + return 4, len(obj.A) == 1 + }) +} diff --git a/vendor/github.com/mailru/easyjson/.gitignore b/vendor/github.com/mailru/easyjson/.gitignore new file mode 100644 index 00000000..db8c66ed --- /dev/null +++ b/vendor/github.com/mailru/easyjson/.gitignore @@ -0,0 +1,4 @@ +.root +*_easyjson.go +*.iml +.idea diff --git a/vendor/github.com/mailru/easyjson/.travis.yml b/vendor/github.com/mailru/easyjson/.travis.yml new file mode 100644 index 00000000..3e5ac132 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/.travis.yml @@ -0,0 +1,8 @@ +language: go + +go: + - tip +install: + - go get github.com/ugorji/go/codec + - go get github.com/pquerna/ffjson/fflib/v1 + - go get github.com/golang/lint/golint diff --git a/vendor/github.com/mailru/easyjson/LICENSE b/vendor/github.com/mailru/easyjson/LICENSE new file mode 100644 index 00000000..fbff658f --- /dev/null +++ b/vendor/github.com/mailru/easyjson/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2016 Mail.Ru Group + +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/mailru/easyjson/Makefile b/vendor/github.com/mailru/easyjson/Makefile new file mode 100644 index 00000000..8e720a08 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/Makefile @@ -0,0 +1,54 @@ +PKG=github.com/mailru/easyjson +GOPATH:=$(PWD)/.root:$(GOPATH) +export GOPATH + +all: test + +.root/src/$(PKG): + mkdir -p $@ + for i in $$PWD/* ; do ln -s $$i $@/`basename $$i` ; done + +root: .root/src/$(PKG) + +clean: + rm -rf .root + +build: + go build -i -o .root/bin/easyjson $(PKG)/easyjson + +generate: root build + .root/bin/easyjson -stubs \ + .root/src/$(PKG)/tests/snake.go \ + .root/src/$(PKG)/tests/data.go \ + .root/src/$(PKG)/tests/omitempty.go \ + .root/src/$(PKG)/tests/nothing.go \ + .root/src/$(PKG)/tests/named_type.go + + .root/bin/easyjson -all .root/src/$(PKG)/tests/data.go + .root/bin/easyjson -all .root/src/$(PKG)/tests/nothing.go + .root/bin/easyjson -all .root/src/$(PKG)/tests/errors.go + .root/bin/easyjson -snake_case .root/src/$(PKG)/tests/snake.go + .root/bin/easyjson -omit_empty .root/src/$(PKG)/tests/omitempty.go + .root/bin/easyjson -build_tags=use_easyjson .root/src/$(PKG)/benchmark/data.go + .root/bin/easyjson .root/src/$(PKG)/tests/nested_easy.go + .root/bin/easyjson .root/src/$(PKG)/tests/named_type.go + +test: generate root + go test \ + $(PKG)/tests \ + $(PKG)/jlexer \ + $(PKG)/gen \ + $(PKG)/buffer + go test -benchmem -tags use_easyjson -bench . $(PKG)/benchmark + golint -set_exit_status .root/src/$(PKG)/tests/*_easyjson.go + +bench-other: generate root + @go test -benchmem -bench . $(PKG)/benchmark + @go test -benchmem -tags use_ffjson -bench . $(PKG)/benchmark + @go test -benchmem -tags use_codec -bench . $(PKG)/benchmark + +bench-python: + benchmark/ujson.sh + + +.PHONY: root clean generate test build diff --git a/vendor/github.com/mailru/easyjson/README.md b/vendor/github.com/mailru/easyjson/README.md new file mode 100644 index 00000000..e990111f --- /dev/null +++ b/vendor/github.com/mailru/easyjson/README.md @@ -0,0 +1,193 @@ +# easyjson [![Build Status](https://travis-ci.org/mailru/easyjson.svg?branch=master)](https://travis-ci.org/mailru/easyjson) + +easyjson allows to (un-)marshal JSON golang structs without the use of reflection by generating marshaller code. + +One of the aims of the library is to keep generated code simple enough so that it can be easily optimized or fixed. Another goal is to provide users with ability to customize the generated code not available in 'encoding/json', such as generating snake_case names or enabling 'omitempty' behavior by default. + +## usage +``` +go get github.com/mailru/easyjson/... +easyjson -all .go +``` + +This will generate `_easyjson.go` with marshaller/unmarshaller methods for structs. `GOPATH` variable needs to be set up correctly, since the generation invokes a `go run` on a temporary file (this is a really convenient approach to code generation borrowed from https://github.com/pquerna/ffjson). + +## options +``` +Usage of .root/bin/easyjson: + -all + generate un-/marshallers for all structs in a file + -build_tags string + build tags to add to generated file + -leave_temps + do not delete temporary files + -no_std_marshalers + don't generate MarshalJSON/UnmarshalJSON methods + -noformat + do not run 'gofmt -w' on output file + -omit_empty + omit empty fields by default + -snake_case + use snake_case names instead of CamelCase by default + -stubs + only generate stubs for marshallers/unmarshallers methods +``` + +Using `-all` will generate (un-)marshallers for all structs in the file. By default, structs need to have a line beginning with `easyjson:json` in their docstring, e.g.: +``` +//easyjson:json +struct A{} +``` + +`-snake_case` tells easyjson to generate snake\_case field names by default (unless explicitly overriden by a field tag). The CamelCase to snake\_case conversion algorithm should work in most cases (e.g. HTTPVersion will be converted to http_version). There can be names like JSONHTTPRPC where the conversion will return an unexpected result (jsonhttprpc without underscores), but such names require a dictionary to do the conversion and may be ambiguous. + +`-build_tags` will add corresponding build tag line for the generated file. +## marshaller/unmarshaller interfaces + +easyjson generates MarshalJSON/UnmarshalJSON methods that are compatible with interfaces from 'encoding/json'. They are usable with 'json.Marshal' and 'json.Unmarshal' functions, however actually using those will result in significantly worse performance compared to custom interfaces. + +`MarshalEasyJSON` / `UnmarshalEasyJSON` methods are generated for faster parsing using custom Lexer/Writer structs (`jlexer.Lexer` and `jwriter.Writer`). The method signature is defined in `easyjson.Marshaler` / `easyjson.Unmarshaler` interfaces. These interfaces allow to avoid using any unnecessary reflection or type assertions during parsing. Functions can be used manually or with `easyjson.Marshal<...>` and `easyjson.Unmarshal<...>` helper methods. + +`jwriter.Writer` struct in addition to function for returning the data as a single slice also has methods to return the size and to send the data to an `io.Writer`. This is aimed at a typical HTTP use-case, when you want to know the `Content-Length` before actually starting to send the data. + +There are helpers in the top-level package for marhsaling/unmarshaling the data using custom interfaces to and from writers, including a helper for `http.ResponseWriter`. + +## custom types +If `easyjson.Marshaler` / `easyjson.Unmarshaler` interfaces are implemented by a type involved in JSON parsing, the type will be marshaled/unmarshaled using these methods. `easyjson.Optional` interface allows for a custom type to integrate with 'omitempty' logic. + +As an example, easyjson includes an `easyjson.RawMessage` analogous to `json.RawMessage`. + +Also, there are 'optional' wrappers for primitive types in `easyjson/opt` package. These are useful in the case when it is necessary to distinguish between missing and default value for the type. Wrappers allow to avoid pointers and extra heap allocations in such cases. + +## memory pooling + +The library uses a custom buffer which allocates data in increasing chunks (128-32768 bytes). Chunks of 512 bytes and larger are reused with the help of `sync.Pool`. The maximum size of a chunk is bounded to reduce redundancy in memory allocation and to make the chunks more reusable in the case of large buffer sizes. + +The buffer code is in `easyjson/buffer` package the exact values can be tweaked by a `buffer.Init()` call before the first serialization. + +## limitations +* The library is at an early stage, there are likely to be some bugs and some features of 'encoding/json' may not be supported. Please report such cases, so that they may be fixed sooner. +* Object keys are case-sensitive (unlike encodin/json). Case-insentive behavior will be implemented as an option (case-insensitive matching is slower). +* Unsafe package is used by the code. While a non-unsafe version of easyjson can be made in the future, using unsafe package simplifies a lot of code by allowing no-copy []byte to string conversion within the library. This is used only during parsing and all the returned values are allocated properly. +* Floats are currently formatted with default precision for 'strconv' package. It is obvious that it is not always the correct way to handle it, but there aren't enough use-cases for floats at hand to do anything better. +* During parsing, parts of JSON that are skipped over are not syntactically validated more than required to skip matching parentheses. +* No true streaming support for encoding/decoding. For many use-cases and protocols, data length is typically known on input and needs to be known before sending the data. + +## benchmarks +Most benchmarks were done using a sample 13kB JSON (9k if serialized back trimming the whitespace) from https://dev.twitter.com/rest/reference/get/search/tweets. The sample is very close to real-world data, quite structured and contains a variety of different types. + +For small request benchmarks, an 80-byte portion of the regular sample was used. + +For large request marshalling benchmarks, a struct containing 50 regular samples was used, making a ~500kB output JSON. + +Benchmarks are available in the repository and are run on 'make'. + +### easyjson vs. encoding/json + +easyjson seems to be 5-6 times faster than the default json serialization for unmarshalling, 3-4 times faster for non-concurrent marshalling. Concurrent marshalling is 6-7x faster if marshalling to a writer. + +### easyjson vs. ffjson + +easyjson uses the same approach for code generation as ffjson, but a significantly different approach to lexing and generated code. This allows easyjson to be 2-3x faster for unmarshalling and 1.5-2x faster for non-concurrent unmarshalling. + +ffjson seems to behave weird if used concurrently: for large request pooling hurts performance instead of boosting it, it also does not quite scale well. These issues are likely to be fixable and until that comparisons might vary from version to version a lot. + +easyjson is similar in performance for small requests and 2-5x times faster for large ones if used with a writer. + +### easyjson vs. go/codec + +github.com/ugorji/go/codec library provides compile-time helpers for JSON generation. In this case, helpers are not exactly marshallers as they are encoding-independent. + +easyjson is generally ~2x faster for non-concurrent benchmarks and about 3x faster for concurrent encoding (without marshalling to a writer). Unsafe option for generated helpers was used. + +As an attempt to measure marshalling performance of 'go/codec' (as opposed to allocations/memcpy/writer interface invocations), a benchmark was done with resetting lenght of a byte slice rather than resetting the whole slice to nil. However, the optimization in this exact form may not be applicable in practice, since the memory is not freed between marshalling operations. + +### easyjson vs 'ujson' python module +ujson is using C code for parsing, so it is interesting to see how plain golang compares to that. It is imporant to note that the resulting object for python is slower to access, since the library parses JSON object into dictionaries. + +easyjson seems to be slightly faster for unmarshalling (finally!) and 2-3x faster for marshalling. + +### benchmark figures +The data was measured on 4 February, 2016 using current ffjson and golang 1.6. Data for go/codec was added on 4 March 2016, benchmarked on the same machine. + +#### Unmarshalling +| lib | json size | MB/s | allocs/op | B/op +|--------|-----------|------|-----------|------- +|standard| regular | 22 | 218 | 10229 +|standard| small | 9.7 | 14 | 720 +|--------|-----------|------|-----------|------- +|easyjson| regular | 125 | 128 | 9794 +|easyjson| small | 67 | 3 | 128 +|--------|-----------|------|-----------|------- +|ffjson | regular | 66 | 141 | 9985 +|ffjson | small | 17.6 | 10 | 488 +|--------|-----------|------|-----------|------- +|codec | regular | 55 | 434 | 19299 +|codec | small | 29 | 7 | 336 +|--------|-----------|------|-----------|------- +|ujson | regular | 103 | N/A | N/A + +#### Marshalling, one goroutine. +| lib | json size | MB/s | allocs/op | B/op +|----------|-----------|------|-----------|------- +|standard | regular | 75 | 9 | 23256 +|standard | small | 32 | 3 | 328 +|standard | large | 80 | 17 | 1.2M +|----------|-----------|------|-----------|------- +|easyjson | regular | 213 | 9 | 10260 +|easyjson* | regular | 263 | 8 | 742 +|easyjson | small | 125 | 1 | 128 +|easyjson | large | 212 | 33 | 490k +|easyjson* | large | 262 | 25 | 2879 +|----------|-----------|------|-----------|------- +|ffjson | regular | 122 | 153 | 21340 +|ffjson** | regular | 146 | 152 | 4897 +|ffjson | small | 36 | 5 | 384 +|ffjson** | small | 64 | 4 | 128 +|ffjson | large | 134 | 7317 | 818k +|ffjson** | large | 125 | 7320 | 827k +|----------|-----------|------|-----------|------- +|codec | regular | 80 | 17 | 33601 +|codec*** | regular | 108 | 9 | 1153 +|codec | small | 42 | 3 | 304 +|codec*** | small | 56 | 1 | 48 +|codec | large | 73 | 483 | 2.5M +|codec*** | large | 103 | 451 | 66007 +|----------|-----------|------|-----------|------- +|ujson | regular | 92 | N/A | N/A +\* marshalling to a writer, +\*\* using `ffjson.Pool()`, +\*\*\* reusing output slice instead of resetting it to nil + +#### Marshalling, concurrent. +| lib | json size | MB/s | allocs/op | B/op +|----------|-----------|-------|-----------|------- +|standard | regular | 252 | 9 | 23257 +|standard | small | 124 | 3 | 328 +|standard | large | 289 | 17 | 1.2M +|----------|-----------|-------|-----------|------- +|easyjson | regular | 792 | 9 | 10597 +|easyjson* | regular | 1748 | 8 | 779 +|easyjson | small | 333 | 1 | 128 +|easyjson | large | 718 | 36 | 548k +|easyjson* | large | 2134 | 25 | 4957 +|----------|-----------|------|-----------|------- +|ffjson | regular | 301 | 153 | 21629 +|ffjson** | regular | 707 | 152 | 5148 +|ffjson | small | 62 | 5 | 384 +|ffjson** | small | 282 | 4 | 128 +|ffjson | large | 438 | 7330 | 1.0M +|ffjson** | large | 131 | 7319 | 820k +|----------|-----------|------|-----------|------- +|codec | regular | 183 | 17 | 33603 +|codec*** | regular | 671 | 9 | 1157 +|codec | small | 147 | 3 | 304 +|codec*** | small | 299 | 1 | 48 +|codec | large | 190 | 483 | 2.5M +|codec*** | large | 752 | 451 | 77574 +\* marshalling to a writer, +\*\* using `ffjson.Pool()`, +\*\*\* reusing output slice instead of resetting it to nil + + + diff --git a/vendor/github.com/mailru/easyjson/benchmark/codec_test.go b/vendor/github.com/mailru/easyjson/benchmark/codec_test.go new file mode 100644 index 00000000..5c77072e --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/codec_test.go @@ -0,0 +1,279 @@ +// +build use_codec + +package benchmark + +import ( + "testing" + + "github.com/ugorji/go/codec" +) + +func BenchmarkCodec_Unmarshal_M(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + dec := codec.NewDecoderBytes(nil, h) + + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + dec.ResetBytes(largeStructText) + if err := dec.Decode(&s); err != nil { + b.Error(err) + } + } +} + +func BenchmarkCodec_Unmarshal_S(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + dec := codec.NewDecoderBytes(nil, h) + + b.SetBytes(int64(len(smallStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + dec.ResetBytes(smallStructText) + if err := dec.Decode(&s); err != nil { + b.Error(err) + } + } +} + +func BenchmarkCodec_Marshal_S(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&smallStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_M(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&largeStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_L(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&xlStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_S_Reuse(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&smallStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_M_Reuse(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&largeStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_L_Reuse(b *testing.B) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + var l int64 + for i := 0; i < b.N; i++ { + enc.ResetBytes(&out) + if err := enc.Encode(&xlStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_S_Parallel(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var out []byte + + var h codec.Handle = new(codec.JsonHandle) + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&smallStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + }) + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_M_Parallel(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&largeStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + }) + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_L_Parallel(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&xlStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = nil + } + }) + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_S_Parallel_Reuse(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var out []byte + + var h codec.Handle = new(codec.JsonHandle) + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&smallStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + }) + + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_M_Parallel_Reuse(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&largeStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + }) + b.SetBytes(l) +} + +func BenchmarkCodec_Marshal_L_Parallel_Reuse(b *testing.B) { + var l int64 + + b.RunParallel(func(pb *testing.PB) { + var h codec.Handle = new(codec.JsonHandle) + + var out []byte + enc := codec.NewEncoderBytes(&out, h) + + for pb.Next() { + enc.ResetBytes(&out) + if err := enc.Encode(&xlStructData); err != nil { + b.Error(err) + } + l = int64(len(out)) + out = out[:0] + } + }) + b.SetBytes(l) +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/data.go b/vendor/github.com/mailru/easyjson/benchmark/data.go new file mode 100644 index 00000000..d2c689cd --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/data.go @@ -0,0 +1,148 @@ +// Package benchmark provides a simple benchmark for easyjson against default serialization and ffjson. +// The data example is taken from https://dev.twitter.com/rest/reference/get/search/tweets +package benchmark + +import ( + "io/ioutil" +) + +var largeStructText, _ = ioutil.ReadFile("example.json") +var xlStructData XLStruct + +func init() { + for i := 0; i < 50; i++ { + xlStructData.Data = append(xlStructData.Data, largeStructData) + } +} + +var smallStructText = []byte(`{"hashtags":[{"indices":[5, 10],"text":"some-text"}],"urls":[],"user_mentions":[]}`) +var smallStructData = Entities{ + Hashtags: []Hashtag{{Indices: []int{5, 10}, Text: "some-text"}}, + Urls: []*string{}, + UserMentions: []*string{}, +} + +type SearchMetadata struct { + CompletedIn float64 `json:"completed_in"` + Count int `json:"count"` + MaxID int `json:"max_id"` + MaxIDStr string `json:"max_id_str"` + NextResults string `json:"next_results"` + Query string `json:"query"` + RefreshURL string `json:"refresh_url"` + SinceID int `json:"since_id"` + SinceIDStr string `json:"since_id_str"` +} + +type Hashtag struct { + Indices []int `json:"indices"` + Text string `json:"text"` +} + +//easyjson:json +type Entities struct { + Hashtags []Hashtag `json:"hashtags"` + Urls []*string `json:"urls"` + UserMentions []*string `json:"user_mentions"` +} + +type UserEntityDescription struct { + Urls []*string `json:"urls"` +} + +type URL struct { + ExpandedURL *string `json:"expanded_url"` + Indices []int `json:"indices"` + URL string `json:"url"` +} + +type UserEntityURL struct { + Urls []URL `json:"urls"` +} + +type UserEntities struct { + Description UserEntityDescription `json:"description"` + URL UserEntityURL `json:"url"` +} + +type User struct { + ContributorsEnabled bool `json:"contributors_enabled"` + CreatedAt string `json:"created_at"` + DefaultProfile bool `json:"default_profile"` + DefaultProfileImage bool `json:"default_profile_image"` + Description string `json:"description"` + Entities UserEntities `json:"entities"` + FavouritesCount int `json:"favourites_count"` + FollowRequestSent *string `json:"follow_request_sent"` + FollowersCount int `json:"followers_count"` + Following *string `json:"following"` + FriendsCount int `json:"friends_count"` + GeoEnabled bool `json:"geo_enabled"` + ID int `json:"id"` + IDStr string `json:"id_str"` + IsTranslator bool `json:"is_translator"` + Lang string `json:"lang"` + ListedCount int `json:"listed_count"` + Location string `json:"location"` + Name string `json:"name"` + Notifications *string `json:"notifications"` + ProfileBackgroundColor string `json:"profile_background_color"` + ProfileBackgroundImageURL string `json:"profile_background_image_url"` + ProfileBackgroundImageURLHTTPS string `json:"profile_background_image_url_https"` + ProfileBackgroundTile bool `json:"profile_background_tile"` + ProfileImageURL string `json:"profile_image_url"` + ProfileImageURLHTTPS string `json:"profile_image_url_https"` + ProfileLinkColor string `json:"profile_link_color"` + ProfileSidebarBorderColor string `json:"profile_sidebar_border_color"` + ProfileSidebarFillColor string `json:"profile_sidebar_fill_color"` + ProfileTextColor string `json:"profile_text_color"` + ProfileUseBackgroundImage bool `json:"profile_use_background_image"` + Protected bool `json:"protected"` + ScreenName string `json:"screen_name"` + ShowAllInlineMedia bool `json:"show_all_inline_media"` + StatusesCount int `json:"statuses_count"` + TimeZone string `json:"time_zone"` + URL *string `json:"url"` + UtcOffset int `json:"utc_offset"` + Verified bool `json:"verified"` +} + +type StatusMetadata struct { + IsoLanguageCode string `json:"iso_language_code"` + ResultType string `json:"result_type"` +} + +type Status struct { + Contributors *string `json:"contributors"` + Coordinates *string `json:"coordinates"` + CreatedAt string `json:"created_at"` + Entities Entities `json:"entities"` + Favorited bool `json:"favorited"` + Geo *string `json:"geo"` + ID int64 `json:"id"` + IDStr string `json:"id_str"` + InReplyToScreenName *string `json:"in_reply_to_screen_name"` + InReplyToStatusID *string `json:"in_reply_to_status_id"` + InReplyToStatusIDStr *string `json:"in_reply_to_status_id_str"` + InReplyToUserID *string `json:"in_reply_to_user_id"` + InReplyToUserIDStr *string `json:"in_reply_to_user_id_str"` + Metadata StatusMetadata `json:"metadata"` + Place *string `json:"place"` + RetweetCount int `json:"retweet_count"` + Retweeted bool `json:"retweeted"` + Source string `json:"source"` + Text string `json:"text"` + Truncated bool `json:"truncated"` + User User `json:"user"` +} + +//easyjson:json +type LargeStruct struct { + SearchMetadata SearchMetadata `json:"search_metadata"` + Statuses []Status `json:"statuses"` +} + +//easyjson:json +type XLStruct struct { + Data []LargeStruct +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/data_codec.go b/vendor/github.com/mailru/easyjson/benchmark/data_codec.go new file mode 100644 index 00000000..0bb8c4c5 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/data_codec.go @@ -0,0 +1,6911 @@ +//+build use_codec + +// ************************************************************ +// DO NOT EDIT. +// THIS FILE IS AUTO-GENERATED BY codecgen. +// ************************************************************ + +package benchmark + +import ( + "errors" + "fmt" + codec1978 "github.com/ugorji/go/codec" + "reflect" + "runtime" + "unsafe" +) + +const ( + // ----- content types ---- + codecSelferC_UTF89225 = 1 + codecSelferC_RAW9225 = 0 + // ----- value types used ---- + codecSelferValueTypeArray9225 = 10 + codecSelferValueTypeMap9225 = 9 + // ----- containerStateValues ---- + codecSelfer_containerMapKey9225 = 2 + codecSelfer_containerMapValue9225 = 3 + codecSelfer_containerMapEnd9225 = 4 + codecSelfer_containerArrayElem9225 = 6 + codecSelfer_containerArrayEnd9225 = 7 +) + +var ( + codecSelferBitsize9225 = uint8(reflect.TypeOf(uint(0)).Bits()) + codecSelferOnlyMapOrArrayEncodeToStructErr9225 = errors.New(`only encoded map or array can be decoded into a struct`) +) + +type codecSelferUnsafeString9225 struct { + Data uintptr + Len int +} + +type codecSelfer9225 struct{} + +func init() { + if codec1978.GenVersion != 5 { + _, file, _, _ := runtime.Caller(0) + err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", + 5, codec1978.GenVersion, file) + panic(err) + } + if false { // reference the types, but skip this branch at build/run time + var v0 unsafe.Pointer + _ = v0 + } +} + +func (x *SearchMetadata) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [9]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(9) + } else { + yynn2 = 9 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeFloat64(float64(x.CompletedIn)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("completed_in")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeFloat64(float64(x.CompletedIn)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeInt(int64(x.Count)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeInt(int64(x.Count)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeInt(int64(x.MaxID)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("max_id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeInt(int64(x.MaxID)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.MaxIDStr)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("max_id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.MaxIDStr)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.NextResults)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("next_results")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym17 := z.EncBinary() + _ = yym17 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.NextResults)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym19 := z.EncBinary() + _ = yym19 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Query)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("query")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym20 := z.EncBinary() + _ = yym20 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Query)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym22 := z.EncBinary() + _ = yym22 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.RefreshURL)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("refresh_url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.RefreshURL)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym25 := z.EncBinary() + _ = yym25 + if false { + } else { + r.EncodeInt(int64(x.SinceID)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("since_id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym26 := z.EncBinary() + _ = yym26 + if false { + } else { + r.EncodeInt(int64(x.SinceID)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym28 := z.EncBinary() + _ = yym28 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.SinceIDStr)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("since_id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym29 := z.EncBinary() + _ = yym29 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.SinceIDStr)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *SearchMetadata) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *SearchMetadata) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "completed_in": + if r.TryDecodeAsNil() { + x.CompletedIn = 0 + } else { + yyv4 := &x.CompletedIn + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*float64)(yyv4)) = float64(r.DecodeFloat(false)) + } + } + case "count": + if r.TryDecodeAsNil() { + x.Count = 0 + } else { + yyv6 := &x.Count + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*int)(yyv6)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "max_id": + if r.TryDecodeAsNil() { + x.MaxID = 0 + } else { + yyv8 := &x.MaxID + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*int)(yyv8)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "max_id_str": + if r.TryDecodeAsNil() { + x.MaxIDStr = "" + } else { + yyv10 := &x.MaxIDStr + yym11 := z.DecBinary() + _ = yym11 + if false { + } else { + *((*string)(yyv10)) = r.DecodeString() + } + } + case "next_results": + if r.TryDecodeAsNil() { + x.NextResults = "" + } else { + yyv12 := &x.NextResults + yym13 := z.DecBinary() + _ = yym13 + if false { + } else { + *((*string)(yyv12)) = r.DecodeString() + } + } + case "query": + if r.TryDecodeAsNil() { + x.Query = "" + } else { + yyv14 := &x.Query + yym15 := z.DecBinary() + _ = yym15 + if false { + } else { + *((*string)(yyv14)) = r.DecodeString() + } + } + case "refresh_url": + if r.TryDecodeAsNil() { + x.RefreshURL = "" + } else { + yyv16 := &x.RefreshURL + yym17 := z.DecBinary() + _ = yym17 + if false { + } else { + *((*string)(yyv16)) = r.DecodeString() + } + } + case "since_id": + if r.TryDecodeAsNil() { + x.SinceID = 0 + } else { + yyv18 := &x.SinceID + yym19 := z.DecBinary() + _ = yym19 + if false { + } else { + *((*int)(yyv18)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "since_id_str": + if r.TryDecodeAsNil() { + x.SinceIDStr = "" + } else { + yyv20 := &x.SinceIDStr + yym21 := z.DecBinary() + _ = yym21 + if false { + } else { + *((*string)(yyv20)) = r.DecodeString() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *SearchMetadata) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj22 int + var yyb22 bool + var yyhl22 bool = l >= 0 + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.CompletedIn = 0 + } else { + yyv23 := &x.CompletedIn + yym24 := z.DecBinary() + _ = yym24 + if false { + } else { + *((*float64)(yyv23)) = float64(r.DecodeFloat(false)) + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Count = 0 + } else { + yyv25 := &x.Count + yym26 := z.DecBinary() + _ = yym26 + if false { + } else { + *((*int)(yyv25)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.MaxID = 0 + } else { + yyv27 := &x.MaxID + yym28 := z.DecBinary() + _ = yym28 + if false { + } else { + *((*int)(yyv27)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.MaxIDStr = "" + } else { + yyv29 := &x.MaxIDStr + yym30 := z.DecBinary() + _ = yym30 + if false { + } else { + *((*string)(yyv29)) = r.DecodeString() + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.NextResults = "" + } else { + yyv31 := &x.NextResults + yym32 := z.DecBinary() + _ = yym32 + if false { + } else { + *((*string)(yyv31)) = r.DecodeString() + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Query = "" + } else { + yyv33 := &x.Query + yym34 := z.DecBinary() + _ = yym34 + if false { + } else { + *((*string)(yyv33)) = r.DecodeString() + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.RefreshURL = "" + } else { + yyv35 := &x.RefreshURL + yym36 := z.DecBinary() + _ = yym36 + if false { + } else { + *((*string)(yyv35)) = r.DecodeString() + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.SinceID = 0 + } else { + yyv37 := &x.SinceID + yym38 := z.DecBinary() + _ = yym38 + if false { + } else { + *((*int)(yyv37)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.SinceIDStr = "" + } else { + yyv39 := &x.SinceIDStr + yym40 := z.DecBinary() + _ = yym40 + if false { + } else { + *((*string)(yyv39)) = r.DecodeString() + } + } + for { + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l + } else { + yyb22 = r.CheckBreak() + } + if yyb22 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj22-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *Hashtag) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Indices == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + z.F.EncSliceIntV(x.Indices, false, e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("indices")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Indices == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + z.F.EncSliceIntV(x.Indices, false, e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Text)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("text")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Text)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *Hashtag) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *Hashtag) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "indices": + if r.TryDecodeAsNil() { + x.Indices = nil + } else { + yyv4 := &x.Indices + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + z.F.DecSliceIntX(yyv4, false, d) + } + } + case "text": + if r.TryDecodeAsNil() { + x.Text = "" + } else { + yyv6 := &x.Text + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(yyv6)) = r.DecodeString() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *Hashtag) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj8 int + var yyb8 bool + var yyhl8 bool = l >= 0 + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Indices = nil + } else { + yyv9 := &x.Indices + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + z.F.DecSliceIntX(yyv9, false, d) + } + } + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Text = "" + } else { + yyv11 := &x.Text + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*string)(yyv11)) = r.DecodeString() + } + } + for { + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj8-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *Entities) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [3]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(3) + } else { + yynn2 = 3 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Hashtags == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSliceHashtag(([]Hashtag)(x.Hashtags), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("hashtags")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Hashtags == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSliceHashtag(([]Hashtag)(x.Hashtags), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.Urls), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("urls")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.Urls), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.UserMentions == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.UserMentions), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("user_mentions")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.UserMentions == nil { + r.EncodeNil() + } else { + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.UserMentions), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *Entities) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *Entities) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "hashtags": + if r.TryDecodeAsNil() { + x.Hashtags = nil + } else { + yyv4 := &x.Hashtags + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSliceHashtag((*[]Hashtag)(yyv4), d) + } + } + case "urls": + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv6 := &x.Urls + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv6), d) + } + } + case "user_mentions": + if r.TryDecodeAsNil() { + x.UserMentions = nil + } else { + yyv8 := &x.UserMentions + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv8), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *Entities) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Hashtags = nil + } else { + yyv11 := &x.Hashtags + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + h.decSliceHashtag((*[]Hashtag)(yyv11), d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv13 := &x.Urls + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv13), d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.UserMentions = nil + } else { + yyv15 := &x.UserMentions + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv15), d) + } + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *UserEntityDescription) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.Urls), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("urls")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSlicePtrtostring(([]*string)(x.Urls), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *UserEntityDescription) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *UserEntityDescription) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "urls": + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv4 := &x.Urls + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv4), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *UserEntityDescription) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv7 := &x.Urls + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + h.decSlicePtrtostring((*[]*string)(yyv7), d) + } + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *URL) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [3]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(3) + } else { + yynn2 = 3 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.ExpandedURL == nil { + r.EncodeNil() + } else { + yy4 := *x.ExpandedURL + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy4)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("expanded_url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.ExpandedURL == nil { + r.EncodeNil() + } else { + yy6 := *x.ExpandedURL + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy6)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Indices == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + z.F.EncSliceIntV(x.Indices, false, e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("indices")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Indices == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + z.F.EncSliceIntV(x.Indices, false, e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.URL)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.URL)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *URL) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *URL) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "expanded_url": + if r.TryDecodeAsNil() { + if x.ExpandedURL != nil { + x.ExpandedURL = nil + } + } else { + if x.ExpandedURL == nil { + x.ExpandedURL = new(string) + } + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*string)(x.ExpandedURL)) = r.DecodeString() + } + } + case "indices": + if r.TryDecodeAsNil() { + x.Indices = nil + } else { + yyv6 := &x.Indices + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + z.F.DecSliceIntX(yyv6, false, d) + } + } + case "url": + if r.TryDecodeAsNil() { + x.URL = "" + } else { + yyv8 := &x.URL + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*string)(yyv8)) = r.DecodeString() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *URL) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.ExpandedURL != nil { + x.ExpandedURL = nil + } + } else { + if x.ExpandedURL == nil { + x.ExpandedURL = new(string) + } + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*string)(x.ExpandedURL)) = r.DecodeString() + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Indices = nil + } else { + yyv13 := &x.Indices + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + z.F.DecSliceIntX(yyv13, false, d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.URL = "" + } else { + yyv15 := &x.URL + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + *((*string)(yyv15)) = r.DecodeString() + } + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *UserEntityURL) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSliceURL(([]URL)(x.Urls), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("urls")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Urls == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSliceURL(([]URL)(x.Urls), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *UserEntityURL) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *UserEntityURL) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "urls": + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv4 := &x.Urls + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSliceURL((*[]URL)(yyv4), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *UserEntityURL) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Urls = nil + } else { + yyv7 := &x.Urls + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + h.decSliceURL((*[]URL)(yyv7), d) + } + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *UserEntities) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy4 := &x.Description + yy4.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("description")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy6 := &x.Description + yy6.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy9 := &x.URL + yy9.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy11 := &x.URL + yy11.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *UserEntities) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *UserEntities) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "description": + if r.TryDecodeAsNil() { + x.Description = UserEntityDescription{} + } else { + yyv4 := &x.Description + yyv4.CodecDecodeSelf(d) + } + case "url": + if r.TryDecodeAsNil() { + x.URL = UserEntityURL{} + } else { + yyv5 := &x.URL + yyv5.CodecDecodeSelf(d) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *UserEntities) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Description = UserEntityDescription{} + } else { + yyv7 := &x.Description + yyv7.CodecDecodeSelf(d) + } + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.URL = UserEntityURL{} + } else { + yyv8 := &x.URL + yyv8.CodecDecodeSelf(d) + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *User) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [39]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(39) + } else { + yynn2 = 39 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeBool(bool(x.ContributorsEnabled)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("contributors_enabled")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeBool(bool(x.ContributorsEnabled)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.CreatedAt)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("created_at")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.CreatedAt)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeBool(bool(x.DefaultProfile)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("default_profile")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeBool(bool(x.DefaultProfile)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeBool(bool(x.DefaultProfileImage)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("default_profile_image")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeBool(bool(x.DefaultProfileImage)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Description)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("description")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym17 := z.EncBinary() + _ = yym17 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Description)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy19 := &x.Entities + yy19.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("entities")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy21 := &x.Entities + yy21.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym24 := z.EncBinary() + _ = yym24 + if false { + } else { + r.EncodeInt(int64(x.FavouritesCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("favourites_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym25 := z.EncBinary() + _ = yym25 + if false { + } else { + r.EncodeInt(int64(x.FavouritesCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.FollowRequestSent == nil { + r.EncodeNil() + } else { + yy27 := *x.FollowRequestSent + yym28 := z.EncBinary() + _ = yym28 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy27)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("follow_request_sent")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.FollowRequestSent == nil { + r.EncodeNil() + } else { + yy29 := *x.FollowRequestSent + yym30 := z.EncBinary() + _ = yym30 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy29)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym32 := z.EncBinary() + _ = yym32 + if false { + } else { + r.EncodeInt(int64(x.FollowersCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("followers_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym33 := z.EncBinary() + _ = yym33 + if false { + } else { + r.EncodeInt(int64(x.FollowersCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Following == nil { + r.EncodeNil() + } else { + yy35 := *x.Following + yym36 := z.EncBinary() + _ = yym36 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy35)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("following")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Following == nil { + r.EncodeNil() + } else { + yy37 := *x.Following + yym38 := z.EncBinary() + _ = yym38 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy37)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym40 := z.EncBinary() + _ = yym40 + if false { + } else { + r.EncodeInt(int64(x.FriendsCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("friends_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym41 := z.EncBinary() + _ = yym41 + if false { + } else { + r.EncodeInt(int64(x.FriendsCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym43 := z.EncBinary() + _ = yym43 + if false { + } else { + r.EncodeBool(bool(x.GeoEnabled)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("geo_enabled")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym44 := z.EncBinary() + _ = yym44 + if false { + } else { + r.EncodeBool(bool(x.GeoEnabled)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym46 := z.EncBinary() + _ = yym46 + if false { + } else { + r.EncodeInt(int64(x.ID)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym47 := z.EncBinary() + _ = yym47 + if false { + } else { + r.EncodeInt(int64(x.ID)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym49 := z.EncBinary() + _ = yym49 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IDStr)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym50 := z.EncBinary() + _ = yym50 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IDStr)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym52 := z.EncBinary() + _ = yym52 + if false { + } else { + r.EncodeBool(bool(x.IsTranslator)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("is_translator")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym53 := z.EncBinary() + _ = yym53 + if false { + } else { + r.EncodeBool(bool(x.IsTranslator)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym55 := z.EncBinary() + _ = yym55 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Lang)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("lang")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym56 := z.EncBinary() + _ = yym56 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Lang)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym58 := z.EncBinary() + _ = yym58 + if false { + } else { + r.EncodeInt(int64(x.ListedCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("listed_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym59 := z.EncBinary() + _ = yym59 + if false { + } else { + r.EncodeInt(int64(x.ListedCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym61 := z.EncBinary() + _ = yym61 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Location)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("location")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym62 := z.EncBinary() + _ = yym62 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Location)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym64 := z.EncBinary() + _ = yym64 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Name)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("name")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym65 := z.EncBinary() + _ = yym65 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Name)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Notifications == nil { + r.EncodeNil() + } else { + yy67 := *x.Notifications + yym68 := z.EncBinary() + _ = yym68 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy67)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("notifications")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Notifications == nil { + r.EncodeNil() + } else { + yy69 := *x.Notifications + yym70 := z.EncBinary() + _ = yym70 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy69)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym72 := z.EncBinary() + _ = yym72 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_background_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym73 := z.EncBinary() + _ = yym73 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym75 := z.EncBinary() + _ = yym75 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundImageURL)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_background_image_url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym76 := z.EncBinary() + _ = yym76 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundImageURL)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym78 := z.EncBinary() + _ = yym78 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundImageURLHTTPS)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_background_image_url_https")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym79 := z.EncBinary() + _ = yym79 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileBackgroundImageURLHTTPS)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym81 := z.EncBinary() + _ = yym81 + if false { + } else { + r.EncodeBool(bool(x.ProfileBackgroundTile)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_background_tile")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym82 := z.EncBinary() + _ = yym82 + if false { + } else { + r.EncodeBool(bool(x.ProfileBackgroundTile)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym84 := z.EncBinary() + _ = yym84 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileImageURL)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_image_url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym85 := z.EncBinary() + _ = yym85 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileImageURL)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym87 := z.EncBinary() + _ = yym87 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileImageURLHTTPS)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_image_url_https")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym88 := z.EncBinary() + _ = yym88 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileImageURLHTTPS)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym90 := z.EncBinary() + _ = yym90 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileLinkColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_link_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym91 := z.EncBinary() + _ = yym91 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileLinkColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym93 := z.EncBinary() + _ = yym93 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileSidebarBorderColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_sidebar_border_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym94 := z.EncBinary() + _ = yym94 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileSidebarBorderColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym96 := z.EncBinary() + _ = yym96 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileSidebarFillColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_sidebar_fill_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym97 := z.EncBinary() + _ = yym97 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileSidebarFillColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym99 := z.EncBinary() + _ = yym99 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileTextColor)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_text_color")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym100 := z.EncBinary() + _ = yym100 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ProfileTextColor)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym102 := z.EncBinary() + _ = yym102 + if false { + } else { + r.EncodeBool(bool(x.ProfileUseBackgroundImage)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("profile_use_background_image")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym103 := z.EncBinary() + _ = yym103 + if false { + } else { + r.EncodeBool(bool(x.ProfileUseBackgroundImage)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym105 := z.EncBinary() + _ = yym105 + if false { + } else { + r.EncodeBool(bool(x.Protected)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("protected")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym106 := z.EncBinary() + _ = yym106 + if false { + } else { + r.EncodeBool(bool(x.Protected)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym108 := z.EncBinary() + _ = yym108 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ScreenName)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("screen_name")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym109 := z.EncBinary() + _ = yym109 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ScreenName)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym111 := z.EncBinary() + _ = yym111 + if false { + } else { + r.EncodeBool(bool(x.ShowAllInlineMedia)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("show_all_inline_media")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym112 := z.EncBinary() + _ = yym112 + if false { + } else { + r.EncodeBool(bool(x.ShowAllInlineMedia)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym114 := z.EncBinary() + _ = yym114 + if false { + } else { + r.EncodeInt(int64(x.StatusesCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("statuses_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym115 := z.EncBinary() + _ = yym115 + if false { + } else { + r.EncodeInt(int64(x.StatusesCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym117 := z.EncBinary() + _ = yym117 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.TimeZone)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("time_zone")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym118 := z.EncBinary() + _ = yym118 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.TimeZone)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.URL == nil { + r.EncodeNil() + } else { + yy120 := *x.URL + yym121 := z.EncBinary() + _ = yym121 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy120)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("url")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.URL == nil { + r.EncodeNil() + } else { + yy122 := *x.URL + yym123 := z.EncBinary() + _ = yym123 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy122)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym125 := z.EncBinary() + _ = yym125 + if false { + } else { + r.EncodeInt(int64(x.UtcOffset)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("utc_offset")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym126 := z.EncBinary() + _ = yym126 + if false { + } else { + r.EncodeInt(int64(x.UtcOffset)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym128 := z.EncBinary() + _ = yym128 + if false { + } else { + r.EncodeBool(bool(x.Verified)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("verified")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym129 := z.EncBinary() + _ = yym129 + if false { + } else { + r.EncodeBool(bool(x.Verified)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *User) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *User) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "contributors_enabled": + if r.TryDecodeAsNil() { + x.ContributorsEnabled = false + } else { + yyv4 := &x.ContributorsEnabled + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*bool)(yyv4)) = r.DecodeBool() + } + } + case "created_at": + if r.TryDecodeAsNil() { + x.CreatedAt = "" + } else { + yyv6 := &x.CreatedAt + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(yyv6)) = r.DecodeString() + } + } + case "default_profile": + if r.TryDecodeAsNil() { + x.DefaultProfile = false + } else { + yyv8 := &x.DefaultProfile + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*bool)(yyv8)) = r.DecodeBool() + } + } + case "default_profile_image": + if r.TryDecodeAsNil() { + x.DefaultProfileImage = false + } else { + yyv10 := &x.DefaultProfileImage + yym11 := z.DecBinary() + _ = yym11 + if false { + } else { + *((*bool)(yyv10)) = r.DecodeBool() + } + } + case "description": + if r.TryDecodeAsNil() { + x.Description = "" + } else { + yyv12 := &x.Description + yym13 := z.DecBinary() + _ = yym13 + if false { + } else { + *((*string)(yyv12)) = r.DecodeString() + } + } + case "entities": + if r.TryDecodeAsNil() { + x.Entities = UserEntities{} + } else { + yyv14 := &x.Entities + yyv14.CodecDecodeSelf(d) + } + case "favourites_count": + if r.TryDecodeAsNil() { + x.FavouritesCount = 0 + } else { + yyv15 := &x.FavouritesCount + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + *((*int)(yyv15)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "follow_request_sent": + if r.TryDecodeAsNil() { + if x.FollowRequestSent != nil { + x.FollowRequestSent = nil + } + } else { + if x.FollowRequestSent == nil { + x.FollowRequestSent = new(string) + } + yym18 := z.DecBinary() + _ = yym18 + if false { + } else { + *((*string)(x.FollowRequestSent)) = r.DecodeString() + } + } + case "followers_count": + if r.TryDecodeAsNil() { + x.FollowersCount = 0 + } else { + yyv19 := &x.FollowersCount + yym20 := z.DecBinary() + _ = yym20 + if false { + } else { + *((*int)(yyv19)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "following": + if r.TryDecodeAsNil() { + if x.Following != nil { + x.Following = nil + } + } else { + if x.Following == nil { + x.Following = new(string) + } + yym22 := z.DecBinary() + _ = yym22 + if false { + } else { + *((*string)(x.Following)) = r.DecodeString() + } + } + case "friends_count": + if r.TryDecodeAsNil() { + x.FriendsCount = 0 + } else { + yyv23 := &x.FriendsCount + yym24 := z.DecBinary() + _ = yym24 + if false { + } else { + *((*int)(yyv23)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "geo_enabled": + if r.TryDecodeAsNil() { + x.GeoEnabled = false + } else { + yyv25 := &x.GeoEnabled + yym26 := z.DecBinary() + _ = yym26 + if false { + } else { + *((*bool)(yyv25)) = r.DecodeBool() + } + } + case "id": + if r.TryDecodeAsNil() { + x.ID = 0 + } else { + yyv27 := &x.ID + yym28 := z.DecBinary() + _ = yym28 + if false { + } else { + *((*int)(yyv27)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "id_str": + if r.TryDecodeAsNil() { + x.IDStr = "" + } else { + yyv29 := &x.IDStr + yym30 := z.DecBinary() + _ = yym30 + if false { + } else { + *((*string)(yyv29)) = r.DecodeString() + } + } + case "is_translator": + if r.TryDecodeAsNil() { + x.IsTranslator = false + } else { + yyv31 := &x.IsTranslator + yym32 := z.DecBinary() + _ = yym32 + if false { + } else { + *((*bool)(yyv31)) = r.DecodeBool() + } + } + case "lang": + if r.TryDecodeAsNil() { + x.Lang = "" + } else { + yyv33 := &x.Lang + yym34 := z.DecBinary() + _ = yym34 + if false { + } else { + *((*string)(yyv33)) = r.DecodeString() + } + } + case "listed_count": + if r.TryDecodeAsNil() { + x.ListedCount = 0 + } else { + yyv35 := &x.ListedCount + yym36 := z.DecBinary() + _ = yym36 + if false { + } else { + *((*int)(yyv35)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "location": + if r.TryDecodeAsNil() { + x.Location = "" + } else { + yyv37 := &x.Location + yym38 := z.DecBinary() + _ = yym38 + if false { + } else { + *((*string)(yyv37)) = r.DecodeString() + } + } + case "name": + if r.TryDecodeAsNil() { + x.Name = "" + } else { + yyv39 := &x.Name + yym40 := z.DecBinary() + _ = yym40 + if false { + } else { + *((*string)(yyv39)) = r.DecodeString() + } + } + case "notifications": + if r.TryDecodeAsNil() { + if x.Notifications != nil { + x.Notifications = nil + } + } else { + if x.Notifications == nil { + x.Notifications = new(string) + } + yym42 := z.DecBinary() + _ = yym42 + if false { + } else { + *((*string)(x.Notifications)) = r.DecodeString() + } + } + case "profile_background_color": + if r.TryDecodeAsNil() { + x.ProfileBackgroundColor = "" + } else { + yyv43 := &x.ProfileBackgroundColor + yym44 := z.DecBinary() + _ = yym44 + if false { + } else { + *((*string)(yyv43)) = r.DecodeString() + } + } + case "profile_background_image_url": + if r.TryDecodeAsNil() { + x.ProfileBackgroundImageURL = "" + } else { + yyv45 := &x.ProfileBackgroundImageURL + yym46 := z.DecBinary() + _ = yym46 + if false { + } else { + *((*string)(yyv45)) = r.DecodeString() + } + } + case "profile_background_image_url_https": + if r.TryDecodeAsNil() { + x.ProfileBackgroundImageURLHTTPS = "" + } else { + yyv47 := &x.ProfileBackgroundImageURLHTTPS + yym48 := z.DecBinary() + _ = yym48 + if false { + } else { + *((*string)(yyv47)) = r.DecodeString() + } + } + case "profile_background_tile": + if r.TryDecodeAsNil() { + x.ProfileBackgroundTile = false + } else { + yyv49 := &x.ProfileBackgroundTile + yym50 := z.DecBinary() + _ = yym50 + if false { + } else { + *((*bool)(yyv49)) = r.DecodeBool() + } + } + case "profile_image_url": + if r.TryDecodeAsNil() { + x.ProfileImageURL = "" + } else { + yyv51 := &x.ProfileImageURL + yym52 := z.DecBinary() + _ = yym52 + if false { + } else { + *((*string)(yyv51)) = r.DecodeString() + } + } + case "profile_image_url_https": + if r.TryDecodeAsNil() { + x.ProfileImageURLHTTPS = "" + } else { + yyv53 := &x.ProfileImageURLHTTPS + yym54 := z.DecBinary() + _ = yym54 + if false { + } else { + *((*string)(yyv53)) = r.DecodeString() + } + } + case "profile_link_color": + if r.TryDecodeAsNil() { + x.ProfileLinkColor = "" + } else { + yyv55 := &x.ProfileLinkColor + yym56 := z.DecBinary() + _ = yym56 + if false { + } else { + *((*string)(yyv55)) = r.DecodeString() + } + } + case "profile_sidebar_border_color": + if r.TryDecodeAsNil() { + x.ProfileSidebarBorderColor = "" + } else { + yyv57 := &x.ProfileSidebarBorderColor + yym58 := z.DecBinary() + _ = yym58 + if false { + } else { + *((*string)(yyv57)) = r.DecodeString() + } + } + case "profile_sidebar_fill_color": + if r.TryDecodeAsNil() { + x.ProfileSidebarFillColor = "" + } else { + yyv59 := &x.ProfileSidebarFillColor + yym60 := z.DecBinary() + _ = yym60 + if false { + } else { + *((*string)(yyv59)) = r.DecodeString() + } + } + case "profile_text_color": + if r.TryDecodeAsNil() { + x.ProfileTextColor = "" + } else { + yyv61 := &x.ProfileTextColor + yym62 := z.DecBinary() + _ = yym62 + if false { + } else { + *((*string)(yyv61)) = r.DecodeString() + } + } + case "profile_use_background_image": + if r.TryDecodeAsNil() { + x.ProfileUseBackgroundImage = false + } else { + yyv63 := &x.ProfileUseBackgroundImage + yym64 := z.DecBinary() + _ = yym64 + if false { + } else { + *((*bool)(yyv63)) = r.DecodeBool() + } + } + case "protected": + if r.TryDecodeAsNil() { + x.Protected = false + } else { + yyv65 := &x.Protected + yym66 := z.DecBinary() + _ = yym66 + if false { + } else { + *((*bool)(yyv65)) = r.DecodeBool() + } + } + case "screen_name": + if r.TryDecodeAsNil() { + x.ScreenName = "" + } else { + yyv67 := &x.ScreenName + yym68 := z.DecBinary() + _ = yym68 + if false { + } else { + *((*string)(yyv67)) = r.DecodeString() + } + } + case "show_all_inline_media": + if r.TryDecodeAsNil() { + x.ShowAllInlineMedia = false + } else { + yyv69 := &x.ShowAllInlineMedia + yym70 := z.DecBinary() + _ = yym70 + if false { + } else { + *((*bool)(yyv69)) = r.DecodeBool() + } + } + case "statuses_count": + if r.TryDecodeAsNil() { + x.StatusesCount = 0 + } else { + yyv71 := &x.StatusesCount + yym72 := z.DecBinary() + _ = yym72 + if false { + } else { + *((*int)(yyv71)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "time_zone": + if r.TryDecodeAsNil() { + x.TimeZone = "" + } else { + yyv73 := &x.TimeZone + yym74 := z.DecBinary() + _ = yym74 + if false { + } else { + *((*string)(yyv73)) = r.DecodeString() + } + } + case "url": + if r.TryDecodeAsNil() { + if x.URL != nil { + x.URL = nil + } + } else { + if x.URL == nil { + x.URL = new(string) + } + yym76 := z.DecBinary() + _ = yym76 + if false { + } else { + *((*string)(x.URL)) = r.DecodeString() + } + } + case "utc_offset": + if r.TryDecodeAsNil() { + x.UtcOffset = 0 + } else { + yyv77 := &x.UtcOffset + yym78 := z.DecBinary() + _ = yym78 + if false { + } else { + *((*int)(yyv77)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "verified": + if r.TryDecodeAsNil() { + x.Verified = false + } else { + yyv79 := &x.Verified + yym80 := z.DecBinary() + _ = yym80 + if false { + } else { + *((*bool)(yyv79)) = r.DecodeBool() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *User) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj81 int + var yyb81 bool + var yyhl81 bool = l >= 0 + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ContributorsEnabled = false + } else { + yyv82 := &x.ContributorsEnabled + yym83 := z.DecBinary() + _ = yym83 + if false { + } else { + *((*bool)(yyv82)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.CreatedAt = "" + } else { + yyv84 := &x.CreatedAt + yym85 := z.DecBinary() + _ = yym85 + if false { + } else { + *((*string)(yyv84)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.DefaultProfile = false + } else { + yyv86 := &x.DefaultProfile + yym87 := z.DecBinary() + _ = yym87 + if false { + } else { + *((*bool)(yyv86)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.DefaultProfileImage = false + } else { + yyv88 := &x.DefaultProfileImage + yym89 := z.DecBinary() + _ = yym89 + if false { + } else { + *((*bool)(yyv88)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Description = "" + } else { + yyv90 := &x.Description + yym91 := z.DecBinary() + _ = yym91 + if false { + } else { + *((*string)(yyv90)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Entities = UserEntities{} + } else { + yyv92 := &x.Entities + yyv92.CodecDecodeSelf(d) + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.FavouritesCount = 0 + } else { + yyv93 := &x.FavouritesCount + yym94 := z.DecBinary() + _ = yym94 + if false { + } else { + *((*int)(yyv93)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.FollowRequestSent != nil { + x.FollowRequestSent = nil + } + } else { + if x.FollowRequestSent == nil { + x.FollowRequestSent = new(string) + } + yym96 := z.DecBinary() + _ = yym96 + if false { + } else { + *((*string)(x.FollowRequestSent)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.FollowersCount = 0 + } else { + yyv97 := &x.FollowersCount + yym98 := z.DecBinary() + _ = yym98 + if false { + } else { + *((*int)(yyv97)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Following != nil { + x.Following = nil + } + } else { + if x.Following == nil { + x.Following = new(string) + } + yym100 := z.DecBinary() + _ = yym100 + if false { + } else { + *((*string)(x.Following)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.FriendsCount = 0 + } else { + yyv101 := &x.FriendsCount + yym102 := z.DecBinary() + _ = yym102 + if false { + } else { + *((*int)(yyv101)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.GeoEnabled = false + } else { + yyv103 := &x.GeoEnabled + yym104 := z.DecBinary() + _ = yym104 + if false { + } else { + *((*bool)(yyv103)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ID = 0 + } else { + yyv105 := &x.ID + yym106 := z.DecBinary() + _ = yym106 + if false { + } else { + *((*int)(yyv105)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.IDStr = "" + } else { + yyv107 := &x.IDStr + yym108 := z.DecBinary() + _ = yym108 + if false { + } else { + *((*string)(yyv107)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.IsTranslator = false + } else { + yyv109 := &x.IsTranslator + yym110 := z.DecBinary() + _ = yym110 + if false { + } else { + *((*bool)(yyv109)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Lang = "" + } else { + yyv111 := &x.Lang + yym112 := z.DecBinary() + _ = yym112 + if false { + } else { + *((*string)(yyv111)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ListedCount = 0 + } else { + yyv113 := &x.ListedCount + yym114 := z.DecBinary() + _ = yym114 + if false { + } else { + *((*int)(yyv113)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Location = "" + } else { + yyv115 := &x.Location + yym116 := z.DecBinary() + _ = yym116 + if false { + } else { + *((*string)(yyv115)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Name = "" + } else { + yyv117 := &x.Name + yym118 := z.DecBinary() + _ = yym118 + if false { + } else { + *((*string)(yyv117)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Notifications != nil { + x.Notifications = nil + } + } else { + if x.Notifications == nil { + x.Notifications = new(string) + } + yym120 := z.DecBinary() + _ = yym120 + if false { + } else { + *((*string)(x.Notifications)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileBackgroundColor = "" + } else { + yyv121 := &x.ProfileBackgroundColor + yym122 := z.DecBinary() + _ = yym122 + if false { + } else { + *((*string)(yyv121)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileBackgroundImageURL = "" + } else { + yyv123 := &x.ProfileBackgroundImageURL + yym124 := z.DecBinary() + _ = yym124 + if false { + } else { + *((*string)(yyv123)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileBackgroundImageURLHTTPS = "" + } else { + yyv125 := &x.ProfileBackgroundImageURLHTTPS + yym126 := z.DecBinary() + _ = yym126 + if false { + } else { + *((*string)(yyv125)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileBackgroundTile = false + } else { + yyv127 := &x.ProfileBackgroundTile + yym128 := z.DecBinary() + _ = yym128 + if false { + } else { + *((*bool)(yyv127)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileImageURL = "" + } else { + yyv129 := &x.ProfileImageURL + yym130 := z.DecBinary() + _ = yym130 + if false { + } else { + *((*string)(yyv129)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileImageURLHTTPS = "" + } else { + yyv131 := &x.ProfileImageURLHTTPS + yym132 := z.DecBinary() + _ = yym132 + if false { + } else { + *((*string)(yyv131)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileLinkColor = "" + } else { + yyv133 := &x.ProfileLinkColor + yym134 := z.DecBinary() + _ = yym134 + if false { + } else { + *((*string)(yyv133)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileSidebarBorderColor = "" + } else { + yyv135 := &x.ProfileSidebarBorderColor + yym136 := z.DecBinary() + _ = yym136 + if false { + } else { + *((*string)(yyv135)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileSidebarFillColor = "" + } else { + yyv137 := &x.ProfileSidebarFillColor + yym138 := z.DecBinary() + _ = yym138 + if false { + } else { + *((*string)(yyv137)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileTextColor = "" + } else { + yyv139 := &x.ProfileTextColor + yym140 := z.DecBinary() + _ = yym140 + if false { + } else { + *((*string)(yyv139)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ProfileUseBackgroundImage = false + } else { + yyv141 := &x.ProfileUseBackgroundImage + yym142 := z.DecBinary() + _ = yym142 + if false { + } else { + *((*bool)(yyv141)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Protected = false + } else { + yyv143 := &x.Protected + yym144 := z.DecBinary() + _ = yym144 + if false { + } else { + *((*bool)(yyv143)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ScreenName = "" + } else { + yyv145 := &x.ScreenName + yym146 := z.DecBinary() + _ = yym146 + if false { + } else { + *((*string)(yyv145)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ShowAllInlineMedia = false + } else { + yyv147 := &x.ShowAllInlineMedia + yym148 := z.DecBinary() + _ = yym148 + if false { + } else { + *((*bool)(yyv147)) = r.DecodeBool() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.StatusesCount = 0 + } else { + yyv149 := &x.StatusesCount + yym150 := z.DecBinary() + _ = yym150 + if false { + } else { + *((*int)(yyv149)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.TimeZone = "" + } else { + yyv151 := &x.TimeZone + yym152 := z.DecBinary() + _ = yym152 + if false { + } else { + *((*string)(yyv151)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.URL != nil { + x.URL = nil + } + } else { + if x.URL == nil { + x.URL = new(string) + } + yym154 := z.DecBinary() + _ = yym154 + if false { + } else { + *((*string)(x.URL)) = r.DecodeString() + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.UtcOffset = 0 + } else { + yyv155 := &x.UtcOffset + yym156 := z.DecBinary() + _ = yym156 + if false { + } else { + *((*int)(yyv155)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Verified = false + } else { + yyv157 := &x.Verified + yym158 := z.DecBinary() + _ = yym158 + if false { + } else { + *((*bool)(yyv157)) = r.DecodeBool() + } + } + for { + yyj81++ + if yyhl81 { + yyb81 = yyj81 > l + } else { + yyb81 = r.CheckBreak() + } + if yyb81 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj81-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *StatusMetadata) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IsoLanguageCode)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("iso_language_code")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IsoLanguageCode)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ResultType)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("result_type")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.ResultType)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *StatusMetadata) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *StatusMetadata) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "iso_language_code": + if r.TryDecodeAsNil() { + x.IsoLanguageCode = "" + } else { + yyv4 := &x.IsoLanguageCode + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*string)(yyv4)) = r.DecodeString() + } + } + case "result_type": + if r.TryDecodeAsNil() { + x.ResultType = "" + } else { + yyv6 := &x.ResultType + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(yyv6)) = r.DecodeString() + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *StatusMetadata) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj8 int + var yyb8 bool + var yyhl8 bool = l >= 0 + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.IsoLanguageCode = "" + } else { + yyv9 := &x.IsoLanguageCode + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + *((*string)(yyv9)) = r.DecodeString() + } + } + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ResultType = "" + } else { + yyv11 := &x.ResultType + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*string)(yyv11)) = r.DecodeString() + } + } + for { + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj8-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *Status) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [21]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(21) + } else { + yynn2 = 21 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Contributors == nil { + r.EncodeNil() + } else { + yy4 := *x.Contributors + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy4)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("contributors")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Contributors == nil { + r.EncodeNil() + } else { + yy6 := *x.Contributors + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy6)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Coordinates == nil { + r.EncodeNil() + } else { + yy9 := *x.Coordinates + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy9)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("coordinates")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Coordinates == nil { + r.EncodeNil() + } else { + yy11 := *x.Coordinates + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy11)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.CreatedAt)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("created_at")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.CreatedAt)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy17 := &x.Entities + yy17.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("entities")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy19 := &x.Entities + yy19.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym22 := z.EncBinary() + _ = yym22 + if false { + } else { + r.EncodeBool(bool(x.Favorited)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("favorited")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeBool(bool(x.Favorited)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Geo == nil { + r.EncodeNil() + } else { + yy25 := *x.Geo + yym26 := z.EncBinary() + _ = yym26 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy25)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("geo")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Geo == nil { + r.EncodeNil() + } else { + yy27 := *x.Geo + yym28 := z.EncBinary() + _ = yym28 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy27)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym30 := z.EncBinary() + _ = yym30 + if false { + } else { + r.EncodeInt(int64(x.ID)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym31 := z.EncBinary() + _ = yym31 + if false { + } else { + r.EncodeInt(int64(x.ID)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym33 := z.EncBinary() + _ = yym33 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IDStr)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym34 := z.EncBinary() + _ = yym34 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.IDStr)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToScreenName == nil { + r.EncodeNil() + } else { + yy36 := *x.InReplyToScreenName + yym37 := z.EncBinary() + _ = yym37 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy36)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_screen_name")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToScreenName == nil { + r.EncodeNil() + } else { + yy38 := *x.InReplyToScreenName + yym39 := z.EncBinary() + _ = yym39 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy38)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToStatusID == nil { + r.EncodeNil() + } else { + yy41 := *x.InReplyToStatusID + yym42 := z.EncBinary() + _ = yym42 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy41)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_status_id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToStatusID == nil { + r.EncodeNil() + } else { + yy43 := *x.InReplyToStatusID + yym44 := z.EncBinary() + _ = yym44 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy43)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToStatusIDStr == nil { + r.EncodeNil() + } else { + yy46 := *x.InReplyToStatusIDStr + yym47 := z.EncBinary() + _ = yym47 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy46)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_status_id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToStatusIDStr == nil { + r.EncodeNil() + } else { + yy48 := *x.InReplyToStatusIDStr + yym49 := z.EncBinary() + _ = yym49 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy48)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToUserID == nil { + r.EncodeNil() + } else { + yy51 := *x.InReplyToUserID + yym52 := z.EncBinary() + _ = yym52 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy51)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_user_id")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToUserID == nil { + r.EncodeNil() + } else { + yy53 := *x.InReplyToUserID + yym54 := z.EncBinary() + _ = yym54 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy53)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.InReplyToUserIDStr == nil { + r.EncodeNil() + } else { + yy56 := *x.InReplyToUserIDStr + yym57 := z.EncBinary() + _ = yym57 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy56)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("in_reply_to_user_id_str")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.InReplyToUserIDStr == nil { + r.EncodeNil() + } else { + yy58 := *x.InReplyToUserIDStr + yym59 := z.EncBinary() + _ = yym59 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy58)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy61 := &x.Metadata + yy61.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy63 := &x.Metadata + yy63.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Place == nil { + r.EncodeNil() + } else { + yy66 := *x.Place + yym67 := z.EncBinary() + _ = yym67 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy66)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("place")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Place == nil { + r.EncodeNil() + } else { + yy68 := *x.Place + yym69 := z.EncBinary() + _ = yym69 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy68)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym71 := z.EncBinary() + _ = yym71 + if false { + } else { + r.EncodeInt(int64(x.RetweetCount)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("retweet_count")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym72 := z.EncBinary() + _ = yym72 + if false { + } else { + r.EncodeInt(int64(x.RetweetCount)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym74 := z.EncBinary() + _ = yym74 + if false { + } else { + r.EncodeBool(bool(x.Retweeted)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("retweeted")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym75 := z.EncBinary() + _ = yym75 + if false { + } else { + r.EncodeBool(bool(x.Retweeted)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym77 := z.EncBinary() + _ = yym77 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Source)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("source")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym78 := z.EncBinary() + _ = yym78 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Source)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym80 := z.EncBinary() + _ = yym80 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Text)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("text")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym81 := z.EncBinary() + _ = yym81 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(x.Text)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yym83 := z.EncBinary() + _ = yym83 + if false { + } else { + r.EncodeBool(bool(x.Truncated)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("truncated")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yym84 := z.EncBinary() + _ = yym84 + if false { + } else { + r.EncodeBool(bool(x.Truncated)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy86 := &x.User + yy86.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("user")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy88 := &x.User + yy88.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *Status) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *Status) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "contributors": + if r.TryDecodeAsNil() { + if x.Contributors != nil { + x.Contributors = nil + } + } else { + if x.Contributors == nil { + x.Contributors = new(string) + } + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*string)(x.Contributors)) = r.DecodeString() + } + } + case "coordinates": + if r.TryDecodeAsNil() { + if x.Coordinates != nil { + x.Coordinates = nil + } + } else { + if x.Coordinates == nil { + x.Coordinates = new(string) + } + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(x.Coordinates)) = r.DecodeString() + } + } + case "created_at": + if r.TryDecodeAsNil() { + x.CreatedAt = "" + } else { + yyv8 := &x.CreatedAt + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*string)(yyv8)) = r.DecodeString() + } + } + case "entities": + if r.TryDecodeAsNil() { + x.Entities = Entities{} + } else { + yyv10 := &x.Entities + yyv10.CodecDecodeSelf(d) + } + case "favorited": + if r.TryDecodeAsNil() { + x.Favorited = false + } else { + yyv11 := &x.Favorited + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*bool)(yyv11)) = r.DecodeBool() + } + } + case "geo": + if r.TryDecodeAsNil() { + if x.Geo != nil { + x.Geo = nil + } + } else { + if x.Geo == nil { + x.Geo = new(string) + } + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + *((*string)(x.Geo)) = r.DecodeString() + } + } + case "id": + if r.TryDecodeAsNil() { + x.ID = 0 + } else { + yyv15 := &x.ID + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + *((*int64)(yyv15)) = int64(r.DecodeInt(64)) + } + } + case "id_str": + if r.TryDecodeAsNil() { + x.IDStr = "" + } else { + yyv17 := &x.IDStr + yym18 := z.DecBinary() + _ = yym18 + if false { + } else { + *((*string)(yyv17)) = r.DecodeString() + } + } + case "in_reply_to_screen_name": + if r.TryDecodeAsNil() { + if x.InReplyToScreenName != nil { + x.InReplyToScreenName = nil + } + } else { + if x.InReplyToScreenName == nil { + x.InReplyToScreenName = new(string) + } + yym20 := z.DecBinary() + _ = yym20 + if false { + } else { + *((*string)(x.InReplyToScreenName)) = r.DecodeString() + } + } + case "in_reply_to_status_id": + if r.TryDecodeAsNil() { + if x.InReplyToStatusID != nil { + x.InReplyToStatusID = nil + } + } else { + if x.InReplyToStatusID == nil { + x.InReplyToStatusID = new(string) + } + yym22 := z.DecBinary() + _ = yym22 + if false { + } else { + *((*string)(x.InReplyToStatusID)) = r.DecodeString() + } + } + case "in_reply_to_status_id_str": + if r.TryDecodeAsNil() { + if x.InReplyToStatusIDStr != nil { + x.InReplyToStatusIDStr = nil + } + } else { + if x.InReplyToStatusIDStr == nil { + x.InReplyToStatusIDStr = new(string) + } + yym24 := z.DecBinary() + _ = yym24 + if false { + } else { + *((*string)(x.InReplyToStatusIDStr)) = r.DecodeString() + } + } + case "in_reply_to_user_id": + if r.TryDecodeAsNil() { + if x.InReplyToUserID != nil { + x.InReplyToUserID = nil + } + } else { + if x.InReplyToUserID == nil { + x.InReplyToUserID = new(string) + } + yym26 := z.DecBinary() + _ = yym26 + if false { + } else { + *((*string)(x.InReplyToUserID)) = r.DecodeString() + } + } + case "in_reply_to_user_id_str": + if r.TryDecodeAsNil() { + if x.InReplyToUserIDStr != nil { + x.InReplyToUserIDStr = nil + } + } else { + if x.InReplyToUserIDStr == nil { + x.InReplyToUserIDStr = new(string) + } + yym28 := z.DecBinary() + _ = yym28 + if false { + } else { + *((*string)(x.InReplyToUserIDStr)) = r.DecodeString() + } + } + case "metadata": + if r.TryDecodeAsNil() { + x.Metadata = StatusMetadata{} + } else { + yyv29 := &x.Metadata + yyv29.CodecDecodeSelf(d) + } + case "place": + if r.TryDecodeAsNil() { + if x.Place != nil { + x.Place = nil + } + } else { + if x.Place == nil { + x.Place = new(string) + } + yym31 := z.DecBinary() + _ = yym31 + if false { + } else { + *((*string)(x.Place)) = r.DecodeString() + } + } + case "retweet_count": + if r.TryDecodeAsNil() { + x.RetweetCount = 0 + } else { + yyv32 := &x.RetweetCount + yym33 := z.DecBinary() + _ = yym33 + if false { + } else { + *((*int)(yyv32)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + case "retweeted": + if r.TryDecodeAsNil() { + x.Retweeted = false + } else { + yyv34 := &x.Retweeted + yym35 := z.DecBinary() + _ = yym35 + if false { + } else { + *((*bool)(yyv34)) = r.DecodeBool() + } + } + case "source": + if r.TryDecodeAsNil() { + x.Source = "" + } else { + yyv36 := &x.Source + yym37 := z.DecBinary() + _ = yym37 + if false { + } else { + *((*string)(yyv36)) = r.DecodeString() + } + } + case "text": + if r.TryDecodeAsNil() { + x.Text = "" + } else { + yyv38 := &x.Text + yym39 := z.DecBinary() + _ = yym39 + if false { + } else { + *((*string)(yyv38)) = r.DecodeString() + } + } + case "truncated": + if r.TryDecodeAsNil() { + x.Truncated = false + } else { + yyv40 := &x.Truncated + yym41 := z.DecBinary() + _ = yym41 + if false { + } else { + *((*bool)(yyv40)) = r.DecodeBool() + } + } + case "user": + if r.TryDecodeAsNil() { + x.User = User{} + } else { + yyv42 := &x.User + yyv42.CodecDecodeSelf(d) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *Status) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj43 int + var yyb43 bool + var yyhl43 bool = l >= 0 + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Contributors != nil { + x.Contributors = nil + } + } else { + if x.Contributors == nil { + x.Contributors = new(string) + } + yym45 := z.DecBinary() + _ = yym45 + if false { + } else { + *((*string)(x.Contributors)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Coordinates != nil { + x.Coordinates = nil + } + } else { + if x.Coordinates == nil { + x.Coordinates = new(string) + } + yym47 := z.DecBinary() + _ = yym47 + if false { + } else { + *((*string)(x.Coordinates)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.CreatedAt = "" + } else { + yyv48 := &x.CreatedAt + yym49 := z.DecBinary() + _ = yym49 + if false { + } else { + *((*string)(yyv48)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Entities = Entities{} + } else { + yyv50 := &x.Entities + yyv50.CodecDecodeSelf(d) + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Favorited = false + } else { + yyv51 := &x.Favorited + yym52 := z.DecBinary() + _ = yym52 + if false { + } else { + *((*bool)(yyv51)) = r.DecodeBool() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Geo != nil { + x.Geo = nil + } + } else { + if x.Geo == nil { + x.Geo = new(string) + } + yym54 := z.DecBinary() + _ = yym54 + if false { + } else { + *((*string)(x.Geo)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.ID = 0 + } else { + yyv55 := &x.ID + yym56 := z.DecBinary() + _ = yym56 + if false { + } else { + *((*int64)(yyv55)) = int64(r.DecodeInt(64)) + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.IDStr = "" + } else { + yyv57 := &x.IDStr + yym58 := z.DecBinary() + _ = yym58 + if false { + } else { + *((*string)(yyv57)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToScreenName != nil { + x.InReplyToScreenName = nil + } + } else { + if x.InReplyToScreenName == nil { + x.InReplyToScreenName = new(string) + } + yym60 := z.DecBinary() + _ = yym60 + if false { + } else { + *((*string)(x.InReplyToScreenName)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToStatusID != nil { + x.InReplyToStatusID = nil + } + } else { + if x.InReplyToStatusID == nil { + x.InReplyToStatusID = new(string) + } + yym62 := z.DecBinary() + _ = yym62 + if false { + } else { + *((*string)(x.InReplyToStatusID)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToStatusIDStr != nil { + x.InReplyToStatusIDStr = nil + } + } else { + if x.InReplyToStatusIDStr == nil { + x.InReplyToStatusIDStr = new(string) + } + yym64 := z.DecBinary() + _ = yym64 + if false { + } else { + *((*string)(x.InReplyToStatusIDStr)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToUserID != nil { + x.InReplyToUserID = nil + } + } else { + if x.InReplyToUserID == nil { + x.InReplyToUserID = new(string) + } + yym66 := z.DecBinary() + _ = yym66 + if false { + } else { + *((*string)(x.InReplyToUserID)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.InReplyToUserIDStr != nil { + x.InReplyToUserIDStr = nil + } + } else { + if x.InReplyToUserIDStr == nil { + x.InReplyToUserIDStr = new(string) + } + yym68 := z.DecBinary() + _ = yym68 + if false { + } else { + *((*string)(x.InReplyToUserIDStr)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Metadata = StatusMetadata{} + } else { + yyv69 := &x.Metadata + yyv69.CodecDecodeSelf(d) + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + if x.Place != nil { + x.Place = nil + } + } else { + if x.Place == nil { + x.Place = new(string) + } + yym71 := z.DecBinary() + _ = yym71 + if false { + } else { + *((*string)(x.Place)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.RetweetCount = 0 + } else { + yyv72 := &x.RetweetCount + yym73 := z.DecBinary() + _ = yym73 + if false { + } else { + *((*int)(yyv72)) = int(r.DecodeInt(codecSelferBitsize9225)) + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Retweeted = false + } else { + yyv74 := &x.Retweeted + yym75 := z.DecBinary() + _ = yym75 + if false { + } else { + *((*bool)(yyv74)) = r.DecodeBool() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Source = "" + } else { + yyv76 := &x.Source + yym77 := z.DecBinary() + _ = yym77 + if false { + } else { + *((*string)(yyv76)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Text = "" + } else { + yyv78 := &x.Text + yym79 := z.DecBinary() + _ = yym79 + if false { + } else { + *((*string)(yyv78)) = r.DecodeString() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Truncated = false + } else { + yyv80 := &x.Truncated + yym81 := z.DecBinary() + _ = yym81 + if false { + } else { + *((*bool)(yyv80)) = r.DecodeBool() + } + } + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.User = User{} + } else { + yyv82 := &x.User + yyv82.CodecDecodeSelf(d) + } + for { + yyj43++ + if yyhl43 { + yyb43 = yyj43 > l + } else { + yyb43 = r.CheckBreak() + } + if yyb43 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj43-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *LargeStruct) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy4 := &x.SearchMetadata + yy4.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("search_metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + yy6 := &x.SearchMetadata + yy6.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Statuses == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + h.encSliceStatus(([]Status)(x.Statuses), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("statuses")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Statuses == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + h.encSliceStatus(([]Status)(x.Statuses), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *LargeStruct) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *LargeStruct) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "search_metadata": + if r.TryDecodeAsNil() { + x.SearchMetadata = SearchMetadata{} + } else { + yyv4 := &x.SearchMetadata + yyv4.CodecDecodeSelf(d) + } + case "statuses": + if r.TryDecodeAsNil() { + x.Statuses = nil + } else { + yyv5 := &x.Statuses + yym6 := z.DecBinary() + _ = yym6 + if false { + } else { + h.decSliceStatus((*[]Status)(yyv5), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *LargeStruct) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj7 int + var yyb7 bool + var yyhl7 bool = l >= 0 + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.SearchMetadata = SearchMetadata{} + } else { + yyv8 := &x.SearchMetadata + yyv8.CodecDecodeSelf(d) + } + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Statuses = nil + } else { + yyv9 := &x.Statuses + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + h.decSliceStatus((*[]Status)(yyv9), d) + } + } + for { + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj7-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x *XLStruct) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if x.Data == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSliceLargeStruct(([]LargeStruct)(x.Data), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey9225) + r.EncodeString(codecSelferC_UTF89225, string("Data")) + z.EncSendContainerState(codecSelfer_containerMapValue9225) + if x.Data == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSliceLargeStruct(([]LargeStruct)(x.Data), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd9225) + } + } + } +} + +func (x *XLStruct) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap9225 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd9225) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray9225 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr9225) + } + } +} + +func (x *XLStruct) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey9225) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3SlcHdr := codecSelferUnsafeString9225{uintptr(unsafe.Pointer(&yys3Slc[0])), len(yys3Slc)} + yys3 := *(*string)(unsafe.Pointer(&yys3SlcHdr)) + z.DecSendContainerState(codecSelfer_containerMapValue9225) + switch yys3 { + case "Data": + if r.TryDecodeAsNil() { + x.Data = nil + } else { + yyv4 := &x.Data + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSliceLargeStruct((*[]LargeStruct)(yyv4), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd9225) +} + +func (x *XLStruct) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + if r.TryDecodeAsNil() { + x.Data = nil + } else { + yyv7 := &x.Data + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + h.decSliceLargeStruct((*[]LargeStruct)(yyv7), d) + } + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem9225) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) encSliceHashtag(v []Hashtag, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSliceHashtag(v *[]Hashtag, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []Hashtag{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 40) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]Hashtag, yyrl1) + } + } else { + yyv1 = make([]Hashtag, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Hashtag{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, Hashtag{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Hashtag{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, Hashtag{}) // var yyz1 Hashtag + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = Hashtag{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []Hashtag{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer9225) encSlicePtrtostring(v []*string, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + if yyv1 == nil { + r.EncodeNil() + } else { + yy2 := *yyv1 + yym3 := z.EncBinary() + _ = yym3 + if false { + } else { + r.EncodeString(codecSelferC_UTF89225, string(yy2)) + } + } + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSlicePtrtostring(v *[]*string, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []*string{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]*string, yyrl1) + } + } else { + yyv1 = make([]*string, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + if yyv1[yyj1] != nil { + *yyv1[yyj1] = "" + } + } else { + if yyv1[yyj1] == nil { + yyv1[yyj1] = new(string) + } + yyw2 := yyv1[yyj1] + yym3 := z.DecBinary() + _ = yym3 + if false { + } else { + *((*string)(yyw2)) = r.DecodeString() + } + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, nil) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + if yyv1[yyj1] != nil { + *yyv1[yyj1] = "" + } + } else { + if yyv1[yyj1] == nil { + yyv1[yyj1] = new(string) + } + yyw4 := yyv1[yyj1] + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*string)(yyw4)) = r.DecodeString() + } + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, nil) // var yyz1 *string + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + if yyv1[yyj1] != nil { + *yyv1[yyj1] = "" + } + } else { + if yyv1[yyj1] == nil { + yyv1[yyj1] = new(string) + } + yyw6 := yyv1[yyj1] + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*string)(yyw6)) = r.DecodeString() + } + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []*string{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer9225) encSliceURL(v []URL, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSliceURL(v *[]URL, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []URL{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 48) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]URL, yyrl1) + } + } else { + yyv1 = make([]URL, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = URL{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, URL{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = URL{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, URL{}) // var yyz1 URL + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = URL{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []URL{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer9225) encSliceStatus(v []Status, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSliceStatus(v *[]Status, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []Status{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 752) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]Status, yyrl1) + } + } else { + yyv1 = make([]Status, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Status{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, Status{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Status{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, Status{}) // var yyz1 Status + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = Status{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []Status{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer9225) encSliceLargeStruct(v []LargeStruct, e *codec1978.Encoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem9225) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd9225) +} + +func (x codecSelfer9225) decSliceLargeStruct(v *[]LargeStruct, d *codec1978.Decoder) { + var h codecSelfer9225 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []LargeStruct{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 136) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]LargeStruct, yyrl1) + } + } else { + yyv1 = make([]LargeStruct, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = LargeStruct{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, LargeStruct{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = LargeStruct{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, LargeStruct{}) // var yyz1 LargeStruct + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = LargeStruct{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []LargeStruct{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/data_ffjson.go b/vendor/github.com/mailru/easyjson/benchmark/data_ffjson.go new file mode 100644 index 00000000..9f000d3a --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/data_ffjson.go @@ -0,0 +1,6723 @@ +// +build use_ffjson + +// DO NOT EDIT! +// Code generated by ffjson +// source: .root/src/github.com/mailru/easyjson/benchmark/data.go +// DO NOT EDIT! + +package benchmark + +import ( + "bytes" + "errors" + "fmt" + fflib "github.com/pquerna/ffjson/fflib/v1" +) + +func (mj *Entities) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *Entities) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"hashtags":`) + if mj.Hashtags != nil { + buf.WriteString(`[`) + for i, v := range mj.Hashtags { + if i != 0 { + buf.WriteString(`,`) + } + + { + + err = v.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteString(`,"urls":`) + if mj.Urls != nil { + buf.WriteString(`[`) + for i, v := range mj.Urls { + if i != 0 { + buf.WriteString(`,`) + } + if v != nil { + fflib.WriteJsonString(buf, string(*v)) + } else { + buf.WriteString(`null`) + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteString(`,"user_mentions":`) + if mj.UserMentions != nil { + buf.WriteString(`[`) + for i, v := range mj.UserMentions { + if i != 0 { + buf.WriteString(`,`) + } + if v != nil { + fflib.WriteJsonString(buf, string(*v)) + } else { + buf.WriteString(`null`) + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_Entitiesbase = iota + ffj_t_Entitiesno_such_key + + ffj_t_Entities_Hashtags + + ffj_t_Entities_Urls + + ffj_t_Entities_UserMentions +) + +var ffj_key_Entities_Hashtags = []byte("hashtags") + +var ffj_key_Entities_Urls = []byte("urls") + +var ffj_key_Entities_UserMentions = []byte("user_mentions") + +func (uj *Entities) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *Entities) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_Entitiesbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_Entitiesno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'h': + + if bytes.Equal(ffj_key_Entities_Hashtags, kn) { + currentKey = ffj_t_Entities_Hashtags + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_Entities_Urls, kn) { + currentKey = ffj_t_Entities_Urls + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Entities_UserMentions, kn) { + currentKey = ffj_t_Entities_UserMentions + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_Entities_UserMentions, kn) { + currentKey = ffj_t_Entities_UserMentions + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Entities_Urls, kn) { + currentKey = ffj_t_Entities_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Entities_Hashtags, kn) { + currentKey = ffj_t_Entities_Hashtags + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_Entitiesno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_Entities_Hashtags: + goto handle_Hashtags + + case ffj_t_Entities_Urls: + goto handle_Urls + + case ffj_t_Entities_UserMentions: + goto handle_UserMentions + + case ffj_t_Entitiesno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Hashtags: + + /* handler: uj.Hashtags type=[]benchmark.Hashtag kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Hashtags = nil + } else { + + uj.Hashtags = make([]Hashtag, 0) + + wantVal := true + + for { + + var tmp_uj__Hashtags Hashtag + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Hashtags type=benchmark.Hashtag kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = tmp_uj__Hashtags.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + uj.Hashtags = append(uj.Hashtags, tmp_uj__Hashtags) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Urls: + + /* handler: uj.Urls type=[]*string kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Urls = nil + } else { + + uj.Urls = make([]*string, 0) + + wantVal := true + + for { + + var tmp_uj__Urls *string + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Urls type=*string kind=ptr quoted=false*/ + + { + + if tok == fflib.FFTok_null { + tmp_uj__Urls = nil + } else { + if tmp_uj__Urls == nil { + tmp_uj__Urls = new(string) + } + + /* handler: tmp_uj__Urls type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + tmp_uj__Urls = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + tmp_uj__Urls = &tval + + } + } + + } + } + + uj.Urls = append(uj.Urls, tmp_uj__Urls) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_UserMentions: + + /* handler: uj.UserMentions type=[]*string kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.UserMentions = nil + } else { + + uj.UserMentions = make([]*string, 0) + + wantVal := true + + for { + + var tmp_uj__UserMentions *string + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__UserMentions type=*string kind=ptr quoted=false*/ + + { + + if tok == fflib.FFTok_null { + tmp_uj__UserMentions = nil + } else { + if tmp_uj__UserMentions == nil { + tmp_uj__UserMentions = new(string) + } + + /* handler: tmp_uj__UserMentions type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + tmp_uj__UserMentions = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + tmp_uj__UserMentions = &tval + + } + } + + } + } + + uj.UserMentions = append(uj.UserMentions, tmp_uj__UserMentions) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *Hashtag) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *Hashtag) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"indices":`) + if mj.Indices != nil { + buf.WriteString(`[`) + for i, v := range mj.Indices { + if i != 0 { + buf.WriteString(`,`) + } + fflib.FormatBits2(buf, uint64(v), 10, v < 0) + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteString(`,"text":`) + fflib.WriteJsonString(buf, string(mj.Text)) + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_Hashtagbase = iota + ffj_t_Hashtagno_such_key + + ffj_t_Hashtag_Indices + + ffj_t_Hashtag_Text +) + +var ffj_key_Hashtag_Indices = []byte("indices") + +var ffj_key_Hashtag_Text = []byte("text") + +func (uj *Hashtag) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *Hashtag) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_Hashtagbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_Hashtagno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'i': + + if bytes.Equal(ffj_key_Hashtag_Indices, kn) { + currentKey = ffj_t_Hashtag_Indices + state = fflib.FFParse_want_colon + goto mainparse + } + + case 't': + + if bytes.Equal(ffj_key_Hashtag_Text, kn) { + currentKey = ffj_t_Hashtag_Text + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_Hashtag_Text, kn) { + currentKey = ffj_t_Hashtag_Text + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Hashtag_Indices, kn) { + currentKey = ffj_t_Hashtag_Indices + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_Hashtagno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_Hashtag_Indices: + goto handle_Indices + + case ffj_t_Hashtag_Text: + goto handle_Text + + case ffj_t_Hashtagno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Indices: + + /* handler: uj.Indices type=[]int kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Indices = nil + } else { + + uj.Indices = make([]int, 0) + + wantVal := true + + for { + + var tmp_uj__Indices int + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Indices type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + tmp_uj__Indices = int(tval) + + } + } + + uj.Indices = append(uj.Indices, tmp_uj__Indices) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Text: + + /* handler: uj.Text type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Text = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *LargeStruct) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *LargeStruct) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"search_metadata":`) + + { + + err = mj.SearchMetadata.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteString(`,"statuses":`) + if mj.Statuses != nil { + buf.WriteString(`[`) + for i, v := range mj.Statuses { + if i != 0 { + buf.WriteString(`,`) + } + + { + + err = v.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_LargeStructbase = iota + ffj_t_LargeStructno_such_key + + ffj_t_LargeStruct_SearchMetadata + + ffj_t_LargeStruct_Statuses +) + +var ffj_key_LargeStruct_SearchMetadata = []byte("search_metadata") + +var ffj_key_LargeStruct_Statuses = []byte("statuses") + +func (uj *LargeStruct) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *LargeStruct) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_LargeStructbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_LargeStructno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 's': + + if bytes.Equal(ffj_key_LargeStruct_SearchMetadata, kn) { + currentKey = ffj_t_LargeStruct_SearchMetadata + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_LargeStruct_Statuses, kn) { + currentKey = ffj_t_LargeStruct_Statuses + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_LargeStruct_Statuses, kn) { + currentKey = ffj_t_LargeStruct_Statuses + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_LargeStruct_SearchMetadata, kn) { + currentKey = ffj_t_LargeStruct_SearchMetadata + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_LargeStructno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_LargeStruct_SearchMetadata: + goto handle_SearchMetadata + + case ffj_t_LargeStruct_Statuses: + goto handle_Statuses + + case ffj_t_LargeStructno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_SearchMetadata: + + /* handler: uj.SearchMetadata type=benchmark.SearchMetadata kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.SearchMetadata.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Statuses: + + /* handler: uj.Statuses type=[]benchmark.Status kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Statuses = nil + } else { + + uj.Statuses = make([]Status, 0) + + wantVal := true + + for { + + var tmp_uj__Statuses Status + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Statuses type=benchmark.Status kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = tmp_uj__Statuses.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + uj.Statuses = append(uj.Statuses, tmp_uj__Statuses) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *SearchMetadata) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *SearchMetadata) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"completed_in":`) + fflib.AppendFloat(buf, float64(mj.CompletedIn), 'g', -1, 64) + buf.WriteString(`,"count":`) + fflib.FormatBits2(buf, uint64(mj.Count), 10, mj.Count < 0) + buf.WriteString(`,"max_id":`) + fflib.FormatBits2(buf, uint64(mj.MaxID), 10, mj.MaxID < 0) + buf.WriteString(`,"max_id_str":`) + fflib.WriteJsonString(buf, string(mj.MaxIDStr)) + buf.WriteString(`,"next_results":`) + fflib.WriteJsonString(buf, string(mj.NextResults)) + buf.WriteString(`,"query":`) + fflib.WriteJsonString(buf, string(mj.Query)) + buf.WriteString(`,"refresh_url":`) + fflib.WriteJsonString(buf, string(mj.RefreshURL)) + buf.WriteString(`,"since_id":`) + fflib.FormatBits2(buf, uint64(mj.SinceID), 10, mj.SinceID < 0) + buf.WriteString(`,"since_id_str":`) + fflib.WriteJsonString(buf, string(mj.SinceIDStr)) + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_SearchMetadatabase = iota + ffj_t_SearchMetadatano_such_key + + ffj_t_SearchMetadata_CompletedIn + + ffj_t_SearchMetadata_Count + + ffj_t_SearchMetadata_MaxID + + ffj_t_SearchMetadata_MaxIDStr + + ffj_t_SearchMetadata_NextResults + + ffj_t_SearchMetadata_Query + + ffj_t_SearchMetadata_RefreshURL + + ffj_t_SearchMetadata_SinceID + + ffj_t_SearchMetadata_SinceIDStr +) + +var ffj_key_SearchMetadata_CompletedIn = []byte("completed_in") + +var ffj_key_SearchMetadata_Count = []byte("count") + +var ffj_key_SearchMetadata_MaxID = []byte("max_id") + +var ffj_key_SearchMetadata_MaxIDStr = []byte("max_id_str") + +var ffj_key_SearchMetadata_NextResults = []byte("next_results") + +var ffj_key_SearchMetadata_Query = []byte("query") + +var ffj_key_SearchMetadata_RefreshURL = []byte("refresh_url") + +var ffj_key_SearchMetadata_SinceID = []byte("since_id") + +var ffj_key_SearchMetadata_SinceIDStr = []byte("since_id_str") + +func (uj *SearchMetadata) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *SearchMetadata) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_SearchMetadatabase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_SearchMetadatano_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'c': + + if bytes.Equal(ffj_key_SearchMetadata_CompletedIn, kn) { + currentKey = ffj_t_SearchMetadata_CompletedIn + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_SearchMetadata_Count, kn) { + currentKey = ffj_t_SearchMetadata_Count + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'm': + + if bytes.Equal(ffj_key_SearchMetadata_MaxID, kn) { + currentKey = ffj_t_SearchMetadata_MaxID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_SearchMetadata_MaxIDStr, kn) { + currentKey = ffj_t_SearchMetadata_MaxIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'n': + + if bytes.Equal(ffj_key_SearchMetadata_NextResults, kn) { + currentKey = ffj_t_SearchMetadata_NextResults + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'q': + + if bytes.Equal(ffj_key_SearchMetadata_Query, kn) { + currentKey = ffj_t_SearchMetadata_Query + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'r': + + if bytes.Equal(ffj_key_SearchMetadata_RefreshURL, kn) { + currentKey = ffj_t_SearchMetadata_RefreshURL + state = fflib.FFParse_want_colon + goto mainparse + } + + case 's': + + if bytes.Equal(ffj_key_SearchMetadata_SinceID, kn) { + currentKey = ffj_t_SearchMetadata_SinceID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_SearchMetadata_SinceIDStr, kn) { + currentKey = ffj_t_SearchMetadata_SinceIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_SinceIDStr, kn) { + currentKey = ffj_t_SearchMetadata_SinceIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_SinceID, kn) { + currentKey = ffj_t_SearchMetadata_SinceID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_RefreshURL, kn) { + currentKey = ffj_t_SearchMetadata_RefreshURL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_SearchMetadata_Query, kn) { + currentKey = ffj_t_SearchMetadata_Query + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_NextResults, kn) { + currentKey = ffj_t_SearchMetadata_NextResults + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_SearchMetadata_MaxIDStr, kn) { + currentKey = ffj_t_SearchMetadata_MaxIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_SearchMetadata_MaxID, kn) { + currentKey = ffj_t_SearchMetadata_MaxID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_SearchMetadata_Count, kn) { + currentKey = ffj_t_SearchMetadata_Count + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_SearchMetadata_CompletedIn, kn) { + currentKey = ffj_t_SearchMetadata_CompletedIn + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_SearchMetadatano_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_SearchMetadata_CompletedIn: + goto handle_CompletedIn + + case ffj_t_SearchMetadata_Count: + goto handle_Count + + case ffj_t_SearchMetadata_MaxID: + goto handle_MaxID + + case ffj_t_SearchMetadata_MaxIDStr: + goto handle_MaxIDStr + + case ffj_t_SearchMetadata_NextResults: + goto handle_NextResults + + case ffj_t_SearchMetadata_Query: + goto handle_Query + + case ffj_t_SearchMetadata_RefreshURL: + goto handle_RefreshURL + + case ffj_t_SearchMetadata_SinceID: + goto handle_SinceID + + case ffj_t_SearchMetadata_SinceIDStr: + goto handle_SinceIDStr + + case ffj_t_SearchMetadatano_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_CompletedIn: + + /* handler: uj.CompletedIn type=float64 kind=float64 quoted=false*/ + + { + if tok != fflib.FFTok_double && tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for float64", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseFloat(fs.Output.Bytes(), 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.CompletedIn = float64(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Count: + + /* handler: uj.Count type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.Count = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_MaxID: + + /* handler: uj.MaxID type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.MaxID = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_MaxIDStr: + + /* handler: uj.MaxIDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.MaxIDStr = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_NextResults: + + /* handler: uj.NextResults type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.NextResults = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Query: + + /* handler: uj.Query type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Query = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_RefreshURL: + + /* handler: uj.RefreshURL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.RefreshURL = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_SinceID: + + /* handler: uj.SinceID type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.SinceID = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_SinceIDStr: + + /* handler: uj.SinceIDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.SinceIDStr = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *Status) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *Status) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + if mj.Contributors != nil { + buf.WriteString(`{"contributors":`) + fflib.WriteJsonString(buf, string(*mj.Contributors)) + } else { + buf.WriteString(`{"contributors":null`) + } + if mj.Coordinates != nil { + buf.WriteString(`,"coordinates":`) + fflib.WriteJsonString(buf, string(*mj.Coordinates)) + } else { + buf.WriteString(`,"coordinates":null`) + } + buf.WriteString(`,"created_at":`) + fflib.WriteJsonString(buf, string(mj.CreatedAt)) + buf.WriteString(`,"entities":`) + + { + + err = mj.Entities.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + if mj.Favorited { + buf.WriteString(`,"favorited":true`) + } else { + buf.WriteString(`,"favorited":false`) + } + if mj.Geo != nil { + buf.WriteString(`,"geo":`) + fflib.WriteJsonString(buf, string(*mj.Geo)) + } else { + buf.WriteString(`,"geo":null`) + } + buf.WriteString(`,"id":`) + fflib.FormatBits2(buf, uint64(mj.ID), 10, mj.ID < 0) + buf.WriteString(`,"id_str":`) + fflib.WriteJsonString(buf, string(mj.IDStr)) + if mj.InReplyToScreenName != nil { + buf.WriteString(`,"in_reply_to_screen_name":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToScreenName)) + } else { + buf.WriteString(`,"in_reply_to_screen_name":null`) + } + if mj.InReplyToStatusID != nil { + buf.WriteString(`,"in_reply_to_status_id":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToStatusID)) + } else { + buf.WriteString(`,"in_reply_to_status_id":null`) + } + if mj.InReplyToStatusIDStr != nil { + buf.WriteString(`,"in_reply_to_status_id_str":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToStatusIDStr)) + } else { + buf.WriteString(`,"in_reply_to_status_id_str":null`) + } + if mj.InReplyToUserID != nil { + buf.WriteString(`,"in_reply_to_user_id":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToUserID)) + } else { + buf.WriteString(`,"in_reply_to_user_id":null`) + } + if mj.InReplyToUserIDStr != nil { + buf.WriteString(`,"in_reply_to_user_id_str":`) + fflib.WriteJsonString(buf, string(*mj.InReplyToUserIDStr)) + } else { + buf.WriteString(`,"in_reply_to_user_id_str":null`) + } + buf.WriteString(`,"metadata":`) + + { + + err = mj.Metadata.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + if mj.Place != nil { + buf.WriteString(`,"place":`) + fflib.WriteJsonString(buf, string(*mj.Place)) + } else { + buf.WriteString(`,"place":null`) + } + buf.WriteString(`,"retweet_count":`) + fflib.FormatBits2(buf, uint64(mj.RetweetCount), 10, mj.RetweetCount < 0) + if mj.Retweeted { + buf.WriteString(`,"retweeted":true`) + } else { + buf.WriteString(`,"retweeted":false`) + } + buf.WriteString(`,"source":`) + fflib.WriteJsonString(buf, string(mj.Source)) + buf.WriteString(`,"text":`) + fflib.WriteJsonString(buf, string(mj.Text)) + if mj.Truncated { + buf.WriteString(`,"truncated":true`) + } else { + buf.WriteString(`,"truncated":false`) + } + buf.WriteString(`,"user":`) + + { + + err = mj.User.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_Statusbase = iota + ffj_t_Statusno_such_key + + ffj_t_Status_Contributors + + ffj_t_Status_Coordinates + + ffj_t_Status_CreatedAt + + ffj_t_Status_Entities + + ffj_t_Status_Favorited + + ffj_t_Status_Geo + + ffj_t_Status_ID + + ffj_t_Status_IDStr + + ffj_t_Status_InReplyToScreenName + + ffj_t_Status_InReplyToStatusID + + ffj_t_Status_InReplyToStatusIDStr + + ffj_t_Status_InReplyToUserID + + ffj_t_Status_InReplyToUserIDStr + + ffj_t_Status_Metadata + + ffj_t_Status_Place + + ffj_t_Status_RetweetCount + + ffj_t_Status_Retweeted + + ffj_t_Status_Source + + ffj_t_Status_Text + + ffj_t_Status_Truncated + + ffj_t_Status_User +) + +var ffj_key_Status_Contributors = []byte("contributors") + +var ffj_key_Status_Coordinates = []byte("coordinates") + +var ffj_key_Status_CreatedAt = []byte("created_at") + +var ffj_key_Status_Entities = []byte("entities") + +var ffj_key_Status_Favorited = []byte("favorited") + +var ffj_key_Status_Geo = []byte("geo") + +var ffj_key_Status_ID = []byte("id") + +var ffj_key_Status_IDStr = []byte("id_str") + +var ffj_key_Status_InReplyToScreenName = []byte("in_reply_to_screen_name") + +var ffj_key_Status_InReplyToStatusID = []byte("in_reply_to_status_id") + +var ffj_key_Status_InReplyToStatusIDStr = []byte("in_reply_to_status_id_str") + +var ffj_key_Status_InReplyToUserID = []byte("in_reply_to_user_id") + +var ffj_key_Status_InReplyToUserIDStr = []byte("in_reply_to_user_id_str") + +var ffj_key_Status_Metadata = []byte("metadata") + +var ffj_key_Status_Place = []byte("place") + +var ffj_key_Status_RetweetCount = []byte("retweet_count") + +var ffj_key_Status_Retweeted = []byte("retweeted") + +var ffj_key_Status_Source = []byte("source") + +var ffj_key_Status_Text = []byte("text") + +var ffj_key_Status_Truncated = []byte("truncated") + +var ffj_key_Status_User = []byte("user") + +func (uj *Status) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *Status) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_Statusbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_Statusno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'c': + + if bytes.Equal(ffj_key_Status_Contributors, kn) { + currentKey = ffj_t_Status_Contributors + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_Coordinates, kn) { + currentKey = ffj_t_Status_Coordinates + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_CreatedAt, kn) { + currentKey = ffj_t_Status_CreatedAt + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'e': + + if bytes.Equal(ffj_key_Status_Entities, kn) { + currentKey = ffj_t_Status_Entities + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'f': + + if bytes.Equal(ffj_key_Status_Favorited, kn) { + currentKey = ffj_t_Status_Favorited + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'g': + + if bytes.Equal(ffj_key_Status_Geo, kn) { + currentKey = ffj_t_Status_Geo + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'i': + + if bytes.Equal(ffj_key_Status_ID, kn) { + currentKey = ffj_t_Status_ID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_IDStr, kn) { + currentKey = ffj_t_Status_IDStr + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToScreenName, kn) { + currentKey = ffj_t_Status_InReplyToScreenName + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToStatusID, kn) { + currentKey = ffj_t_Status_InReplyToStatusID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToStatusIDStr, kn) { + currentKey = ffj_t_Status_InReplyToStatusIDStr + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToUserID, kn) { + currentKey = ffj_t_Status_InReplyToUserID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_InReplyToUserIDStr, kn) { + currentKey = ffj_t_Status_InReplyToUserIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'm': + + if bytes.Equal(ffj_key_Status_Metadata, kn) { + currentKey = ffj_t_Status_Metadata + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'p': + + if bytes.Equal(ffj_key_Status_Place, kn) { + currentKey = ffj_t_Status_Place + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'r': + + if bytes.Equal(ffj_key_Status_RetweetCount, kn) { + currentKey = ffj_t_Status_RetweetCount + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_Retweeted, kn) { + currentKey = ffj_t_Status_Retweeted + state = fflib.FFParse_want_colon + goto mainparse + } + + case 's': + + if bytes.Equal(ffj_key_Status_Source, kn) { + currentKey = ffj_t_Status_Source + state = fflib.FFParse_want_colon + goto mainparse + } + + case 't': + + if bytes.Equal(ffj_key_Status_Text, kn) { + currentKey = ffj_t_Status_Text + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_Status_Truncated, kn) { + currentKey = ffj_t_Status_Truncated + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_Status_User, kn) { + currentKey = ffj_t_Status_User + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_Status_User, kn) { + currentKey = ffj_t_Status_User + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Truncated, kn) { + currentKey = ffj_t_Status_Truncated + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Text, kn) { + currentKey = ffj_t_Status_Text + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_Source, kn) { + currentKey = ffj_t_Status_Source + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Retweeted, kn) { + currentKey = ffj_t_Status_Retweeted + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_Status_RetweetCount, kn) { + currentKey = ffj_t_Status_RetweetCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Place, kn) { + currentKey = ffj_t_Status_Place + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Metadata, kn) { + currentKey = ffj_t_Status_Metadata + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToUserIDStr, kn) { + currentKey = ffj_t_Status_InReplyToUserIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToUserID, kn) { + currentKey = ffj_t_Status_InReplyToUserID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToStatusIDStr, kn) { + currentKey = ffj_t_Status_InReplyToStatusIDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToStatusID, kn) { + currentKey = ffj_t_Status_InReplyToStatusID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_InReplyToScreenName, kn) { + currentKey = ffj_t_Status_InReplyToScreenName + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_IDStr, kn) { + currentKey = ffj_t_Status_IDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_ID, kn) { + currentKey = ffj_t_Status_ID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Geo, kn) { + currentKey = ffj_t_Status_Geo + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_Status_Favorited, kn) { + currentKey = ffj_t_Status_Favorited + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_Entities, kn) { + currentKey = ffj_t_Status_Entities + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_Status_CreatedAt, kn) { + currentKey = ffj_t_Status_CreatedAt + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_Coordinates, kn) { + currentKey = ffj_t_Status_Coordinates + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_Status_Contributors, kn) { + currentKey = ffj_t_Status_Contributors + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_Statusno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_Status_Contributors: + goto handle_Contributors + + case ffj_t_Status_Coordinates: + goto handle_Coordinates + + case ffj_t_Status_CreatedAt: + goto handle_CreatedAt + + case ffj_t_Status_Entities: + goto handle_Entities + + case ffj_t_Status_Favorited: + goto handle_Favorited + + case ffj_t_Status_Geo: + goto handle_Geo + + case ffj_t_Status_ID: + goto handle_ID + + case ffj_t_Status_IDStr: + goto handle_IDStr + + case ffj_t_Status_InReplyToScreenName: + goto handle_InReplyToScreenName + + case ffj_t_Status_InReplyToStatusID: + goto handle_InReplyToStatusID + + case ffj_t_Status_InReplyToStatusIDStr: + goto handle_InReplyToStatusIDStr + + case ffj_t_Status_InReplyToUserID: + goto handle_InReplyToUserID + + case ffj_t_Status_InReplyToUserIDStr: + goto handle_InReplyToUserIDStr + + case ffj_t_Status_Metadata: + goto handle_Metadata + + case ffj_t_Status_Place: + goto handle_Place + + case ffj_t_Status_RetweetCount: + goto handle_RetweetCount + + case ffj_t_Status_Retweeted: + goto handle_Retweeted + + case ffj_t_Status_Source: + goto handle_Source + + case ffj_t_Status_Text: + goto handle_Text + + case ffj_t_Status_Truncated: + goto handle_Truncated + + case ffj_t_Status_User: + goto handle_User + + case ffj_t_Statusno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Contributors: + + /* handler: uj.Contributors type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Contributors = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Contributors = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Coordinates: + + /* handler: uj.Coordinates type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Coordinates = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Coordinates = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_CreatedAt: + + /* handler: uj.CreatedAt type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.CreatedAt = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Entities: + + /* handler: uj.Entities type=benchmark.Entities kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.Entities.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Favorited: + + /* handler: uj.Favorited type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Favorited = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Favorited = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Geo: + + /* handler: uj.Geo type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Geo = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Geo = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ID: + + /* handler: uj.ID type=int64 kind=int64 quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int64", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.ID = int64(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_IDStr: + + /* handler: uj.IDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.IDStr = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToScreenName: + + /* handler: uj.InReplyToScreenName type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToScreenName = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToScreenName = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToStatusID: + + /* handler: uj.InReplyToStatusID type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToStatusID = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToStatusID = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToStatusIDStr: + + /* handler: uj.InReplyToStatusIDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToStatusIDStr = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToStatusIDStr = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToUserID: + + /* handler: uj.InReplyToUserID type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToUserID = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToUserID = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_InReplyToUserIDStr: + + /* handler: uj.InReplyToUserIDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.InReplyToUserIDStr = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.InReplyToUserIDStr = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Metadata: + + /* handler: uj.Metadata type=benchmark.StatusMetadata kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.Metadata.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Place: + + /* handler: uj.Place type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Place = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Place = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_RetweetCount: + + /* handler: uj.RetweetCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.RetweetCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Retweeted: + + /* handler: uj.Retweeted type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Retweeted = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Retweeted = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Source: + + /* handler: uj.Source type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Source = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Text: + + /* handler: uj.Text type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Text = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Truncated: + + /* handler: uj.Truncated type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Truncated = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Truncated = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_User: + + /* handler: uj.User type=benchmark.User kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.User.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *StatusMetadata) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *StatusMetadata) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"iso_language_code":`) + fflib.WriteJsonString(buf, string(mj.IsoLanguageCode)) + buf.WriteString(`,"result_type":`) + fflib.WriteJsonString(buf, string(mj.ResultType)) + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_StatusMetadatabase = iota + ffj_t_StatusMetadatano_such_key + + ffj_t_StatusMetadata_IsoLanguageCode + + ffj_t_StatusMetadata_ResultType +) + +var ffj_key_StatusMetadata_IsoLanguageCode = []byte("iso_language_code") + +var ffj_key_StatusMetadata_ResultType = []byte("result_type") + +func (uj *StatusMetadata) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *StatusMetadata) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_StatusMetadatabase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_StatusMetadatano_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'i': + + if bytes.Equal(ffj_key_StatusMetadata_IsoLanguageCode, kn) { + currentKey = ffj_t_StatusMetadata_IsoLanguageCode + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'r': + + if bytes.Equal(ffj_key_StatusMetadata_ResultType, kn) { + currentKey = ffj_t_StatusMetadata_ResultType + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_StatusMetadata_ResultType, kn) { + currentKey = ffj_t_StatusMetadata_ResultType + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_StatusMetadata_IsoLanguageCode, kn) { + currentKey = ffj_t_StatusMetadata_IsoLanguageCode + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_StatusMetadatano_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_StatusMetadata_IsoLanguageCode: + goto handle_IsoLanguageCode + + case ffj_t_StatusMetadata_ResultType: + goto handle_ResultType + + case ffj_t_StatusMetadatano_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_IsoLanguageCode: + + /* handler: uj.IsoLanguageCode type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.IsoLanguageCode = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ResultType: + + /* handler: uj.ResultType type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ResultType = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *URL) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *URL) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + if mj.ExpandedURL != nil { + buf.WriteString(`{"expanded_url":`) + fflib.WriteJsonString(buf, string(*mj.ExpandedURL)) + } else { + buf.WriteString(`{"expanded_url":null`) + } + buf.WriteString(`,"indices":`) + if mj.Indices != nil { + buf.WriteString(`[`) + for i, v := range mj.Indices { + if i != 0 { + buf.WriteString(`,`) + } + fflib.FormatBits2(buf, uint64(v), 10, v < 0) + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteString(`,"url":`) + fflib.WriteJsonString(buf, string(mj.URL)) + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_URLbase = iota + ffj_t_URLno_such_key + + ffj_t_URL_ExpandedURL + + ffj_t_URL_Indices + + ffj_t_URL_URL +) + +var ffj_key_URL_ExpandedURL = []byte("expanded_url") + +var ffj_key_URL_Indices = []byte("indices") + +var ffj_key_URL_URL = []byte("url") + +func (uj *URL) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *URL) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_URLbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_URLno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'e': + + if bytes.Equal(ffj_key_URL_ExpandedURL, kn) { + currentKey = ffj_t_URL_ExpandedURL + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'i': + + if bytes.Equal(ffj_key_URL_Indices, kn) { + currentKey = ffj_t_URL_Indices + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_URL_URL, kn) { + currentKey = ffj_t_URL_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_URL_URL, kn) { + currentKey = ffj_t_URL_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_URL_Indices, kn) { + currentKey = ffj_t_URL_Indices + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_URL_ExpandedURL, kn) { + currentKey = ffj_t_URL_ExpandedURL + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_URLno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_URL_ExpandedURL: + goto handle_ExpandedURL + + case ffj_t_URL_Indices: + goto handle_Indices + + case ffj_t_URL_URL: + goto handle_URL + + case ffj_t_URLno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_ExpandedURL: + + /* handler: uj.ExpandedURL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.ExpandedURL = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.ExpandedURL = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Indices: + + /* handler: uj.Indices type=[]int kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Indices = nil + } else { + + uj.Indices = make([]int, 0) + + wantVal := true + + for { + + var tmp_uj__Indices int + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Indices type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + tmp_uj__Indices = int(tval) + + } + } + + uj.Indices = append(uj.Indices, tmp_uj__Indices) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_URL: + + /* handler: uj.URL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.URL = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *User) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *User) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + if mj.ContributorsEnabled { + buf.WriteString(`{"contributors_enabled":true`) + } else { + buf.WriteString(`{"contributors_enabled":false`) + } + buf.WriteString(`,"created_at":`) + fflib.WriteJsonString(buf, string(mj.CreatedAt)) + if mj.DefaultProfile { + buf.WriteString(`,"default_profile":true`) + } else { + buf.WriteString(`,"default_profile":false`) + } + if mj.DefaultProfileImage { + buf.WriteString(`,"default_profile_image":true`) + } else { + buf.WriteString(`,"default_profile_image":false`) + } + buf.WriteString(`,"description":`) + fflib.WriteJsonString(buf, string(mj.Description)) + buf.WriteString(`,"entities":`) + + { + + err = mj.Entities.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteString(`,"favourites_count":`) + fflib.FormatBits2(buf, uint64(mj.FavouritesCount), 10, mj.FavouritesCount < 0) + if mj.FollowRequestSent != nil { + buf.WriteString(`,"follow_request_sent":`) + fflib.WriteJsonString(buf, string(*mj.FollowRequestSent)) + } else { + buf.WriteString(`,"follow_request_sent":null`) + } + buf.WriteString(`,"followers_count":`) + fflib.FormatBits2(buf, uint64(mj.FollowersCount), 10, mj.FollowersCount < 0) + if mj.Following != nil { + buf.WriteString(`,"following":`) + fflib.WriteJsonString(buf, string(*mj.Following)) + } else { + buf.WriteString(`,"following":null`) + } + buf.WriteString(`,"friends_count":`) + fflib.FormatBits2(buf, uint64(mj.FriendsCount), 10, mj.FriendsCount < 0) + if mj.GeoEnabled { + buf.WriteString(`,"geo_enabled":true`) + } else { + buf.WriteString(`,"geo_enabled":false`) + } + buf.WriteString(`,"id":`) + fflib.FormatBits2(buf, uint64(mj.ID), 10, mj.ID < 0) + buf.WriteString(`,"id_str":`) + fflib.WriteJsonString(buf, string(mj.IDStr)) + if mj.IsTranslator { + buf.WriteString(`,"is_translator":true`) + } else { + buf.WriteString(`,"is_translator":false`) + } + buf.WriteString(`,"lang":`) + fflib.WriteJsonString(buf, string(mj.Lang)) + buf.WriteString(`,"listed_count":`) + fflib.FormatBits2(buf, uint64(mj.ListedCount), 10, mj.ListedCount < 0) + buf.WriteString(`,"location":`) + fflib.WriteJsonString(buf, string(mj.Location)) + buf.WriteString(`,"name":`) + fflib.WriteJsonString(buf, string(mj.Name)) + if mj.Notifications != nil { + buf.WriteString(`,"notifications":`) + fflib.WriteJsonString(buf, string(*mj.Notifications)) + } else { + buf.WriteString(`,"notifications":null`) + } + buf.WriteString(`,"profile_background_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileBackgroundColor)) + buf.WriteString(`,"profile_background_image_url":`) + fflib.WriteJsonString(buf, string(mj.ProfileBackgroundImageURL)) + buf.WriteString(`,"profile_background_image_url_https":`) + fflib.WriteJsonString(buf, string(mj.ProfileBackgroundImageURLHTTPS)) + if mj.ProfileBackgroundTile { + buf.WriteString(`,"profile_background_tile":true`) + } else { + buf.WriteString(`,"profile_background_tile":false`) + } + buf.WriteString(`,"profile_image_url":`) + fflib.WriteJsonString(buf, string(mj.ProfileImageURL)) + buf.WriteString(`,"profile_image_url_https":`) + fflib.WriteJsonString(buf, string(mj.ProfileImageURLHTTPS)) + buf.WriteString(`,"profile_link_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileLinkColor)) + buf.WriteString(`,"profile_sidebar_border_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileSidebarBorderColor)) + buf.WriteString(`,"profile_sidebar_fill_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileSidebarFillColor)) + buf.WriteString(`,"profile_text_color":`) + fflib.WriteJsonString(buf, string(mj.ProfileTextColor)) + if mj.ProfileUseBackgroundImage { + buf.WriteString(`,"profile_use_background_image":true`) + } else { + buf.WriteString(`,"profile_use_background_image":false`) + } + if mj.Protected { + buf.WriteString(`,"protected":true`) + } else { + buf.WriteString(`,"protected":false`) + } + buf.WriteString(`,"screen_name":`) + fflib.WriteJsonString(buf, string(mj.ScreenName)) + if mj.ShowAllInlineMedia { + buf.WriteString(`,"show_all_inline_media":true`) + } else { + buf.WriteString(`,"show_all_inline_media":false`) + } + buf.WriteString(`,"statuses_count":`) + fflib.FormatBits2(buf, uint64(mj.StatusesCount), 10, mj.StatusesCount < 0) + buf.WriteString(`,"time_zone":`) + fflib.WriteJsonString(buf, string(mj.TimeZone)) + if mj.URL != nil { + buf.WriteString(`,"url":`) + fflib.WriteJsonString(buf, string(*mj.URL)) + } else { + buf.WriteString(`,"url":null`) + } + buf.WriteString(`,"utc_offset":`) + fflib.FormatBits2(buf, uint64(mj.UtcOffset), 10, mj.UtcOffset < 0) + if mj.Verified { + buf.WriteString(`,"verified":true`) + } else { + buf.WriteString(`,"verified":false`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_Userbase = iota + ffj_t_Userno_such_key + + ffj_t_User_ContributorsEnabled + + ffj_t_User_CreatedAt + + ffj_t_User_DefaultProfile + + ffj_t_User_DefaultProfileImage + + ffj_t_User_Description + + ffj_t_User_Entities + + ffj_t_User_FavouritesCount + + ffj_t_User_FollowRequestSent + + ffj_t_User_FollowersCount + + ffj_t_User_Following + + ffj_t_User_FriendsCount + + ffj_t_User_GeoEnabled + + ffj_t_User_ID + + ffj_t_User_IDStr + + ffj_t_User_IsTranslator + + ffj_t_User_Lang + + ffj_t_User_ListedCount + + ffj_t_User_Location + + ffj_t_User_Name + + ffj_t_User_Notifications + + ffj_t_User_ProfileBackgroundColor + + ffj_t_User_ProfileBackgroundImageURL + + ffj_t_User_ProfileBackgroundImageURLHTTPS + + ffj_t_User_ProfileBackgroundTile + + ffj_t_User_ProfileImageURL + + ffj_t_User_ProfileImageURLHTTPS + + ffj_t_User_ProfileLinkColor + + ffj_t_User_ProfileSidebarBorderColor + + ffj_t_User_ProfileSidebarFillColor + + ffj_t_User_ProfileTextColor + + ffj_t_User_ProfileUseBackgroundImage + + ffj_t_User_Protected + + ffj_t_User_ScreenName + + ffj_t_User_ShowAllInlineMedia + + ffj_t_User_StatusesCount + + ffj_t_User_TimeZone + + ffj_t_User_URL + + ffj_t_User_UtcOffset + + ffj_t_User_Verified +) + +var ffj_key_User_ContributorsEnabled = []byte("contributors_enabled") + +var ffj_key_User_CreatedAt = []byte("created_at") + +var ffj_key_User_DefaultProfile = []byte("default_profile") + +var ffj_key_User_DefaultProfileImage = []byte("default_profile_image") + +var ffj_key_User_Description = []byte("description") + +var ffj_key_User_Entities = []byte("entities") + +var ffj_key_User_FavouritesCount = []byte("favourites_count") + +var ffj_key_User_FollowRequestSent = []byte("follow_request_sent") + +var ffj_key_User_FollowersCount = []byte("followers_count") + +var ffj_key_User_Following = []byte("following") + +var ffj_key_User_FriendsCount = []byte("friends_count") + +var ffj_key_User_GeoEnabled = []byte("geo_enabled") + +var ffj_key_User_ID = []byte("id") + +var ffj_key_User_IDStr = []byte("id_str") + +var ffj_key_User_IsTranslator = []byte("is_translator") + +var ffj_key_User_Lang = []byte("lang") + +var ffj_key_User_ListedCount = []byte("listed_count") + +var ffj_key_User_Location = []byte("location") + +var ffj_key_User_Name = []byte("name") + +var ffj_key_User_Notifications = []byte("notifications") + +var ffj_key_User_ProfileBackgroundColor = []byte("profile_background_color") + +var ffj_key_User_ProfileBackgroundImageURL = []byte("profile_background_image_url") + +var ffj_key_User_ProfileBackgroundImageURLHTTPS = []byte("profile_background_image_url_https") + +var ffj_key_User_ProfileBackgroundTile = []byte("profile_background_tile") + +var ffj_key_User_ProfileImageURL = []byte("profile_image_url") + +var ffj_key_User_ProfileImageURLHTTPS = []byte("profile_image_url_https") + +var ffj_key_User_ProfileLinkColor = []byte("profile_link_color") + +var ffj_key_User_ProfileSidebarBorderColor = []byte("profile_sidebar_border_color") + +var ffj_key_User_ProfileSidebarFillColor = []byte("profile_sidebar_fill_color") + +var ffj_key_User_ProfileTextColor = []byte("profile_text_color") + +var ffj_key_User_ProfileUseBackgroundImage = []byte("profile_use_background_image") + +var ffj_key_User_Protected = []byte("protected") + +var ffj_key_User_ScreenName = []byte("screen_name") + +var ffj_key_User_ShowAllInlineMedia = []byte("show_all_inline_media") + +var ffj_key_User_StatusesCount = []byte("statuses_count") + +var ffj_key_User_TimeZone = []byte("time_zone") + +var ffj_key_User_URL = []byte("url") + +var ffj_key_User_UtcOffset = []byte("utc_offset") + +var ffj_key_User_Verified = []byte("verified") + +func (uj *User) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *User) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_Userbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_Userno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'c': + + if bytes.Equal(ffj_key_User_ContributorsEnabled, kn) { + currentKey = ffj_t_User_ContributorsEnabled + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_CreatedAt, kn) { + currentKey = ffj_t_User_CreatedAt + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'd': + + if bytes.Equal(ffj_key_User_DefaultProfile, kn) { + currentKey = ffj_t_User_DefaultProfile + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_DefaultProfileImage, kn) { + currentKey = ffj_t_User_DefaultProfileImage + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Description, kn) { + currentKey = ffj_t_User_Description + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'e': + + if bytes.Equal(ffj_key_User_Entities, kn) { + currentKey = ffj_t_User_Entities + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'f': + + if bytes.Equal(ffj_key_User_FavouritesCount, kn) { + currentKey = ffj_t_User_FavouritesCount + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_FollowRequestSent, kn) { + currentKey = ffj_t_User_FollowRequestSent + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_FollowersCount, kn) { + currentKey = ffj_t_User_FollowersCount + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Following, kn) { + currentKey = ffj_t_User_Following + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_FriendsCount, kn) { + currentKey = ffj_t_User_FriendsCount + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'g': + + if bytes.Equal(ffj_key_User_GeoEnabled, kn) { + currentKey = ffj_t_User_GeoEnabled + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'i': + + if bytes.Equal(ffj_key_User_ID, kn) { + currentKey = ffj_t_User_ID + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_IDStr, kn) { + currentKey = ffj_t_User_IDStr + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_IsTranslator, kn) { + currentKey = ffj_t_User_IsTranslator + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'l': + + if bytes.Equal(ffj_key_User_Lang, kn) { + currentKey = ffj_t_User_Lang + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ListedCount, kn) { + currentKey = ffj_t_User_ListedCount + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Location, kn) { + currentKey = ffj_t_User_Location + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'n': + + if bytes.Equal(ffj_key_User_Name, kn) { + currentKey = ffj_t_User_Name + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Notifications, kn) { + currentKey = ffj_t_User_Notifications + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'p': + + if bytes.Equal(ffj_key_User_ProfileBackgroundColor, kn) { + currentKey = ffj_t_User_ProfileBackgroundColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileBackgroundImageURL, kn) { + currentKey = ffj_t_User_ProfileBackgroundImageURL + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileBackgroundImageURLHTTPS, kn) { + currentKey = ffj_t_User_ProfileBackgroundImageURLHTTPS + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileBackgroundTile, kn) { + currentKey = ffj_t_User_ProfileBackgroundTile + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileImageURL, kn) { + currentKey = ffj_t_User_ProfileImageURL + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileImageURLHTTPS, kn) { + currentKey = ffj_t_User_ProfileImageURLHTTPS + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileLinkColor, kn) { + currentKey = ffj_t_User_ProfileLinkColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileSidebarBorderColor, kn) { + currentKey = ffj_t_User_ProfileSidebarBorderColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileSidebarFillColor, kn) { + currentKey = ffj_t_User_ProfileSidebarFillColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileTextColor, kn) { + currentKey = ffj_t_User_ProfileTextColor + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ProfileUseBackgroundImage, kn) { + currentKey = ffj_t_User_ProfileUseBackgroundImage + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_Protected, kn) { + currentKey = ffj_t_User_Protected + state = fflib.FFParse_want_colon + goto mainparse + } + + case 's': + + if bytes.Equal(ffj_key_User_ScreenName, kn) { + currentKey = ffj_t_User_ScreenName + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_ShowAllInlineMedia, kn) { + currentKey = ffj_t_User_ShowAllInlineMedia + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_StatusesCount, kn) { + currentKey = ffj_t_User_StatusesCount + state = fflib.FFParse_want_colon + goto mainparse + } + + case 't': + + if bytes.Equal(ffj_key_User_TimeZone, kn) { + currentKey = ffj_t_User_TimeZone + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_User_URL, kn) { + currentKey = ffj_t_User_URL + state = fflib.FFParse_want_colon + goto mainparse + + } else if bytes.Equal(ffj_key_User_UtcOffset, kn) { + currentKey = ffj_t_User_UtcOffset + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'v': + + if bytes.Equal(ffj_key_User_Verified, kn) { + currentKey = ffj_t_User_Verified + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Verified, kn) { + currentKey = ffj_t_User_Verified + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_UtcOffset, kn) { + currentKey = ffj_t_User_UtcOffset + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_URL, kn) { + currentKey = ffj_t_User_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_TimeZone, kn) { + currentKey = ffj_t_User_TimeZone + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_StatusesCount, kn) { + currentKey = ffj_t_User_StatusesCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ShowAllInlineMedia, kn) { + currentKey = ffj_t_User_ShowAllInlineMedia + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ScreenName, kn) { + currentKey = ffj_t_User_ScreenName + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Protected, kn) { + currentKey = ffj_t_User_Protected + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileUseBackgroundImage, kn) { + currentKey = ffj_t_User_ProfileUseBackgroundImage + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_ProfileTextColor, kn) { + currentKey = ffj_t_User_ProfileTextColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileSidebarFillColor, kn) { + currentKey = ffj_t_User_ProfileSidebarFillColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileSidebarBorderColor, kn) { + currentKey = ffj_t_User_ProfileSidebarBorderColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileLinkColor, kn) { + currentKey = ffj_t_User_ProfileLinkColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileImageURLHTTPS, kn) { + currentKey = ffj_t_User_ProfileImageURLHTTPS + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_ProfileImageURL, kn) { + currentKey = ffj_t_User_ProfileImageURL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileBackgroundTile, kn) { + currentKey = ffj_t_User_ProfileBackgroundTile + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileBackgroundImageURLHTTPS, kn) { + currentKey = ffj_t_User_ProfileBackgroundImageURLHTTPS + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileBackgroundImageURL, kn) { + currentKey = ffj_t_User_ProfileBackgroundImageURL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ProfileBackgroundColor, kn) { + currentKey = ffj_t_User_ProfileBackgroundColor + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_Notifications, kn) { + currentKey = ffj_t_User_Notifications + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Name, kn) { + currentKey = ffj_t_User_Name + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Location, kn) { + currentKey = ffj_t_User_Location + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ListedCount, kn) { + currentKey = ffj_t_User_ListedCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Lang, kn) { + currentKey = ffj_t_User_Lang + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_IsTranslator, kn) { + currentKey = ffj_t_User_IsTranslator + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_IDStr, kn) { + currentKey = ffj_t_User_IDStr + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_ID, kn) { + currentKey = ffj_t_User_ID + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_GeoEnabled, kn) { + currentKey = ffj_t_User_GeoEnabled + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_FriendsCount, kn) { + currentKey = ffj_t_User_FriendsCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.SimpleLetterEqualFold(ffj_key_User_Following, kn) { + currentKey = ffj_t_User_Following + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_FollowersCount, kn) { + currentKey = ffj_t_User_FollowersCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_FollowRequestSent, kn) { + currentKey = ffj_t_User_FollowRequestSent + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_FavouritesCount, kn) { + currentKey = ffj_t_User_FavouritesCount + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_Entities, kn) { + currentKey = ffj_t_User_Entities + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_Description, kn) { + currentKey = ffj_t_User_Description + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_DefaultProfileImage, kn) { + currentKey = ffj_t_User_DefaultProfileImage + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_DefaultProfile, kn) { + currentKey = ffj_t_User_DefaultProfile + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.AsciiEqualFold(ffj_key_User_CreatedAt, kn) { + currentKey = ffj_t_User_CreatedAt + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_User_ContributorsEnabled, kn) { + currentKey = ffj_t_User_ContributorsEnabled + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_Userno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_User_ContributorsEnabled: + goto handle_ContributorsEnabled + + case ffj_t_User_CreatedAt: + goto handle_CreatedAt + + case ffj_t_User_DefaultProfile: + goto handle_DefaultProfile + + case ffj_t_User_DefaultProfileImage: + goto handle_DefaultProfileImage + + case ffj_t_User_Description: + goto handle_Description + + case ffj_t_User_Entities: + goto handle_Entities + + case ffj_t_User_FavouritesCount: + goto handle_FavouritesCount + + case ffj_t_User_FollowRequestSent: + goto handle_FollowRequestSent + + case ffj_t_User_FollowersCount: + goto handle_FollowersCount + + case ffj_t_User_Following: + goto handle_Following + + case ffj_t_User_FriendsCount: + goto handle_FriendsCount + + case ffj_t_User_GeoEnabled: + goto handle_GeoEnabled + + case ffj_t_User_ID: + goto handle_ID + + case ffj_t_User_IDStr: + goto handle_IDStr + + case ffj_t_User_IsTranslator: + goto handle_IsTranslator + + case ffj_t_User_Lang: + goto handle_Lang + + case ffj_t_User_ListedCount: + goto handle_ListedCount + + case ffj_t_User_Location: + goto handle_Location + + case ffj_t_User_Name: + goto handle_Name + + case ffj_t_User_Notifications: + goto handle_Notifications + + case ffj_t_User_ProfileBackgroundColor: + goto handle_ProfileBackgroundColor + + case ffj_t_User_ProfileBackgroundImageURL: + goto handle_ProfileBackgroundImageURL + + case ffj_t_User_ProfileBackgroundImageURLHTTPS: + goto handle_ProfileBackgroundImageURLHTTPS + + case ffj_t_User_ProfileBackgroundTile: + goto handle_ProfileBackgroundTile + + case ffj_t_User_ProfileImageURL: + goto handle_ProfileImageURL + + case ffj_t_User_ProfileImageURLHTTPS: + goto handle_ProfileImageURLHTTPS + + case ffj_t_User_ProfileLinkColor: + goto handle_ProfileLinkColor + + case ffj_t_User_ProfileSidebarBorderColor: + goto handle_ProfileSidebarBorderColor + + case ffj_t_User_ProfileSidebarFillColor: + goto handle_ProfileSidebarFillColor + + case ffj_t_User_ProfileTextColor: + goto handle_ProfileTextColor + + case ffj_t_User_ProfileUseBackgroundImage: + goto handle_ProfileUseBackgroundImage + + case ffj_t_User_Protected: + goto handle_Protected + + case ffj_t_User_ScreenName: + goto handle_ScreenName + + case ffj_t_User_ShowAllInlineMedia: + goto handle_ShowAllInlineMedia + + case ffj_t_User_StatusesCount: + goto handle_StatusesCount + + case ffj_t_User_TimeZone: + goto handle_TimeZone + + case ffj_t_User_URL: + goto handle_URL + + case ffj_t_User_UtcOffset: + goto handle_UtcOffset + + case ffj_t_User_Verified: + goto handle_Verified + + case ffj_t_Userno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_ContributorsEnabled: + + /* handler: uj.ContributorsEnabled type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.ContributorsEnabled = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.ContributorsEnabled = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_CreatedAt: + + /* handler: uj.CreatedAt type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.CreatedAt = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_DefaultProfile: + + /* handler: uj.DefaultProfile type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.DefaultProfile = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.DefaultProfile = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_DefaultProfileImage: + + /* handler: uj.DefaultProfileImage type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.DefaultProfileImage = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.DefaultProfileImage = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Description: + + /* handler: uj.Description type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Description = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Entities: + + /* handler: uj.Entities type=benchmark.UserEntities kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.Entities.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_FavouritesCount: + + /* handler: uj.FavouritesCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.FavouritesCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_FollowRequestSent: + + /* handler: uj.FollowRequestSent type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.FollowRequestSent = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.FollowRequestSent = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_FollowersCount: + + /* handler: uj.FollowersCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.FollowersCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Following: + + /* handler: uj.Following type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Following = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Following = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_FriendsCount: + + /* handler: uj.FriendsCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.FriendsCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_GeoEnabled: + + /* handler: uj.GeoEnabled type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.GeoEnabled = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.GeoEnabled = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ID: + + /* handler: uj.ID type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.ID = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_IDStr: + + /* handler: uj.IDStr type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.IDStr = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_IsTranslator: + + /* handler: uj.IsTranslator type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.IsTranslator = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.IsTranslator = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Lang: + + /* handler: uj.Lang type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Lang = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ListedCount: + + /* handler: uj.ListedCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.ListedCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Location: + + /* handler: uj.Location type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Location = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Name: + + /* handler: uj.Name type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.Name = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Notifications: + + /* handler: uj.Notifications type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.Notifications = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.Notifications = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileBackgroundColor: + + /* handler: uj.ProfileBackgroundColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileBackgroundColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileBackgroundImageURL: + + /* handler: uj.ProfileBackgroundImageURL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileBackgroundImageURL = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileBackgroundImageURLHTTPS: + + /* handler: uj.ProfileBackgroundImageURLHTTPS type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileBackgroundImageURLHTTPS = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileBackgroundTile: + + /* handler: uj.ProfileBackgroundTile type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.ProfileBackgroundTile = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.ProfileBackgroundTile = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileImageURL: + + /* handler: uj.ProfileImageURL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileImageURL = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileImageURLHTTPS: + + /* handler: uj.ProfileImageURLHTTPS type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileImageURLHTTPS = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileLinkColor: + + /* handler: uj.ProfileLinkColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileLinkColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileSidebarBorderColor: + + /* handler: uj.ProfileSidebarBorderColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileSidebarBorderColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileSidebarFillColor: + + /* handler: uj.ProfileSidebarFillColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileSidebarFillColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileTextColor: + + /* handler: uj.ProfileTextColor type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ProfileTextColor = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ProfileUseBackgroundImage: + + /* handler: uj.ProfileUseBackgroundImage type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.ProfileUseBackgroundImage = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.ProfileUseBackgroundImage = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Protected: + + /* handler: uj.Protected type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Protected = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Protected = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ScreenName: + + /* handler: uj.ScreenName type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.ScreenName = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_ShowAllInlineMedia: + + /* handler: uj.ShowAllInlineMedia type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.ShowAllInlineMedia = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.ShowAllInlineMedia = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_StatusesCount: + + /* handler: uj.StatusesCount type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.StatusesCount = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_TimeZone: + + /* handler: uj.TimeZone type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + } else { + + outBuf := fs.Output.Bytes() + + uj.TimeZone = string(string(outBuf)) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_URL: + + /* handler: uj.URL type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + uj.URL = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + uj.URL = &tval + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_UtcOffset: + + /* handler: uj.UtcOffset type=int kind=int quoted=false*/ + + { + if tok != fflib.FFTok_integer && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for int", tok)) + } + } + + { + + if tok == fflib.FFTok_null { + + } else { + + tval, err := fflib.ParseInt(fs.Output.Bytes(), 10, 64) + + if err != nil { + return fs.WrapErr(err) + } + + uj.UtcOffset = int(tval) + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_Verified: + + /* handler: uj.Verified type=bool kind=bool quoted=false*/ + + { + if tok != fflib.FFTok_bool && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for bool", tok)) + } + } + + { + if tok == fflib.FFTok_null { + + } else { + tmpb := fs.Output.Bytes() + + if bytes.Compare([]byte{'t', 'r', 'u', 'e'}, tmpb) == 0 { + + uj.Verified = true + + } else if bytes.Compare([]byte{'f', 'a', 'l', 's', 'e'}, tmpb) == 0 { + + uj.Verified = false + + } else { + err = errors.New("unexpected bytes for true/false value") + return fs.WrapErr(err) + } + + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *UserEntities) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *UserEntities) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"description":`) + + { + + err = mj.Description.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteString(`,"url":`) + + { + + err = mj.URL.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_UserEntitiesbase = iota + ffj_t_UserEntitiesno_such_key + + ffj_t_UserEntities_Description + + ffj_t_UserEntities_URL +) + +var ffj_key_UserEntities_Description = []byte("description") + +var ffj_key_UserEntities_URL = []byte("url") + +func (uj *UserEntities) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *UserEntities) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_UserEntitiesbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_UserEntitiesno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'd': + + if bytes.Equal(ffj_key_UserEntities_Description, kn) { + currentKey = ffj_t_UserEntities_Description + state = fflib.FFParse_want_colon + goto mainparse + } + + case 'u': + + if bytes.Equal(ffj_key_UserEntities_URL, kn) { + currentKey = ffj_t_UserEntities_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_UserEntities_URL, kn) { + currentKey = ffj_t_UserEntities_URL + state = fflib.FFParse_want_colon + goto mainparse + } + + if fflib.EqualFoldRight(ffj_key_UserEntities_Description, kn) { + currentKey = ffj_t_UserEntities_Description + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_UserEntitiesno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_UserEntities_Description: + goto handle_Description + + case ffj_t_UserEntities_URL: + goto handle_URL + + case ffj_t_UserEntitiesno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Description: + + /* handler: uj.Description type=benchmark.UserEntityDescription kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.Description.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +handle_URL: + + /* handler: uj.URL type=benchmark.UserEntityURL kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = uj.URL.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *UserEntityDescription) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *UserEntityDescription) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"urls":`) + if mj.Urls != nil { + buf.WriteString(`[`) + for i, v := range mj.Urls { + if i != 0 { + buf.WriteString(`,`) + } + if v != nil { + fflib.WriteJsonString(buf, string(*v)) + } else { + buf.WriteString(`null`) + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_UserEntityDescriptionbase = iota + ffj_t_UserEntityDescriptionno_such_key + + ffj_t_UserEntityDescription_Urls +) + +var ffj_key_UserEntityDescription_Urls = []byte("urls") + +func (uj *UserEntityDescription) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *UserEntityDescription) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_UserEntityDescriptionbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_UserEntityDescriptionno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'u': + + if bytes.Equal(ffj_key_UserEntityDescription_Urls, kn) { + currentKey = ffj_t_UserEntityDescription_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_UserEntityDescription_Urls, kn) { + currentKey = ffj_t_UserEntityDescription_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_UserEntityDescriptionno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_UserEntityDescription_Urls: + goto handle_Urls + + case ffj_t_UserEntityDescriptionno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Urls: + + /* handler: uj.Urls type=[]*string kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Urls = nil + } else { + + uj.Urls = make([]*string, 0) + + wantVal := true + + for { + + var tmp_uj__Urls *string + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Urls type=*string kind=ptr quoted=false*/ + + { + + if tok == fflib.FFTok_null { + tmp_uj__Urls = nil + } else { + if tmp_uj__Urls == nil { + tmp_uj__Urls = new(string) + } + + /* handler: tmp_uj__Urls type=string kind=string quoted=false*/ + + { + + { + if tok != fflib.FFTok_string && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) + } + } + + if tok == fflib.FFTok_null { + + tmp_uj__Urls = nil + + } else { + + var tval string + outBuf := fs.Output.Bytes() + + tval = string(string(outBuf)) + tmp_uj__Urls = &tval + + } + } + + } + } + + uj.Urls = append(uj.Urls, tmp_uj__Urls) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *UserEntityURL) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *UserEntityURL) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"urls":`) + if mj.Urls != nil { + buf.WriteString(`[`) + for i, v := range mj.Urls { + if i != 0 { + buf.WriteString(`,`) + } + + { + + err = v.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_UserEntityURLbase = iota + ffj_t_UserEntityURLno_such_key + + ffj_t_UserEntityURL_Urls +) + +var ffj_key_UserEntityURL_Urls = []byte("urls") + +func (uj *UserEntityURL) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *UserEntityURL) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_UserEntityURLbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_UserEntityURLno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'u': + + if bytes.Equal(ffj_key_UserEntityURL_Urls, kn) { + currentKey = ffj_t_UserEntityURL_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.EqualFoldRight(ffj_key_UserEntityURL_Urls, kn) { + currentKey = ffj_t_UserEntityURL_Urls + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_UserEntityURLno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_UserEntityURL_Urls: + goto handle_Urls + + case ffj_t_UserEntityURLno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Urls: + + /* handler: uj.Urls type=[]benchmark.URL kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Urls = nil + } else { + + uj.Urls = make([]URL, 0) + + wantVal := true + + for { + + var tmp_uj__Urls URL + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Urls type=benchmark.URL kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = tmp_uj__Urls.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + uj.Urls = append(uj.Urls, tmp_uj__Urls) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} + +func (mj *XLStruct) MarshalJSON() ([]byte, error) { + var buf fflib.Buffer + if mj == nil { + buf.WriteString("null") + return buf.Bytes(), nil + } + err := mj.MarshalJSONBuf(&buf) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} +func (mj *XLStruct) MarshalJSONBuf(buf fflib.EncodingBuffer) error { + if mj == nil { + buf.WriteString("null") + return nil + } + var err error + var obj []byte + _ = obj + _ = err + buf.WriteString(`{"Data":`) + if mj.Data != nil { + buf.WriteString(`[`) + for i, v := range mj.Data { + if i != 0 { + buf.WriteString(`,`) + } + + { + + err = v.MarshalJSONBuf(buf) + if err != nil { + return err + } + + } + } + buf.WriteString(`]`) + } else { + buf.WriteString(`null`) + } + buf.WriteByte('}') + return nil +} + +const ( + ffj_t_XLStructbase = iota + ffj_t_XLStructno_such_key + + ffj_t_XLStruct_Data +) + +var ffj_key_XLStruct_Data = []byte("Data") + +func (uj *XLStruct) UnmarshalJSON(input []byte) error { + fs := fflib.NewFFLexer(input) + return uj.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) +} + +func (uj *XLStruct) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { + var err error = nil + currentKey := ffj_t_XLStructbase + _ = currentKey + tok := fflib.FFTok_init + wantedTok := fflib.FFTok_init + +mainparse: + for { + tok = fs.Scan() + // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) + if tok == fflib.FFTok_error { + goto tokerror + } + + switch state { + + case fflib.FFParse_map_start: + if tok != fflib.FFTok_left_bracket { + wantedTok = fflib.FFTok_left_bracket + goto wrongtokenerror + } + state = fflib.FFParse_want_key + continue + + case fflib.FFParse_after_value: + if tok == fflib.FFTok_comma { + state = fflib.FFParse_want_key + } else if tok == fflib.FFTok_right_bracket { + goto done + } else { + wantedTok = fflib.FFTok_comma + goto wrongtokenerror + } + + case fflib.FFParse_want_key: + // json {} ended. goto exit. woo. + if tok == fflib.FFTok_right_bracket { + goto done + } + if tok != fflib.FFTok_string { + wantedTok = fflib.FFTok_string + goto wrongtokenerror + } + + kn := fs.Output.Bytes() + if len(kn) <= 0 { + // "" case. hrm. + currentKey = ffj_t_XLStructno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } else { + switch kn[0] { + + case 'D': + + if bytes.Equal(ffj_key_XLStruct_Data, kn) { + currentKey = ffj_t_XLStruct_Data + state = fflib.FFParse_want_colon + goto mainparse + } + + } + + if fflib.SimpleLetterEqualFold(ffj_key_XLStruct_Data, kn) { + currentKey = ffj_t_XLStruct_Data + state = fflib.FFParse_want_colon + goto mainparse + } + + currentKey = ffj_t_XLStructno_such_key + state = fflib.FFParse_want_colon + goto mainparse + } + + case fflib.FFParse_want_colon: + if tok != fflib.FFTok_colon { + wantedTok = fflib.FFTok_colon + goto wrongtokenerror + } + state = fflib.FFParse_want_value + continue + case fflib.FFParse_want_value: + + if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { + switch currentKey { + + case ffj_t_XLStruct_Data: + goto handle_Data + + case ffj_t_XLStructno_such_key: + err = fs.SkipField(tok) + if err != nil { + return fs.WrapErr(err) + } + state = fflib.FFParse_after_value + goto mainparse + } + } else { + goto wantedvalue + } + } + } + +handle_Data: + + /* handler: uj.Data type=[]benchmark.LargeStruct kind=slice quoted=false*/ + + { + + { + if tok != fflib.FFTok_left_brace && tok != fflib.FFTok_null { + return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for ", tok)) + } + } + + if tok == fflib.FFTok_null { + uj.Data = nil + } else { + + uj.Data = make([]LargeStruct, 0) + + wantVal := true + + for { + + var tmp_uj__Data LargeStruct + + tok = fs.Scan() + if tok == fflib.FFTok_error { + goto tokerror + } + if tok == fflib.FFTok_right_brace { + break + } + + if tok == fflib.FFTok_comma { + if wantVal == true { + // TODO(pquerna): this isn't an ideal error message, this handles + // things like [,,,] as an array value. + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) + } + continue + } else { + wantVal = true + } + + /* handler: tmp_uj__Data type=benchmark.LargeStruct kind=struct quoted=false*/ + + { + if tok == fflib.FFTok_null { + + state = fflib.FFParse_after_value + goto mainparse + } + + err = tmp_uj__Data.UnmarshalJSONFFLexer(fs, fflib.FFParse_want_key) + if err != nil { + return err + } + state = fflib.FFParse_after_value + } + + uj.Data = append(uj.Data, tmp_uj__Data) + wantVal = false + } + } + } + + state = fflib.FFParse_after_value + goto mainparse + +wantedvalue: + return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) +wrongtokenerror: + return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) +tokerror: + if fs.BigError != nil { + return fs.WrapErr(fs.BigError) + } + err = fs.Error.ToError() + if err != nil { + return fs.WrapErr(err) + } + panic("ffjson-generated: unreachable, please report bug.") +done: + return nil +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/data_var.go b/vendor/github.com/mailru/easyjson/benchmark/data_var.go new file mode 100644 index 00000000..ea4202db --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/data_var.go @@ -0,0 +1,350 @@ +package benchmark + +var largeStructData = LargeStruct{ + SearchMetadata: SearchMetadata{ + CompletedIn: 0.035, + Count: 4, + MaxID: 250126199840518145, + MaxIDStr: "250126199840518145", + NextResults: "?max_id=249279667666817023&q=%23freebandnames&count=4&include_entities=1&result_type=mixed", + Query: "%23freebandnames", + RefreshURL: "?since_id=250126199840518145&q=%23freebandnames&result_type=mixed&include_entities=1", + SinceID: 24012619984051000, + SinceIDStr: "24012619984051000", + }, + Statuses: []Status{ + { + Contributors: nil, + Coordinates: nil, + CreatedAt: "Mon Sep 24 03:35:21 +0000 2012", + Entities: Entities{ + Hashtags: []Hashtag{{ + Indices: []int{20, 34}, + Text: "freebandnames"}, + }, + Urls: []*string{}, + UserMentions: []*string{}, + }, + Favorited: false, + Geo: nil, + ID: 250075927172759552, + IDStr: "250075927172759552", + InReplyToScreenName: nil, + InReplyToStatusID: nil, + InReplyToStatusIDStr: nil, + InReplyToUserID: nil, + InReplyToUserIDStr: nil, + Metadata: StatusMetadata{ + IsoLanguageCode: "en", + ResultType: "recent", + }, + Place: nil, + RetweetCount: 0, + Retweeted: false, + Source: "Twitter for Mac", + Text: "Aggressive Ponytail #freebandnames", + Truncated: false, + User: User{ + ContributorsEnabled: false, + CreatedAt: "Mon Apr 26 06:01:55 +0000 2010", + DefaultProfile: true, + DefaultProfileImage: false, + Description: "Born 330 Live 310", + Entities: UserEntities{ + Description: UserEntityDescription{ + Urls: []*string{}, + }, + URL: UserEntityURL{ + Urls: []URL{{ + ExpandedURL: nil, + Indices: []int{0, 0}, + URL: "", + }}, + }, + }, + FavouritesCount: 0, + FollowRequestSent: nil, + FollowersCount: 70, + Following: nil, + FriendsCount: 110, + GeoEnabled: true, + ID: 137238150, + IDStr: "137238150", + IsTranslator: false, + Lang: "en", + ListedCount: 2, + Location: "LA, CA", + Name: "Sean Cummings", + Notifications: nil, + ProfileBackgroundColor: "C0DEED", + ProfileBackgroundImageURL: "http://a0.twimg.com/images/themes/theme1/bg.png", + ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/images/themes/theme1/bg.png", + ProfileBackgroundTile: false, + ProfileImageURL: "http://a0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", + ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", + ProfileLinkColor: "0084B4", + ProfileSidebarBorderColor: "C0DEED", + ProfileSidebarFillColor: "DDEEF6", + ProfileTextColor: "333333", + ProfileUseBackgroundImage: true, + Protected: false, + ScreenName: "sean_cummings", + ShowAllInlineMedia: false, + StatusesCount: 579, + TimeZone: "Pacific Time (US & Canada)", + URL: nil, + UtcOffset: -28800, + Verified: false, + }, + }, + { + Contributors: nil, + Coordinates: nil, + CreatedAt: "Fri Sep 21 23:40:54 +0000 2012", + Entities: Entities{ + Hashtags: []Hashtag{{ + Indices: []int{20, 34}, + Text: "FreeBandNames", + }}, + Urls: []*string{}, + UserMentions: []*string{}, + }, + Favorited: false, + Geo: nil, + ID: 249292149810667520, + IDStr: "249292149810667520", + InReplyToScreenName: nil, + InReplyToStatusID: nil, + InReplyToStatusIDStr: nil, + InReplyToUserID: nil, + InReplyToUserIDStr: nil, + Metadata: StatusMetadata{ + IsoLanguageCode: "pl", + ResultType: "recent", + }, + Place: nil, + RetweetCount: 0, + Retweeted: false, + Source: "web", + Text: "Thee Namaste Nerdz. #FreeBandNames", + Truncated: false, + User: User{ + ContributorsEnabled: false, + CreatedAt: "Tue Apr 07 19:05:07 +0000 2009", + DefaultProfile: false, + DefaultProfileImage: false, + Description: "You will come to Durham, North Carolina. I will sell you some records then, here in Durham, North Carolina. Fun will happen.", + Entities: UserEntities{ + Description: UserEntityDescription{Urls: []*string{}}, + URL: UserEntityURL{ + Urls: []URL{{ + ExpandedURL: nil, + Indices: []int{0, 32}, + URL: "http://bullcityrecords.com/wnng/"}}, + }, + }, + FavouritesCount: 8, + FollowRequestSent: nil, + FollowersCount: 2052, + Following: nil, + FriendsCount: 348, + GeoEnabled: false, + ID: 29516238, + IDStr: "29516238", + IsTranslator: false, + Lang: "en", + ListedCount: 118, + Location: "Durham, NC", + Name: "Chaz Martenstein", + Notifications: nil, + ProfileBackgroundColor: "9AE4E8", + ProfileBackgroundImageURL: "http://a0.twimg.com/profile_background_images/9423277/background_tile.bmp", + ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/profile_background_images/9423277/background_tile.bmp", + ProfileBackgroundTile: true, + ProfileImageURL: "http://a0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", + ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", + ProfileLinkColor: "0084B4", + ProfileSidebarBorderColor: "BDDCAD", + ProfileSidebarFillColor: "DDFFCC", + ProfileTextColor: "333333", + ProfileUseBackgroundImage: true, + Protected: false, + ScreenName: "bullcityrecords", + ShowAllInlineMedia: true, + StatusesCount: 7579, + TimeZone: "Eastern Time (US & Canada)", + URL: nil, + UtcOffset: -18000, + Verified: false, + }, + }, + Status{ + Contributors: nil, + Coordinates: nil, + CreatedAt: "Fri Sep 21 23:30:20 +0000 2012", + Entities: Entities{ + Hashtags: []Hashtag{{ + Indices: []int{29, 43}, + Text: "freebandnames", + }}, + Urls: []*string{}, + UserMentions: []*string{}, + }, + Favorited: false, + Geo: nil, + ID: 249289491129438208, + IDStr: "249289491129438208", + InReplyToScreenName: nil, + InReplyToStatusID: nil, + InReplyToStatusIDStr: nil, + InReplyToUserID: nil, + InReplyToUserIDStr: nil, + Metadata: StatusMetadata{ + IsoLanguageCode: "en", + ResultType: "recent", + }, + Place: nil, + RetweetCount: 0, + Retweeted: false, + Source: "web", + Text: "Mexican Heaven, Mexican Hell #freebandnames", + Truncated: false, + User: User{ + ContributorsEnabled: false, + CreatedAt: "Tue Sep 01 21:21:35 +0000 2009", + DefaultProfile: false, + DefaultProfileImage: false, + Description: "Science Fiction Writer, sort of. Likes Superheroes, Mole People, Alt. Timelines.", + Entities: UserEntities{ + Description: UserEntityDescription{ + Urls: nil, + }, + URL: UserEntityURL{ + Urls: []URL{{ + ExpandedURL: nil, + Indices: []int{0, 0}, + URL: "", + }}, + }, + }, + FavouritesCount: 19, + FollowRequestSent: nil, + FollowersCount: 63, + Following: nil, + FriendsCount: 63, + GeoEnabled: false, + ID: 70789458, + IDStr: "70789458", + IsTranslator: false, + Lang: "en", + ListedCount: 1, + Location: "Kingston New York", + Name: "Thomas John Wakeman", + Notifications: nil, + ProfileBackgroundColor: "352726", + ProfileBackgroundImageURL: "http://a0.twimg.com/images/themes/theme5/bg.gif", + ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/images/themes/theme5/bg.gif", + ProfileBackgroundTile: false, + ProfileImageURL: "http://a0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", + ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", + ProfileLinkColor: "D02B55", + ProfileSidebarBorderColor: "829D5E", + ProfileSidebarFillColor: "99CC33", + ProfileTextColor: "3E4415", + ProfileUseBackgroundImage: true, + Protected: false, + ScreenName: "MonkiesFist", + ShowAllInlineMedia: false, + StatusesCount: 1048, + TimeZone: "Eastern Time (US & Canada)", + URL: nil, + UtcOffset: -18000, + Verified: false, + }, + }, + Status{ + Contributors: nil, + Coordinates: nil, + CreatedAt: "Fri Sep 21 22:51:18 +0000 2012", + Entities: Entities{ + Hashtags: []Hashtag{{ + Indices: []int{20, 34}, + Text: "freebandnames", + }}, + Urls: []*string{}, + UserMentions: []*string{}, + }, + Favorited: false, + Geo: nil, + ID: 249279667666817024, + IDStr: "249279667666817024", + InReplyToScreenName: nil, + InReplyToStatusID: nil, + InReplyToStatusIDStr: nil, + InReplyToUserID: nil, + InReplyToUserIDStr: nil, + Metadata: StatusMetadata{ + IsoLanguageCode: "en", + ResultType: "recent", + }, + Place: nil, + RetweetCount: 0, + Retweeted: false, + Source: "Twitter for iPhone", + Text: "The Foolish Mortals #freebandnames", + Truncated: false, + User: User{ + ContributorsEnabled: false, + CreatedAt: "Mon May 04 00:05:00 +0000 2009", + DefaultProfile: false, + DefaultProfileImage: false, + Description: "Cartoonist, Illustrator, and T-Shirt connoisseur", + Entities: UserEntities{ + Description: UserEntityDescription{ + Urls: []*string{}, + }, + URL: UserEntityURL{ + Urls: []URL{{ + ExpandedURL: nil, + Indices: []int{0, 24}, + URL: "http://www.omnitarian.me", + }}, + }, + }, + FavouritesCount: 647, + FollowRequestSent: nil, + FollowersCount: 608, + Following: nil, + FriendsCount: 249, + GeoEnabled: false, + ID: 37539828, + IDStr: "37539828", + IsTranslator: false, + Lang: "en", + ListedCount: 52, + Location: "Wisconsin, USA", + Name: "Marty Elmer", + Notifications: nil, + ProfileBackgroundColor: "EEE3C4", + ProfileBackgroundImageURL: "http://a0.twimg.com/profile_background_images/106455659/rect6056-9.png", + ProfileBackgroundImageURLHTTPS: "https://si0.twimg.com/profile_background_images/106455659/rect6056-9.png", + ProfileBackgroundTile: true, + ProfileImageURL: "http://a0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", + ProfileImageURLHTTPS: "https://si0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", + ProfileLinkColor: "3B2A26", + ProfileSidebarBorderColor: "615A44", + ProfileSidebarFillColor: "BFAC83", + ProfileTextColor: "000000", + ProfileUseBackgroundImage: true, + Protected: false, + ScreenName: "Omnitarian", + ShowAllInlineMedia: true, + StatusesCount: 3575, + TimeZone: "Central Time (US & Canada)", + URL: nil, + UtcOffset: -21600, + Verified: false, + }, + }, + }, +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/default_test.go b/vendor/github.com/mailru/easyjson/benchmark/default_test.go new file mode 100644 index 00000000..b647bef2 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/default_test.go @@ -0,0 +1,118 @@ +// +build !use_easyjson,!use_ffjson,!use_codec + +package benchmark + +import ( + "encoding/json" + "testing" +) + +func BenchmarkStd_Unmarshal_M(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + err := json.Unmarshal(largeStructText, &s) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkStd_Unmarshal_S(b *testing.B) { + for i := 0; i < b.N; i++ { + var s Entities + err := json.Unmarshal(smallStructText, &s) + if err != nil { + b.Error(err) + } + } + b.SetBytes(int64(len(smallStructText))) +} + +func BenchmarkStd_Marshal_M(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := json.Marshal(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_L(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := json.Marshal(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_M_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := json.Marshal(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_L_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := json.Marshal(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_S(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := json.Marshal(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_S_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := json.Marshal(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkStd_Marshal_M_ToWriter(b *testing.B) { + enc := json.NewEncoder(&DummyWriter{}) + for i := 0; i < b.N; i++ { + err := enc.Encode(&largeStructData) + if err != nil { + b.Error(err) + } + } +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/dummy_test.go b/vendor/github.com/mailru/easyjson/benchmark/dummy_test.go new file mode 100644 index 00000000..3d928ca7 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/dummy_test.go @@ -0,0 +1,11 @@ +package benchmark + +import ( + "testing" +) + +type DummyWriter struct{} + +func (w DummyWriter) Write(data []byte) (int, error) { return len(data), nil } + +func TestToSuppressNoTestsWarning(t *testing.T) {} diff --git a/vendor/github.com/mailru/easyjson/benchmark/easyjson_test.go b/vendor/github.com/mailru/easyjson/benchmark/easyjson_test.go new file mode 100644 index 00000000..16b670b2 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/easyjson_test.go @@ -0,0 +1,184 @@ +// +build use_easyjson + +package benchmark + +import ( + "testing" + + "github.com/mailru/easyjson" + "github.com/mailru/easyjson/jwriter" +) + +func BenchmarkEJ_Unmarshal_M(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + err := s.UnmarshalJSON(largeStructText) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkEJ_Unmarshal_S(b *testing.B) { + b.SetBytes(int64(len(smallStructText))) + + for i := 0; i < b.N; i++ { + var s Entities + err := s.UnmarshalJSON(smallStructText) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkEJ_Marshal_M(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := easyjson.Marshal(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkEJ_Marshal_L(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := easyjson.Marshal(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkEJ_Marshal_L_ToWriter(b *testing.B) { + var l int64 + out := &DummyWriter{} + for i := 0; i < b.N; i++ { + w := jwriter.Writer{} + xlStructData.MarshalEasyJSON(&w) + if w.Error != nil { + b.Error(w.Error) + } + + l = int64(w.Size()) + w.DumpTo(out) + } + b.SetBytes(l) + +} +func BenchmarkEJ_Marshal_M_Parallel(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _, err := largeStructData.MarshalJSON() + if err != nil { + b.Error(err) + } + } + }) +} + +func BenchmarkEJ_Marshal_M_ToWriter(b *testing.B) { + var l int64 + out := &DummyWriter{} + for i := 0; i < b.N; i++ { + w := jwriter.Writer{} + largeStructData.MarshalEasyJSON(&w) + if w.Error != nil { + b.Error(w.Error) + } + + l = int64(w.Size()) + w.DumpTo(out) + } + b.SetBytes(l) + +} +func BenchmarkEJ_Marshal_M_ToWriter_Parallel(b *testing.B) { + out := &DummyWriter{} + + b.RunParallel(func(pb *testing.PB) { + var l int64 + for pb.Next() { + w := jwriter.Writer{} + largeStructData.MarshalEasyJSON(&w) + if w.Error != nil { + b.Error(w.Error) + } + + l = int64(w.Size()) + w.DumpTo(out) + } + if l > 0 { + b.SetBytes(l) + } + }) + +} + +func BenchmarkEJ_Marshal_L_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := xlStructData.MarshalJSON() + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkEJ_Marshal_L_ToWriter_Parallel(b *testing.B) { + out := &DummyWriter{} + b.RunParallel(func(pb *testing.PB) { + var l int64 + for pb.Next() { + w := jwriter.Writer{} + + xlStructData.MarshalEasyJSON(&w) + if w.Error != nil { + b.Error(w.Error) + } + l = int64(w.Size()) + w.DumpTo(out) + } + if l > 0 { + b.SetBytes(l) + } + }) +} + +func BenchmarkEJ_Marshal_S(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := smallStructData.MarshalJSON() + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkEJ_Marshal_S_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := smallStructData.MarshalJSON() + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/example.json b/vendor/github.com/mailru/easyjson/benchmark/example.json new file mode 100644 index 00000000..2405022c --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/example.json @@ -0,0 +1,415 @@ +{ + "statuses": [ + { + "coordinates": null, + "favorited": false, + "truncated": false, + "created_at": "Mon Sep 24 03:35:21 +0000 2012", + "id_str": "250075927172759552", + "entities": { + "urls": [ + + ], + "hashtags": [ + { + "text": "freebandnames", + "indices": [ + 20, + 34 + ] + } + ], + "user_mentions": [ + + ] + }, + "in_reply_to_user_id_str": null, + "contributors": null, + "text": "Aggressive Ponytail #freebandnames", + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + }, + "retweet_count": 0, + "in_reply_to_status_id_str": null, + "id": 250075927172759552, + "geo": null, + "retweeted": false, + "in_reply_to_user_id": null, + "place": null, + "user": { + "profile_sidebar_fill_color": "DDEEF6", + "profile_sidebar_border_color": "C0DEED", + "profile_background_tile": false, + "name": "Sean Cummings", + "profile_image_url": "http://a0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", + "created_at": "Mon Apr 26 06:01:55 +0000 2010", + "location": "LA, CA", + "follow_request_sent": null, + "profile_link_color": "0084B4", + "is_translator": false, + "id_str": "137238150", + "entities": { + "url": { + "urls": [ + { + "expanded_url": null, + "url": "", + "indices": [ + 0, + 0 + ] + } + ] + }, + "description": { + "urls": [ + + ] + } + }, + "default_profile": true, + "contributors_enabled": false, + "favourites_count": 0, + "url": null, + "profile_image_url_https": "https://si0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg", + "utc_offset": -28800, + "id": 137238150, + "profile_use_background_image": true, + "listed_count": 2, + "profile_text_color": "333333", + "lang": "en", + "followers_count": 70, + "protected": false, + "notifications": null, + "profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme1/bg.png", + "profile_background_color": "C0DEED", + "verified": false, + "geo_enabled": true, + "time_zone": "Pacific Time (US & Canada)", + "description": "Born 330 Live 310", + "default_profile_image": false, + "profile_background_image_url": "http://a0.twimg.com/images/themes/theme1/bg.png", + "statuses_count": 579, + "friends_count": 110, + "following": null, + "show_all_inline_media": false, + "screen_name": "sean_cummings" + }, + "in_reply_to_screen_name": null, + "source": "Twitter for Mac", + "in_reply_to_status_id": null + }, + { + "coordinates": null, + "favorited": false, + "truncated": false, + "created_at": "Fri Sep 21 23:40:54 +0000 2012", + "id_str": "249292149810667520", + "entities": { + "urls": [ + + ], + "hashtags": [ + { + "text": "FreeBandNames", + "indices": [ + 20, + 34 + ] + } + ], + "user_mentions": [ + + ] + }, + "in_reply_to_user_id_str": null, + "contributors": null, + "text": "Thee Namaste Nerdz. #FreeBandNames", + "metadata": { + "iso_language_code": "pl", + "result_type": "recent" + }, + "retweet_count": 0, + "in_reply_to_status_id_str": null, + "id": 249292149810667520, + "geo": null, + "retweeted": false, + "in_reply_to_user_id": null, + "place": null, + "user": { + "profile_sidebar_fill_color": "DDFFCC", + "profile_sidebar_border_color": "BDDCAD", + "profile_background_tile": true, + "name": "Chaz Martenstein", + "profile_image_url": "http://a0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", + "created_at": "Tue Apr 07 19:05:07 +0000 2009", + "location": "Durham, NC", + "follow_request_sent": null, + "profile_link_color": "0084B4", + "is_translator": false, + "id_str": "29516238", + "entities": { + "url": { + "urls": [ + { + "expanded_url": null, + "url": "http://bullcityrecords.com/wnng/", + "indices": [ + 0, + 32 + ] + } + ] + }, + "description": { + "urls": [ + + ] + } + }, + "default_profile": false, + "contributors_enabled": false, + "favourites_count": 8, + "url": "http://bullcityrecords.com/wnng/", + "profile_image_url_https": "https://si0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg", + "utc_offset": -18000, + "id": 29516238, + "profile_use_background_image": true, + "listed_count": 118, + "profile_text_color": "333333", + "lang": "en", + "followers_count": 2052, + "protected": false, + "notifications": null, + "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/9423277/background_tile.bmp", + "profile_background_color": "9AE4E8", + "verified": false, + "geo_enabled": false, + "time_zone": "Eastern Time (US & Canada)", + "description": "You will come to Durham, North Carolina. I will sell you some records then, here in Durham, North Carolina. Fun will happen.", + "default_profile_image": false, + "profile_background_image_url": "http://a0.twimg.com/profile_background_images/9423277/background_tile.bmp", + "statuses_count": 7579, + "friends_count": 348, + "following": null, + "show_all_inline_media": true, + "screen_name": "bullcityrecords" + }, + "in_reply_to_screen_name": null, + "source": "web", + "in_reply_to_status_id": null + }, + { + "coordinates": null, + "favorited": false, + "truncated": false, + "created_at": "Fri Sep 21 23:30:20 +0000 2012", + "id_str": "249289491129438208", + "entities": { + "urls": [ + + ], + "hashtags": [ + { + "text": "freebandnames", + "indices": [ + 29, + 43 + ] + } + ], + "user_mentions": [ + + ] + }, + "in_reply_to_user_id_str": null, + "contributors": null, + "text": "Mexican Heaven, Mexican Hell #freebandnames", + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + }, + "retweet_count": 0, + "in_reply_to_status_id_str": null, + "id": 249289491129438208, + "geo": null, + "retweeted": false, + "in_reply_to_user_id": null, + "place": null, + "user": { + "profile_sidebar_fill_color": "99CC33", + "profile_sidebar_border_color": "829D5E", + "profile_background_tile": false, + "name": "Thomas John Wakeman", + "profile_image_url": "http://a0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", + "created_at": "Tue Sep 01 21:21:35 +0000 2009", + "location": "Kingston New York", + "follow_request_sent": null, + "profile_link_color": "D02B55", + "is_translator": false, + "id_str": "70789458", + "entities": { + "url": { + "urls": [ + { + "expanded_url": null, + "url": "", + "indices": [ + 0, + 0 + ] + } + ] + }, + "description": { + "urls": [ + + ] + } + }, + "default_profile": false, + "contributors_enabled": false, + "favourites_count": 19, + "url": null, + "profile_image_url_https": "https://si0.twimg.com/profile_images/2219333930/Froggystyle_normal.png", + "utc_offset": -18000, + "id": 70789458, + "profile_use_background_image": true, + "listed_count": 1, + "profile_text_color": "3E4415", + "lang": "en", + "followers_count": 63, + "protected": false, + "notifications": null, + "profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme5/bg.gif", + "profile_background_color": "352726", + "verified": false, + "geo_enabled": false, + "time_zone": "Eastern Time (US & Canada)", + "description": "Science Fiction Writer, sort of. Likes Superheroes, Mole People, Alt. Timelines.", + "default_profile_image": false, + "profile_background_image_url": "http://a0.twimg.com/images/themes/theme5/bg.gif", + "statuses_count": 1048, + "friends_count": 63, + "following": null, + "show_all_inline_media": false, + "screen_name": "MonkiesFist" + }, + "in_reply_to_screen_name": null, + "source": "web", + "in_reply_to_status_id": null + }, + { + "coordinates": null, + "favorited": false, + "truncated": false, + "created_at": "Fri Sep 21 22:51:18 +0000 2012", + "id_str": "249279667666817024", + "entities": { + "urls": [ + + ], + "hashtags": [ + { + "text": "freebandnames", + "indices": [ + 20, + 34 + ] + } + ], + "user_mentions": [ + + ] + }, + "in_reply_to_user_id_str": null, + "contributors": null, + "text": "The Foolish Mortals #freebandnames", + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + }, + "retweet_count": 0, + "in_reply_to_status_id_str": null, + "id": 249279667666817024, + "geo": null, + "retweeted": false, + "in_reply_to_user_id": null, + "place": null, + "user": { + "profile_sidebar_fill_color": "BFAC83", + "profile_sidebar_border_color": "615A44", + "profile_background_tile": true, + "name": "Marty Elmer", + "profile_image_url": "http://a0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", + "created_at": "Mon May 04 00:05:00 +0000 2009", + "location": "Wisconsin, USA", + "follow_request_sent": null, + "profile_link_color": "3B2A26", + "is_translator": false, + "id_str": "37539828", + "entities": { + "url": { + "urls": [ + { + "expanded_url": null, + "url": "http://www.omnitarian.me", + "indices": [ + 0, + 24 + ] + } + ] + }, + "description": { + "urls": [ + + ] + } + }, + "default_profile": false, + "contributors_enabled": false, + "favourites_count": 647, + "url": "http://www.omnitarian.me", + "profile_image_url_https": "https://si0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png", + "utc_offset": -21600, + "id": 37539828, + "profile_use_background_image": true, + "listed_count": 52, + "profile_text_color": "000000", + "lang": "en", + "followers_count": 608, + "protected": false, + "notifications": null, + "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/106455659/rect6056-9.png", + "profile_background_color": "EEE3C4", + "verified": false, + "geo_enabled": false, + "time_zone": "Central Time (US & Canada)", + "description": "Cartoonist, Illustrator, and T-Shirt connoisseur", + "default_profile_image": false, + "profile_background_image_url": "http://a0.twimg.com/profile_background_images/106455659/rect6056-9.png", + "statuses_count": 3575, + "friends_count": 249, + "following": null, + "show_all_inline_media": true, + "screen_name": "Omnitarian" + }, + "in_reply_to_screen_name": null, + "source": "Twitter for iPhone", + "in_reply_to_status_id": null + } + ], + "search_metadata": { + "max_id": 250126199840518145, + "since_id": 24012619984051000, + "refresh_url": "?since_id=250126199840518145&q=%23freebandnames&result_type=mixed&include_entities=1", + "next_results": "?max_id=249279667666817023&q=%23freebandnames&count=4&include_entities=1&result_type=mixed", + "count": 4, + "completed_in": 0.035, + "since_id_str": "24012619984051000", + "query": "%23freebandnames", + "max_id_str": "250126199840518145" + } +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/ffjson_test.go b/vendor/github.com/mailru/easyjson/benchmark/ffjson_test.go new file mode 100644 index 00000000..03671827 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/ffjson_test.go @@ -0,0 +1,190 @@ +// +build use_ffjson + +package benchmark + +import ( + "testing" + + "github.com/pquerna/ffjson/ffjson" +) + +func BenchmarkFF_Unmarshal_M(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + err := ffjson.UnmarshalFast(largeStructText, &s) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkFF_Unmarshal_S(b *testing.B) { + for i := 0; i < b.N; i++ { + var s Entities + err := ffjson.UnmarshalFast(smallStructText, &s) + if err != nil { + b.Error(err) + } + } + b.SetBytes(int64(len(smallStructText))) +} + +func BenchmarkFF_Marshal_M(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_S(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_M_Pool(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_L(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_L_Pool(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_L_Pool_Parallel(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + b.SetBytes(l) +} +func BenchmarkFF_Marshal_M_Pool_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + }) + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_S_Pool(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := ffjson.MarshalFast(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_S_Pool_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + ffjson.Pool(data) + } + }) + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_S_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_M_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkFF_Marshal_L_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := ffjson.MarshalFast(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} diff --git a/vendor/github.com/mailru/easyjson/benchmark/ujson.sh b/vendor/github.com/mailru/easyjson/benchmark/ujson.sh new file mode 100755 index 00000000..378e7df4 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/ujson.sh @@ -0,0 +1,7 @@ +#/bin/bash + +echo -n "Python ujson module, DECODE: " +python -m timeit -s "import ujson; data = open('`dirname $0`/example.json', 'r').read()" 'ujson.loads(data)' + +echo -n "Python ujson module, ENCODE: " +python -m timeit -s "import ujson; data = open('`dirname $0`/example.json', 'r').read(); obj = ujson.loads(data)" 'ujson.dumps(obj)' diff --git a/vendor/github.com/mailru/easyjson/bootstrap/bootstrap.go b/vendor/github.com/mailru/easyjson/bootstrap/bootstrap.go new file mode 100644 index 00000000..04aaaad5 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/bootstrap/bootstrap.go @@ -0,0 +1,180 @@ +// Package bootstrap implements the bootstrapping logic: generation of a .go file to +// launch the actual generator and launching the generator itself. +// +// The package may be preferred to a command-line utility if generating the serializers +// from golang code is required. +package bootstrap + +import ( + "fmt" + "io/ioutil" + "os" + "os/exec" + "path/filepath" +) + +const genPackage = "github.com/mailru/easyjson/gen" +const pkgWriter = "github.com/mailru/easyjson/jwriter" +const pkgLexer = "github.com/mailru/easyjson/jlexer" + +type Generator struct { + PkgPath, PkgName string + Types []string + + NoStdMarshalers bool + SnakeCase bool + OmitEmpty bool + + OutName string + BuildTags string + + StubsOnly bool + LeaveTemps bool + NoFormat bool +} + +// writeStub outputs an initial stubs for marshalers/unmarshalers so that the package +// using marshalers/unmarshales compiles correctly for boostrapping code. +func (g *Generator) writeStub() error { + f, err := os.Create(g.OutName) + if err != nil { + return err + } + defer f.Close() + + if g.BuildTags != "" { + fmt.Fprintln(f, "// +build ", g.BuildTags) + fmt.Fprintln(f) + } + fmt.Fprintln(f, "// TEMPORARY AUTOGENERATED FILE: easyjson stub code to make the package") + fmt.Fprintln(f, "// compilable during generation.") + fmt.Fprintln(f) + fmt.Fprintln(f, "package ", g.PkgName) + + if len(g.Types) > 0 { + fmt.Fprintln(f) + fmt.Fprintln(f, "import (") + fmt.Fprintln(f, ` "`+pkgWriter+`"`) + fmt.Fprintln(f, ` "`+pkgLexer+`"`) + fmt.Fprintln(f, ")") + } + + for _, t := range g.Types { + fmt.Fprintln(f) + if !g.NoStdMarshalers { + fmt.Fprintln(f, "func (", t, ") MarshalJSON() ([]byte, error) { return nil, nil }") + fmt.Fprintln(f, "func (*", t, ") UnmarshalJSON([]byte) error { return nil }") + } + + fmt.Fprintln(f, "func (", t, ") MarshalEasyJSON(w *jwriter.Writer) {}") + fmt.Fprintln(f, "func (*", t, ") UnmarshalEasyJSON(l *jlexer.Lexer) {}") + fmt.Fprintln(f) + fmt.Fprintln(f, "type EasyJSON_exporter_"+t+" *"+t) + } + return nil +} + +// writeMain creates a .go file that launches the generator if 'go run'. +func (g *Generator) writeMain() (path string, err error) { + f, err := ioutil.TempFile(filepath.Dir(g.OutName), "easyjson-bootstrap") + if err != nil { + return "", err + } + + fmt.Fprintln(f, "// +build ignore") + fmt.Fprintln(f) + fmt.Fprintln(f, "// TEMPORARY AUTOGENERATED FILE: easyjson bootstapping code to launch") + fmt.Fprintln(f, "// the actual generator.") + fmt.Fprintln(f) + fmt.Fprintln(f, "package main") + fmt.Fprintln(f) + fmt.Fprintln(f, "import (") + fmt.Fprintln(f, ` "fmt"`) + fmt.Fprintln(f, ` "os"`) + fmt.Fprintln(f) + fmt.Fprintf(f, " %q\n", genPackage) + if len(g.Types) > 0 { + fmt.Fprintln(f) + fmt.Fprintf(f, " pkg %q\n", g.PkgPath) + } + fmt.Fprintln(f, ")") + fmt.Fprintln(f) + fmt.Fprintln(f, "func main() {") + fmt.Fprintf(f, " g := gen.NewGenerator(%q)\n", filepath.Base(g.OutName)) + fmt.Fprintf(f, " g.SetPkg(%q, %q)\n", g.PkgName, g.PkgPath) + if g.BuildTags != "" { + fmt.Fprintf(f, " g.SetBuildTags(%q)\n", g.BuildTags) + } + if g.SnakeCase { + fmt.Fprintln(f, " g.UseSnakeCase()") + } + if g.OmitEmpty { + fmt.Fprintln(f, " g.OmitEmpty()") + } + if g.NoStdMarshalers { + fmt.Fprintln(f, " g.NoStdMarshalers()") + } + for _, v := range g.Types { + fmt.Fprintln(f, " g.Add(pkg.EasyJSON_exporter_"+v+"(nil))") + } + + fmt.Fprintln(f, " if err := g.Run(os.Stdout); err != nil {") + fmt.Fprintln(f, " fmt.Fprintln(os.Stderr, err)") + fmt.Fprintln(f, " os.Exit(1)") + fmt.Fprintln(f, " }") + fmt.Fprintln(f, "}") + + src := f.Name() + if err := f.Close(); err != nil { + return src, err + } + + dest := src + ".go" + return dest, os.Rename(src, dest) +} + +func (g *Generator) Run() error { + if err := g.writeStub(); err != nil { + return err + } + if g.StubsOnly { + return nil + } + + path, err := g.writeMain() + if err != nil { + return err + } + if !g.LeaveTemps { + defer os.Remove(path) + } + + f, err := os.Create(g.OutName + ".tmp") + if err != nil { + return err + } + if !g.LeaveTemps { + defer os.Remove(f.Name()) // will not remove after rename + } + + cmd := exec.Command("go", "run", "-tags", g.BuildTags, path) + cmd.Stdout = f + cmd.Stderr = os.Stderr + if err = cmd.Run(); err != nil { + return err + } + + f.Close() + + if !g.NoFormat { + cmd = exec.Command("gofmt", "-w", f.Name()) + cmd.Stderr = os.Stderr + cmd.Stdout = os.Stdout + + if err = cmd.Run(); err != nil { + return err + } + } + + return os.Rename(f.Name(), g.OutName) +} diff --git a/vendor/github.com/mailru/easyjson/buffer/pool.go b/vendor/github.com/mailru/easyjson/buffer/pool.go new file mode 100644 index 00000000..4de4a51d --- /dev/null +++ b/vendor/github.com/mailru/easyjson/buffer/pool.go @@ -0,0 +1,207 @@ +// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to +// reduce copying and to allow reuse of individual chunks. +package buffer + +import ( + "io" + "sync" +) + +// PoolConfig contains configuration for the allocation and reuse strategy. +type PoolConfig struct { + StartSize int // Minimum chunk size that is allocated. + PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. + MaxSize int // Maximum chunk size that will be allocated. +} + +var config = PoolConfig{ + StartSize: 128, + PooledSize: 512, + MaxSize: 32768, +} + +// Reuse pool: chunk size -> pool. +var buffers = map[int]*sync.Pool{} + +func initBuffers() { + for l := config.PooledSize; l <= config.MaxSize; l *= 2 { + buffers[l] = new(sync.Pool) + } +} + +func init() { + initBuffers() +} + +// Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. +func Init(cfg PoolConfig) { + config = cfg + initBuffers() +} + +// putBuf puts a chunk to reuse pool if it can be reused. +func putBuf(buf []byte) { + size := cap(buf) + if size < config.PooledSize { + return + } + if c := buffers[size]; c != nil { + c.Put(buf[:0]) + } +} + +// getBuf gets a chunk from reuse pool or creates a new one if reuse failed. +func getBuf(size int) []byte { + if size < config.PooledSize { + return make([]byte, 0, size) + } + + if c := buffers[size]; c != nil { + v := c.Get() + if v != nil { + return v.([]byte) + } + } + return make([]byte, 0, size) +} + +// Buffer is a buffer optimized for serialization without extra copying. +type Buffer struct { + + // Buf is the current chunk that can be used for serialization. + Buf []byte + + toPool []byte + bufs [][]byte +} + +// EnsureSpace makes sure that the current chunk contains at least s free bytes, +// possibly creating a new chunk. +func (b *Buffer) EnsureSpace(s int) { + if cap(b.Buf)-len(b.Buf) >= s { + return + } + l := len(b.Buf) + if l > 0 { + if cap(b.toPool) != cap(b.Buf) { + // Chunk was reallocated, toPool can be pooled. + putBuf(b.toPool) + } + if cap(b.bufs) == 0 { + b.bufs = make([][]byte, 0, 8) + } + b.bufs = append(b.bufs, b.Buf) + l = cap(b.toPool) * 2 + } else { + l = config.StartSize + } + + if l > config.MaxSize { + l = config.MaxSize + } + b.Buf = getBuf(l) + b.toPool = b.Buf +} + +// AppendByte appends a single byte to buffer. +func (b *Buffer) AppendByte(data byte) { + if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. + b.EnsureSpace(1) + } + b.Buf = append(b.Buf, data) +} + +// AppendBytes appends a byte slice to buffer. +func (b *Buffer) AppendBytes(data []byte) { + for len(data) > 0 { + if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. + b.EnsureSpace(1) + } + + sz := cap(b.Buf) - len(b.Buf) + if sz > len(data) { + sz = len(data) + } + + b.Buf = append(b.Buf, data[:sz]...) + data = data[sz:] + } +} + +// AppendBytes appends a string to buffer. +func (b *Buffer) AppendString(data string) { + for len(data) > 0 { + if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. + b.EnsureSpace(1) + } + + sz := cap(b.Buf) - len(b.Buf) + if sz > len(data) { + sz = len(data) + } + + b.Buf = append(b.Buf, data[:sz]...) + data = data[sz:] + } +} + +// Size computes the size of a buffer by adding sizes of every chunk. +func (b *Buffer) Size() int { + size := len(b.Buf) + for _, buf := range b.bufs { + size += len(buf) + } + return size +} + +// DumpTo outputs the contents of a buffer to a writer and resets the buffer. +func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { + var n int + for _, buf := range b.bufs { + if err == nil { + n, err = w.Write(buf) + written += n + } + putBuf(buf) + } + + if err == nil { + n, err = w.Write(b.Buf) + written += n + } + putBuf(b.toPool) + + b.bufs = nil + b.Buf = nil + b.toPool = nil + + return +} + +// BuildBytes creates a single byte slice with all the contents of the buffer. Data is +// copied if it does not fit in a single chunk. +func (b *Buffer) BuildBytes() []byte { + if len(b.bufs) == 0 { + + ret := b.Buf + b.toPool = nil + b.Buf = nil + + return ret + } + + ret := make([]byte, 0, b.Size()) + for _, buf := range b.bufs { + ret = append(ret, buf...) + putBuf(buf) + } + + ret = append(ret, b.Buf...) + putBuf(b.toPool) + + b.bufs = nil + b.toPool = nil + b.Buf = nil + + return ret +} diff --git a/vendor/github.com/mailru/easyjson/buffer/pool_test.go b/vendor/github.com/mailru/easyjson/buffer/pool_test.go new file mode 100644 index 00000000..254ca6fe --- /dev/null +++ b/vendor/github.com/mailru/easyjson/buffer/pool_test.go @@ -0,0 +1,79 @@ +package buffer + +import ( + "bytes" + "testing" +) + +func TestAppendByte(t *testing.T) { + var b Buffer + var want []byte + + for i := 0; i < 1000; i++ { + b.AppendByte(1) + b.AppendByte(2) + want = append(want, 1, 2) + } + + got := b.BuildBytes() + if !bytes.Equal(got, want) { + t.Errorf("BuildBytes() = %v; want %v", got, want) + } +} + +func TestAppendBytes(t *testing.T) { + var b Buffer + var want []byte + + for i := 0; i < 1000; i++ { + b.AppendBytes([]byte{1, 2}) + want = append(want, 1, 2) + } + + got := b.BuildBytes() + if !bytes.Equal(got, want) { + t.Errorf("BuildBytes() = %v; want %v", got, want) + } +} + +func TestAppendString(t *testing.T) { + var b Buffer + var want []byte + + s := "test" + for i := 0; i < 1000; i++ { + b.AppendBytes([]byte(s)) + want = append(want, s...) + } + + got := b.BuildBytes() + if !bytes.Equal(got, want) { + t.Errorf("BuildBytes() = %v; want %v", got, want) + } +} + +func TestDumpTo(t *testing.T) { + var b Buffer + var want []byte + + s := "test" + for i := 0; i < 1000; i++ { + b.AppendBytes([]byte(s)) + want = append(want, s...) + } + + out := &bytes.Buffer{} + n, err := b.DumpTo(out) + if err != nil { + t.Errorf("DumpTo() error: %v", err) + } + + got := out.Bytes() + if !bytes.Equal(got, want) { + t.Errorf("DumpTo(): got %v; want %v", got, want) + } + + if n != len(want) { + t.Errorf("DumpTo() = %v; want %v", n, len(want)) + } +} diff --git a/vendor/github.com/mailru/easyjson/easyjson/main.go b/vendor/github.com/mailru/easyjson/easyjson/main.go new file mode 100644 index 00000000..c9a6d9d3 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/easyjson/main.go @@ -0,0 +1,99 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/mailru/easyjson/bootstrap" + // Reference the gen package to be friendly to vendoring tools, + // as it is an indirect dependency. + // (The temporary bootstrapping code uses it.) + _ "github.com/mailru/easyjson/gen" + "github.com/mailru/easyjson/parser" +) + +var buildTags = flag.String("build_tags", "", "build tags to add to generated file") +var snakeCase = flag.Bool("snake_case", false, "use snake_case names instead of CamelCase by default") +var noStdMarshalers = flag.Bool("no_std_marshalers", false, "don't generate MarshalJSON/UnmarshalJSON methods") +var omitEmpty = flag.Bool("omit_empty", false, "omit empty fields by default") +var allStructs = flag.Bool("all", false, "generate un-/marshallers for all structs in a file") +var leaveTemps = flag.Bool("leave_temps", false, "do not delete temporary files") +var stubs = flag.Bool("stubs", false, "only generate stubs for marshallers/unmarshallers methods") +var noformat = flag.Bool("noformat", false, "do not run 'gofmt -w' on output file") +var specifiedName = flag.String("output_filename", "", "specify the filename of the output") +var processPkg = flag.Bool("pkg", false, "process the whole package instead of just the given file") + +func generate(fname string) (err error) { + fInfo, err := os.Stat(fname) + if err != nil { + return err + } + + p := parser.Parser{AllStructs: *allStructs} + if err := p.Parse(fname, fInfo.IsDir()); err != nil { + return fmt.Errorf("Error parsing %v: %v", fname, err) + } + + var outName string + if fInfo.IsDir() { + outName = filepath.Join(fname, p.PkgName+"_easyjson.go") + } else { + if s := strings.TrimSuffix(fname, ".go"); s == fname { + return errors.New("Filename must end in '.go'") + } else { + outName = s + "_easyjson.go" + } + } + + if *specifiedName != "" { + outName = *specifiedName + } + + g := bootstrap.Generator{ + BuildTags: *buildTags, + PkgPath: p.PkgPath, + PkgName: p.PkgName, + Types: p.StructNames, + SnakeCase: *snakeCase, + NoStdMarshalers: *noStdMarshalers, + OmitEmpty: *omitEmpty, + LeaveTemps: *leaveTemps, + OutName: outName, + StubsOnly: *stubs, + NoFormat: *noformat, + } + + if err := g.Run(); err != nil { + return fmt.Errorf("Bootstrap failed: %v", err) + } + return nil +} + +func main() { + flag.Parse() + + files := flag.Args() + + gofile := os.Getenv("GOFILE") + if *processPkg { + gofile = filepath.Dir(gofile) + } + + if len(files) == 0 && gofile != "" { + files = []string{gofile} + } else if len(files) == 0 { + flag.Usage() + os.Exit(1) + } + + for _, fname := range files { + if err := generate(fname); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + } +} diff --git a/vendor/github.com/mailru/easyjson/gen/decoder.go b/vendor/github.com/mailru/easyjson/gen/decoder.go new file mode 100644 index 00000000..8a7afbda --- /dev/null +++ b/vendor/github.com/mailru/easyjson/gen/decoder.go @@ -0,0 +1,458 @@ +package gen + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" + "unicode" + + "github.com/mailru/easyjson" +) + +// Target this byte size for initial slice allocation to reduce garbage collection. +const minSliceBytes = 64 + +func (g *Generator) getDecoderName(t reflect.Type) string { + return g.functionName("decode", t) +} + +var primitiveDecoders = map[reflect.Kind]string{ + reflect.String: "in.String()", + reflect.Bool: "in.Bool()", + reflect.Int: "in.Int()", + reflect.Int8: "in.Int8()", + reflect.Int16: "in.Int16()", + reflect.Int32: "in.Int32()", + reflect.Int64: "in.Int64()", + reflect.Uint: "in.Uint()", + reflect.Uint8: "in.Uint8()", + reflect.Uint16: "in.Uint16()", + reflect.Uint32: "in.Uint32()", + reflect.Uint64: "in.Uint64()", + reflect.Float32: "in.Float32()", + reflect.Float64: "in.Float64()", +} + +var primitiveStringDecoders = map[reflect.Kind]string{ + reflect.Int: "in.IntStr()", + reflect.Int8: "in.Int8Str()", + reflect.Int16: "in.Int16Str()", + reflect.Int32: "in.Int32Str()", + reflect.Int64: "in.Int64Str()", + reflect.Uint: "in.UintStr()", + reflect.Uint8: "in.Uint8Str()", + reflect.Uint16: "in.Uint16Str()", + reflect.Uint32: "in.Uint32Str()", + reflect.Uint64: "in.Uint64Str()", +} + +// genTypeDecoder generates decoding code for the type t, but uses unmarshaler interface if implemented by t. +func (g *Generator) genTypeDecoder(t reflect.Type, out string, tags fieldTags, indent int) error { + ws := strings.Repeat(" ", indent) + + unmarshalerIface := reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(unmarshalerIface) { + fmt.Fprintln(g.out, ws+"("+out+").UnmarshalEasyJSON(in)") + return nil + } + + unmarshalerIface = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(unmarshalerIface) { + fmt.Fprintln(g.out, ws+"if data := in.Raw(); in.Ok() {") + fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalJSON(data) )") + fmt.Fprintln(g.out, ws+"}") + return nil + } + + err := g.genTypeDecoderNoCheck(t, out, tags, indent) + return err +} + +// genTypeDecoderNoCheck generates decoding code for the type t. +func (g *Generator) genTypeDecoderNoCheck(t reflect.Type, out string, tags fieldTags, indent int) error { + ws := strings.Repeat(" ", indent) + // Check whether type is primitive, needs to be done after interface check. + if dec := primitiveStringDecoders[t.Kind()]; dec != "" && tags.asString { + fmt.Fprintln(g.out, ws+out+" = "+g.getType(t)+"("+dec+")") + return nil + } else if dec := primitiveDecoders[t.Kind()]; dec != "" { + fmt.Fprintln(g.out, ws+out+" = "+g.getType(t)+"("+dec+")") + return nil + } + + switch t.Kind() { + case reflect.Slice: + tmpVar := g.uniqueVarName() + elem := t.Elem() + + if elem.Kind() == reflect.Uint8 { + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+" "+out+" = nil") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" "+out+" = in.Bytes()") + fmt.Fprintln(g.out, ws+"}") + + } else { + + capacity := minSliceBytes / elem.Size() + if capacity == 0 { + capacity = 1 + } + + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+" "+out+" = nil") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" in.Delim('[')") + fmt.Fprintln(g.out, ws+" if !in.IsDelim(']') {") + fmt.Fprintln(g.out, ws+" "+out+" = make("+g.getType(t)+", 0, "+fmt.Sprint(capacity)+")") + fmt.Fprintln(g.out, ws+" } else {") + fmt.Fprintln(g.out, ws+" "+out+" = "+g.getType(t)+"{}") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" for !in.IsDelim(']') {") + fmt.Fprintln(g.out, ws+" var "+tmpVar+" "+g.getType(elem)) + + g.genTypeDecoder(elem, tmpVar, tags, indent+2) + + fmt.Fprintln(g.out, ws+" "+out+" = append("+out+", "+tmpVar+")") + fmt.Fprintln(g.out, ws+" in.WantComma()") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" in.Delim(']')") + fmt.Fprintln(g.out, ws+"}") + } + + case reflect.Array: + iterVar := g.uniqueVarName() + elem := t.Elem() + + if elem.Kind() == reflect.Uint8 { + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" copy("+out+"[:], in.Bytes())") + fmt.Fprintln(g.out, ws+"}") + + } else { + + length := t.Len() + + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" in.Delim('[')") + fmt.Fprintln(g.out, ws+" "+iterVar+" := 0") + fmt.Fprintln(g.out, ws+" for !in.IsDelim(']') {") + fmt.Fprintln(g.out, ws+" if "+iterVar+" < "+fmt.Sprint(length)+" {") + + g.genTypeDecoder(elem, out+"["+iterVar+"]", tags, indent+3) + + fmt.Fprintln(g.out, ws+" "+iterVar+"++") + fmt.Fprintln(g.out, ws+" } else {") + fmt.Fprintln(g.out, ws+" in.SkipRecursive()") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" in.WantComma()") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" in.Delim(']')") + fmt.Fprintln(g.out, ws+"}") + } + + case reflect.Struct: + dec := g.getDecoderName(t) + g.addType(t) + + fmt.Fprintln(g.out, ws+dec+"(in, &"+out+")") + + case reflect.Ptr: + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+" "+out+" = nil") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" if "+out+" == nil {") + fmt.Fprintln(g.out, ws+" "+out+" = new("+g.getType(t.Elem())+")") + fmt.Fprintln(g.out, ws+" }") + + g.genTypeDecoder(t.Elem(), "*"+out, tags, indent+1) + + fmt.Fprintln(g.out, ws+"}") + + case reflect.Map: + key := t.Key() + if key.Kind() != reflect.String { + return fmt.Errorf("map type %v not supported: only string keys are allowed", key) + } + elem := t.Elem() + tmpVar := g.uniqueVarName() + + fmt.Fprintln(g.out, ws+"if in.IsNull() {") + fmt.Fprintln(g.out, ws+" in.Skip()") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" in.Delim('{')") + fmt.Fprintln(g.out, ws+" if !in.IsDelim('}') {") + fmt.Fprintln(g.out, ws+" "+out+" = make("+g.getType(t)+")") + fmt.Fprintln(g.out, ws+" } else {") + fmt.Fprintln(g.out, ws+" "+out+" = nil") + fmt.Fprintln(g.out, ws+" }") + + fmt.Fprintln(g.out, ws+" for !in.IsDelim('}') {") + fmt.Fprintln(g.out, ws+" key := "+g.getType(t.Key())+"(in.String())") + fmt.Fprintln(g.out, ws+" in.WantColon()") + fmt.Fprintln(g.out, ws+" var "+tmpVar+" "+g.getType(elem)) + + g.genTypeDecoder(elem, tmpVar, tags, indent+2) + + fmt.Fprintln(g.out, ws+" ("+out+")[key] = "+tmpVar) + fmt.Fprintln(g.out, ws+" in.WantComma()") + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" in.Delim('}')") + fmt.Fprintln(g.out, ws+"}") + + case reflect.Interface: + if t.NumMethod() != 0 { + return fmt.Errorf("interface type %v not supported: only interface{} is allowed", t) + } + fmt.Fprintln(g.out, ws+"if m, ok := "+out+".(easyjson.Unmarshaler); ok {") + fmt.Fprintln(g.out, ws+"m.UnmarshalEasyJSON(in)") + fmt.Fprintln(g.out, ws+"} else if m, ok := "+out+".(json.Unmarshaler); ok {") + fmt.Fprintln(g.out, ws+"m.UnmarshalJSON(in.Raw())") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" "+out+" = in.Interface()") + fmt.Fprintln(g.out, ws+"}") + default: + return fmt.Errorf("don't know how to decode %v", t) + } + return nil + +} + +func (g *Generator) genStructFieldDecoder(t reflect.Type, f reflect.StructField) error { + jsonName := g.fieldNamer.GetJSONFieldName(t, f) + tags := parseFieldTags(f) + + if tags.omit { + return nil + } + + fmt.Fprintf(g.out, " case %q:\n", jsonName) + if err := g.genTypeDecoder(f.Type, "out."+f.Name, tags, 3); err != nil { + return err + } + + if tags.required { + fmt.Fprintf(g.out, "%sSet = true\n", f.Name) + } + + return nil +} + +func (g *Generator) genRequiredFieldSet(t reflect.Type, f reflect.StructField) { + tags := parseFieldTags(f) + + if !tags.required { + return + } + + fmt.Fprintf(g.out, "var %sSet bool\n", f.Name) +} + +func (g *Generator) genRequiredFieldCheck(t reflect.Type, f reflect.StructField) { + jsonName := g.fieldNamer.GetJSONFieldName(t, f) + tags := parseFieldTags(f) + + if !tags.required { + return + } + + g.imports["fmt"] = "fmt" + + fmt.Fprintf(g.out, "if !%sSet {\n", f.Name) + fmt.Fprintf(g.out, " in.AddError(fmt.Errorf(\"key '%s' is required\"))\n", jsonName) + fmt.Fprintf(g.out, "}\n") +} + +func mergeStructFields(fields1, fields2 []reflect.StructField) (fields []reflect.StructField) { + used := map[string]bool{} + for _, f := range fields2 { + used[f.Name] = true + fields = append(fields, f) + } + + for _, f := range fields1 { + if !used[f.Name] { + fields = append(fields, f) + } + } + return +} + +func getStructFields(t reflect.Type) ([]reflect.StructField, error) { + if t.Kind() != reflect.Struct { + return nil, fmt.Errorf("got %v; expected a struct", t) + } + + var efields []reflect.StructField + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if !f.Anonymous { + continue + } + + t1 := f.Type + if t1.Kind() == reflect.Ptr { + t1 = t1.Elem() + } + + fs, err := getStructFields(t1) + if err != nil { + return nil, fmt.Errorf("error processing embedded field: %v", err) + } + efields = mergeStructFields(efields, fs) + } + + var fields []reflect.StructField + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Anonymous { + continue + } + + c := []rune(f.Name)[0] + if unicode.IsUpper(c) { + fields = append(fields, f) + } + } + return mergeStructFields(efields, fields), nil +} + +func (g *Generator) genDecoder(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map: + return g.genSliceArrayDecoder(t) + default: + return g.genStructDecoder(t) + } +} + +func (g *Generator) genSliceArrayDecoder(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map: + default: + return fmt.Errorf("cannot generate encoder/decoder for %v, not a slice/array/map type", t) + } + + fname := g.getDecoderName(t) + typ := g.getType(t) + + fmt.Fprintln(g.out, "func "+fname+"(in *jlexer.Lexer, out *"+typ+") {") + fmt.Fprintln(g.out, " isTopLevel := in.IsStart()") + err := g.genTypeDecoderNoCheck(t, "*out", fieldTags{}, 1) + if err != nil { + return err + } + fmt.Fprintln(g.out, " if isTopLevel {") + fmt.Fprintln(g.out, " in.Consumed()") + fmt.Fprintln(g.out, " }") + fmt.Fprintln(g.out, "}") + + return nil +} + +func (g *Generator) genStructDecoder(t reflect.Type) error { + if t.Kind() != reflect.Struct { + return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct type", t) + } + + fname := g.getDecoderName(t) + typ := g.getType(t) + + fmt.Fprintln(g.out, "func "+fname+"(in *jlexer.Lexer, out *"+typ+") {") + fmt.Fprintln(g.out, " isTopLevel := in.IsStart()") + fmt.Fprintln(g.out, " if in.IsNull() {") + fmt.Fprintln(g.out, " if isTopLevel {") + fmt.Fprintln(g.out, " in.Consumed()") + fmt.Fprintln(g.out, " }") + fmt.Fprintln(g.out, " in.Skip()") + fmt.Fprintln(g.out, " return") + fmt.Fprintln(g.out, " }") + + // Init embedded pointer fields. + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if !f.Anonymous || f.Type.Kind() != reflect.Ptr { + continue + } + fmt.Fprintln(g.out, " out."+f.Name+" = new("+g.getType(f.Type.Elem())+")") + } + + fs, err := getStructFields(t) + if err != nil { + return fmt.Errorf("cannot generate decoder for %v: %v", t, err) + } + + for _, f := range fs { + g.genRequiredFieldSet(t, f) + } + + fmt.Fprintln(g.out, " in.Delim('{')") + fmt.Fprintln(g.out, " for !in.IsDelim('}') {") + fmt.Fprintln(g.out, " key := in.UnsafeString()") + fmt.Fprintln(g.out, " in.WantColon()") + fmt.Fprintln(g.out, " if in.IsNull() {") + fmt.Fprintln(g.out, " in.Skip()") + fmt.Fprintln(g.out, " in.WantComma()") + fmt.Fprintln(g.out, " continue") + fmt.Fprintln(g.out, " }") + + fmt.Fprintln(g.out, " switch key {") + for _, f := range fs { + if err := g.genStructFieldDecoder(t, f); err != nil { + return err + } + } + + fmt.Fprintln(g.out, " default:") + fmt.Fprintln(g.out, " in.SkipRecursive()") + fmt.Fprintln(g.out, " }") + fmt.Fprintln(g.out, " in.WantComma()") + fmt.Fprintln(g.out, " }") + fmt.Fprintln(g.out, " in.Delim('}')") + fmt.Fprintln(g.out, " if isTopLevel {") + fmt.Fprintln(g.out, " in.Consumed()") + fmt.Fprintln(g.out, " }") + + for _, f := range fs { + g.genRequiredFieldCheck(t, f) + } + + fmt.Fprintln(g.out, "}") + + return nil +} + +func (g *Generator) genStructUnmarshaller(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: + default: + return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct/slice/array/map type", t) + } + + fname := g.getDecoderName(t) + typ := g.getType(t) + + if !g.noStdMarshalers { + fmt.Fprintln(g.out, "// UnmarshalJSON supports json.Unmarshaler interface") + fmt.Fprintln(g.out, "func (v *"+typ+") UnmarshalJSON(data []byte) error {") + fmt.Fprintln(g.out, " r := jlexer.Lexer{Data: data}") + fmt.Fprintln(g.out, " "+fname+"(&r, v)") + fmt.Fprintln(g.out, " return r.Error()") + fmt.Fprintln(g.out, "}") + } + + fmt.Fprintln(g.out, "// UnmarshalEasyJSON supports easyjson.Unmarshaler interface") + fmt.Fprintln(g.out, "func (v *"+typ+") UnmarshalEasyJSON(l *jlexer.Lexer) {") + fmt.Fprintln(g.out, " "+fname+"(l, v)") + fmt.Fprintln(g.out, "}") + + return nil +} diff --git a/vendor/github.com/mailru/easyjson/gen/encoder.go b/vendor/github.com/mailru/easyjson/gen/encoder.go new file mode 100644 index 00000000..30dbbc97 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/gen/encoder.go @@ -0,0 +1,351 @@ +package gen + +import ( + "encoding/json" + "fmt" + "reflect" + "strconv" + "strings" + + "github.com/mailru/easyjson" +) + +func (g *Generator) getEncoderName(t reflect.Type) string { + return g.functionName("encode", t) +} + +var primitiveEncoders = map[reflect.Kind]string{ + reflect.String: "out.String(string(%v))", + reflect.Bool: "out.Bool(bool(%v))", + reflect.Int: "out.Int(int(%v))", + reflect.Int8: "out.Int8(int8(%v))", + reflect.Int16: "out.Int16(int16(%v))", + reflect.Int32: "out.Int32(int32(%v))", + reflect.Int64: "out.Int64(int64(%v))", + reflect.Uint: "out.Uint(uint(%v))", + reflect.Uint8: "out.Uint8(uint8(%v))", + reflect.Uint16: "out.Uint16(uint16(%v))", + reflect.Uint32: "out.Uint32(uint32(%v))", + reflect.Uint64: "out.Uint64(uint64(%v))", + reflect.Float32: "out.Float32(float32(%v))", + reflect.Float64: "out.Float64(float64(%v))", +} + +var primitiveStringEncoders = map[reflect.Kind]string{ + reflect.Int: "out.IntStr(int(%v))", + reflect.Int8: "out.Int8Str(int8(%v))", + reflect.Int16: "out.Int16Str(int16(%v))", + reflect.Int32: "out.Int32Str(int32(%v))", + reflect.Int64: "out.Int64Str(int64(%v))", + reflect.Uint: "out.UintStr(uint(%v))", + reflect.Uint8: "out.Uint8Str(uint8(%v))", + reflect.Uint16: "out.Uint16Str(uint16(%v))", + reflect.Uint32: "out.Uint32Str(uint32(%v))", + reflect.Uint64: "out.Uint64Str(uint64(%v))", +} + +// fieldTags contains parsed version of json struct field tags. +type fieldTags struct { + name string + + omit bool + omitEmpty bool + noOmitEmpty bool + asString bool + required bool +} + +// parseFieldTags parses the json field tag into a structure. +func parseFieldTags(f reflect.StructField) fieldTags { + var ret fieldTags + + for i, s := range strings.Split(f.Tag.Get("json"), ",") { + switch { + case i == 0 && s == "-": + ret.omit = true + case i == 0: + ret.name = s + case s == "omitempty": + ret.omitEmpty = true + case s == "!omitempty": + ret.noOmitEmpty = true + case s == "string": + ret.asString = true + case s == "required": + ret.required = true + } + } + + return ret +} + +// genTypeEncoder generates code that encodes in of type t into the writer, but uses marshaler interface if implemented by t. +func (g *Generator) genTypeEncoder(t reflect.Type, in string, tags fieldTags, indent int) error { + ws := strings.Repeat(" ", indent) + + marshalerIface := reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(marshalerIface) { + fmt.Fprintln(g.out, ws+"("+in+").MarshalEasyJSON(out)") + return nil + } + + marshalerIface = reflect.TypeOf((*json.Marshaler)(nil)).Elem() + if reflect.PtrTo(t).Implements(marshalerIface) { + fmt.Fprintln(g.out, ws+"out.Raw( ("+in+").MarshalJSON() )") + return nil + } + + err := g.genTypeEncoderNoCheck(t, in, tags, indent) + return err +} + +// genTypeEncoderNoCheck generates code that encodes in of type t into the writer. +func (g *Generator) genTypeEncoderNoCheck(t reflect.Type, in string, tags fieldTags, indent int) error { + ws := strings.Repeat(" ", indent) + + // Check whether type is primitive, needs to be done after interface check. + if enc := primitiveStringEncoders[t.Kind()]; enc != "" && tags.asString { + fmt.Fprintf(g.out, ws+enc+"\n", in) + return nil + } else if enc := primitiveEncoders[t.Kind()]; enc != "" { + fmt.Fprintf(g.out, ws+enc+"\n", in) + return nil + } + + switch t.Kind() { + case reflect.Slice: + elem := t.Elem() + iVar := g.uniqueVarName() + vVar := g.uniqueVarName() + + if t.Elem().Kind() == reflect.Uint8 { + fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+")") + } else { + fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilSliceAsEmpty) == 0 {") + fmt.Fprintln(g.out, ws+` out.RawString("null")`) + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" out.RawByte('[')") + fmt.Fprintln(g.out, ws+" for "+iVar+", "+vVar+" := range "+in+" {") + fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") + fmt.Fprintln(g.out, ws+" out.RawByte(',')") + fmt.Fprintln(g.out, ws+" }") + + g.genTypeEncoder(elem, vVar, tags, indent+2) + + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" out.RawByte(']')") + fmt.Fprintln(g.out, ws+"}") + } + + case reflect.Array: + elem := t.Elem() + iVar := g.uniqueVarName() + + if t.Elem().Kind() == reflect.Uint8 { + fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+"[:])") + } else { + fmt.Fprintln(g.out, ws+"out.RawByte('[')") + fmt.Fprintln(g.out, ws+"for "+iVar+" := range "+in+" {") + fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") + fmt.Fprintln(g.out, ws+" out.RawByte(',')") + fmt.Fprintln(g.out, ws+" }") + + g.genTypeEncoder(elem, in+"["+iVar+"]", tags, indent+1) + + fmt.Fprintln(g.out, ws+"}") + fmt.Fprintln(g.out, ws+"out.RawByte(']')") + } + + case reflect.Struct: + enc := g.getEncoderName(t) + g.addType(t) + + fmt.Fprintln(g.out, ws+enc+"(out, "+in+")") + + case reflect.Ptr: + fmt.Fprintln(g.out, ws+"if "+in+" == nil {") + fmt.Fprintln(g.out, ws+` out.RawString("null")`) + fmt.Fprintln(g.out, ws+"} else {") + + g.genTypeEncoder(t.Elem(), "*"+in, tags, indent+1) + + fmt.Fprintln(g.out, ws+"}") + + case reflect.Map: + key := t.Key() + if key.Kind() != reflect.String { + return fmt.Errorf("map type %v not supported: only string keys are allowed", key) + } + tmpVar := g.uniqueVarName() + + fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {") + fmt.Fprintln(g.out, ws+" out.RawString(`null`)") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" out.RawByte('{')") + fmt.Fprintln(g.out, ws+" "+tmpVar+"First := true") + fmt.Fprintln(g.out, ws+" for "+tmpVar+"Name, "+tmpVar+"Value := range "+in+" {") + fmt.Fprintln(g.out, ws+" if !"+tmpVar+"First { out.RawByte(',') }") + fmt.Fprintln(g.out, ws+" "+tmpVar+"First = false") + fmt.Fprintln(g.out, ws+" out.String(string("+tmpVar+"Name))") + fmt.Fprintln(g.out, ws+" out.RawByte(':')") + + g.genTypeEncoder(t.Elem(), tmpVar+"Value", tags, indent+2) + + fmt.Fprintln(g.out, ws+" }") + fmt.Fprintln(g.out, ws+" out.RawByte('}')") + fmt.Fprintln(g.out, ws+"}") + + case reflect.Interface: + if t.NumMethod() != 0 { + return fmt.Errorf("interface type %v not supported: only interface{} is allowed", t) + } + fmt.Fprintln(g.out, ws+"if m, ok := "+in+".(easyjson.Marshaler); ok {") + fmt.Fprintln(g.out, ws+" m.MarshalEasyJSON(out)") + fmt.Fprintln(g.out, ws+"} else if m, ok := "+in+".(json.Marshaler); ok {") + fmt.Fprintln(g.out, ws+" out.Raw(m.MarshalJSON())") + fmt.Fprintln(g.out, ws+"} else {") + fmt.Fprintln(g.out, ws+" out.Raw(json.Marshal("+in+"))") + fmt.Fprintln(g.out, ws+"}") + + default: + return fmt.Errorf("don't know how to encode %v", t) + } + return nil +} + +func (g *Generator) notEmptyCheck(t reflect.Type, v string) string { + optionalIface := reflect.TypeOf((*easyjson.Optional)(nil)).Elem() + if reflect.PtrTo(t).Implements(optionalIface) { + return "(" + v + ").IsDefined()" + } + + switch t.Kind() { + case reflect.Slice, reflect.Map: + return "len(" + v + ") != 0" + case reflect.Interface, reflect.Ptr: + return v + " != nil" + case reflect.Bool: + return v + case reflect.String: + return v + ` != ""` + case reflect.Float32, reflect.Float64, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + + return v + " != 0" + + default: + // note: Array types don't have a useful empty value + return "true" + } +} + +func (g *Generator) genStructFieldEncoder(t reflect.Type, f reflect.StructField) error { + jsonName := g.fieldNamer.GetJSONFieldName(t, f) + tags := parseFieldTags(f) + + if tags.omit { + return nil + } + if !tags.omitEmpty && !g.omitEmpty || tags.noOmitEmpty { + fmt.Fprintln(g.out, " if !first { out.RawByte(',') }") + fmt.Fprintln(g.out, " first = false") + fmt.Fprintf(g.out, " out.RawString(%q)\n", strconv.Quote(jsonName)+":") + return g.genTypeEncoder(f.Type, "in."+f.Name, tags, 1) + } + + fmt.Fprintln(g.out, " if", g.notEmptyCheck(f.Type, "in."+f.Name), "{") + fmt.Fprintln(g.out, " if !first { out.RawByte(',') }") + fmt.Fprintln(g.out, " first = false") + + fmt.Fprintf(g.out, " out.RawString(%q)\n", strconv.Quote(jsonName)+":") + if err := g.genTypeEncoder(f.Type, "in."+f.Name, tags, 2); err != nil { + return err + } + fmt.Fprintln(g.out, " }") + return nil +} + +func (g *Generator) genEncoder(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map: + return g.genSliceArrayMapEncoder(t) + default: + return g.genStructEncoder(t) + } +} + +func (g *Generator) genSliceArrayMapEncoder(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map: + default: + return fmt.Errorf("cannot generate encoder/decoder for %v, not a slice/array/map type", t) + } + + fname := g.getEncoderName(t) + typ := g.getType(t) + + fmt.Fprintln(g.out, "func "+fname+"(out *jwriter.Writer, in "+typ+") {") + err := g.genTypeEncoderNoCheck(t, "in", fieldTags{}, 1) + if err != nil { + return err + } + fmt.Fprintln(g.out, "}") + return nil +} + +func (g *Generator) genStructEncoder(t reflect.Type) error { + if t.Kind() != reflect.Struct { + return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct type", t) + } + + fname := g.getEncoderName(t) + typ := g.getType(t) + + fmt.Fprintln(g.out, "func "+fname+"(out *jwriter.Writer, in "+typ+") {") + fmt.Fprintln(g.out, " out.RawByte('{')") + fmt.Fprintln(g.out, " first := true") + fmt.Fprintln(g.out, " _ = first") + + fs, err := getStructFields(t) + if err != nil { + return fmt.Errorf("cannot generate encoder for %v: %v", t, err) + } + for _, f := range fs { + if err := g.genStructFieldEncoder(t, f); err != nil { + return err + } + } + + fmt.Fprintln(g.out, " out.RawByte('}')") + fmt.Fprintln(g.out, "}") + + return nil +} + +func (g *Generator) genStructMarshaller(t reflect.Type) error { + switch t.Kind() { + case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: + default: + return fmt.Errorf("cannot generate encoder/decoder for %v, not a struct/slice/array/map type", t) + } + + fname := g.getEncoderName(t) + typ := g.getType(t) + + if !g.noStdMarshalers { + fmt.Fprintln(g.out, "// MarshalJSON supports json.Marshaler interface") + fmt.Fprintln(g.out, "func (v "+typ+") MarshalJSON() ([]byte, error) {") + fmt.Fprintln(g.out, " w := jwriter.Writer{}") + fmt.Fprintln(g.out, " "+fname+"(&w, v)") + fmt.Fprintln(g.out, " return w.Buffer.BuildBytes(), w.Error") + fmt.Fprintln(g.out, "}") + } + + fmt.Fprintln(g.out, "// MarshalEasyJSON supports easyjson.Marshaler interface") + fmt.Fprintln(g.out, "func (v "+typ+") MarshalEasyJSON(w *jwriter.Writer) {") + fmt.Fprintln(g.out, " "+fname+"(w, v)") + fmt.Fprintln(g.out, "}") + + return nil +} diff --git a/vendor/github.com/mailru/easyjson/gen/generator.go b/vendor/github.com/mailru/easyjson/gen/generator.go new file mode 100644 index 00000000..db232d8e --- /dev/null +++ b/vendor/github.com/mailru/easyjson/gen/generator.go @@ -0,0 +1,438 @@ +package gen + +import ( + "bytes" + "fmt" + "hash/fnv" + "io" + "path" + "reflect" + "sort" + "strconv" + "strings" + "unicode" +) + +const pkgWriter = "github.com/mailru/easyjson/jwriter" +const pkgLexer = "github.com/mailru/easyjson/jlexer" +const pkgEasyJSON = "github.com/mailru/easyjson" + +// FieldNamer defines a policy for generating names for struct fields. +type FieldNamer interface { + GetJSONFieldName(t reflect.Type, f reflect.StructField) string +} + +// Generator generates the requested marshallers/unmarshallers. +type Generator struct { + out *bytes.Buffer + + pkgName string + pkgPath string + buildTags string + hashString string + + varCounter int + + noStdMarshalers bool + omitEmpty bool + fieldNamer FieldNamer + + // package path to local alias map for tracking imports + imports map[string]string + + // types that marshallers were requested for by user + marshallers map[reflect.Type]bool + + // types that encoders were already generated for + typesSeen map[reflect.Type]bool + + // types that encoders were requested for (e.g. by encoders of other types) + typesUnseen []reflect.Type + + // function name to relevant type maps to track names of de-/encoders in + // case of a name clash or unnamed structs + functionNames map[string]reflect.Type +} + +// NewGenerator initializes and returns a Generator. +func NewGenerator(filename string) *Generator { + ret := &Generator{ + imports: map[string]string{ + pkgWriter: "jwriter", + pkgLexer: "jlexer", + pkgEasyJSON: "easyjson", + "encoding/json": "json", + }, + fieldNamer: DefaultFieldNamer{}, + marshallers: make(map[reflect.Type]bool), + typesSeen: make(map[reflect.Type]bool), + functionNames: make(map[string]reflect.Type), + } + + // Use a file-unique prefix on all auxiliary functions to avoid + // name clashes. + hash := fnv.New32() + hash.Write([]byte(filename)) + ret.hashString = fmt.Sprintf("%x", hash.Sum32()) + + return ret +} + +// SetPkg sets the name and path of output package. +func (g *Generator) SetPkg(name, path string) { + g.pkgName = name + g.pkgPath = path +} + +// SetBuildTags sets build tags for the output file. +func (g *Generator) SetBuildTags(tags string) { + g.buildTags = tags +} + +// SetFieldNamer sets field naming strategy. +func (g *Generator) SetFieldNamer(n FieldNamer) { + g.fieldNamer = n +} + +// UseSnakeCase sets snake_case field naming strategy. +func (g *Generator) UseSnakeCase() { + g.fieldNamer = SnakeCaseFieldNamer{} +} + +// NoStdMarshalers instructs not to generate standard MarshalJSON/UnmarshalJSON +// methods (only the custom interface). +func (g *Generator) NoStdMarshalers() { + g.noStdMarshalers = true +} + +// OmitEmpty triggers `json=",omitempty"` behaviour by default. +func (g *Generator) OmitEmpty() { + g.omitEmpty = true +} + +// addTypes requests to generate en-/decoding functions for the given type. +func (g *Generator) addType(t reflect.Type) { + if g.typesSeen[t] { + return + } + for _, t1 := range g.typesUnseen { + if t1 == t { + return + } + } + g.typesUnseen = append(g.typesUnseen, t) +} + +// Add requests to generate (un-)marshallers and en-/decoding functions for the type of given object. +func (g *Generator) Add(obj interface{}) { + t := reflect.TypeOf(obj) + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + g.addType(t) + g.marshallers[t] = true +} + +// printHeader prints package declaration and imports. +func (g *Generator) printHeader() { + if g.buildTags != "" { + fmt.Println("// +build ", g.buildTags) + fmt.Println() + } + fmt.Println("// AUTOGENERATED FILE: easyjson marshaller/unmarshallers.") + fmt.Println() + fmt.Println("package ", g.pkgName) + fmt.Println() + + byAlias := map[string]string{} + var aliases []string + for path, alias := range g.imports { + aliases = append(aliases, alias) + byAlias[alias] = path + } + + sort.Strings(aliases) + fmt.Println("import (") + for _, alias := range g.imports { + fmt.Printf(" %s %q\n", alias, byAlias[alias]) + } + + fmt.Println(")") + fmt.Println("") + fmt.Println("// suppress unused package warning") + fmt.Println("var (") + fmt.Println(" _ *json.RawMessage") + fmt.Println(" _ *jlexer.Lexer") + fmt.Println(" _ *jwriter.Writer") + fmt.Println(" _ easyjson.Marshaler") + fmt.Println(")") + + fmt.Println() +} + +// Run runs the generator and outputs generated code to out. +func (g *Generator) Run(out io.Writer) error { + g.out = &bytes.Buffer{} + + for len(g.typesUnseen) > 0 { + t := g.typesUnseen[len(g.typesUnseen)-1] + g.typesUnseen = g.typesUnseen[:len(g.typesUnseen)-1] + g.typesSeen[t] = true + + if err := g.genDecoder(t); err != nil { + return err + } + if err := g.genEncoder(t); err != nil { + return err + } + + if !g.marshallers[t] { + continue + } + + if err := g.genStructMarshaller(t); err != nil { + return err + } + if err := g.genStructUnmarshaller(t); err != nil { + return err + } + } + g.printHeader() + _, err := out.Write(g.out.Bytes()) + return err +} + +// fixes vendored paths +func fixPkgPathVendoring(pkgPath string) string { + const vendor = "/vendor/" + if i := strings.LastIndex(pkgPath, vendor); i != -1 { + return pkgPath[i+len(vendor):] + } + return pkgPath +} + +// pkgAlias creates and returns and import alias for a given package. +func (g *Generator) pkgAlias(pkgPath string) string { + pkgPath = fixPkgPathVendoring(pkgPath) + if alias := g.imports[pkgPath]; alias != "" { + return alias + } + + for i := 0; ; i++ { + alias := path.Base(pkgPath) + if i > 0 { + alias += fmt.Sprint(i) + } + + exists := false + for _, v := range g.imports { + if v == alias { + exists = true + break + } + } + + if !exists { + g.imports[pkgPath] = alias + return alias + } + } +} + +// getType return the textual type name of given type that can be used in generated code. +func (g *Generator) getType(t reflect.Type) string { + if t.Name() == "" { + switch t.Kind() { + case reflect.Ptr: + return "*" + g.getType(t.Elem()) + case reflect.Slice: + return "[]" + g.getType(t.Elem()) + case reflect.Array: + return "[" + strconv.Itoa(t.Len()) + "]" + g.getType(t.Elem()) + case reflect.Map: + return "map[" + g.getType(t.Key()) + "]" + g.getType(t.Elem()) + } + } + + if t.Name() == "" || t.PkgPath() == "" { + if t.Kind() == reflect.Struct { + // the fields of an anonymous struct can have named types, + // and t.String() will not be sufficient because it does not + // remove the package name when it matches g.pkgPath. + // so we convert by hand + nf := t.NumField() + lines := make([]string, 0, nf) + for i := 0; i < nf; i++ { + f := t.Field(i) + line := f.Name + " " + g.getType(f.Type) + t := f.Tag + if t != "" { + line += " " + escapeTag(t) + } + lines = append(lines, line) + } + return strings.Join([]string{"struct { ", strings.Join(lines, "; "), " }"}, "") + } + return t.String() + } else if t.PkgPath() == g.pkgPath { + return t.Name() + } + return g.pkgAlias(t.PkgPath()) + "." + t.Name() +} + +// escape a struct field tag string back to source code +func escapeTag(tag reflect.StructTag) string { + t := string(tag) + if strings.ContainsRune(t, '`') { + // there are ` in the string; we can't use ` to enclose the string + return strconv.Quote(t) + } + return "`" + t + "`" +} + +// uniqueVarName returns a file-unique name that can be used for generated variables. +func (g *Generator) uniqueVarName() string { + g.varCounter++ + return fmt.Sprint("v", g.varCounter) +} + +// safeName escapes unsafe characters in pkg/type name and returns a string that can be used +// in encoder/decoder names for the type. +func (g *Generator) safeName(t reflect.Type) string { + name := t.PkgPath() + if t.Name() == "" { + name += "anonymous" + } else { + name += "." + t.Name() + } + + parts := []string{} + part := []rune{} + for _, c := range name { + if unicode.IsLetter(c) || unicode.IsDigit(c) { + part = append(part, c) + } else if len(part) > 0 { + parts = append(parts, string(part)) + part = []rune{} + } + } + return joinFunctionNameParts(false, parts...) +} + +// functionName returns a function name for a given type with a given prefix. If a function +// with this prefix already exists for a type, it is returned. +// +// Method is used to track encoder/decoder names for the type. +func (g *Generator) functionName(prefix string, t reflect.Type) string { + prefix = joinFunctionNameParts(true, "easyjson", g.hashString, prefix) + name := joinFunctionNameParts(true, prefix, g.safeName(t)) + + // Most of the names will be unique, try a shortcut first. + if e, ok := g.functionNames[name]; !ok || e == t { + g.functionNames[name] = t + return name + } + + // Search if the function already exists. + for name1, t1 := range g.functionNames { + if t1 == t && strings.HasPrefix(name1, prefix) { + return name1 + } + } + + // Create a new name in the case of a clash. + for i := 1; ; i++ { + nm := fmt.Sprint(name, i) + if _, ok := g.functionNames[nm]; ok { + continue + } + g.functionNames[nm] = t + return nm + } +} + +// DefaultFieldsNamer implements trivial naming policy equivalent to encoding/json. +type DefaultFieldNamer struct{} + +func (DefaultFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) string { + jsonName := strings.Split(f.Tag.Get("json"), ",")[0] + if jsonName != "" { + return jsonName + } else { + return f.Name + } +} + +// SnakeCaseFieldNamer implements CamelCase to snake_case conversion for fields names. +type SnakeCaseFieldNamer struct{} + +func camelToSnake(name string) string { + var ret bytes.Buffer + + multipleUpper := false + var lastUpper rune + var beforeUpper rune + + for _, c := range name { + // Non-lowercase character after uppercase is considered to be uppercase too. + isUpper := (unicode.IsUpper(c) || (lastUpper != 0 && !unicode.IsLower(c))) + + if lastUpper != 0 { + // Output a delimiter if last character was either the first uppercase character + // in a row, or the last one in a row (e.g. 'S' in "HTTPServer"). + // Do not output a delimiter at the beginning of the name. + + firstInRow := !multipleUpper + lastInRow := !isUpper + + if ret.Len() > 0 && (firstInRow || lastInRow) && beforeUpper != '_' { + ret.WriteByte('_') + } + ret.WriteRune(unicode.ToLower(lastUpper)) + } + + // Buffer uppercase char, do not output it yet as a delimiter may be required if the + // next character is lowercase. + if isUpper { + multipleUpper = (lastUpper != 0) + lastUpper = c + continue + } + + ret.WriteRune(c) + lastUpper = 0 + beforeUpper = c + multipleUpper = false + } + + if lastUpper != 0 { + ret.WriteRune(unicode.ToLower(lastUpper)) + } + return string(ret.Bytes()) +} + +func (SnakeCaseFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) string { + jsonName := strings.Split(f.Tag.Get("json"), ",")[0] + if jsonName != "" { + return jsonName + } + + return camelToSnake(f.Name) +} + +func joinFunctionNameParts(keepFirst bool, parts ...string) string { + buf := bytes.NewBufferString("") + for i, part := range parts { + if i == 0 && keepFirst { + buf.WriteString(part) + } else { + if len(part) > 0 { + buf.WriteString(strings.ToUpper(string(part[0]))) + } + if len(part) > 1 { + buf.WriteString(part[1:]) + } + } + } + return buf.String() +} diff --git a/vendor/github.com/mailru/easyjson/gen/generator_test.go b/vendor/github.com/mailru/easyjson/gen/generator_test.go new file mode 100644 index 00000000..62c03f08 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/gen/generator_test.go @@ -0,0 +1,65 @@ +package gen + +import ( + "testing" +) + +func TestCamelToSnake(t *testing.T) { + for i, test := range []struct { + In, Out string + }{ + {"", ""}, + {"A", "a"}, + {"SimpleExample", "simple_example"}, + {"internalField", "internal_field"}, + + {"SomeHTTPStuff", "some_http_stuff"}, + {"WriteJSON", "write_json"}, + {"HTTP2Server", "http2_server"}, + {"Some_Mixed_Case", "some_mixed_case"}, + {"do_nothing", "do_nothing"}, + + {"JSONHTTPRPCServer", "jsonhttprpc_server"}, // nothing can be done here without a dictionary + } { + got := camelToSnake(test.In) + if got != test.Out { + t.Errorf("[%d] camelToSnake(%s) = %s; want %s", i, test.In, got, test.Out) + } + } +} + +func TestJoinFunctionNameParts(t *testing.T) { + for i, test := range []struct { + keepFirst bool + parts []string + out string + }{ + {false, []string{}, ""}, + {false, []string{"a"}, "A"}, + {false, []string{"simple", "example"}, "SimpleExample"}, + {true, []string{"first", "example"}, "firstExample"}, + {false, []string{"some", "UPPER", "case"}, "SomeUPPERCase"}, + {false, []string{"number", "123"}, "Number123"}, + } { + got := joinFunctionNameParts(test.keepFirst, test.parts...) + if got != test.out { + t.Errorf("[%d] joinFunctionNameParts(%v) = %s; want %s", i, test.parts, got, test.out) + } + } +} + +func TestFixVendorPath(t *testing.T) { + for i, test := range []struct { + In, Out string + }{ + {"", ""}, + {"time", "time"}, + {"project/vendor/subpackage", "subpackage"}, + } { + got := fixPkgPathVendoring(test.In) + if got != test.Out { + t.Errorf("[%d] fixPkgPathVendoring(%s) = %s; want %s", i, test.In, got, test.Out) + } + } + +} diff --git a/vendor/github.com/mailru/easyjson/helpers.go b/vendor/github.com/mailru/easyjson/helpers.go new file mode 100644 index 00000000..b86b87d2 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/helpers.go @@ -0,0 +1,78 @@ +// Package easyjson contains marshaler/unmarshaler interfaces and helper functions. +package easyjson + +import ( + "io" + "io/ioutil" + "net/http" + "strconv" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// Marshaler is an easyjson-compatible marshaler interface. +type Marshaler interface { + MarshalEasyJSON(w *jwriter.Writer) +} + +// Marshaler is an easyjson-compatible unmarshaler interface. +type Unmarshaler interface { + UnmarshalEasyJSON(w *jlexer.Lexer) +} + +// Optional defines an undefined-test method for a type to integrate with 'omitempty' logic. +type Optional interface { + IsDefined() bool +} + +// Marshal returns data as a single byte slice. Method is suboptimal as the data is likely to be copied +// from a chain of smaller chunks. +func Marshal(v Marshaler) ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.BuildBytes() +} + +// MarshalToWriter marshals the data to an io.Writer. +func MarshalToWriter(v Marshaler, w io.Writer) (written int, err error) { + jw := jwriter.Writer{} + v.MarshalEasyJSON(&jw) + return jw.DumpTo(w) +} + +// MarshalToHTTPResponseWriter sets Content-Length and Content-Type headers for the +// http.ResponseWriter, and send the data to the writer. started will be equal to +// false if an error occurred before any http.ResponseWriter methods were actually +// invoked (in this case a 500 reply is possible). +func MarshalToHTTPResponseWriter(v Marshaler, w http.ResponseWriter) (started bool, written int, err error) { + jw := jwriter.Writer{} + v.MarshalEasyJSON(&jw) + if jw.Error != nil { + return false, 0, jw.Error + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(jw.Size())) + + started = true + written, err = jw.DumpTo(w) + return +} + +// Unmarshal decodes the JSON in data into the object. +func Unmarshal(data []byte, v Unmarshaler) error { + l := jlexer.Lexer{Data: data} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// UnmarshalFromReader reads all the data in the reader and decodes as JSON into the object. +func UnmarshalFromReader(r io.Reader, v Unmarshaler) error { + data, err := ioutil.ReadAll(r) + if err != nil { + return err + } + l := jlexer.Lexer{Data: data} + v.UnmarshalEasyJSON(&l) + return l.Error() +} diff --git a/vendor/github.com/mailru/easyjson/jlexer/error.go b/vendor/github.com/mailru/easyjson/jlexer/error.go new file mode 100644 index 00000000..e90ec40d --- /dev/null +++ b/vendor/github.com/mailru/easyjson/jlexer/error.go @@ -0,0 +1,15 @@ +package jlexer + +import "fmt" + +// LexerError implements the error interface and represents all possible errors that can be +// generated during parsing the JSON data. +type LexerError struct { + Reason string + Offset int + Data string +} + +func (l *LexerError) Error() string { + return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data) +} diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/vendor/github.com/mailru/easyjson/jlexer/lexer.go new file mode 100644 index 00000000..db4939d5 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/jlexer/lexer.go @@ -0,0 +1,1121 @@ +// Package jlexer contains a JSON lexer implementation. +// +// It is expected that it is mostly used with generated parser code, so the interface is tuned +// for a parser that knows what kind of data is expected. +package jlexer + +import ( + "encoding/base64" + "errors" + "fmt" + "io" + "reflect" + "strconv" + "unicode" + "unicode/utf16" + "unicode/utf8" + "unsafe" +) + +// tokenKind determines type of a token. +type tokenKind byte + +const ( + tokenUndef tokenKind = iota // No token. + tokenDelim // Delimiter: one of '{', '}', '[' or ']'. + tokenString // A string literal, e.g. "abc\u1234" + tokenNumber // Number literal, e.g. 1.5e5 + tokenBool // Boolean literal: true or false. + tokenNull // null keyword. +) + +// token describes a single token: type, position in the input and value. +type token struct { + kind tokenKind // Type of a token. + + boolValue bool // Value if a boolean literal token. + byteValue []byte // Raw value of a token. + delimValue byte +} + +// Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice. +type Lexer struct { + Data []byte // Input data given to the lexer. + + start int // Start of the current token. + pos int // Current unscanned position in the input stream. + token token // Last scanned token, if token.kind != tokenUndef. + + firstElement bool // Whether current element is the first in array or an object. + wantSep byte // A comma or a colon character, which need to occur before a token. + + UseMultipleErrors bool // If we want to use multiple errors. + fatalError error // Fatal error occured during lexing. It is usually a syntax error. + multipleErrors []*LexerError // Semantic errors occured during lexing. Marshalling will be continued after finding this errors. +} + +// FetchToken scans the input for the next token. +func (r *Lexer) FetchToken() { + r.token.kind = tokenUndef + r.start = r.pos + + // Check if r.Data has r.pos element + // If it doesn't, it mean corrupted input data + if len(r.Data) < r.pos { + r.errParse("Unexpected end of data") + return + } + // Determine the type of a token by skipping whitespace and reading the + // first character. + for _, c := range r.Data[r.pos:] { + switch c { + case ':', ',': + if r.wantSep == c { + r.pos++ + r.start++ + r.wantSep = 0 + } else { + r.errSyntax() + } + + case ' ', '\t', '\r', '\n': + r.pos++ + r.start++ + + case '"': + if r.wantSep != 0 { + r.errSyntax() + } + + r.token.kind = tokenString + r.fetchString() + return + + case '{', '[': + if r.wantSep != 0 { + r.errSyntax() + } + r.firstElement = true + r.token.kind = tokenDelim + r.token.delimValue = r.Data[r.pos] + r.pos++ + return + + case '}', ']': + if !r.firstElement && (r.wantSep != ',') { + r.errSyntax() + } + r.wantSep = 0 + r.token.kind = tokenDelim + r.token.delimValue = r.Data[r.pos] + r.pos++ + return + + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': + if r.wantSep != 0 { + r.errSyntax() + } + r.token.kind = tokenNumber + r.fetchNumber() + return + + case 'n': + if r.wantSep != 0 { + r.errSyntax() + } + + r.token.kind = tokenNull + r.fetchNull() + return + + case 't': + if r.wantSep != 0 { + r.errSyntax() + } + + r.token.kind = tokenBool + r.token.boolValue = true + r.fetchTrue() + return + + case 'f': + if r.wantSep != 0 { + r.errSyntax() + } + + r.token.kind = tokenBool + r.token.boolValue = false + r.fetchFalse() + return + + default: + r.errSyntax() + return + } + } + r.fatalError = io.EOF + return +} + +// isTokenEnd returns true if the char can follow a non-delimiter token +func isTokenEnd(c byte) bool { + return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' +} + +// fetchNull fetches and checks remaining bytes of null keyword. +func (r *Lexer) fetchNull() { + r.pos += 4 + if r.pos > len(r.Data) || + r.Data[r.pos-3] != 'u' || + r.Data[r.pos-2] != 'l' || + r.Data[r.pos-1] != 'l' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { + + r.pos -= 4 + r.errSyntax() + } +} + +// fetchTrue fetches and checks remaining bytes of true keyword. +func (r *Lexer) fetchTrue() { + r.pos += 4 + if r.pos > len(r.Data) || + r.Data[r.pos-3] != 'r' || + r.Data[r.pos-2] != 'u' || + r.Data[r.pos-1] != 'e' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { + + r.pos -= 4 + r.errSyntax() + } +} + +// fetchFalse fetches and checks remaining bytes of false keyword. +func (r *Lexer) fetchFalse() { + r.pos += 5 + if r.pos > len(r.Data) || + r.Data[r.pos-4] != 'a' || + r.Data[r.pos-3] != 'l' || + r.Data[r.pos-2] != 's' || + r.Data[r.pos-1] != 'e' || + (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { + + r.pos -= 5 + r.errSyntax() + } +} + +// bytesToStr creates a string pointing at the slice to avoid copying. +// +// Warning: the string returned by the function should be used with care, as the whole input data +// chunk may be either blocked from being freed by GC because of a single string or the buffer.Data +// may be garbage-collected even when the string exists. +func bytesToStr(data []byte) string { + h := (*reflect.SliceHeader)(unsafe.Pointer(&data)) + shdr := reflect.StringHeader{h.Data, h.Len} + return *(*string)(unsafe.Pointer(&shdr)) +} + +// fetchNumber scans a number literal token. +func (r *Lexer) fetchNumber() { + hasE := false + afterE := false + hasDot := false + + r.pos++ + for i, c := range r.Data[r.pos:] { + switch { + case c >= '0' && c <= '9': + afterE = false + case c == '.' && !hasDot: + hasDot = true + case (c == 'e' || c == 'E') && !hasE: + hasE = true + hasDot = true + afterE = true + case (c == '+' || c == '-') && afterE: + afterE = false + default: + r.pos += i + if !isTokenEnd(c) { + r.errSyntax() + } else { + r.token.byteValue = r.Data[r.start:r.pos] + } + return + } + } + + r.pos = len(r.Data) + r.token.byteValue = r.Data[r.start:] +} + +// findStringLen tries to scan into the string literal for ending quote char to determine required size. +// The size will be exact if no escapes are present and may be inexact if there are escaped chars. +func findStringLen(data []byte) (hasEscapes bool, length int) { + delta := 0 + + for i := 0; i < len(data); i++ { + switch data[i] { + case '\\': + i++ + delta++ + if i < len(data) && data[i] == 'u' { + delta++ + } + case '"': + return (delta > 0), (i - delta) + } + } + + return false, len(data) +} + +// getu4 decodes \uXXXX from the beginning of s, returning the hex value, +// or it returns -1. +func getu4(s []byte) rune { + if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { + return -1 + } + var val rune + for i := 2; i < len(s) && i < 6; i++ { + var v byte + c := s[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + v = c - '0' + case 'a', 'b', 'c', 'd', 'e', 'f': + v = c - 'a' + 10 + case 'A', 'B', 'C', 'D', 'E', 'F': + v = c - 'A' + 10 + default: + return -1 + } + + val <<= 4 + val |= rune(v) + } + return val +} + +// processEscape processes a single escape sequence and returns number of bytes processed. +func (r *Lexer) processEscape(data []byte) (int, error) { + if len(data) < 2 { + return 0, fmt.Errorf("syntax error at %v", string(data)) + } + + c := data[1] + switch c { + case '"', '/', '\\': + r.token.byteValue = append(r.token.byteValue, c) + return 2, nil + case 'b': + r.token.byteValue = append(r.token.byteValue, '\b') + return 2, nil + case 'f': + r.token.byteValue = append(r.token.byteValue, '\f') + return 2, nil + case 'n': + r.token.byteValue = append(r.token.byteValue, '\n') + return 2, nil + case 'r': + r.token.byteValue = append(r.token.byteValue, '\r') + return 2, nil + case 't': + r.token.byteValue = append(r.token.byteValue, '\t') + return 2, nil + case 'u': + rr := getu4(data) + if rr < 0 { + return 0, errors.New("syntax error") + } + + read := 6 + if utf16.IsSurrogate(rr) { + rr1 := getu4(data[read:]) + if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { + read += 6 + rr = dec + } else { + rr = unicode.ReplacementChar + } + } + var d [4]byte + s := utf8.EncodeRune(d[:], rr) + r.token.byteValue = append(r.token.byteValue, d[:s]...) + return read, nil + } + + return 0, errors.New("syntax error") +} + +// fetchString scans a string literal token. +func (r *Lexer) fetchString() { + r.pos++ + data := r.Data[r.pos:] + + hasEscapes, length := findStringLen(data) + if !hasEscapes { + r.token.byteValue = data[:length] + r.pos += length + 1 + return + } + + r.token.byteValue = make([]byte, 0, length) + p := 0 + for i := 0; i < len(data); { + switch data[i] { + case '"': + r.pos += i + 1 + r.token.byteValue = append(r.token.byteValue, data[p:i]...) + i++ + return + + case '\\': + r.token.byteValue = append(r.token.byteValue, data[p:i]...) + off, err := r.processEscape(data[i:]) + if err != nil { + r.errParse(err.Error()) + return + } + i += off + p = i + + default: + i++ + } + } + r.errParse("unterminated string literal") +} + +// scanToken scans the next token if no token is currently available in the lexer. +func (r *Lexer) scanToken() { + if r.token.kind != tokenUndef || r.fatalError != nil { + return + } + + r.FetchToken() +} + +// consume resets the current token to allow scanning the next one. +func (r *Lexer) consume() { + r.token.kind = tokenUndef + r.token.delimValue = 0 +} + +// Ok returns true if no error (including io.EOF) was encountered during scanning. +func (r *Lexer) Ok() bool { + return r.fatalError == nil +} + +const maxErrorContextLen = 13 + +func (r *Lexer) errParse(what string) { + if r.fatalError == nil { + var str string + if len(r.Data)-r.pos <= maxErrorContextLen { + str = string(r.Data) + } else { + str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..." + } + r.fatalError = &LexerError{ + Reason: what, + Offset: r.pos, + Data: str, + } + } +} + +func (r *Lexer) errSyntax() { + r.errParse("syntax error") +} + +func (r *Lexer) errInvalidToken(expected string) { + if r.fatalError != nil { + return + } + if r.UseMultipleErrors { + r.pos = r.start + r.consume() + r.SkipRecursive() + switch expected { + case "[": + r.token.delimValue = ']' + r.token.kind = tokenDelim + case "{": + r.token.delimValue = '}' + r.token.kind = tokenDelim + } + r.addNonfatalError(&LexerError{ + Reason: fmt.Sprintf("expected %s", expected), + Offset: r.start, + Data: string(r.Data[r.start:r.pos]), + }) + return + } + + var str string + if len(r.token.byteValue) <= maxErrorContextLen { + str = string(r.token.byteValue) + } else { + str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..." + } + r.fatalError = &LexerError{ + Reason: fmt.Sprintf("expected %s", expected), + Offset: r.pos, + Data: str, + } +} + +func (r *Lexer) GetPos() int { + return r.pos +} + +// Delim consumes a token and verifies that it is the given delimiter. +func (r *Lexer) Delim(c byte) { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + + if !r.Ok() || r.token.delimValue != c { + r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled. + r.errInvalidToken(string([]byte{c})) + } else { + r.consume() + } +} + +// IsDelim returns true if there was no scanning error and next token is the given delimiter. +func (r *Lexer) IsDelim(c byte) bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + return !r.Ok() || r.token.delimValue == c +} + +// Null verifies that the next token is null and consumes it. +func (r *Lexer) Null() { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenNull { + r.errInvalidToken("null") + } + r.consume() +} + +// IsNull returns true if the next token is a null keyword. +func (r *Lexer) IsNull() bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + return r.Ok() && r.token.kind == tokenNull +} + +// Skip skips a single token. +func (r *Lexer) Skip() { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + r.consume() +} + +// SkipRecursive skips next array or object completely, or just skips a single token if not +// an array/object. +// +// Note: no syntax validation is performed on the skipped data. +func (r *Lexer) SkipRecursive() { + r.scanToken() + var start, end byte + + if r.token.delimValue == '{' { + start, end = '{', '}' + } else if r.token.delimValue == '[' { + start, end = '[', ']' + } else { + r.consume() + return + } + + r.consume() + + level := 1 + inQuotes := false + wasEscape := false + + for i, c := range r.Data[r.pos:] { + switch { + case c == start && !inQuotes: + level++ + case c == end && !inQuotes: + level-- + if level == 0 { + r.pos += i + 1 + return + } + case c == '\\' && inQuotes: + wasEscape = !wasEscape + continue + case c == '"' && inQuotes: + inQuotes = wasEscape + case c == '"': + inQuotes = true + } + wasEscape = false + } + r.pos = len(r.Data) + r.fatalError = &LexerError{ + Reason: "EOF reached while skipping array/object or token", + Offset: r.pos, + Data: string(r.Data[r.pos:]), + } +} + +// Raw fetches the next item recursively as a data slice +func (r *Lexer) Raw() []byte { + r.SkipRecursive() + if !r.Ok() { + return nil + } + return r.Data[r.start:r.pos] +} + +// IsStart returns whether the lexer is positioned at the start +// of an input string. +func (r *Lexer) IsStart() bool { + return r.pos == 0 +} + +// Consumed reads all remaining bytes from the input, publishing an error if +// there is anything but whitespace remaining. +func (r *Lexer) Consumed() { + if r.pos > len(r.Data) { + return + } + + for _, c := range r.Data[r.pos:] { + if c != ' ' && c != '\t' && c != '\r' && c != '\n' { + r.fatalError = &LexerError{ + Reason: "invalid character '" + string(c) + "' after top-level value", + Offset: r.pos, + Data: string(r.Data[r.pos:]), + } + return + } + + r.pos++ + r.start++ + } +} + +func (r *Lexer) unsafeString() (string, []byte) { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return "", nil + } + bytes := r.token.byteValue + ret := bytesToStr(r.token.byteValue) + r.consume() + return ret, bytes +} + +// UnsafeString returns the string value if the token is a string literal. +// +// Warning: returned string may point to the input buffer, so the string should not outlive +// the input buffer. Intended pattern of usage is as an argument to a switch statement. +func (r *Lexer) UnsafeString() string { + ret, _ := r.unsafeString() + return ret +} + +// String reads a string literal. +func (r *Lexer) String() string { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return "" + } + ret := string(r.token.byteValue) + r.consume() + return ret +} + +// Bytes reads a string literal and base64 decodes it into a byte slice. +func (r *Lexer) Bytes() []byte { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenString { + r.errInvalidToken("string") + return nil + } + ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue))) + len, err := base64.StdEncoding.Decode(ret, r.token.byteValue) + if err != nil { + r.fatalError = &LexerError{ + Reason: err.Error(), + } + return nil + } + + r.consume() + return ret[:len] +} + +// Bool reads a true or false boolean keyword. +func (r *Lexer) Bool() bool { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenBool { + r.errInvalidToken("bool") + return false + } + ret := r.token.boolValue + r.consume() + return ret +} + +func (r *Lexer) number() string { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() || r.token.kind != tokenNumber { + r.errInvalidToken("number") + return "" + } + ret := bytesToStr(r.token.byteValue) + r.consume() + return ret +} + +func (r *Lexer) Uint8() uint8 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return uint8(n) +} + +func (r *Lexer) Uint16() uint16 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return uint16(n) +} + +func (r *Lexer) Uint32() uint32 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return uint32(n) +} + +func (r *Lexer) Uint64() uint64 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return n +} + +func (r *Lexer) Uint() uint { + return uint(r.Uint64()) +} + +func (r *Lexer) Int8() int8 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return int8(n) +} + +func (r *Lexer) Int16() int16 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return int16(n) +} + +func (r *Lexer) Int32() int32 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return int32(n) +} + +func (r *Lexer) Int64() int64 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return n +} + +func (r *Lexer) Int() int { + return int(r.Int64()) +} + +func (r *Lexer) Uint8Str() uint8 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return uint8(n) +} + +func (r *Lexer) Uint16Str() uint16 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return uint16(n) +} + +func (r *Lexer) Uint32Str() uint32 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return uint32(n) +} + +func (r *Lexer) Uint64Str() uint64 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return n +} + +func (r *Lexer) UintStr() uint { + return uint(r.Uint64Str()) +} + +func (r *Lexer) Int8Str() int8 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 8) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return int8(n) +} + +func (r *Lexer) Int16Str() int16 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 16) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return int16(n) +} + +func (r *Lexer) Int32Str() int32 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return int32(n) +} + +func (r *Lexer) Int64Str() int64 { + s, b := r.unsafeString() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: string(b), + }) + } + return n +} + +func (r *Lexer) IntStr() int { + return int(r.Int64Str()) +} + +func (r *Lexer) Float32() float32 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseFloat(s, 32) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return float32(n) +} + +func (r *Lexer) Float64() float64 { + s := r.number() + if !r.Ok() { + return 0 + } + + n, err := strconv.ParseFloat(s, 64) + if err != nil { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Reason: err.Error(), + Data: s, + }) + } + return n +} + +func (r *Lexer) Error() error { + return r.fatalError +} + +func (r *Lexer) AddError(e error) { + if r.fatalError == nil { + r.fatalError = e + } +} + +func (r *Lexer) AddNonFatalError(e error) { + r.addNonfatalError(&LexerError{ + Offset: r.start, + Data: string(r.Data[r.start:r.pos]), + Reason: e.Error(), + }) +} + +func (r *Lexer) addNonfatalError(err *LexerError) { + if r.UseMultipleErrors { + // We don't want to add errors with the same offset. + if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset { + return + } + r.multipleErrors = append(r.multipleErrors, err) + return + } + r.fatalError = err +} + +func (r *Lexer) GetNonFatalErrors() []*LexerError { + return r.multipleErrors +} + +// Interface fetches an interface{} analogous to the 'encoding/json' package. +func (r *Lexer) Interface() interface{} { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + + if !r.Ok() { + return nil + } + switch r.token.kind { + case tokenString: + return r.String() + case tokenNumber: + return r.Float64() + case tokenBool: + return r.Bool() + case tokenNull: + r.Null() + return nil + } + + if r.token.delimValue == '{' { + r.consume() + + ret := map[string]interface{}{} + for !r.IsDelim('}') { + key := r.String() + r.WantColon() + ret[key] = r.Interface() + r.WantComma() + } + r.Delim('}') + + if r.Ok() { + return ret + } else { + return nil + } + } else if r.token.delimValue == '[' { + r.consume() + + var ret []interface{} + for !r.IsDelim(']') { + ret = append(ret, r.Interface()) + r.WantComma() + } + r.Delim(']') + + if r.Ok() { + return ret + } else { + return nil + } + } + r.errSyntax() + return nil +} + +// WantComma requires a comma to be present before fetching next token. +func (r *Lexer) WantComma() { + r.wantSep = ',' + r.firstElement = false +} + +// WantColon requires a colon to be present before fetching next token. +func (r *Lexer) WantColon() { + r.wantSep = ':' + r.firstElement = false +} diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer_test.go b/vendor/github.com/mailru/easyjson/jlexer/lexer_test.go new file mode 100644 index 00000000..b8a64989 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/jlexer/lexer_test.go @@ -0,0 +1,251 @@ +package jlexer + +import ( + "bytes" + "reflect" + "testing" +) + +func TestString(t *testing.T) { + for i, test := range []struct { + toParse string + want string + wantError bool + }{ + {toParse: `"simple string"`, want: "simple string"}, + {toParse: " \r\r\n\t " + `"test"`, want: "test"}, + {toParse: `"\n\t\"\/\\\f\r"`, want: "\n\t\"/\\\f\r"}, + {toParse: `"\u0020"`, want: " "}, + {toParse: `"\u0020-\t"`, want: " -\t"}, + {toParse: `"\ufffd\uFFFD"`, want: "\ufffd\ufffd"}, + {toParse: `"\ud83d\ude00"`, want: "😀"}, + {toParse: `"\ud83d\ude08"`, want: "😈"}, + {toParse: `"\ud8"`, wantError: true}, + + {toParse: `"test"junk`, want: "test"}, + + {toParse: `5`, wantError: true}, // not a string + {toParse: `"\x"`, wantError: true}, // invalid escape + {toParse: `"\ud800"`, want: "�"}, // invalid utf-8 char; return replacement char + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.String() + if got != test.want { + t.Errorf("[%d, %q] String() = %v; want %v", i, test.toParse, got, test.want) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] String() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] String() ok; want error", i, test.toParse) + } + } +} + +func TestBytes(t *testing.T) { + for i, test := range []struct { + toParse string + want string + wantError bool + }{ + {toParse: `"c2ltcGxlIHN0cmluZw=="`, want: "simple string"}, + {toParse: " \r\r\n\t " + `"dGVzdA=="`, want: "test"}, + + {toParse: `5`, wantError: true}, // not a JSON string + {toParse: `"foobar"`, wantError: true}, // not base64 encoded + {toParse: `"c2ltcGxlIHN0cmluZw="`, wantError: true}, // invalid base64 padding + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.Bytes() + if bytes.Compare(got, []byte(test.want)) != 0 { + t.Errorf("[%d, %q] Bytes() = %v; want: %v", i, test.toParse, got, []byte(test.want)) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] Bytes() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] Bytes() ok; want error", i, test.toParse) + } + } +} + +func TestNumber(t *testing.T) { + for i, test := range []struct { + toParse string + want string + wantError bool + }{ + {toParse: "123", want: "123"}, + {toParse: "-123", want: "-123"}, + {toParse: "\r\n12.35", want: "12.35"}, + {toParse: "12.35e+1", want: "12.35e+1"}, + {toParse: "12.35e-15", want: "12.35e-15"}, + {toParse: "12.35E-15", want: "12.35E-15"}, + {toParse: "12.35E15", want: "12.35E15"}, + + {toParse: `"a"`, wantError: true}, + {toParse: "123junk", wantError: true}, + {toParse: "1.2.3", wantError: true}, + {toParse: "1e2e3", wantError: true}, + {toParse: "1e2.3", wantError: true}, + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.number() + if got != test.want { + t.Errorf("[%d, %q] number() = %v; want %v", i, test.toParse, got, test.want) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] number() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] number() ok; want error", i, test.toParse) + } + } +} + +func TestBool(t *testing.T) { + for i, test := range []struct { + toParse string + want bool + wantError bool + }{ + {toParse: "true", want: true}, + {toParse: "false", want: false}, + + {toParse: "1", wantError: true}, + {toParse: "truejunk", wantError: true}, + {toParse: `false"junk"`, wantError: true}, + {toParse: "True", wantError: true}, + {toParse: "False", wantError: true}, + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.Bool() + if got != test.want { + t.Errorf("[%d, %q] Bool() = %v; want %v", i, test.toParse, got, test.want) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] Bool() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] Bool() ok; want error", i, test.toParse) + } + } +} + +func TestSkipRecursive(t *testing.T) { + for i, test := range []struct { + toParse string + left string + wantError bool + }{ + {toParse: "5, 4", left: ", 4"}, + {toParse: "[5, 6], 4", left: ", 4"}, + {toParse: "[5, [7,8]]: 4", left: ": 4"}, + + {toParse: `{"a":1}, 4`, left: ", 4"}, + {toParse: `{"a":1, "b":{"c": 5}, "e":[12,15]}, 4`, left: ", 4"}, + + // array start/end chars in a string + {toParse: `[5, "]"], 4`, left: ", 4"}, + {toParse: `[5, "\"]"], 4`, left: ", 4"}, + {toParse: `[5, "["], 4`, left: ", 4"}, + {toParse: `[5, "\"["], 4`, left: ", 4"}, + + // object start/end chars in a string + {toParse: `{"a}":1}, 4`, left: ", 4"}, + {toParse: `{"a\"}":1}, 4`, left: ", 4"}, + {toParse: `{"a{":1}, 4`, left: ", 4"}, + {toParse: `{"a\"{":1}, 4`, left: ", 4"}, + + // object with double slashes at the end of string + {toParse: `{"a":"hey\\"}, 4`, left: ", 4"}, + } { + l := Lexer{Data: []byte(test.toParse)} + + l.SkipRecursive() + + got := string(l.Data[l.pos:]) + if got != test.left { + t.Errorf("[%d, %q] SkipRecursive() left = %v; want %v", i, test.toParse, got, test.left) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] SkipRecursive() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] SkipRecursive() ok; want error", i, test.toParse) + } + } +} + +func TestInterface(t *testing.T) { + for i, test := range []struct { + toParse string + want interface{} + wantError bool + }{ + {toParse: "null", want: nil}, + {toParse: "true", want: true}, + {toParse: `"a"`, want: "a"}, + {toParse: "5", want: float64(5)}, + + {toParse: `{}`, want: map[string]interface{}{}}, + {toParse: `[]`, want: []interface{}(nil)}, + + {toParse: `{"a": "b"}`, want: map[string]interface{}{"a": "b"}}, + {toParse: `[5]`, want: []interface{}{float64(5)}}, + + {toParse: `{"a":5 , "b" : "string"}`, want: map[string]interface{}{"a": float64(5), "b": "string"}}, + {toParse: `["a", 5 , null, true]`, want: []interface{}{"a", float64(5), nil, true}}, + + {toParse: `{"a" "b"}`, wantError: true}, + {toParse: `{"a": "b",}`, wantError: true}, + {toParse: `{"a":"b","c" "b"}`, wantError: true}, + {toParse: `{"a": "b","c":"d",}`, wantError: true}, + {toParse: `{,}`, wantError: true}, + + {toParse: `[1, 2,]`, wantError: true}, + {toParse: `[1 2]`, wantError: true}, + {toParse: `[,]`, wantError: true}, + } { + l := Lexer{Data: []byte(test.toParse)} + + got := l.Interface() + if !reflect.DeepEqual(got, test.want) { + t.Errorf("[%d, %q] Interface() = %v; want %v", i, test.toParse, got, test.want) + } + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] Interface() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] Interface() ok; want error", i, test.toParse) + } + } +} + +func TestConsumed(t *testing.T) { + for i, test := range []struct { + toParse string + wantError bool + }{ + {toParse: "", wantError: false}, + {toParse: " ", wantError: false}, + {toParse: "\r\n", wantError: false}, + {toParse: "\t\t", wantError: false}, + + {toParse: "{", wantError: true}, + } { + l := Lexer{Data: []byte(test.toParse)} + l.Consumed() + + err := l.Error() + if err != nil && !test.wantError { + t.Errorf("[%d, %q] Consumed() error: %v", i, test.toParse, err) + } else if err == nil && test.wantError { + t.Errorf("[%d, %q] Consumed() ok; want error", i, test.toParse) + } + } +} diff --git a/vendor/github.com/mailru/easyjson/jwriter/writer.go b/vendor/github.com/mailru/easyjson/jwriter/writer.go new file mode 100644 index 00000000..04bfddf7 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/jwriter/writer.go @@ -0,0 +1,302 @@ +// Package jwriter contains a JSON writer. +package jwriter + +import ( + "encoding/base64" + "io" + "strconv" + "unicode/utf8" + + "github.com/mailru/easyjson/buffer" +) + +// Flags describe various encoding options. The behavior may be actually implemented in the encoder, but +// Flags field in Writer is used to set and pass them around. +type Flags int + +const ( + NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. + NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. +) + +// Writer is a JSON writer. +type Writer struct { + Flags Flags + + Error error + Buffer buffer.Buffer + NoEscapeHTML bool +} + +// Size returns the size of the data that was written out. +func (w *Writer) Size() int { + return w.Buffer.Size() +} + +// DumpTo outputs the data to given io.Writer, resetting the buffer. +func (w *Writer) DumpTo(out io.Writer) (written int, err error) { + return w.Buffer.DumpTo(out) +} + +// BuildBytes returns writer data as a single byte slice. +func (w *Writer) BuildBytes() ([]byte, error) { + if w.Error != nil { + return nil, w.Error + } + + return w.Buffer.BuildBytes(), nil +} + +// RawByte appends raw binary data to the buffer. +func (w *Writer) RawByte(c byte) { + w.Buffer.AppendByte(c) +} + +// RawByte appends raw binary data to the buffer. +func (w *Writer) RawString(s string) { + w.Buffer.AppendString(s) +} + +// RawByte appends raw binary data to the buffer or sets the error if it is given. Useful for +// calling with results of MarshalJSON-like functions. +func (w *Writer) Raw(data []byte, err error) { + switch { + case w.Error != nil: + return + case err != nil: + w.Error = err + case len(data) > 0: + w.Buffer.AppendBytes(data) + default: + w.RawString("null") + } +} + +// Base64Bytes appends data to the buffer after base64 encoding it +func (w *Writer) Base64Bytes(data []byte) { + if data == nil { + w.Buffer.AppendString("null") + return + } + w.Buffer.AppendByte('"') + dst := make([]byte, base64.StdEncoding.EncodedLen(len(data))) + base64.StdEncoding.Encode(dst, data) + w.Buffer.AppendBytes(dst) + w.Buffer.AppendByte('"') +} + +func (w *Writer) Uint8(n uint8) { + w.Buffer.EnsureSpace(3) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) +} + +func (w *Writer) Uint16(n uint16) { + w.Buffer.EnsureSpace(5) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) +} + +func (w *Writer) Uint32(n uint32) { + w.Buffer.EnsureSpace(10) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) +} + +func (w *Writer) Uint(n uint) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) +} + +func (w *Writer) Uint64(n uint64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) +} + +func (w *Writer) Int8(n int8) { + w.Buffer.EnsureSpace(4) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) +} + +func (w *Writer) Int16(n int16) { + w.Buffer.EnsureSpace(6) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) +} + +func (w *Writer) Int32(n int32) { + w.Buffer.EnsureSpace(11) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) +} + +func (w *Writer) Int(n int) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) +} + +func (w *Writer) Int64(n int64) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) +} + +func (w *Writer) Uint8Str(n uint8) { + w.Buffer.EnsureSpace(3) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Uint16Str(n uint16) { + w.Buffer.EnsureSpace(5) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Uint32Str(n uint32) { + w.Buffer.EnsureSpace(10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) UintStr(n uint) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Uint64Str(n uint64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Int8Str(n int8) { + w.Buffer.EnsureSpace(4) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Int16Str(n int16) { + w.Buffer.EnsureSpace(6) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Int32Str(n int32) { + w.Buffer.EnsureSpace(11) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) IntStr(n int) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Int64Str(n int64) { + w.Buffer.EnsureSpace(21) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + +func (w *Writer) Float32(n float32) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) +} + +func (w *Writer) Float64(n float64) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) +} + +func (w *Writer) Bool(v bool) { + w.Buffer.EnsureSpace(5) + if v { + w.Buffer.Buf = append(w.Buffer.Buf, "true"...) + } else { + w.Buffer.Buf = append(w.Buffer.Buf, "false"...) + } +} + +const chars = "0123456789abcdef" + +func isNotEscapedSingleChar(c byte, escapeHTML bool) bool { + // Note: might make sense to use a table if there are more chars to escape. With 4 chars + // it benchmarks the same. + if escapeHTML { + return c != '<' && c != '>' && c != '&' && c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf + } else { + return c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf + } +} + +func (w *Writer) String(s string) { + w.Buffer.AppendByte('"') + + // Portions of the string that contain no escapes are appended as + // byte slices. + + p := 0 // last non-escape symbol + + for i := 0; i < len(s); { + c := s[i] + + if isNotEscapedSingleChar(c, !w.NoEscapeHTML) { + // single-width character, no escaping is required + i++ + continue + } else if c < utf8.RuneSelf { + // single-with character, need to escape + w.Buffer.AppendString(s[p:i]) + switch c { + case '\t': + w.Buffer.AppendString(`\t`) + case '\r': + w.Buffer.AppendString(`\r`) + case '\n': + w.Buffer.AppendString(`\n`) + case '\\': + w.Buffer.AppendString(`\\`) + case '"': + w.Buffer.AppendString(`\"`) + default: + w.Buffer.AppendString(`\u00`) + w.Buffer.AppendByte(chars[c>>4]) + w.Buffer.AppendByte(chars[c&0xf]) + } + + i++ + p = i + continue + } + + // broken utf + runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) + if runeValue == utf8.RuneError && runeWidth == 1 { + w.Buffer.AppendString(s[p:i]) + w.Buffer.AppendString(`\ufffd`) + i++ + p = i + continue + } + + // jsonp stuff - tab separator and line separator + if runeValue == '\u2028' || runeValue == '\u2029' { + w.Buffer.AppendString(s[p:i]) + w.Buffer.AppendString(`\u202`) + w.Buffer.AppendByte(chars[runeValue&0xf]) + i += runeWidth + p = i + continue + } + i += runeWidth + } + w.Buffer.AppendString(s[p:]) + w.Buffer.AppendByte('"') +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Bool.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Bool.go new file mode 100644 index 00000000..89e61326 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Bool.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Bool struct { + V bool + Defined bool +} + +// Creates an optional type with a given value. +func OBool(v bool) Bool { + return Bool{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Bool) Get(deflt bool) bool { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Bool) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Bool(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Bool) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Bool{} + } else { + v.V = l.Bool() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Bool) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Bool) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Bool) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Bool) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Float32.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Float32.go new file mode 100644 index 00000000..93ade1c7 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Float32.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Float32 struct { + V float32 + Defined bool +} + +// Creates an optional type with a given value. +func OFloat32(v float32) Float32 { + return Float32{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Float32) Get(deflt float32) float32 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Float32) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Float32(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Float32) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Float32{} + } else { + v.V = l.Float32() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Float32) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Float32) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Float32) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Float32) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Float64.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Float64.go new file mode 100644 index 00000000..90af91b0 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Float64.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Float64 struct { + V float64 + Defined bool +} + +// Creates an optional type with a given value. +func OFloat64(v float64) Float64 { + return Float64{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Float64) Get(deflt float64) float64 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Float64) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Float64(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Float64) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Float64{} + } else { + v.V = l.Float64() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Float64) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Float64) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Float64) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Float64) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Int.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int.go new file mode 100644 index 00000000..71e74e83 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int struct { + V int + Defined bool +} + +// Creates an optional type with a given value. +func OInt(v int) Int { + return Int{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int) Get(deflt int) int { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int{} + } else { + v.V = l.Int() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Int16.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int16.go new file mode 100644 index 00000000..987e3df6 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int16.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int16 struct { + V int16 + Defined bool +} + +// Creates an optional type with a given value. +func OInt16(v int16) Int16 { + return Int16{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int16) Get(deflt int16) int16 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int16) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int16(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int16) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int16{} + } else { + v.V = l.Int16() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int16) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int16) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int16) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int16) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Int32.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int32.go new file mode 100644 index 00000000..e5f30d8c --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int32.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int32 struct { + V int32 + Defined bool +} + +// Creates an optional type with a given value. +func OInt32(v int32) Int32 { + return Int32{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int32) Get(deflt int32) int32 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int32) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int32(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int32) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int32{} + } else { + v.V = l.Int32() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int32) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int32) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int32) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int32) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Int64.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int64.go new file mode 100644 index 00000000..ff67a335 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int64.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int64 struct { + V int64 + Defined bool +} + +// Creates an optional type with a given value. +func OInt64(v int64) Int64 { + return Int64{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int64) Get(deflt int64) int64 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int64) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int64(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int64) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int64{} + } else { + v.V = l.Int64() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int64) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int64) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int64) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int64) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Int8.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int8.go new file mode 100644 index 00000000..41312d17 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Int8.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Int8 struct { + V int8 + Defined bool +} + +// Creates an optional type with a given value. +func OInt8(v int8) Int8 { + return Int8{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Int8) Get(deflt int8) int8 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Int8) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Int8(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Int8) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Int8{} + } else { + v.V = l.Int8() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int8) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Int8) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Int8) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Int8) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_String.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_String.go new file mode 100644 index 00000000..3d818fa3 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_String.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type String struct { + V string + Defined bool +} + +// Creates an optional type with a given value. +func OString(v string) String { + return String{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v String) Get(deflt string) string { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v String) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.String(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *String) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = String{} + } else { + v.V = l.String() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *String) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *String) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v String) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v String) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint.go new file mode 100644 index 00000000..367db675 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint struct { + V uint + Defined bool +} + +// Creates an optional type with a given value. +func OUint(v uint) Uint { + return Uint{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint) Get(deflt uint) uint { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint{} + } else { + v.V = l.Uint() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint16.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint16.go new file mode 100644 index 00000000..6abc71dd --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint16.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint16 struct { + V uint16 + Defined bool +} + +// Creates an optional type with a given value. +func OUint16(v uint16) Uint16 { + return Uint16{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint16) Get(deflt uint16) uint16 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint16) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint16(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint16) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint16{} + } else { + v.V = l.Uint16() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint16) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint16) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint16) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint16) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint32.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint32.go new file mode 100644 index 00000000..490945c2 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint32.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint32 struct { + V uint32 + Defined bool +} + +// Creates an optional type with a given value. +func OUint32(v uint32) Uint32 { + return Uint32{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint32) Get(deflt uint32) uint32 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint32) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint32(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint32) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint32{} + } else { + v.V = l.Uint32() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint32) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint32) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint32) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint32) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint64.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint64.go new file mode 100644 index 00000000..37d2d418 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint64.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint64 struct { + V uint64 + Defined bool +} + +// Creates an optional type with a given value. +func OUint64(v uint64) Uint64 { + return Uint64{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint64) Get(deflt uint64) uint64 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint64) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint64(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint64) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint64{} + } else { + v.V = l.Uint64() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint64) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint64) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint64) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint64) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint8.go b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint8.go new file mode 100644 index 00000000..55c4cdba --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/gotemplate_Uint8.go @@ -0,0 +1,79 @@ +// generated by gotemplate + +package opt + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Uint8 struct { + V uint8 + Defined bool +} + +// Creates an optional type with a given value. +func OUint8(v uint8) Uint8 { + return Uint8{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Uint8) Get(deflt uint8) uint8 { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Uint8) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Uint8(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Uint8) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Uint8{} + } else { + v.V = l.Uint8() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint8) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Uint8) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Uint8) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Uint8) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/optional/opt.go b/vendor/github.com/mailru/easyjson/opt/optional/opt.go new file mode 100644 index 00000000..6d3a0798 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/optional/opt.go @@ -0,0 +1,80 @@ +// +build none + +package optional + +import ( + "fmt" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// template type Optional(A) +type A int + +// A 'gotemplate'-based type for providing optional semantics without using pointers. +type Optional struct { + V A + Defined bool +} + +// Creates an optional type with a given value. +func OOptional(v A) Optional { + return Optional{V: v, Defined: true} +} + +// Get returns the value or given default in the case the value is undefined. +func (v Optional) Get(deflt A) A { + if !v.Defined { + return deflt + } + return v.V +} + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v Optional) MarshalEasyJSON(w *jwriter.Writer) { + if v.Defined { + w.Optional(v.V) + } else { + w.RawString("null") + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *Optional) UnmarshalEasyJSON(l *jlexer.Lexer) { + if l.IsNull() { + l.Skip() + *v = Optional{} + } else { + v.V = l.Optional() + v.Defined = true + } +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Optional) MarshalJSON() ([]byte, error) { + w := jwriter.Writer{} + v.MarshalEasyJSON(&w) + return w.Buffer.BuildBytes(), w.Error +} + +// MarshalJSON implements a standard json marshaler interface. +func (v *Optional) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{} + v.UnmarshalEasyJSON(&l) + return l.Error() +} + +// IsDefined returns whether the value is defined, a function is required so that it can +// be used in an interface. +func (v Optional) IsDefined() bool { + return v.Defined +} + +// String implements a stringer interface using fmt.Sprint for the value. +func (v Optional) String() string { + if !v.Defined { + return "" + } + return fmt.Sprint(v.V) +} diff --git a/vendor/github.com/mailru/easyjson/opt/opts.go b/vendor/github.com/mailru/easyjson/opt/opts.go new file mode 100644 index 00000000..3617f7f9 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/opt/opts.go @@ -0,0 +1,22 @@ +package opt + +//go:generate sed -i "s/\\+build none/generated by gotemplate/" optional/opt.go +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int(int) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint(uint) + +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int8(int8) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int16(int16) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int32(int32) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Int64(int64) + +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint8(uint8) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint16(uint16) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint32(uint32) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Uint64(uint64) + +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Float32(float32) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Float64(float64) + +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" Bool(bool) +//go:generate gotemplate "github.com/mailru/easyjson/opt/optional" String(string) +//go:generate sed -i "s/generated by gotemplate/+build none/" optional/opt.go diff --git a/vendor/github.com/mailru/easyjson/parser/parser.go b/vendor/github.com/mailru/easyjson/parser/parser.go new file mode 100644 index 00000000..1c0b94ca --- /dev/null +++ b/vendor/github.com/mailru/easyjson/parser/parser.go @@ -0,0 +1,91 @@ +package parser + +import ( + "go/ast" + "go/parser" + "go/token" + "strings" +) + +const structComment = "easyjson:json" + +type Parser struct { + PkgPath string + PkgName string + StructNames []string + AllStructs bool +} + +type visitor struct { + *Parser + + name string + explicit bool +} + +func (p *Parser) needType(comments string) bool { + for _, v := range strings.Split(comments, "\n") { + if strings.HasPrefix(v, structComment) { + return true + } + } + return false +} + +func (v *visitor) Visit(n ast.Node) (w ast.Visitor) { + switch n := n.(type) { + case *ast.Package: + return v + case *ast.File: + v.PkgName = n.Name.String() + return v + + case *ast.GenDecl: + v.explicit = v.needType(n.Doc.Text()) + + if !v.explicit && !v.AllStructs { + return nil + } + return v + case *ast.TypeSpec: + v.name = n.Name.String() + + // Allow to specify non-structs explicitly independent of '-all' flag. + if v.explicit { + v.StructNames = append(v.StructNames, v.name) + return nil + } + return v + case *ast.StructType: + v.StructNames = append(v.StructNames, v.name) + return nil + } + return nil +} + +func (p *Parser) Parse(fname string, isDir bool) error { + var err error + if p.PkgPath, err = getPkgPath(fname, isDir); err != nil { + return err + } + + fset := token.NewFileSet() + if isDir { + packages, err := parser.ParseDir(fset, fname, nil, parser.ParseComments) + if err != nil { + return err + } + + for _, pckg := range packages { + ast.Walk(&visitor{Parser: p}, pckg) + } + } else { + f, err := parser.ParseFile(fset, fname, nil, parser.ParseComments) + if err != nil { + return err + } + + ast.Walk(&visitor{Parser: p}, f) + } + return nil +} diff --git a/vendor/github.com/mailru/easyjson/parser/parser_unix.go b/vendor/github.com/mailru/easyjson/parser/parser_unix.go new file mode 100644 index 00000000..a1b9d84d --- /dev/null +++ b/vendor/github.com/mailru/easyjson/parser/parser_unix.go @@ -0,0 +1,33 @@ +// +build !windows + +package parser + +import ( + "fmt" + "os" + "path" + "strings" +) + +func getPkgPath(fname string, isDir bool) (string, error) { + if !path.IsAbs(fname) { + pwd, err := os.Getwd() + if err != nil { + return "", err + } + fname = path.Join(pwd, fname) + } + + for _, p := range strings.Split(os.Getenv("GOPATH"), ":") { + prefix := path.Join(p, "src") + "/" + if rel := strings.TrimPrefix(fname, prefix); rel != fname { + if !isDir { + return path.Dir(rel), nil + } else { + return path.Clean(rel), nil + } + } + } + + return "", fmt.Errorf("file '%v' is not in GOPATH", fname) +} diff --git a/vendor/github.com/mailru/easyjson/parser/parser_windows.go b/vendor/github.com/mailru/easyjson/parser/parser_windows.go new file mode 100644 index 00000000..64974aa9 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/parser/parser_windows.go @@ -0,0 +1,37 @@ +package parser + +import ( + "fmt" + "os" + "path" + "strings" +) + +func normalizePath(path string) string { + return strings.Replace(path, "\\", "/", -1) +} + +func getPkgPath(fname string, isDir bool) (string, error) { + if !path.IsAbs(fname) { + pwd, err := os.Getwd() + if err != nil { + return "", err + } + fname = path.Join(pwd, fname) + } + + fname = normalizePath(fname) + + for _, p := range strings.Split(os.Getenv("GOPATH"), ";") { + prefix := path.Join(normalizePath(p), "src") + "/" + if rel := strings.TrimPrefix(fname, prefix); rel != fname { + if !isDir { + return path.Dir(rel), nil + } else { + return path.Clean(rel), nil + } + } + } + + return "", fmt.Errorf("file '%v' is not in GOPATH", fname) +} diff --git a/vendor/github.com/mailru/easyjson/raw.go b/vendor/github.com/mailru/easyjson/raw.go new file mode 100644 index 00000000..737c73a8 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/raw.go @@ -0,0 +1,45 @@ +package easyjson + +import ( + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// RawMessage is a raw piece of JSON (number, string, bool, object, array or null) that is extracted +// without parsing and output as is during marshalling. +type RawMessage []byte + +// MarshalEasyJSON does JSON marshaling using easyjson interface. +func (v *RawMessage) MarshalEasyJSON(w *jwriter.Writer) { + if len(*v) == 0 { + w.RawString("null") + } else { + w.Raw(*v, nil) + } +} + +// UnmarshalEasyJSON does JSON unmarshaling using easyjson interface. +func (v *RawMessage) UnmarshalEasyJSON(l *jlexer.Lexer) { + *v = RawMessage(l.Raw()) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler interface. +func (v *RawMessage) UnmarshalJSON(data []byte) error { + *v = data + return nil +} + +var nullBytes = []byte("null") + +// MarshalJSON implements encoding/json.Marshaler interface. +func (v RawMessage) MarshalJSON() ([]byte, error) { + if len(v) == 0 { + return nullBytes, nil + } + return v, nil +} + +// IsDefined is required for integration with omitempty easyjson logic. +func (v *RawMessage) IsDefined() bool { + return len(*v) > 0 +} diff --git a/vendor/github.com/mailru/easyjson/tests/basic_test.go b/vendor/github.com/mailru/easyjson/tests/basic_test.go new file mode 100644 index 00000000..4e7c20cd --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/basic_test.go @@ -0,0 +1,221 @@ +package tests + +import ( + "reflect" + "testing" + + "encoding/json" + + "github.com/mailru/easyjson" + "github.com/mailru/easyjson/jwriter" +) + +type testType interface { + json.Marshaler + json.Unmarshaler +} + +var testCases = []struct { + Decoded testType + Encoded string +}{ + {&primitiveTypesValue, primitiveTypesString}, + {&namedPrimitiveTypesValue, namedPrimitiveTypesString}, + {&structsValue, structsString}, + {&omitEmptyValue, omitEmptyString}, + {&snakeStructValue, snakeStructString}, + {&omitEmptyDefaultValue, omitEmptyDefaultString}, + {&optsValue, optsString}, + {&rawValue, rawString}, + {&stdMarshalerValue, stdMarshalerString}, + {&unexportedStructValue, unexportedStructString}, + {&excludedFieldValue, excludedFieldString}, + {&sliceValue, sliceString}, + {&arrayValue, arrayString}, + {&mapsValue, mapsString}, + {&deepNestValue, deepNestString}, + {&IntsValue, IntsString}, + {&mapStringStringValue, mapStringStringString}, + {&namedTypeValue, namedTypeValueString}, +} + +func TestMarshal(t *testing.T) { + for i, test := range testCases { + data, err := test.Decoded.MarshalJSON() + if err != nil { + t.Errorf("[%d, %T] MarshalJSON() error: %v", i, test.Decoded, err) + } + + got := string(data) + if got != test.Encoded { + t.Errorf("[%d, %T] MarshalJSON(): got \n%v\n\t\t want \n%v", i, test.Decoded, got, test.Encoded) + } + } +} + +func TestUnmarshal(t *testing.T) { + for i, test := range testCases { + v1 := reflect.New(reflect.TypeOf(test.Decoded).Elem()).Interface() + v := v1.(testType) + + err := v.UnmarshalJSON([]byte(test.Encoded)) + if err != nil { + t.Errorf("[%d, %T] UnmarshalJSON() error: %v", i, test.Decoded, err) + } + + if !reflect.DeepEqual(v, test.Decoded) { + t.Errorf("[%d, %T] UnmarshalJSON(): got \n%+v\n\t\t want \n%+v", i, test.Decoded, v, test.Decoded) + } + } +} + +func TestRawMessageSTD(t *testing.T) { + type T struct { + F easyjson.RawMessage + Fnil easyjson.RawMessage + } + + val := T{F: easyjson.RawMessage([]byte(`"test"`))} + str := `{"F":"test","Fnil":null}` + + data, err := json.Marshal(val) + if err != nil { + t.Errorf("json.Marshal() error: %v", err) + } + got := string(data) + if got != str { + t.Errorf("json.Marshal() = %v; want %v", got, str) + } + + wantV := T{F: easyjson.RawMessage([]byte(`"test"`)), Fnil: easyjson.RawMessage([]byte("null"))} + var gotV T + + err = json.Unmarshal([]byte(str), &gotV) + if err != nil { + t.Errorf("json.Unmarshal() error: %v", err) + } + if !reflect.DeepEqual(gotV, wantV) { + t.Errorf("json.Unmarshal() = %v; want %v", gotV, wantV) + } +} + +func TestParseNull(t *testing.T) { + var got, want SubStruct + if err := easyjson.Unmarshal([]byte("null"), &got); err != nil { + t.Errorf("Unmarshal() error: %v", err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf("Unmarshal() = %+v; want %+v", got, want) + } +} + +var testSpecialCases = []struct { + EncodedString string + Value string +}{ + {`"Username \u003cuser@example.com\u003e"`, `Username `}, + {`"Username\ufffd"`, "Username\xc5"}, + {`"тестzтест"`, "тестzтест"}, + {`"тест\ufffdтест"`, "тест\xc5тест"}, + {`"绿茶"`, "绿茶"}, + {`"绿\ufffd茶"`, "绿\xc5茶"}, + {`"тест\u2028"`, "тест\xE2\x80\xA8"}, + {`"\\\r\n\t\""`, "\\\r\n\t\""}, + {`"ü"`, "ü"}, +} + +func TestSpecialCases(t *testing.T) { + for i, test := range testSpecialCases { + w := jwriter.Writer{} + w.String(test.Value) + got := string(w.Buffer.BuildBytes()) + if got != test.EncodedString { + t.Errorf("[%d] Encoded() = %+v; want %+v", i, got, test.EncodedString) + } + } +} + +func TestOverflowArray(t *testing.T) { + var a Arrays + err := easyjson.Unmarshal([]byte(arrayOverflowString), &a) + if err != nil { + t.Error(err) + } + if a != arrayValue { + t.Errorf("Unmarshal(%v) = %+v; want %+v", arrayOverflowString, a, arrayValue) + } +} + +func TestUnderflowArray(t *testing.T) { + var a Arrays + err := easyjson.Unmarshal([]byte(arrayUnderflowString), &a) + if err != nil { + t.Error(err) + } + if a != arrayUnderflowValue { + t.Errorf("Unmarshal(%v) = %+v; want %+v", arrayUnderflowString, a, arrayUnderflowValue) + } +} + +func TestEncodingFlags(t *testing.T) { + for i, test := range []struct { + Flags jwriter.Flags + In easyjson.Marshaler + Want string + }{ + {0, EncodingFlagsTestMap{}, `{"F":null}`}, + {0, EncodingFlagsTestSlice{}, `{"F":null}`}, + {jwriter.NilMapAsEmpty, EncodingFlagsTestMap{}, `{"F":{}}`}, + {jwriter.NilSliceAsEmpty, EncodingFlagsTestSlice{}, `{"F":[]}`}, + } { + w := &jwriter.Writer{Flags: test.Flags} + test.In.MarshalEasyJSON(w) + + data, err := w.BuildBytes() + if err != nil { + t.Errorf("[%v] easyjson.Marshal(%+v) error: %v", i, test.In, err) + } + + v := string(data) + if v != test.Want { + t.Errorf("[%v] easyjson.Marshal(%+v) = %v; want %v", i, test.In, v, test.Want) + } + } + +} + +func TestNestedEasyJsonMarshal(t *testing.T) { + n := map[string]*NestedEasyMarshaler{ + "Value": {}, + "Slice1": {}, + "Slice2": {}, + "Map1": {}, + "Map2": {}, + } + + ni := NestedInterfaces{ + Value: n["Value"], + Slice: []interface{}{n["Slice1"], n["Slice2"]}, + Map: map[string]interface{}{"1": n["Map1"], "2": n["Map2"]}, + } + easyjson.Marshal(ni) + + for k, v := range n { + if !v.EasilyMarshaled { + t.Errorf("Nested interface %s wasn't easily marshaled", k) + } + } +} + +func TestUnmarshalStructWithEmbeddedPtrStruct(t *testing.T) { + var s = StructWithInterface{Field2: &EmbeddedStruct{}} + var err error + err = easyjson.Unmarshal([]byte(structWithInterfaceString), &s) + if err != nil { + t.Errorf("easyjson.Unmarshal() error: %v", err) + } + if !reflect.DeepEqual(s, structWithInterfaceValueFilled) { + t.Errorf("easyjson.Unmarshal() = %#v; want %#v", s, structWithInterfaceValueFilled) + } +} diff --git a/vendor/github.com/mailru/easyjson/tests/data.go b/vendor/github.com/mailru/easyjson/tests/data.go new file mode 100644 index 00000000..b13bcd82 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/data.go @@ -0,0 +1,650 @@ +package tests + +import ( + "fmt" + "math" + "time" + + "github.com/mailru/easyjson" + "github.com/mailru/easyjson/opt" +) + +type PrimitiveTypes struct { + String string + Bool bool + + Int int + Int8 int8 + Int16 int16 + Int32 int32 + Int64 int64 + + Uint uint + Uint8 uint8 + Uint16 uint16 + Uint32 uint32 + Uint64 uint64 + + IntString int `json:",string"` + Int8String int8 `json:",string"` + Int16String int16 `json:",string"` + Int32String int32 `json:",string"` + Int64String int64 `json:",string"` + + UintString uint `json:",string"` + Uint8String uint8 `json:",string"` + Uint16String uint16 `json:",string"` + Uint32String uint32 `json:",string"` + Uint64String uint64 `json:",string"` + + Float32 float32 + Float64 float64 + + Ptr *string + PtrNil *string +} + +var str = "bla" + +var primitiveTypesValue = PrimitiveTypes{ + String: "test", Bool: true, + + Int: math.MinInt32, + Int8: math.MinInt8, + Int16: math.MinInt16, + Int32: math.MinInt32, + Int64: math.MinInt64, + + Uint: math.MaxUint32, + Uint8: math.MaxUint8, + Uint16: math.MaxUint16, + Uint32: math.MaxUint32, + Uint64: math.MaxUint64, + + IntString: math.MinInt32, + Int8String: math.MinInt8, + Int16String: math.MinInt16, + Int32String: math.MinInt32, + Int64String: math.MinInt64, + + UintString: math.MaxUint32, + Uint8String: math.MaxUint8, + Uint16String: math.MaxUint16, + Uint32String: math.MaxUint32, + Uint64String: math.MaxUint64, + + Float32: 1.5, + Float64: math.MaxFloat64, + + Ptr: &str, +} + +var primitiveTypesString = "{" + + `"String":"test","Bool":true,` + + + `"Int":` + fmt.Sprint(math.MinInt32) + `,` + + `"Int8":` + fmt.Sprint(math.MinInt8) + `,` + + `"Int16":` + fmt.Sprint(math.MinInt16) + `,` + + `"Int32":` + fmt.Sprint(math.MinInt32) + `,` + + `"Int64":` + fmt.Sprint(int64(math.MinInt64)) + `,` + + + `"Uint":` + fmt.Sprint(math.MaxUint32) + `,` + + `"Uint8":` + fmt.Sprint(math.MaxUint8) + `,` + + `"Uint16":` + fmt.Sprint(math.MaxUint16) + `,` + + `"Uint32":` + fmt.Sprint(math.MaxUint32) + `,` + + `"Uint64":` + fmt.Sprint(uint64(math.MaxUint64)) + `,` + + + `"IntString":"` + fmt.Sprint(math.MinInt32) + `",` + + `"Int8String":"` + fmt.Sprint(math.MinInt8) + `",` + + `"Int16String":"` + fmt.Sprint(math.MinInt16) + `",` + + `"Int32String":"` + fmt.Sprint(math.MinInt32) + `",` + + `"Int64String":"` + fmt.Sprint(int64(math.MinInt64)) + `",` + + + `"UintString":"` + fmt.Sprint(math.MaxUint32) + `",` + + `"Uint8String":"` + fmt.Sprint(math.MaxUint8) + `",` + + `"Uint16String":"` + fmt.Sprint(math.MaxUint16) + `",` + + `"Uint32String":"` + fmt.Sprint(math.MaxUint32) + `",` + + `"Uint64String":"` + fmt.Sprint(uint64(math.MaxUint64)) + `",` + + + `"Float32":` + fmt.Sprint(1.5) + `,` + + `"Float64":` + fmt.Sprint(math.MaxFloat64) + `,` + + + `"Ptr":"bla",` + + `"PtrNil":null` + + + "}" + +type ( + NamedString string + NamedBool bool + + NamedInt int + NamedInt8 int8 + NamedInt16 int16 + NamedInt32 int32 + NamedInt64 int64 + + NamedUint uint + NamedUint8 uint8 + NamedUint16 uint16 + NamedUint32 uint32 + NamedUint64 uint64 + + NamedFloat32 float32 + NamedFloat64 float64 + + NamedStrPtr *string +) + +type NamedPrimitiveTypes struct { + String NamedString + Bool NamedBool + + Int NamedInt + Int8 NamedInt8 + Int16 NamedInt16 + Int32 NamedInt32 + Int64 NamedInt64 + + Uint NamedUint + Uint8 NamedUint8 + Uint16 NamedUint16 + Uint32 NamedUint32 + Uint64 NamedUint64 + + Float32 NamedFloat32 + Float64 NamedFloat64 + + Ptr NamedStrPtr + PtrNil NamedStrPtr +} + +var namedPrimitiveTypesValue = NamedPrimitiveTypes{ + String: "test", + Bool: true, + + Int: math.MinInt32, + Int8: math.MinInt8, + Int16: math.MinInt16, + Int32: math.MinInt32, + Int64: math.MinInt64, + + Uint: math.MaxUint32, + Uint8: math.MaxUint8, + Uint16: math.MaxUint16, + Uint32: math.MaxUint32, + Uint64: math.MaxUint64, + + Float32: 1.5, + Float64: math.MaxFloat64, + + Ptr: NamedStrPtr(&str), +} + +var namedPrimitiveTypesString = "{" + + `"String":"test",` + + `"Bool":true,` + + + `"Int":` + fmt.Sprint(math.MinInt32) + `,` + + `"Int8":` + fmt.Sprint(math.MinInt8) + `,` + + `"Int16":` + fmt.Sprint(math.MinInt16) + `,` + + `"Int32":` + fmt.Sprint(math.MinInt32) + `,` + + `"Int64":` + fmt.Sprint(int64(math.MinInt64)) + `,` + + + `"Uint":` + fmt.Sprint(math.MaxUint32) + `,` + + `"Uint8":` + fmt.Sprint(math.MaxUint8) + `,` + + `"Uint16":` + fmt.Sprint(math.MaxUint16) + `,` + + `"Uint32":` + fmt.Sprint(math.MaxUint32) + `,` + + `"Uint64":` + fmt.Sprint(uint64(math.MaxUint64)) + `,` + + + `"Float32":` + fmt.Sprint(1.5) + `,` + + `"Float64":` + fmt.Sprint(math.MaxFloat64) + `,` + + + `"Ptr":"bla",` + + `"PtrNil":null` + + "}" + +type SubStruct struct { + Value string + Value2 string + unexpored bool +} + +type SubP struct { + V string +} + +type SubStructAlias SubStruct + +type Structs struct { + SubStruct + *SubP + + Value2 int + + Sub1 SubStruct `json:"substruct"` + Sub2 *SubStruct + SubNil *SubStruct + + SubSlice []SubStruct + SubSliceNil []SubStruct + + SubPtrSlice []*SubStruct + SubPtrSliceNil []*SubStruct + + SubA1 SubStructAlias + SubA2 *SubStructAlias + + Anonymous struct { + V string + I int + } + Anonymous1 *struct { + V string + } + + AnonymousSlice []struct{ V int } + AnonymousPtrSlice []*struct{ V int } + + Slice []string + + unexported bool +} + +var structsValue = Structs{ + SubStruct: SubStruct{Value: "test"}, + SubP: &SubP{V: "subp"}, + + Value2: 5, + + Sub1: SubStruct{Value: "test1", Value2: "v"}, + Sub2: &SubStruct{Value: "test2", Value2: "v2"}, + + SubSlice: []SubStruct{ + {Value: "s1"}, + {Value: "s2"}, + }, + + SubPtrSlice: []*SubStruct{ + {Value: "p1"}, + {Value: "p2"}, + }, + + SubA1: SubStructAlias{Value: "test3", Value2: "v3"}, + SubA2: &SubStructAlias{Value: "test4", Value2: "v4"}, + + Anonymous: struct { + V string + I int + }{V: "bla", I: 5}, + + Anonymous1: &struct { + V string + }{V: "bla1"}, + + AnonymousSlice: []struct{ V int }{{1}, {2}}, + AnonymousPtrSlice: []*struct{ V int }{{3}, {4}}, + + Slice: []string{"test5", "test6"}, +} + +var structsString = "{" + + `"Value2":5,` + + + `"substruct":{"Value":"test1","Value2":"v"},` + + `"Sub2":{"Value":"test2","Value2":"v2"},` + + `"SubNil":null,` + + + `"SubSlice":[{"Value":"s1","Value2":""},{"Value":"s2","Value2":""}],` + + `"SubSliceNil":null,` + + + `"SubPtrSlice":[{"Value":"p1","Value2":""},{"Value":"p2","Value2":""}],` + + `"SubPtrSliceNil":null,` + + + `"SubA1":{"Value":"test3","Value2":"v3"},` + + `"SubA2":{"Value":"test4","Value2":"v4"},` + + + `"Anonymous":{"V":"bla","I":5},` + + `"Anonymous1":{"V":"bla1"},` + + + `"AnonymousSlice":[{"V":1},{"V":2}],` + + `"AnonymousPtrSlice":[{"V":3},{"V":4}],` + + + `"Slice":["test5","test6"],` + + + // Embedded fields go last. + `"V":"subp",` + + `"Value":"test"` + + "}" + +type OmitEmpty struct { + // NOTE: first field is empty to test comma printing. + + StrE, StrNE string `json:",omitempty"` + PtrE, PtrNE *string `json:",omitempty"` + + IntNE int `json:"intField,omitempty"` + IntE int `json:",omitempty"` + + // NOTE: omitempty has no effect on non-pointer struct fields. + SubE, SubNE SubStruct `json:",omitempty"` + SubPE, SubPNE *SubStruct `json:",omitempty"` +} + +var omitEmptyValue = OmitEmpty{ + StrNE: "str", + PtrNE: &str, + IntNE: 6, + SubNE: SubStruct{Value: "1", Value2: "2"}, + SubPNE: &SubStruct{Value: "3", Value2: "4"}, +} + +var omitEmptyString = "{" + + `"StrNE":"str",` + + `"PtrNE":"bla",` + + `"intField":6,` + + `"SubE":{"Value":"","Value2":""},` + + `"SubNE":{"Value":"1","Value2":"2"},` + + `"SubPNE":{"Value":"3","Value2":"4"}` + + "}" + +type Opts struct { + StrNull opt.String + StrEmpty opt.String + Str opt.String + StrOmitempty opt.String `json:",omitempty"` + + IntNull opt.Int + IntZero opt.Int + Int opt.Int +} + +var optsValue = Opts{ + StrEmpty: opt.OString(""), + Str: opt.OString("test"), + + IntZero: opt.OInt(0), + Int: opt.OInt(5), +} + +var optsString = `{` + + `"StrNull":null,` + + `"StrEmpty":"",` + + `"Str":"test",` + + `"IntNull":null,` + + `"IntZero":0,` + + `"Int":5` + + `}` + +type Raw struct { + Field easyjson.RawMessage + Field2 string +} + +var rawValue = Raw{ + Field: []byte(`{"a" : "b"}`), + Field2: "test", +} + +var rawString = `{` + + `"Field":{"a" : "b"},` + + `"Field2":"test"` + + `}` + +type StdMarshaler struct { + T time.Time +} + +var stdMarshalerValue = StdMarshaler{T: time.Date(2016, 01, 02, 14, 15, 10, 0, time.UTC)} +var stdMarshalerString = `{"T":"2016-01-02T14:15:10Z"}` + +type unexportedStruct struct { + Value string +} + +var unexportedStructValue = unexportedStruct{"test"} +var unexportedStructString = `{"Value":"test"}` + +type ExcludedField struct { + Process bool `json:"process"` + DoNotProcess bool `json:"-"` + DoNotProcess1 bool `json:"-"` +} + +var excludedFieldValue = ExcludedField{ + Process: true, + DoNotProcess: false, + DoNotProcess1: false, +} +var excludedFieldString = `{"process":true}` + +type Slices struct { + ByteSlice []byte + EmptyByteSlice []byte + NilByteSlice []byte + IntSlice []int + EmptyIntSlice []int + NilIntSlice []int +} + +var sliceValue = Slices{ + ByteSlice: []byte("abc"), + EmptyByteSlice: []byte{}, + NilByteSlice: []byte(nil), + IntSlice: []int{1, 2, 3, 4, 5}, + EmptyIntSlice: []int{}, + NilIntSlice: []int(nil), +} + +var sliceString = `{` + + `"ByteSlice":"YWJj",` + + `"EmptyByteSlice":"",` + + `"NilByteSlice":null,` + + `"IntSlice":[1,2,3,4,5],` + + `"EmptyIntSlice":[],` + + `"NilIntSlice":null` + + `}` + +type Arrays struct { + ByteArray [3]byte + EmptyByteArray [0]byte + IntArray [5]int + EmptyIntArray [0]int +} + +var arrayValue = Arrays{ + ByteArray: [3]byte{'a', 'b', 'c'}, + EmptyByteArray: [0]byte{}, + IntArray: [5]int{1, 2, 3, 4, 5}, + EmptyIntArray: [0]int{}, +} + +var arrayString = `{` + + `"ByteArray":"YWJj",` + + `"EmptyByteArray":"",` + + `"IntArray":[1,2,3,4,5],` + + `"EmptyIntArray":[]` + + `}` + +var arrayOverflowString = `{` + + `"ByteArray":"YWJjbnNk",` + + `"EmptyByteArray":"YWJj",` + + `"IntArray":[1,2,3,4,5,6],` + + `"EmptyIntArray":[7,8]` + + `}` + +var arrayUnderflowValue = Arrays{ + ByteArray: [3]byte{'x', 0, 0}, + EmptyByteArray: [0]byte{}, + IntArray: [5]int{1, 2, 0, 0, 0}, + EmptyIntArray: [0]int{}, +} + +var arrayUnderflowString = `{` + + `"ByteArray":"eA==",` + + `"IntArray":[1,2]` + + `}` + +type Str string + +type Maps struct { + Map map[string]string + InterfaceMap map[string]interface{} + NilMap map[string]string + + CustomMap map[Str]Str +} + +var mapsValue = Maps{ + Map: map[string]string{"A": "b"}, // only one item since map iteration is randomized + InterfaceMap: map[string]interface{}{"G": float64(1)}, + + CustomMap: map[Str]Str{"c": "d"}, +} + +var mapsString = `{` + + `"Map":{"A":"b"},` + + `"InterfaceMap":{"G":1},` + + `"NilMap":null,` + + `"CustomMap":{"c":"d"}` + + `}` + +type NamedSlice []Str +type NamedMap map[Str]Str + +type DeepNest struct { + SliceMap map[Str][]Str + SliceMap1 map[Str][]Str + SliceMap2 map[Str][]Str + NamedSliceMap map[Str]NamedSlice + NamedMapMap map[Str]NamedMap + MapSlice []map[Str]Str + NamedSliceSlice []NamedSlice + NamedMapSlice []NamedMap + NamedStringSlice []NamedString +} + +var deepNestValue = DeepNest{ + SliceMap: map[Str][]Str{ + "testSliceMap": []Str{ + "0", + "1", + }, + }, + SliceMap1: map[Str][]Str{ + "testSliceMap1": []Str(nil), + }, + SliceMap2: map[Str][]Str{ + "testSliceMap2": []Str{}, + }, + NamedSliceMap: map[Str]NamedSlice{ + "testNamedSliceMap": NamedSlice{ + "2", + "3", + }, + }, + NamedMapMap: map[Str]NamedMap{ + "testNamedMapMap": NamedMap{ + "key1": "value1", + }, + }, + MapSlice: []map[Str]Str{ + map[Str]Str{ + "testMapSlice": "someValue", + }, + }, + NamedSliceSlice: []NamedSlice{ + NamedSlice{ + "someValue1", + "someValue2", + }, + NamedSlice{ + "someValue3", + "someValue4", + }, + }, + NamedMapSlice: []NamedMap{ + NamedMap{ + "key2": "value2", + }, + NamedMap{ + "key3": "value3", + }, + }, + NamedStringSlice: []NamedString{ + "value4", "value5", + }, +} + +var deepNestString = `{` + + `"SliceMap":{` + + `"testSliceMap":["0","1"]` + + `},` + + `"SliceMap1":{` + + `"testSliceMap1":null` + + `},` + + `"SliceMap2":{` + + `"testSliceMap2":[]` + + `},` + + `"NamedSliceMap":{` + + `"testNamedSliceMap":["2","3"]` + + `},` + + `"NamedMapMap":{` + + `"testNamedMapMap":{"key1":"value1"}` + + `},` + + `"MapSlice":[` + + `{"testMapSlice":"someValue"}` + + `],` + + `"NamedSliceSlice":[` + + `["someValue1","someValue2"],` + + `["someValue3","someValue4"]` + + `],` + + `"NamedMapSlice":[` + + `{"key2":"value2"},` + + `{"key3":"value3"}` + + `],` + + `"NamedStringSlice":["value4","value5"]` + + `}` + +//easyjson:json +type Ints []int + +var IntsValue = Ints{1, 2, 3, 4, 5} + +var IntsString = `[1,2,3,4,5]` + +//easyjson:json +type MapStringString map[string]string + +var mapStringStringValue = MapStringString{"a": "b"} + +var mapStringStringString = `{"a":"b"}` + +type RequiredOptionalStruct struct { + FirstName string `json:"first_name,required"` + Lastname string `json:"last_name"` +} + +//easyjson:json +type EncodingFlagsTestMap struct { + F map[string]string +} + +//easyjson:json +type EncodingFlagsTestSlice struct { + F []string +} + +type StructWithInterface struct { + Field1 int `json:"f1"` + Field2 interface{} `json:"f2"` + Field3 string `json:"f3"` +} + +type EmbeddedStruct struct { + Field1 int `json:"f1"` + Field2 string `json:"f2"` +} + +var structWithInterfaceString = `{"f1":1,"f2":{"f1":11,"f2":"22"},"f3":"3"}` +var structWithInterfaceValueFilled = StructWithInterface{1, &EmbeddedStruct{11, "22"}, "3"} diff --git a/vendor/github.com/mailru/easyjson/tests/errors.go b/vendor/github.com/mailru/easyjson/tests/errors.go new file mode 100644 index 00000000..2ec3299a --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/errors.go @@ -0,0 +1,23 @@ +package tests + +//easyjson:json +type ErrorIntSlice []int + +//easyjson:json +type ErrorBoolSlice []bool + +//easyjson:json +type ErrorUintSlice []uint + +//easyjson:json +type ErrorStruct struct { + Int int `json:"int"` + String string `json:"string"` + Slice []int `json:"slice"` + IntSlice []int `json:"int_slice"` +} + +type ErrorNestedStruct struct { + ErrorStruct ErrorStruct `json:"error_struct"` + Int int `json:"int"` +} diff --git a/vendor/github.com/mailru/easyjson/tests/errors_test.go b/vendor/github.com/mailru/easyjson/tests/errors_test.go new file mode 100644 index 00000000..756f7db6 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/errors_test.go @@ -0,0 +1,243 @@ +package tests + +import ( + "testing" + + "github.com/mailru/easyjson/jlexer" +) + +func TestMultipleErrorsInt(t *testing.T) { + for i, test := range []struct { + Data []byte + Offsets []int + }{ + { + Data: []byte(`[1, 2, 3, "4", "5"]`), + Offsets: []int{10, 15}, + }, + { + Data: []byte(`[1, {"2":"3"}, 3, "4"]`), + Offsets: []int{4, 18}, + }, + { + Data: []byte(`[1, "2", "3", "4", "5", "6"]`), + Offsets: []int{4, 9, 14, 19, 24}, + }, + { + Data: []byte(`[1, 2, 3, 4, "5"]`), + Offsets: []int{13}, + }, + { + Data: []byte(`[{"1": "2"}]`), + Offsets: []int{1}, + }, + } { + l := jlexer.Lexer{ + Data: test.Data, + UseMultipleErrors: true, + } + + var v ErrorIntSlice + + v.UnmarshalEasyJSON(&l) + + errors := l.GetNonFatalErrors() + + if len(errors) != len(test.Offsets) { + t.Errorf("[%d] TestMultipleErrorsInt(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) + return + } + + for ii, e := range errors { + if e.Offset != test.Offsets[ii] { + t.Errorf("[%d] TestMultipleErrorsInt(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) + } + } + } +} + +func TestMultipleErrorsBool(t *testing.T) { + for i, test := range []struct { + Data []byte + Offsets []int + }{ + { + Data: []byte(`[true, false, true, false]`), + }, + { + Data: []byte(`["test", "value", "lol", "1"]`), + Offsets: []int{1, 9, 18, 25}, + }, + { + Data: []byte(`[true, 42, {"a":"b", "c":"d"}, false]`), + Offsets: []int{7, 11}, + }, + } { + l := jlexer.Lexer{ + Data: test.Data, + UseMultipleErrors: true, + } + + var v ErrorBoolSlice + v.UnmarshalEasyJSON(&l) + + errors := l.GetNonFatalErrors() + + if len(errors) != len(test.Offsets) { + t.Errorf("[%d] TestMultipleErrorsBool(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) + return + } + for ii, e := range errors { + if e.Offset != test.Offsets[ii] { + t.Errorf("[%d] TestMultipleErrorsBool(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) + } + } + } +} + +func TestMultipleErrorsUint(t *testing.T) { + for i, test := range []struct { + Data []byte + Offsets []int + }{ + { + Data: []byte(`[42, 42, 42]`), + }, + { + Data: []byte(`[17, "42", 32]`), + Offsets: []int{5}, + }, + { + Data: []byte(`["zz", "zz"]`), + Offsets: []int{1, 7}, + }, + { + Data: []byte(`[{}, 42]`), + Offsets: []int{1}, + }, + } { + l := jlexer.Lexer{ + Data: test.Data, + UseMultipleErrors: true, + } + + var v ErrorUintSlice + v.UnmarshalEasyJSON(&l) + + errors := l.GetNonFatalErrors() + + if len(errors) != len(test.Offsets) { + t.Errorf("[%d] TestMultipleErrorsUint(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) + return + } + for ii, e := range errors { + if e.Offset != test.Offsets[ii] { + t.Errorf("[%d] TestMultipleErrorsUint(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) + } + } + } +} + +func TestMultipleErrorsStruct(t *testing.T) { + for i, test := range []struct { + Data []byte + Offsets []int + }{ + { + Data: []byte(`{"string": "test", "slice":[42, 42, 42], "int_slice":[1, 2, 3]}`), + }, + { + Data: []byte(`{"string": {"test": "test"}, "slice":[42, 42, 42], "int_slice":["1", 2, 3]}`), + Offsets: []int{11, 64}, + }, + { + Data: []byte(`{"slice": [42, 42], "string": {"test": "test"}, "int_slice":["1", "2", 3]}`), + Offsets: []int{30, 61, 66}, + }, + { + Data: []byte(`{"string": "test", "slice": {}}`), + Offsets: []int{28}, + }, + { + Data: []byte(`{"slice":5, "string" : "test"}`), + Offsets: []int{9}, + }, + { + Data: []byte(`{"slice" : "test", "string" : "test"}`), + Offsets: []int{11}, + }, + { + Data: []byte(`{"slice": "", "string" : {}, "int":{}}`), + Offsets: []int{10, 25, 35}, + }, + } { + l := jlexer.Lexer{ + Data: test.Data, + UseMultipleErrors: true, + } + var v ErrorStruct + v.UnmarshalEasyJSON(&l) + + errors := l.GetNonFatalErrors() + + if len(errors) != len(test.Offsets) { + t.Errorf("[%d] TestMultipleErrorsStruct(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) + return + } + for ii, e := range errors { + if e.Offset != test.Offsets[ii] { + t.Errorf("[%d] TestMultipleErrorsStruct(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) + } + } + } +} + +func TestMultipleErrorsNestedStruct(t *testing.T) { + for i, test := range []struct { + Data []byte + Offsets []int + }{ + { + Data: []byte(`{"error_struct":{}}`), + }, + { + Data: []byte(`{"error_struct":5}`), + Offsets: []int{16}, + }, + { + Data: []byte(`{"error_struct":[]}`), + Offsets: []int{16}, + }, + { + Data: []byte(`{"error_struct":{"int":{}}}`), + Offsets: []int{23}, + }, + { + Data: []byte(`{"error_struct":{"int_slice":{}}, "int":4}`), + Offsets: []int{29}, + }, + { + Data: []byte(`{"error_struct":{"int_slice":["1", 2, "3"]}, "int":[]}`), + Offsets: []int{30, 38, 51}, + }, + } { + l := jlexer.Lexer{ + Data: test.Data, + UseMultipleErrors: true, + } + var v ErrorNestedStruct + v.UnmarshalEasyJSON(&l) + + errors := l.GetNonFatalErrors() + + if len(errors) != len(test.Offsets) { + t.Errorf("[%d] TestMultipleErrorsNestedStruct(): errornum: want: %d, got %d", i, len(test.Offsets), len(errors)) + return + } + for ii, e := range errors { + if e.Offset != test.Offsets[ii] { + t.Errorf("[%d] TestMultipleErrorsNestedStruct(): offset[%d]: want %d, got %d", i, ii, test.Offsets[ii], e.Offset) + } + } + } +} diff --git a/vendor/github.com/mailru/easyjson/tests/named_type.go b/vendor/github.com/mailru/easyjson/tests/named_type.go new file mode 100644 index 00000000..0ff8dfeb --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/named_type.go @@ -0,0 +1,22 @@ +package tests + +//easyjson:json +type NamedType struct { + Inner struct { + // easyjson is mistakenly naming the type of this field 'tests.MyString' in the generated output + // something about a named type inside an anonmymous type is triggering this bug + Field MyString `tag:"value"` + Field2 int "tag:\"value with ` in it\"" + } +} + +type MyString string + +var namedTypeValue NamedType + +func init() { + namedTypeValue.Inner.Field = "test" + namedTypeValue.Inner.Field2 = 123 +} + +var namedTypeValueString = `{"Inner":{"Field":"test","Field2":123}}` diff --git a/vendor/github.com/mailru/easyjson/tests/nested_easy.go b/vendor/github.com/mailru/easyjson/tests/nested_easy.go new file mode 100644 index 00000000..6309a49f --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/nested_easy.go @@ -0,0 +1,25 @@ +package tests + +import ( + "github.com/mailru/easyjson" + "github.com/mailru/easyjson/jwriter" +) + +//easyjson:json +type NestedInterfaces struct { + Value interface{} + Slice []interface{} + Map map[string]interface{} +} + +type NestedEasyMarshaler struct { + EasilyMarshaled bool +} + +var _ easyjson.Marshaler = &NestedEasyMarshaler{} + +func (i *NestedEasyMarshaler) MarshalEasyJSON(w *jwriter.Writer) { + // We use this method only to indicate that easyjson.Marshaler + // interface was really used while encoding. + i.EasilyMarshaled = true +} \ No newline at end of file diff --git a/vendor/github.com/mailru/easyjson/tests/nothing.go b/vendor/github.com/mailru/easyjson/tests/nothing.go new file mode 100644 index 00000000..35334f5f --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/nothing.go @@ -0,0 +1,3 @@ +package tests + +// No structs in this file diff --git a/vendor/github.com/mailru/easyjson/tests/omitempty.go b/vendor/github.com/mailru/easyjson/tests/omitempty.go new file mode 100644 index 00000000..ede5eb95 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/omitempty.go @@ -0,0 +1,12 @@ +package tests + +//easyjson:json +type OmitEmptyDefault struct { + Field string + Str string + Str1 string `json:"s,!omitempty"` + Str2 string `json:",!omitempty"` +} + +var omitEmptyDefaultValue = OmitEmptyDefault{Field: "test"} +var omitEmptyDefaultString = `{"Field":"test","s":"","Str2":""}` diff --git a/vendor/github.com/mailru/easyjson/tests/required_test.go b/vendor/github.com/mailru/easyjson/tests/required_test.go new file mode 100644 index 00000000..8b03be6e --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/required_test.go @@ -0,0 +1,28 @@ +package tests + +import ( + "testing" + "fmt" +) + +func TestRequiredField(t *testing.T) { + cases := []struct{ json, errorMessage string }{ + {`{"first_name":"Foo", "last_name": "Bar"}`, ""}, + {`{"last_name":"Bar"}`, "key 'first_name' is required"}, + {"{}", "key 'first_name' is required"}, + } + + for _, tc := range cases { + var v RequiredOptionalStruct + err := v.UnmarshalJSON([]byte(tc.json)) + if tc.errorMessage == "" { + if err != nil { + t.Errorf("%s. UnmarshallJSON didn`t expect error: %v", tc.json, err) + } + } else { + if fmt.Sprintf("%v", err) != tc.errorMessage { + t.Errorf("%s. UnmarshallJSON expected error: %v. got: %v", tc.json, tc.errorMessage, err) + } + } + } +} diff --git a/vendor/github.com/mailru/easyjson/tests/snake.go b/vendor/github.com/mailru/easyjson/tests/snake.go new file mode 100644 index 00000000..9b64f861 --- /dev/null +++ b/vendor/github.com/mailru/easyjson/tests/snake.go @@ -0,0 +1,10 @@ +package tests + +//easyjson:json +type SnakeStruct struct { + WeirdHTTPStuff bool + CustomNamedField string `json:"cUsToM"` +} + +var snakeStructValue SnakeStruct +var snakeStructString = `{"weird_http_stuff":false,"cUsToM":""}` diff --git a/vendor/github.com/mitchellh/go-wordwrap/LICENSE.md b/vendor/github.com/mitchellh/go-wordwrap/LICENSE.md new file mode 100644 index 00000000..22985159 --- /dev/null +++ b/vendor/github.com/mitchellh/go-wordwrap/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mitchell Hashimoto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/go-wordwrap/README.md b/vendor/github.com/mitchellh/go-wordwrap/README.md new file mode 100644 index 00000000..60ae3117 --- /dev/null +++ b/vendor/github.com/mitchellh/go-wordwrap/README.md @@ -0,0 +1,39 @@ +# go-wordwrap + +`go-wordwrap` (Golang package: `wordwrap`) is a package for Go that +automatically wraps words into multiple lines. The primary use case for this +is in formatting CLI output, but of course word wrapping is a generally useful +thing to do. + +## Installation and Usage + +Install using `go get github.com/mitchellh/go-wordwrap`. + +Full documentation is available at +http://godoc.org/github.com/mitchellh/go-wordwrap + +Below is an example of its usage ignoring errors: + +```go +wrapped := wordwrap.WrapString("foo bar baz", 3) +fmt.Println(wrapped) +``` + +Would output: + +``` +foo +bar +baz +``` + +## Word Wrap Algorithm + +This library doesn't use any clever algorithm for word wrapping. The wrapping +is actually very naive: whenever there is whitespace or an explicit linebreak. +The goal of this library is for word wrapping CLI output, so the input is +typically pretty well controlled human language. Because of this, the naive +approach typically works just fine. + +In the future, we'd like to make the algorithm more advanced. We would do +so without breaking the API. diff --git a/vendor/github.com/mitchellh/go-wordwrap/wordwrap.go b/vendor/github.com/mitchellh/go-wordwrap/wordwrap.go new file mode 100644 index 00000000..ac67205b --- /dev/null +++ b/vendor/github.com/mitchellh/go-wordwrap/wordwrap.go @@ -0,0 +1,73 @@ +package wordwrap + +import ( + "bytes" + "unicode" +) + +// WrapString wraps the given string within lim width in characters. +// +// Wrapping is currently naive and only happens at white-space. A future +// version of the library will implement smarter wrapping. This means that +// pathological cases can dramatically reach past the limit, such as a very +// long word. +func WrapString(s string, lim uint) string { + // Initialize a buffer with a slightly larger size to account for breaks + init := make([]byte, 0, len(s)) + buf := bytes.NewBuffer(init) + + var current uint + var wordBuf, spaceBuf bytes.Buffer + + for _, char := range s { + if char == '\n' { + if wordBuf.Len() == 0 { + if current+uint(spaceBuf.Len()) > lim { + current = 0 + } else { + current += uint(spaceBuf.Len()) + spaceBuf.WriteTo(buf) + } + spaceBuf.Reset() + } else { + current += uint(spaceBuf.Len() + wordBuf.Len()) + spaceBuf.WriteTo(buf) + spaceBuf.Reset() + wordBuf.WriteTo(buf) + wordBuf.Reset() + } + buf.WriteRune(char) + current = 0 + } else if unicode.IsSpace(char) { + if spaceBuf.Len() == 0 || wordBuf.Len() > 0 { + current += uint(spaceBuf.Len() + wordBuf.Len()) + spaceBuf.WriteTo(buf) + spaceBuf.Reset() + wordBuf.WriteTo(buf) + wordBuf.Reset() + } + + spaceBuf.WriteRune(char) + } else { + + wordBuf.WriteRune(char) + + if current+uint(spaceBuf.Len()+wordBuf.Len()) > lim && uint(wordBuf.Len()) < lim { + buf.WriteRune('\n') + current = 0 + spaceBuf.Reset() + } + } + } + + if wordBuf.Len() == 0 { + if current+uint(spaceBuf.Len()) <= lim { + spaceBuf.WriteTo(buf) + } + } else { + spaceBuf.WriteTo(buf) + wordBuf.WriteTo(buf) + } + + return buf.String() +} diff --git a/vendor/github.com/mitchellh/go-wordwrap/wordwrap_test.go b/vendor/github.com/mitchellh/go-wordwrap/wordwrap_test.go new file mode 100644 index 00000000..bf6ae13d --- /dev/null +++ b/vendor/github.com/mitchellh/go-wordwrap/wordwrap_test.go @@ -0,0 +1,85 @@ +package wordwrap + +import ( + "testing" +) + +func TestWrapString(t *testing.T) { + cases := []struct { + Input, Output string + Lim uint + }{ + // A simple word passes through. + { + "foo", + "foo", + 4, + }, + // A single word that is too long passes through. + // We do not break words. + { + "foobarbaz", + "foobarbaz", + 4, + }, + // Lines are broken at whitespace. + { + "foo bar baz", + "foo\nbar\nbaz", + 4, + }, + // Lines are broken at whitespace, even if words + // are too long. We do not break words. + { + "foo bars bazzes", + "foo\nbars\nbazzes", + 4, + }, + // A word that would run beyond the width is wrapped. + { + "fo sop", + "fo\nsop", + 4, + }, + // Whitespace that trails a line and fits the width + // passes through, as does whitespace prefixing an + // explicit line break. A tab counts as one character. + { + "foo\nb\t r\n baz", + "foo\nb\t r\n baz", + 4, + }, + // Trailing whitespace is removed if it doesn't fit the width. + // Runs of whitespace on which a line is broken are removed. + { + "foo \nb ar ", + "foo\nb\nar", + 4, + }, + // An explicit line break at the end of the input is preserved. + { + "foo bar baz\n", + "foo\nbar\nbaz\n", + 4, + }, + // Explicit break are always preserved. + { + "\nfoo bar\n\n\nbaz\n", + "\nfoo\nbar\n\n\nbaz\n", + 4, + }, + // Complete example: + { + " This is a list: \n\n\t* foo\n\t* bar\n\n\n\t* baz \nBAM ", + " This\nis a\nlist: \n\n\t* foo\n\t* bar\n\n\n\t* baz\nBAM", + 6, + }, + } + + for i, tc := range cases { + actual := WrapString(tc.Input, tc.Lim) + if actual != tc.Output { + t.Fatalf("Case %d Input:\n\n`%s`\n\nActual Output:\n\n`%s`", i, tc.Input, actual) + } + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/Godeps.json b/vendor/github.com/opencontainers/runc/Godeps/Godeps.json new file mode 100644 index 00000000..1a0332b5 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/Godeps.json @@ -0,0 +1,87 @@ +{ + "ImportPath": "github.com/opencontainers/runc", + "GoVersion": "go1.5.3", + "GodepVersion": "v75", + "Deps": [ + { + "ImportPath": "github.com/Sirupsen/logrus", + "Comment": "v0.7.3-2-g26709e2", + "Rev": "26709e2714106fb8ad40b773b711ebce25b78914" + }, + { + "ImportPath": "github.com/urfave/cli", + "Comment": "v1.18.0-67-gd53eb99", + "Rev": "d53eb991652b1d438abdd34ce4bfa3ef1539108e" + }, + { + "ImportPath": "github.com/coreos/go-systemd/activation", + "Comment": "v14", + "Rev": "48702e0da86bd25e76cfef347e2adeb434a0d0a6" + }, + { + "ImportPath": "github.com/coreos/go-systemd/dbus", + "Comment": "v14", + "Rev": "48702e0da86bd25e76cfef347e2adeb434a0d0a6" + }, + { + "ImportPath": "github.com/coreos/go-systemd/util", + "Comment": "v14", + "Rev": "48702e0da86bd25e76cfef347e2adeb434a0d0a6" + }, + { + "ImportPath": "github.com/docker/docker/pkg/mount", + "Comment": "v1.4.1-4831-g0f5c9d3", + "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + }, + { + "ImportPath": "github.com/docker/docker/pkg/symlink", + "Comment": "v1.4.1-4831-g0f5c9d3", + "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + }, + { + "ImportPath": "github.com/docker/docker/pkg/term", + "Comment": "v1.4.1-4831-g0f5c9d3", + "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + }, + { + "ImportPath": "github.com/docker/go-units", + "Comment": "v0.1.0", + "Rev": "9b001659dd36225e356b4467c465d732e745f53d" + }, + { + "ImportPath": "github.com/godbus/dbus", + "Comment": "v3", + "Rev": "c7fdd8b5cd55e87b4e1f4e372cdb1db61dd6c66f" + }, + { + "ImportPath": "github.com/golang/protobuf/proto", + "Rev": "f7137ae6b19afbfd61a94b746fda3b3fe0491874" + }, + { + "ImportPath": "github.com/opencontainers/runtime-spec/specs-go", + "Comment": "v1.0.0-rc3", + "Rev": "794ca7ac88234607f9d2c76da8a6e9bbbade8cb9" + }, + { + "ImportPath": "github.com/seccomp/libseccomp-golang", + "Rev": "32f571b70023028bd57d9288c20efbcb237f3ce0" + }, + { + "ImportPath": "github.com/syndtr/gocapability/capability", + "Rev": "e7cb7fa329f456b3855136a2642b197bad7366ba" + }, + { + "ImportPath": "github.com/vishvananda/netlink", + "Rev": "1e2e08e8a2dcdacaae3f14ac44c5cfa31361f270" + }, + { + "ImportPath": "github.com/mrunalp/fileutils", + "Rev": "ed869b029674c0e9ce4c0dfa781405c2d9946d08" + }, + { + "ImportPath": "github.com/coreos/pkg/dlopen", + "Comment": "v3", + "Rev": "3ac0863d7acf3bc44daf49afef8919af12f704ef" + } + ] +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/Readme b/vendor/github.com/opencontainers/runc/Godeps/Readme new file mode 100644 index 00000000..4cdaa53d --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/Readme @@ -0,0 +1,5 @@ +This directory tree is generated automatically by godep. + +Please do not edit. + +See https://github.com/tools/godep for more information. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/.gitignore b/vendor/github.com/opencontainers/runc/Godeps/_workspace/.gitignore new file mode 100644 index 00000000..f037d684 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/.gitignore @@ -0,0 +1,2 @@ +/pkg +/bin diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore new file mode 100644 index 00000000..66be63a0 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore @@ -0,0 +1 @@ +logrus diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml new file mode 100644 index 00000000..2d8c0866 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml @@ -0,0 +1,8 @@ +language: go +go: + - 1.2 + - 1.3 + - 1.4 + - tip +install: + - go get -t ./... diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md new file mode 100644 index 00000000..eb72bff9 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md @@ -0,0 +1,7 @@ +# 0.7.3 + +formatter/\*: allow configuration of timestamp layout + +# 0.7.2 + +formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE new file mode 100644 index 00000000..f090cb42 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Simon Eskildsen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md new file mode 100644 index 00000000..d55f9092 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md @@ -0,0 +1,349 @@ +# Logrus :walrus: [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![godoc reference](https://godoc.org/github.com/Sirupsen/logrus?status.png)][godoc] + +Logrus is a structured logger for Go (golang), completely API compatible with +the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not +yet stable (pre 1.0). Logrus itself is completely stable and has been used in +many large deployments. The core API is unlikely to change much but please +version control your Logrus to make sure you aren't fetching latest `master` on +every build.** + +Nicely color-coded in development (when a TTY is attached, otherwise just +plain text): + +![Colored](http://i.imgur.com/PY7qMwd.png) + +With `log.Formatter = new(logrus.JSONFormatter)`, for easy parsing by logstash +or Splunk: + +```json +{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the +ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} + +{"level":"warning","msg":"The group's number increased tremendously!", +"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"A giant walrus appears!", +"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", +"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} + +{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, +"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} +``` + +With the default `log.Formatter = new(logrus.TextFormatter)` when a TTY is not +attached, the output is compatible with the +[logfmt](http://godoc.org/github.com/kr/logfmt) format: + +```text +time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 +time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 +time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true +time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 +time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 +time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true +exit status 1 +``` + +#### Example + +The simplest way to use Logrus is simply the package-level exported logger: + +```go +package main + +import ( + log "github.com/Sirupsen/logrus" +) + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + }).Info("A walrus appears") +} +``` + +Note that it's completely api-compatible with the stdlib logger, so you can +replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"` +and you'll now have the flexibility of Logrus. You can customize it all you +want: + +```go +package main + +import ( + "os" + log "github.com/Sirupsen/logrus" + "github.com/Sirupsen/logrus/hooks/airbrake" +) + +func init() { + // Log as JSON instead of the default ASCII formatter. + log.SetFormatter(&log.JSONFormatter{}) + + // Use the Airbrake hook to report errors that have Error severity or above to + // an exception tracker. You can create custom hooks, see the Hooks section. + log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development")) + + // Output to stderr instead of stdout, could also be a file. + log.SetOutput(os.Stderr) + + // Only log the warning severity or above. + log.SetLevel(log.WarnLevel) +} + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(log.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(log.Fields{ + "omg": true, + "number": 100, + }).Fatal("The ice breaks!") + + // A common pattern is to re-use fields between logging statements by re-using + // the logrus.Entry returned from WithFields() + contextLogger := log.WithFields(log.Fields{ + "common": "this is a common field", + "other": "I also should be logged always", + }) + + contextLogger.Info("I'll be logged with common and other field") + contextLogger.Info("Me too") +} +``` + +For more advanced usage such as logging to multiple locations from the same +application, you can also create an instance of the `logrus` Logger: + +```go +package main + +import ( + "github.com/Sirupsen/logrus" +) + +// Create a new instance of the logger. You can have any number of instances. +var log = logrus.New() + +func main() { + // The API for setting attributes is a little different than the package level + // exported logger. See Godoc. + log.Out = os.Stderr + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") +} +``` + +#### Fields + +Logrus encourages careful, structured logging though logging fields instead of +long, unparseable error messages. For example, instead of: `log.Fatalf("Failed +to send event %s to topic %s with key %d")`, you should log the much more +discoverable: + +```go +log.WithFields(log.Fields{ + "event": event, + "topic": topic, + "key": key, +}).Fatal("Failed to send event") +``` + +We've found this API forces you to think about logging in a way that produces +much more useful logging messages. We've been in countless situations where just +a single added field to a log statement that was already there would've saved us +hours. The `WithFields` call is optional. + +In general, with Logrus using any of the `printf`-family functions should be +seen as a hint you should add a field, however, you can still use the +`printf`-family functions with Logrus. + +#### Hooks + +You can add hooks for logging levels. For example to send errors to an exception +tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to +multiple places simultaneously, e.g. syslog. + +Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in +`init`: + +```go +import ( + log "github.com/Sirupsen/logrus" + "github.com/Sirupsen/logrus/hooks/airbrake" + "github.com/Sirupsen/logrus/hooks/syslog" + "log/syslog" +) + +func init() { + log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development")) + + hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + if err != nil { + log.Error("Unable to connect to local syslog daemon") + } else { + log.AddHook(hook) + } +} +``` + + +| Hook | Description | +| ----- | ----------- | +| [Airbrake](https://github.com/Sirupsen/logrus/blob/master/hooks/airbrake/airbrake.go) | Send errors to an exception tracking service compatible with the Airbrake API. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. | +| [Papertrail](https://github.com/Sirupsen/logrus/blob/master/hooks/papertrail/papertrail.go) | Send errors to the Papertrail hosted logging service via UDP. | +| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. | +| [BugSnag](https://github.com/Sirupsen/logrus/blob/master/hooks/bugsnag/bugsnag.go) | Send errors to the Bugsnag exception tracking service. | +| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. | +| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) | +| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. | +| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` | +| [Graylog](https://github.com/gemnasium/logrus-hooks/tree/master/graylog) | Hook for logging to [Graylog](http://graylog2.org/) | + +#### Level logging + +Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. + +```go +log.Debug("Useful debugging information.") +log.Info("Something noteworthy happened!") +log.Warn("You should probably take a look at this.") +log.Error("Something failed but I'm not quitting.") +// Calls os.Exit(1) after logging +log.Fatal("Bye.") +// Calls panic() after logging +log.Panic("I'm bailing.") +``` + +You can set the logging level on a `Logger`, then it will only log entries with +that severity or anything above it: + +```go +// Will log anything that is info or above (warn, error, fatal, panic). Default. +log.SetLevel(log.InfoLevel) +``` + +It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose +environment if your application has that. + +#### Entries + +Besides the fields added with `WithField` or `WithFields` some fields are +automatically added to all logging events: + +1. `time`. The timestamp when the entry was created. +2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after + the `AddFields` call. E.g. `Failed to send event.` +3. `level`. The logging level. E.g. `info`. + +#### Environments + +Logrus has no notion of environment. + +If you wish for hooks and formatters to only be used in specific environments, +you should handle that yourself. For example, if your application has a global +variable `Environment`, which is a string representation of the environment you +could do: + +```go +import ( + log "github.com/Sirupsen/logrus" +) + +init() { + // do something here to set environment depending on an environment variable + // or command-line flag + if Environment == "production" { + log.SetFormatter(logrus.JSONFormatter) + } else { + // The TextFormatter is default, you don't actually have to do this. + log.SetFormatter(logrus.TextFormatter) + } +} +``` + +This configuration is how `logrus` was intended to be used, but JSON in +production is mostly only useful if you do log aggregation with tools like +Splunk or Logstash. + +#### Formatters + +The built-in logging formatters are: + +* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise + without colors. + * *Note:* to force colored output when there is no TTY, set the `ForceColors` + field to `true`. To force no colored output even if there is a TTY set the + `DisableColors` field to `true` +* `logrus.JSONFormatter`. Logs fields as JSON. +* `logrus_logstash.LogstashFormatter`. Logs fields as Logstash Events (http://logstash.net). + + ```go + logrus.SetFormatter(&logrus_logstash.LogstashFormatter{Type: “application_name"}) + ``` + +Third party logging formatters: + +* [`zalgo`](https://github.com/aybabtme/logzalgo): invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. + +You can define your formatter by implementing the `Formatter` interface, +requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a +`Fields` type (`map[string]interface{}`) with all your fields as well as the +default ones (see Entries section above): + +```go +type MyJSONFormatter struct { +} + +log.SetFormatter(new(MyJSONFormatter)) + +func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { + // Note this doesn't include Time, Level and Message which are available on + // the Entry. Consult `godoc` on information about those fields or read the + // source of the official loggers. + serialized, err := json.Marshal(entry.Data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} +``` + +#### Logger as an `io.Writer` + +Logrus can be transormed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. + +```go +w := logger.Writer() +defer w.Close() + +srv := http.Server{ + // create a stdlib log.Logger that writes to + // logrus.Logger. + ErrorLog: log.New(w, "", 0), +} +``` + +Each line written to that writer will be printed the usual way, using formatters +and hooks. The level for those entries is `info`. + +#### Rotation + +Log rotation is not provided with Logrus. Log rotation should be done by an +external program (like `logrotate(8)`) that can compress and delete old log +entries. It should not be a feature of the application-level logger. + + +[godoc]: https://godoc.org/github.com/Sirupsen/logrus diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go new file mode 100644 index 00000000..17fe6f70 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go @@ -0,0 +1,252 @@ +package logrus + +import ( + "bytes" + "fmt" + "io" + "os" + "time" +) + +// An entry is the final or intermediate Logrus logging entry. It contains all +// the fields passed with WithField{,s}. It's finally logged when Debug, Info, +// Warn, Error, Fatal or Panic is called on it. These objects can be reused and +// passed around as much as you wish to avoid field duplication. +type Entry struct { + Logger *Logger + + // Contains all the fields set by the user. + Data Fields + + // Time at which the log entry was created + Time time.Time + + // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic + Level Level + + // Message passed to Debug, Info, Warn, Error, Fatal or Panic + Message string +} + +func NewEntry(logger *Logger) *Entry { + return &Entry{ + Logger: logger, + // Default is three fields, give a little extra room + Data: make(Fields, 5), + } +} + +// Returns a reader for the entry, which is a proxy to the formatter. +func (entry *Entry) Reader() (*bytes.Buffer, error) { + serialized, err := entry.Logger.Formatter.Format(entry) + return bytes.NewBuffer(serialized), err +} + +// Returns the string representation from the reader and ultimately the +// formatter. +func (entry *Entry) String() (string, error) { + reader, err := entry.Reader() + if err != nil { + return "", err + } + + return reader.String(), err +} + +// Add a single field to the Entry. +func (entry *Entry) WithField(key string, value interface{}) *Entry { + return entry.WithFields(Fields{key: value}) +} + +// Add a map of fields to the Entry. +func (entry *Entry) WithFields(fields Fields) *Entry { + data := Fields{} + for k, v := range entry.Data { + data[k] = v + } + for k, v := range fields { + data[k] = v + } + return &Entry{Logger: entry.Logger, Data: data} +} + +func (entry *Entry) log(level Level, msg string) { + entry.Time = time.Now() + entry.Level = level + entry.Message = msg + + if err := entry.Logger.Hooks.Fire(level, entry); err != nil { + entry.Logger.mu.Lock() + fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) + entry.Logger.mu.Unlock() + } + + reader, err := entry.Reader() + if err != nil { + entry.Logger.mu.Lock() + fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) + entry.Logger.mu.Unlock() + } + + entry.Logger.mu.Lock() + defer entry.Logger.mu.Unlock() + + _, err = io.Copy(entry.Logger.Out, reader) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) + } + + // To avoid Entry#log() returning a value that only would make sense for + // panic() to use in Entry#Panic(), we avoid the allocation by checking + // directly here. + if level <= PanicLevel { + panic(entry) + } +} + +func (entry *Entry) Debug(args ...interface{}) { + if entry.Logger.Level >= DebugLevel { + entry.log(DebugLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Print(args ...interface{}) { + entry.Info(args...) +} + +func (entry *Entry) Info(args ...interface{}) { + if entry.Logger.Level >= InfoLevel { + entry.log(InfoLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Warn(args ...interface{}) { + if entry.Logger.Level >= WarnLevel { + entry.log(WarnLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Warning(args ...interface{}) { + entry.Warn(args...) +} + +func (entry *Entry) Error(args ...interface{}) { + if entry.Logger.Level >= ErrorLevel { + entry.log(ErrorLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Fatal(args ...interface{}) { + if entry.Logger.Level >= FatalLevel { + entry.log(FatalLevel, fmt.Sprint(args...)) + } + os.Exit(1) +} + +func (entry *Entry) Panic(args ...interface{}) { + if entry.Logger.Level >= PanicLevel { + entry.log(PanicLevel, fmt.Sprint(args...)) + } + panic(fmt.Sprint(args...)) +} + +// Entry Printf family functions + +func (entry *Entry) Debugf(format string, args ...interface{}) { + if entry.Logger.Level >= DebugLevel { + entry.Debug(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Infof(format string, args ...interface{}) { + if entry.Logger.Level >= InfoLevel { + entry.Info(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Printf(format string, args ...interface{}) { + entry.Infof(format, args...) +} + +func (entry *Entry) Warnf(format string, args ...interface{}) { + if entry.Logger.Level >= WarnLevel { + entry.Warn(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Warningf(format string, args ...interface{}) { + entry.Warnf(format, args...) +} + +func (entry *Entry) Errorf(format string, args ...interface{}) { + if entry.Logger.Level >= ErrorLevel { + entry.Error(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Fatalf(format string, args ...interface{}) { + if entry.Logger.Level >= FatalLevel { + entry.Fatal(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Panicf(format string, args ...interface{}) { + if entry.Logger.Level >= PanicLevel { + entry.Panic(fmt.Sprintf(format, args...)) + } +} + +// Entry Println family functions + +func (entry *Entry) Debugln(args ...interface{}) { + if entry.Logger.Level >= DebugLevel { + entry.Debug(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Infoln(args ...interface{}) { + if entry.Logger.Level >= InfoLevel { + entry.Info(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Println(args ...interface{}) { + entry.Infoln(args...) +} + +func (entry *Entry) Warnln(args ...interface{}) { + if entry.Logger.Level >= WarnLevel { + entry.Warn(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Warningln(args ...interface{}) { + entry.Warnln(args...) +} + +func (entry *Entry) Errorln(args ...interface{}) { + if entry.Logger.Level >= ErrorLevel { + entry.Error(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Fatalln(args ...interface{}) { + if entry.Logger.Level >= FatalLevel { + entry.Fatal(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Panicln(args ...interface{}) { + if entry.Logger.Level >= PanicLevel { + entry.Panic(entry.sprintlnn(args...)) + } +} + +// Sprintlnn => Sprint no newline. This is to get the behavior of how +// fmt.Sprintln where spaces are always added between operands, regardless of +// their type. Instead of vendoring the Sprintln implementation to spare a +// string allocation, we do the simplest thing. +func (entry *Entry) sprintlnn(args ...interface{}) string { + msg := fmt.Sprintln(args...) + return msg[:len(msg)-1] +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go new file mode 100644 index 00000000..a1623ec0 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go @@ -0,0 +1,50 @@ +package main + +import ( + "github.com/Sirupsen/logrus" +) + +var log = logrus.New() + +func init() { + log.Formatter = new(logrus.JSONFormatter) + log.Formatter = new(logrus.TextFormatter) // default + log.Level = logrus.DebugLevel +} + +func main() { + defer func() { + err := recover() + if err != nil { + log.WithFields(logrus.Fields{ + "omg": true, + "err": err, + "number": 100, + }).Fatal("The ice breaks!") + } + }() + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "number": 8, + }).Debug("Started observing beach") + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(logrus.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(logrus.Fields{ + "temperature": -4, + }).Debug("Temperature changes") + + log.WithFields(logrus.Fields{ + "animal": "orca", + "size": 9009, + }).Panic("It's over 9000!") +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go new file mode 100644 index 00000000..cb5759a3 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go @@ -0,0 +1,30 @@ +package main + +import ( + "github.com/Sirupsen/logrus" + "github.com/Sirupsen/logrus/hooks/airbrake" +) + +var log = logrus.New() + +func init() { + log.Formatter = new(logrus.TextFormatter) // default + log.Hooks.Add(airbrake.NewHook("https://example.com", "xyz", "development")) +} + +func main() { + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(logrus.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(logrus.Fields{ + "omg": true, + "number": 100, + }).Fatal("The ice breaks!") +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go new file mode 100644 index 00000000..a67e1b80 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go @@ -0,0 +1,188 @@ +package logrus + +import ( + "io" +) + +var ( + // std is the name of the standard logger in stdlib `log` + std = New() +) + +func StandardLogger() *Logger { + return std +} + +// SetOutput sets the standard logger output. +func SetOutput(out io.Writer) { + std.mu.Lock() + defer std.mu.Unlock() + std.Out = out +} + +// SetFormatter sets the standard logger formatter. +func SetFormatter(formatter Formatter) { + std.mu.Lock() + defer std.mu.Unlock() + std.Formatter = formatter +} + +// SetLevel sets the standard logger level. +func SetLevel(level Level) { + std.mu.Lock() + defer std.mu.Unlock() + std.Level = level +} + +// GetLevel returns the standard logger level. +func GetLevel() Level { + std.mu.Lock() + defer std.mu.Unlock() + return std.Level +} + +// AddHook adds a hook to the standard logger hooks. +func AddHook(hook Hook) { + std.mu.Lock() + defer std.mu.Unlock() + std.Hooks.Add(hook) +} + +// WithField creates an entry from the standard logger and adds a field to +// it. If you want multiple fields, use `WithFields`. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithField(key string, value interface{}) *Entry { + return std.WithField(key, value) +} + +// WithFields creates an entry from the standard logger and adds multiple +// fields to it. This is simply a helper for `WithField`, invoking it +// once for each field. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithFields(fields Fields) *Entry { + return std.WithFields(fields) +} + +// Debug logs a message at level Debug on the standard logger. +func Debug(args ...interface{}) { + std.Debug(args...) +} + +// Print logs a message at level Info on the standard logger. +func Print(args ...interface{}) { + std.Print(args...) +} + +// Info logs a message at level Info on the standard logger. +func Info(args ...interface{}) { + std.Info(args...) +} + +// Warn logs a message at level Warn on the standard logger. +func Warn(args ...interface{}) { + std.Warn(args...) +} + +// Warning logs a message at level Warn on the standard logger. +func Warning(args ...interface{}) { + std.Warning(args...) +} + +// Error logs a message at level Error on the standard logger. +func Error(args ...interface{}) { + std.Error(args...) +} + +// Panic logs a message at level Panic on the standard logger. +func Panic(args ...interface{}) { + std.Panic(args...) +} + +// Fatal logs a message at level Fatal on the standard logger. +func Fatal(args ...interface{}) { + std.Fatal(args...) +} + +// Debugf logs a message at level Debug on the standard logger. +func Debugf(format string, args ...interface{}) { + std.Debugf(format, args...) +} + +// Printf logs a message at level Info on the standard logger. +func Printf(format string, args ...interface{}) { + std.Printf(format, args...) +} + +// Infof logs a message at level Info on the standard logger. +func Infof(format string, args ...interface{}) { + std.Infof(format, args...) +} + +// Warnf logs a message at level Warn on the standard logger. +func Warnf(format string, args ...interface{}) { + std.Warnf(format, args...) +} + +// Warningf logs a message at level Warn on the standard logger. +func Warningf(format string, args ...interface{}) { + std.Warningf(format, args...) +} + +// Errorf logs a message at level Error on the standard logger. +func Errorf(format string, args ...interface{}) { + std.Errorf(format, args...) +} + +// Panicf logs a message at level Panic on the standard logger. +func Panicf(format string, args ...interface{}) { + std.Panicf(format, args...) +} + +// Fatalf logs a message at level Fatal on the standard logger. +func Fatalf(format string, args ...interface{}) { + std.Fatalf(format, args...) +} + +// Debugln logs a message at level Debug on the standard logger. +func Debugln(args ...interface{}) { + std.Debugln(args...) +} + +// Println logs a message at level Info on the standard logger. +func Println(args ...interface{}) { + std.Println(args...) +} + +// Infoln logs a message at level Info on the standard logger. +func Infoln(args ...interface{}) { + std.Infoln(args...) +} + +// Warnln logs a message at level Warn on the standard logger. +func Warnln(args ...interface{}) { + std.Warnln(args...) +} + +// Warningln logs a message at level Warn on the standard logger. +func Warningln(args ...interface{}) { + std.Warningln(args...) +} + +// Errorln logs a message at level Error on the standard logger. +func Errorln(args ...interface{}) { + std.Errorln(args...) +} + +// Panicln logs a message at level Panic on the standard logger. +func Panicln(args ...interface{}) { + std.Panicln(args...) +} + +// Fatalln logs a message at level Fatal on the standard logger. +func Fatalln(args ...interface{}) { + std.Fatalln(args...) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go new file mode 100644 index 00000000..104d689f --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go @@ -0,0 +1,48 @@ +package logrus + +import "time" + +const DefaultTimestampFormat = time.RFC3339 + +// The Formatter interface is used to implement a custom Formatter. It takes an +// `Entry`. It exposes all the fields, including the default ones: +// +// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. +// * `entry.Data["time"]`. The timestamp. +// * `entry.Data["level"]. The level the entry was logged at. +// +// Any additional fields added with `WithField` or `WithFields` are also in +// `entry.Data`. Format is expected to return an array of bytes which are then +// logged to `logger.Out`. +type Formatter interface { + Format(*Entry) ([]byte, error) +} + +// This is to not silently overwrite `time`, `msg` and `level` fields when +// dumping it. If this code wasn't there doing: +// +// logrus.WithField("level", 1).Info("hello") +// +// Would just silently drop the user provided level. Instead with this code +// it'll logged as: +// +// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} +// +// It's not exported because it's still using Data in an opinionated way. It's to +// avoid code duplication between the two default formatters. +func prefixFieldClashes(data Fields) { + _, ok := data["time"] + if ok { + data["fields.time"] = data["time"] + } + + _, ok = data["msg"] + if ok { + data["fields.msg"] = data["msg"] + } + + _, ok = data["level"] + if ok { + data["fields.level"] = data["level"] + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go new file mode 100644 index 00000000..8ea93ddf --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go @@ -0,0 +1,56 @@ +package logstash + +import ( + "encoding/json" + "fmt" + + "github.com/Sirupsen/logrus" +) + +// Formatter generates json in logstash format. +// Logstash site: http://logstash.net/ +type LogstashFormatter struct { + Type string // if not empty use for logstash type field. + + // TimestampFormat sets the format used for timestamps. + TimestampFormat string +} + +func (f *LogstashFormatter) Format(entry *logrus.Entry) ([]byte, error) { + entry.Data["@version"] = 1 + + if f.TimestampFormat == "" { + f.TimestampFormat = logrus.DefaultTimestampFormat + } + + entry.Data["@timestamp"] = entry.Time.Format(f.TimestampFormat) + + // set message field + v, ok := entry.Data["message"] + if ok { + entry.Data["fields.message"] = v + } + entry.Data["message"] = entry.Message + + // set level field + v, ok = entry.Data["level"] + if ok { + entry.Data["fields.level"] = v + } + entry.Data["level"] = entry.Level.String() + + // set type field + if f.Type != "" { + v, ok = entry.Data["type"] + if ok { + entry.Data["fields.type"] = v + } + entry.Data["type"] = f.Type + } + + serialized, err := json.Marshal(entry.Data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go new file mode 100644 index 00000000..0da2b365 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go @@ -0,0 +1,34 @@ +package logrus + +// A hook to be fired when logging on the logging levels returned from +// `Levels()` on your implementation of the interface. Note that this is not +// fired in a goroutine or a channel with workers, you should handle such +// functionality yourself if your call is non-blocking and you don't wish for +// the logging calls for levels returned from `Levels()` to block. +type Hook interface { + Levels() []Level + Fire(*Entry) error +} + +// Internal type for storing the hooks on a logger instance. +type levelHooks map[Level][]Hook + +// Add a hook to an instance of logger. This is called with +// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. +func (hooks levelHooks) Add(hook Hook) { + for _, level := range hook.Levels() { + hooks[level] = append(hooks[level], hook) + } +} + +// Fire all the hooks for the passed level. Used by `entry.log` to fire +// appropriate hooks for a log entry. +func (hooks levelHooks) Fire(level Level, entry *Entry) error { + for _, hook := range hooks[level] { + if err := hook.Fire(entry); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go new file mode 100644 index 00000000..b0502c33 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go @@ -0,0 +1,54 @@ +package airbrake + +import ( + "errors" + "fmt" + + "github.com/Sirupsen/logrus" + "github.com/tobi/airbrake-go" +) + +// AirbrakeHook to send exceptions to an exception-tracking service compatible +// with the Airbrake API. +type airbrakeHook struct { + APIKey string + Endpoint string + Environment string +} + +func NewHook(endpoint, apiKey, env string) *airbrakeHook { + return &airbrakeHook{ + APIKey: apiKey, + Endpoint: endpoint, + Environment: env, + } +} + +func (hook *airbrakeHook) Fire(entry *logrus.Entry) error { + airbrake.ApiKey = hook.APIKey + airbrake.Endpoint = hook.Endpoint + airbrake.Environment = hook.Environment + + var notifyErr error + err, ok := entry.Data["error"].(error) + if ok { + notifyErr = err + } else { + notifyErr = errors.New(entry.Message) + } + + airErr := airbrake.Notify(notifyErr) + if airErr != nil { + return fmt.Errorf("Failed to send error to Airbrake: %s", airErr) + } + + return nil +} + +func (hook *airbrakeHook) Levels() []logrus.Level { + return []logrus.Level{ + logrus.ErrorLevel, + logrus.FatalLevel, + logrus.PanicLevel, + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go new file mode 100644 index 00000000..d20a0f54 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go @@ -0,0 +1,68 @@ +package logrus_bugsnag + +import ( + "errors" + + "github.com/Sirupsen/logrus" + "github.com/bugsnag/bugsnag-go" +) + +type bugsnagHook struct{} + +// ErrBugsnagUnconfigured is returned if NewBugsnagHook is called before +// bugsnag.Configure. Bugsnag must be configured before the hook. +var ErrBugsnagUnconfigured = errors.New("bugsnag must be configured before installing this logrus hook") + +// ErrBugsnagSendFailed indicates that the hook failed to submit an error to +// bugsnag. The error was successfully generated, but `bugsnag.Notify()` +// failed. +type ErrBugsnagSendFailed struct { + err error +} + +func (e ErrBugsnagSendFailed) Error() string { + return "failed to send error to Bugsnag: " + e.err.Error() +} + +// NewBugsnagHook initializes a logrus hook which sends exceptions to an +// exception-tracking service compatible with the Bugsnag API. Before using +// this hook, you must call bugsnag.Configure(). The returned object should be +// registered with a log via `AddHook()` +// +// Entries that trigger an Error, Fatal or Panic should now include an "error" +// field to send to Bugsnag. +func NewBugsnagHook() (*bugsnagHook, error) { + if bugsnag.Config.APIKey == "" { + return nil, ErrBugsnagUnconfigured + } + return &bugsnagHook{}, nil +} + +// Fire forwards an error to Bugsnag. Given a logrus.Entry, it extracts the +// "error" field (or the Message if the error isn't present) and sends it off. +func (hook *bugsnagHook) Fire(entry *logrus.Entry) error { + var notifyErr error + err, ok := entry.Data["error"].(error) + if ok { + notifyErr = err + } else { + notifyErr = errors.New(entry.Message) + } + + bugsnagErr := bugsnag.Notify(notifyErr) + if bugsnagErr != nil { + return ErrBugsnagSendFailed{bugsnagErr} + } + + return nil +} + +// Levels enumerates the log levels on which the error should be forwarded to +// bugsnag: everything at or above the "Error" level. +func (hook *bugsnagHook) Levels() []logrus.Level { + return []logrus.Level{ + logrus.ErrorLevel, + logrus.FatalLevel, + logrus.PanicLevel, + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md new file mode 100644 index 00000000..ae61e922 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md @@ -0,0 +1,28 @@ +# Papertrail Hook for Logrus :walrus: + +[Papertrail](https://papertrailapp.com) provides hosted log management. Once stored in Papertrail, you can [group](http://help.papertrailapp.com/kb/how-it-works/groups/) your logs on various dimensions, [search](http://help.papertrailapp.com/kb/how-it-works/search-syntax) them, and trigger [alerts](http://help.papertrailapp.com/kb/how-it-works/alerts). + +In most deployments, you'll want to send logs to Papertrail via their [remote_syslog](http://help.papertrailapp.com/kb/configuration/configuring-centralized-logging-from-text-log-files-in-unix/) daemon, which requires no application-specific configuration. This hook is intended for relatively low-volume logging, likely in managed cloud hosting deployments where installing `remote_syslog` is not possible. + +## Usage + +You can find your Papertrail UDP port on your [Papertrail account page](https://papertrailapp.com/account/destinations). Substitute it below for `YOUR_PAPERTRAIL_UDP_PORT`. + +For `YOUR_APP_NAME`, substitute a short string that will readily identify your application or service in the logs. + +```go +import ( + "log/syslog" + "github.com/Sirupsen/logrus" + "github.com/Sirupsen/logrus/hooks/papertrail" +) + +func main() { + log := logrus.New() + hook, err := logrus_papertrail.NewPapertrailHook("logs.papertrailapp.com", YOUR_PAPERTRAIL_UDP_PORT, YOUR_APP_NAME) + + if err == nil { + log.Hooks.Add(hook) + } +} +``` diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go new file mode 100644 index 00000000..c0f10c1b --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go @@ -0,0 +1,55 @@ +package logrus_papertrail + +import ( + "fmt" + "net" + "os" + "time" + + "github.com/Sirupsen/logrus" +) + +const ( + format = "Jan 2 15:04:05" +) + +// PapertrailHook to send logs to a logging service compatible with the Papertrail API. +type PapertrailHook struct { + Host string + Port int + AppName string + UDPConn net.Conn +} + +// NewPapertrailHook creates a hook to be added to an instance of logger. +func NewPapertrailHook(host string, port int, appName string) (*PapertrailHook, error) { + conn, err := net.Dial("udp", fmt.Sprintf("%s:%d", host, port)) + return &PapertrailHook{host, port, appName, conn}, err +} + +// Fire is called when a log event is fired. +func (hook *PapertrailHook) Fire(entry *logrus.Entry) error { + date := time.Now().Format(format) + msg, _ := entry.String() + payload := fmt.Sprintf("<22> %s %s: %s", date, hook.AppName, msg) + + bytesWritten, err := hook.UDPConn.Write([]byte(payload)) + if err != nil { + fmt.Fprintf(os.Stderr, "Unable to send log line to Papertrail via UDP. Wrote %d bytes before error: %v", bytesWritten, err) + return err + } + + return nil +} + +// Levels returns the available logging levels. +func (hook *PapertrailHook) Levels() []logrus.Level { + return []logrus.Level{ + logrus.PanicLevel, + logrus.FatalLevel, + logrus.ErrorLevel, + logrus.WarnLevel, + logrus.InfoLevel, + logrus.DebugLevel, + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md new file mode 100644 index 00000000..19e58bb4 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md @@ -0,0 +1,61 @@ +# Sentry Hook for Logrus :walrus: + +[Sentry](https://getsentry.com) provides both self-hosted and hosted +solutions for exception tracking. +Both client and server are +[open source](https://github.com/getsentry/sentry). + +## Usage + +Every sentry application defined on the server gets a different +[DSN](https://www.getsentry.com/docs/). In the example below replace +`YOUR_DSN` with the one created for your application. + +```go +import ( + "github.com/Sirupsen/logrus" + "github.com/Sirupsen/logrus/hooks/sentry" +) + +func main() { + log := logrus.New() + hook, err := logrus_sentry.NewSentryHook(YOUR_DSN, []logrus.Level{ + logrus.PanicLevel, + logrus.FatalLevel, + logrus.ErrorLevel, + }) + + if err == nil { + log.Hooks.Add(hook) + } +} +``` + +## Special fields + +Some logrus fields have a special meaning in this hook, +these are server_name and logger. +When logs are sent to sentry these fields are treated differently. +- server_name (also known as hostname) is the name of the server which +is logging the event (hostname.example.com) +- logger is the part of the application which is logging the event. +In go this usually means setting it to the name of the package. + +## Timeout + +`Timeout` is the time the sentry hook will wait for a response +from the sentry server. + +If this time elapses with no response from +the server an error will be returned. + +If `Timeout` is set to 0 the SentryHook will not wait for a reply +and will assume a correct delivery. + +The SentryHook has a default timeout of `100 milliseconds` when created +with a call to `NewSentryHook`. This can be changed by assigning a value to the `Timeout` field: + +```go +hook, _ := logrus_sentry.NewSentryHook(...) +hook.Timeout = 20*time.Second +``` diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go new file mode 100644 index 00000000..379f281c --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go @@ -0,0 +1,100 @@ +package logrus_sentry + +import ( + "fmt" + "time" + + "github.com/Sirupsen/logrus" + "github.com/getsentry/raven-go" +) + +var ( + severityMap = map[logrus.Level]raven.Severity{ + logrus.DebugLevel: raven.DEBUG, + logrus.InfoLevel: raven.INFO, + logrus.WarnLevel: raven.WARNING, + logrus.ErrorLevel: raven.ERROR, + logrus.FatalLevel: raven.FATAL, + logrus.PanicLevel: raven.FATAL, + } +) + +func getAndDel(d logrus.Fields, key string) (string, bool) { + var ( + ok bool + v interface{} + val string + ) + if v, ok = d[key]; !ok { + return "", false + } + + if val, ok = v.(string); !ok { + return "", false + } + delete(d, key) + return val, true +} + +// SentryHook delivers logs to a sentry server. +type SentryHook struct { + // Timeout sets the time to wait for a delivery error from the sentry server. + // If this is set to zero the server will not wait for any response and will + // consider the message correctly sent + Timeout time.Duration + + client *raven.Client + levels []logrus.Level +} + +// NewSentryHook creates a hook to be added to an instance of logger +// and initializes the raven client. +// This method sets the timeout to 100 milliseconds. +func NewSentryHook(DSN string, levels []logrus.Level) (*SentryHook, error) { + client, err := raven.NewClient(DSN, nil) + if err != nil { + return nil, err + } + return &SentryHook{100 * time.Millisecond, client, levels}, nil +} + +// Called when an event should be sent to sentry +// Special fields that sentry uses to give more information to the server +// are extracted from entry.Data (if they are found) +// These fields are: logger and server_name +func (hook *SentryHook) Fire(entry *logrus.Entry) error { + packet := &raven.Packet{ + Message: entry.Message, + Timestamp: raven.Timestamp(entry.Time), + Level: severityMap[entry.Level], + Platform: "go", + } + + d := entry.Data + + if logger, ok := getAndDel(d, "logger"); ok { + packet.Logger = logger + } + if serverName, ok := getAndDel(d, "server_name"); ok { + packet.ServerName = serverName + } + packet.Extra = map[string]interface{}(d) + + _, errCh := hook.client.Capture(packet, nil) + timeout := hook.Timeout + if timeout != 0 { + timeoutCh := time.After(timeout) + select { + case err := <-errCh: + return err + case <-timeoutCh: + return fmt.Errorf("no response from sentry server in %s", timeout) + } + } + return nil +} + +// Levels returns the available logging levels. +func (hook *SentryHook) Levels() []logrus.Level { + return hook.levels +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md new file mode 100644 index 00000000..4dbb8e72 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md @@ -0,0 +1,20 @@ +# Syslog Hooks for Logrus :walrus: + +## Usage + +```go +import ( + "log/syslog" + "github.com/Sirupsen/logrus" + logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog" +) + +func main() { + log := logrus.New() + hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + + if err == nil { + log.Hooks.Add(hook) + } +} +``` diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go new file mode 100644 index 00000000..b6fa3746 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go @@ -0,0 +1,59 @@ +package logrus_syslog + +import ( + "fmt" + "github.com/Sirupsen/logrus" + "log/syslog" + "os" +) + +// SyslogHook to send logs via syslog. +type SyslogHook struct { + Writer *syslog.Writer + SyslogNetwork string + SyslogRaddr string +} + +// Creates a hook to be added to an instance of logger. This is called with +// `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")` +// `if err == nil { log.Hooks.Add(hook) }` +func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) { + w, err := syslog.Dial(network, raddr, priority, tag) + return &SyslogHook{w, network, raddr}, err +} + +func (hook *SyslogHook) Fire(entry *logrus.Entry) error { + line, err := entry.String() + if err != nil { + fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err) + return err + } + + switch entry.Level { + case logrus.PanicLevel: + return hook.Writer.Crit(line) + case logrus.FatalLevel: + return hook.Writer.Crit(line) + case logrus.ErrorLevel: + return hook.Writer.Err(line) + case logrus.WarnLevel: + return hook.Writer.Warning(line) + case logrus.InfoLevel: + return hook.Writer.Info(line) + case logrus.DebugLevel: + return hook.Writer.Debug(line) + default: + return nil + } +} + +func (hook *SyslogHook) Levels() []logrus.Level { + return []logrus.Level{ + logrus.PanicLevel, + logrus.FatalLevel, + logrus.ErrorLevel, + logrus.WarnLevel, + logrus.InfoLevel, + logrus.DebugLevel, + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go new file mode 100644 index 00000000..dcc4f1d9 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go @@ -0,0 +1,40 @@ +package logrus + +import ( + "encoding/json" + "fmt" +) + +type JSONFormatter struct { + // TimestampFormat sets the format used for marshaling timestamps. + TimestampFormat string +} + +func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { + data := make(Fields, len(entry.Data)+3) + for k, v := range entry.Data { + switch v := v.(type) { + case error: + // Otherwise errors are ignored by `encoding/json` + // https://github.com/Sirupsen/logrus/issues/137 + data[k] = v.Error() + default: + data[k] = v + } + } + prefixFieldClashes(data) + + if f.TimestampFormat == "" { + f.TimestampFormat = DefaultTimestampFormat + } + + data["time"] = entry.Time.Format(f.TimestampFormat) + data["msg"] = entry.Message + data["level"] = entry.Level.String() + + serialized, err := json.Marshal(data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go new file mode 100644 index 00000000..da928a37 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go @@ -0,0 +1,203 @@ +package logrus + +import ( + "io" + "os" + "sync" +) + +type Logger struct { + // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a + // file, or leave it default which is `os.Stdout`. You can also set this to + // something more adventorous, such as logging to Kafka. + Out io.Writer + // Hooks for the logger instance. These allow firing events based on logging + // levels and log entries. For example, to send errors to an error tracking + // service, log to StatsD or dump the core on fatal errors. + Hooks levelHooks + // All log entries pass through the formatter before logged to Out. The + // included formatters are `TextFormatter` and `JSONFormatter` for which + // TextFormatter is the default. In development (when a TTY is attached) it + // logs with colors, but to a file it wouldn't. You can easily implement your + // own that implements the `Formatter` interface, see the `README` or included + // formatters for examples. + Formatter Formatter + // The logging level the logger should log at. This is typically (and defaults + // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be + // logged. `logrus.Debug` is useful in + Level Level + // Used to sync writing to the log. + mu sync.Mutex +} + +// Creates a new logger. Configuration should be set by changing `Formatter`, +// `Out` and `Hooks` directly on the default logger instance. You can also just +// instantiate your own: +// +// var log = &Logger{ +// Out: os.Stderr, +// Formatter: new(JSONFormatter), +// Hooks: make(levelHooks), +// Level: logrus.DebugLevel, +// } +// +// It's recommended to make this a global instance called `log`. +func New() *Logger { + return &Logger{ + Out: os.Stdout, + Formatter: new(TextFormatter), + Hooks: make(levelHooks), + Level: InfoLevel, + } +} + +// Adds a field to the log entry, note that you it doesn't log until you call +// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. +// Ff you want multiple fields, use `WithFields`. +func (logger *Logger) WithField(key string, value interface{}) *Entry { + return NewEntry(logger).WithField(key, value) +} + +// Adds a struct of fields to the log entry. All it does is call `WithField` for +// each `Field`. +func (logger *Logger) WithFields(fields Fields) *Entry { + return NewEntry(logger).WithFields(fields) +} + +func (logger *Logger) Debugf(format string, args ...interface{}) { + if logger.Level >= DebugLevel { + NewEntry(logger).Debugf(format, args...) + } +} + +func (logger *Logger) Infof(format string, args ...interface{}) { + if logger.Level >= InfoLevel { + NewEntry(logger).Infof(format, args...) + } +} + +func (logger *Logger) Printf(format string, args ...interface{}) { + NewEntry(logger).Printf(format, args...) +} + +func (logger *Logger) Warnf(format string, args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warnf(format, args...) + } +} + +func (logger *Logger) Warningf(format string, args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warnf(format, args...) + } +} + +func (logger *Logger) Errorf(format string, args ...interface{}) { + if logger.Level >= ErrorLevel { + NewEntry(logger).Errorf(format, args...) + } +} + +func (logger *Logger) Fatalf(format string, args ...interface{}) { + if logger.Level >= FatalLevel { + NewEntry(logger).Fatalf(format, args...) + } +} + +func (logger *Logger) Panicf(format string, args ...interface{}) { + if logger.Level >= PanicLevel { + NewEntry(logger).Panicf(format, args...) + } +} + +func (logger *Logger) Debug(args ...interface{}) { + if logger.Level >= DebugLevel { + NewEntry(logger).Debug(args...) + } +} + +func (logger *Logger) Info(args ...interface{}) { + if logger.Level >= InfoLevel { + NewEntry(logger).Info(args...) + } +} + +func (logger *Logger) Print(args ...interface{}) { + NewEntry(logger).Info(args...) +} + +func (logger *Logger) Warn(args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warn(args...) + } +} + +func (logger *Logger) Warning(args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warn(args...) + } +} + +func (logger *Logger) Error(args ...interface{}) { + if logger.Level >= ErrorLevel { + NewEntry(logger).Error(args...) + } +} + +func (logger *Logger) Fatal(args ...interface{}) { + if logger.Level >= FatalLevel { + NewEntry(logger).Fatal(args...) + } +} + +func (logger *Logger) Panic(args ...interface{}) { + if logger.Level >= PanicLevel { + NewEntry(logger).Panic(args...) + } +} + +func (logger *Logger) Debugln(args ...interface{}) { + if logger.Level >= DebugLevel { + NewEntry(logger).Debugln(args...) + } +} + +func (logger *Logger) Infoln(args ...interface{}) { + if logger.Level >= InfoLevel { + NewEntry(logger).Infoln(args...) + } +} + +func (logger *Logger) Println(args ...interface{}) { + NewEntry(logger).Println(args...) +} + +func (logger *Logger) Warnln(args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warnln(args...) + } +} + +func (logger *Logger) Warningln(args ...interface{}) { + if logger.Level >= WarnLevel { + NewEntry(logger).Warnln(args...) + } +} + +func (logger *Logger) Errorln(args ...interface{}) { + if logger.Level >= ErrorLevel { + NewEntry(logger).Errorln(args...) + } +} + +func (logger *Logger) Fatalln(args ...interface{}) { + if logger.Level >= FatalLevel { + NewEntry(logger).Fatalln(args...) + } +} + +func (logger *Logger) Panicln(args ...interface{}) { + if logger.Level >= PanicLevel { + NewEntry(logger).Panicln(args...) + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go new file mode 100644 index 00000000..43ee12e9 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go @@ -0,0 +1,94 @@ +package logrus + +import ( + "fmt" + "log" +) + +// Fields type, used to pass to `WithFields`. +type Fields map[string]interface{} + +// Level type +type Level uint8 + +// Convert the Level to a string. E.g. PanicLevel becomes "panic". +func (level Level) String() string { + switch level { + case DebugLevel: + return "debug" + case InfoLevel: + return "info" + case WarnLevel: + return "warning" + case ErrorLevel: + return "error" + case FatalLevel: + return "fatal" + case PanicLevel: + return "panic" + } + + return "unknown" +} + +// ParseLevel takes a string level and returns the Logrus log level constant. +func ParseLevel(lvl string) (Level, error) { + switch lvl { + case "panic": + return PanicLevel, nil + case "fatal": + return FatalLevel, nil + case "error": + return ErrorLevel, nil + case "warn", "warning": + return WarnLevel, nil + case "info": + return InfoLevel, nil + case "debug": + return DebugLevel, nil + } + + var l Level + return l, fmt.Errorf("not a valid logrus Level: %q", lvl) +} + +// These are the different logging levels. You can set the logging level to log +// on your instance of logger, obtained with `logrus.New()`. +const ( + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel Level = iota + // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel +) + +// Won't compile if StdLogger can't be realized by a log.Logger +var _ StdLogger = &log.Logger{} + +// StdLogger is what your logrus-enabled library should take, that way +// it'll accept a stdlib logger and a logrus logger. There's no standard +// interface, this is the closest we get, unfortunately. +type StdLogger interface { + Print(...interface{}) + Printf(string, ...interface{}) + Println(...interface{}) + + Fatal(...interface{}) + Fatalf(string, ...interface{}) + Fatalln(...interface{}) + + Panic(...interface{}) + Panicf(string, ...interface{}) + Panicln(...interface{}) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_darwin.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_darwin.go new file mode 100644 index 00000000..8fe02a4a --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_darwin.go @@ -0,0 +1,12 @@ +// Based on ssh/terminal: +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package logrus + +import "syscall" + +const ioctlReadTermios = syscall.TIOCGETA + +type Termios syscall.Termios diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_freebsd.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_freebsd.go new file mode 100644 index 00000000..0428ee5d --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_freebsd.go @@ -0,0 +1,20 @@ +/* + Go 1.2 doesn't include Termios for FreeBSD. This should be added in 1.3 and this could be merged with terminal_darwin. +*/ +package logrus + +import ( + "syscall" +) + +const ioctlReadTermios = syscall.TIOCGETA + +type Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]uint8 + Ispeed uint32 + Ospeed uint32 +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go new file mode 100644 index 00000000..a2c0b40d --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go @@ -0,0 +1,12 @@ +// Based on ssh/terminal: +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package logrus + +import "syscall" + +const ioctlReadTermios = syscall.TCGETS + +type Termios syscall.Termios diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go new file mode 100644 index 00000000..b8bebc13 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go @@ -0,0 +1,21 @@ +// Based on ssh/terminal: +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build linux darwin freebsd openbsd + +package logrus + +import ( + "syscall" + "unsafe" +) + +// IsTerminal returns true if the given file descriptor is a terminal. +func IsTerminal() bool { + fd := syscall.Stdout + var termios Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_openbsd.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_openbsd.go new file mode 100644 index 00000000..af609a53 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_openbsd.go @@ -0,0 +1,7 @@ +package logrus + +import "syscall" + +const ioctlReadTermios = syscall.TIOCGETA + +type Termios syscall.Termios diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go new file mode 100644 index 00000000..2e09f6f7 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go @@ -0,0 +1,27 @@ +// Based on ssh/terminal: +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build windows + +package logrus + +import ( + "syscall" + "unsafe" +) + +var kernel32 = syscall.NewLazyDLL("kernel32.dll") + +var ( + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") +) + +// IsTerminal returns true if the given file descriptor is a terminal. +func IsTerminal() bool { + fd := syscall.Stdout + var st uint32 + r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0) + return r != 0 && e == 0 +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go new file mode 100644 index 00000000..612417ff --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go @@ -0,0 +1,149 @@ +package logrus + +import ( + "bytes" + "fmt" + "sort" + "strings" + "time" +) + +const ( + nocolor = 0 + red = 31 + green = 32 + yellow = 33 + blue = 34 + gray = 37 +) + +var ( + baseTimestamp time.Time + isTerminal bool +) + +func init() { + baseTimestamp = time.Now() + isTerminal = IsTerminal() +} + +func miniTS() int { + return int(time.Since(baseTimestamp) / time.Second) +} + +type TextFormatter struct { + // Set to true to bypass checking for a TTY before outputting colors. + ForceColors bool + + // Force disabling colors. + DisableColors bool + + // Disable timestamp logging. useful when output is redirected to logging + // system that already adds timestamps. + DisableTimestamp bool + + // Enable logging the full timestamp when a TTY is attached instead of just + // the time passed since beginning of execution. + FullTimestamp bool + + // TimestampFormat to use for display when a full timestamp is printed + TimestampFormat string + + // The fields are sorted by default for a consistent output. For applications + // that log extremely frequently and don't use the JSON formatter this may not + // be desired. + DisableSorting bool +} + +func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { + var keys []string = make([]string, 0, len(entry.Data)) + for k := range entry.Data { + keys = append(keys, k) + } + + if !f.DisableSorting { + sort.Strings(keys) + } + + b := &bytes.Buffer{} + + prefixFieldClashes(entry.Data) + + isColored := (f.ForceColors || isTerminal) && !f.DisableColors + + if f.TimestampFormat == "" { + f.TimestampFormat = DefaultTimestampFormat + } + if isColored { + f.printColored(b, entry, keys) + } else { + if !f.DisableTimestamp { + f.appendKeyValue(b, "time", entry.Time.Format(f.TimestampFormat)) + } + f.appendKeyValue(b, "level", entry.Level.String()) + f.appendKeyValue(b, "msg", entry.Message) + for _, key := range keys { + f.appendKeyValue(b, key, entry.Data[key]) + } + } + + b.WriteByte('\n') + return b.Bytes(), nil +} + +func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string) { + var levelColor int + switch entry.Level { + case DebugLevel: + levelColor = gray + case WarnLevel: + levelColor = yellow + case ErrorLevel, FatalLevel, PanicLevel: + levelColor = red + default: + levelColor = blue + } + + levelText := strings.ToUpper(entry.Level.String())[0:4] + + if !f.FullTimestamp { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message) + } else { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(f.TimestampFormat), entry.Message) + } + for _, k := range keys { + v := entry.Data[k] + fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%v", levelColor, k, v) + } +} + +func needsQuoting(text string) bool { + for _, ch := range text { + if !((ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || + ch == '-' || ch == '.') { + return false + } + } + return true +} + +func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key, value interface{}) { + switch value.(type) { + case string: + if needsQuoting(value.(string)) { + fmt.Fprintf(b, "%v=%s ", key, value) + } else { + fmt.Fprintf(b, "%v=%q ", key, value) + } + case error: + if needsQuoting(value.(error).Error()) { + fmt.Fprintf(b, "%v=%s ", key, value) + } else { + fmt.Fprintf(b, "%v=%q ", key, value) + } + default: + fmt.Fprintf(b, "%v=%v ", key, value) + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go new file mode 100644 index 00000000..1e30b1c7 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go @@ -0,0 +1,31 @@ +package logrus + +import ( + "bufio" + "io" + "runtime" +) + +func (logger *Logger) Writer() *io.PipeWriter { + reader, writer := io.Pipe() + + go logger.writerScanner(reader) + runtime.SetFinalizer(writer, writerFinalizer) + + return writer +} + +func (logger *Logger) writerScanner(reader *io.PipeReader) { + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + logger.Print(scanner.Text()) + } + if err := scanner.Err(); err != nil { + logger.Errorf("Error while reading from Writer: %s", err) + } + reader.Close() +} + +func writerFinalizer(writer *io.PipeWriter) { + writer.Close() +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/LICENSE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/LICENSE new file mode 100644 index 00000000..37ec93a1 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/LICENSE @@ -0,0 +1,191 @@ +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/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/files.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/files.go new file mode 100644 index 00000000..c8e85fcd --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/files.go @@ -0,0 +1,52 @@ +// Copyright 2015 CoreOS, 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 activation implements primitives for systemd socket activation. +package activation + +import ( + "os" + "strconv" + "syscall" +) + +// based on: https://gist.github.com/alberts/4640792 +const ( + listenFdsStart = 3 +) + +func Files(unsetEnv bool) []*os.File { + if unsetEnv { + defer os.Unsetenv("LISTEN_PID") + defer os.Unsetenv("LISTEN_FDS") + } + + pid, err := strconv.Atoi(os.Getenv("LISTEN_PID")) + if err != nil || pid != os.Getpid() { + return nil + } + + nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS")) + if err != nil || nfds == 0 { + return nil + } + + files := make([]*os.File, 0, nfds) + for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ { + syscall.CloseOnExec(fd) + files = append(files, os.NewFile(uintptr(fd), "LISTEN_FD_"+strconv.Itoa(fd))) + } + + return files +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/listeners.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/listeners.go new file mode 100644 index 00000000..fd5dfc70 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/listeners.go @@ -0,0 +1,60 @@ +// Copyright 2015 CoreOS, 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 activation + +import ( + "crypto/tls" + "net" +) + +// Listeners returns a slice containing a net.Listener for each matching socket type +// passed to this process. +// +// The order of the file descriptors is preserved in the returned slice. +// Nil values are used to fill any gaps. For example if systemd were to return file descriptors +// corresponding with "udp, tcp, tcp", then the slice would contain {nil, net.Listener, net.Listener} +func Listeners(unsetEnv bool) ([]net.Listener, error) { + files := Files(unsetEnv) + listeners := make([]net.Listener, len(files)) + + for i, f := range files { + if pc, err := net.FileListener(f); err == nil { + listeners[i] = pc + } + } + return listeners, nil +} + +// TLSListeners returns a slice containing a net.listener for each matching TCP socket type +// passed to this process. +// It uses default Listeners func and forces TCP sockets handlers to use TLS based on tlsConfig. +func TLSListeners(unsetEnv bool, tlsConfig *tls.Config) ([]net.Listener, error) { + listeners, err := Listeners(unsetEnv) + + if listeners == nil || err != nil { + return nil, err + } + + if tlsConfig != nil && err == nil { + for i, l := range listeners { + // Activate TLS only for TCP sockets + if l.Addr().Network() == "tcp" { + listeners[i] = tls.NewListener(l, tlsConfig) + } + } + } + + return listeners, err +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/packetconns.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/packetconns.go new file mode 100644 index 00000000..48b2ca02 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/activation/packetconns.go @@ -0,0 +1,37 @@ +// Copyright 2015 CoreOS, 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 activation + +import ( + "net" +) + +// PacketConns returns a slice containing a net.PacketConn for each matching socket type +// passed to this process. +// +// The order of the file descriptors is preserved in the returned slice. +// Nil values are used to fill any gaps. For example if systemd were to return file descriptors +// corresponding with "udp, tcp, udp", then the slice would contain {net.PacketConn, nil, net.PacketConn} +func PacketConns(unsetEnv bool) ([]net.PacketConn, error) { + files := Files(unsetEnv) + conns := make([]net.PacketConn, len(files)) + + for i, f := range files { + if pc, err := net.FilePacketConn(f); err == nil { + conns[i] = pc + } + } + return conns, nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/dbus.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/dbus.go new file mode 100644 index 00000000..c1694fb5 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/dbus.go @@ -0,0 +1,213 @@ +// Copyright 2015 CoreOS, 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. + +// Integration with the systemd D-Bus API. See http://www.freedesktop.org/wiki/Software/systemd/dbus/ +package dbus + +import ( + "fmt" + "os" + "strconv" + "strings" + "sync" + + "github.com/godbus/dbus" +) + +const ( + alpha = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` + num = `0123456789` + alphanum = alpha + num + signalBuffer = 100 +) + +// needsEscape checks whether a byte in a potential dbus ObjectPath needs to be escaped +func needsEscape(i int, b byte) bool { + // Escape everything that is not a-z-A-Z-0-9 + // Also escape 0-9 if it's the first character + return strings.IndexByte(alphanum, b) == -1 || + (i == 0 && strings.IndexByte(num, b) != -1) +} + +// PathBusEscape sanitizes a constituent string of a dbus ObjectPath using the +// rules that systemd uses for serializing special characters. +func PathBusEscape(path string) string { + // Special case the empty string + if len(path) == 0 { + return "_" + } + n := []byte{} + for i := 0; i < len(path); i++ { + c := path[i] + if needsEscape(i, c) { + e := fmt.Sprintf("_%x", c) + n = append(n, []byte(e)...) + } else { + n = append(n, c) + } + } + return string(n) +} + +// Conn is a connection to systemd's dbus endpoint. +type Conn struct { + // sysconn/sysobj are only used to call dbus methods + sysconn *dbus.Conn + sysobj dbus.BusObject + + // sigconn/sigobj are only used to receive dbus signals + sigconn *dbus.Conn + sigobj dbus.BusObject + + jobListener struct { + jobs map[dbus.ObjectPath]chan<- string + sync.Mutex + } + subscriber struct { + updateCh chan<- *SubStateUpdate + errCh chan<- error + sync.Mutex + ignore map[dbus.ObjectPath]int64 + cleanIgnore int64 + } +} + +// New establishes a connection to any available bus and authenticates. +// Callers should call Close() when done with the connection. +func New() (*Conn, error) { + conn, err := NewSystemConnection() + if err != nil && os.Geteuid() == 0 { + return NewSystemdConnection() + } + return conn, err +} + +// NewSystemConnection establishes a connection to the system bus and authenticates. +// Callers should call Close() when done with the connection +func NewSystemConnection() (*Conn, error) { + return NewConnection(func() (*dbus.Conn, error) { + return dbusAuthHelloConnection(dbus.SystemBusPrivate) + }) +} + +// NewUserConnection establishes a connection to the session bus and +// authenticates. This can be used to connect to systemd user instances. +// Callers should call Close() when done with the connection. +func NewUserConnection() (*Conn, error) { + return NewConnection(func() (*dbus.Conn, error) { + return dbusAuthHelloConnection(dbus.SessionBusPrivate) + }) +} + +// NewSystemdConnection establishes a private, direct connection to systemd. +// This can be used for communicating with systemd without a dbus daemon. +// Callers should call Close() when done with the connection. +func NewSystemdConnection() (*Conn, error) { + return NewConnection(func() (*dbus.Conn, error) { + // We skip Hello when talking directly to systemd. + return dbusAuthConnection(func() (*dbus.Conn, error) { + return dbus.Dial("unix:path=/run/systemd/private") + }) + }) +} + +// Close closes an established connection +func (c *Conn) Close() { + c.sysconn.Close() + c.sigconn.Close() +} + +// NewConnection establishes a connection to a bus using a caller-supplied function. +// This allows connecting to remote buses through a user-supplied mechanism. +// The supplied function may be called multiple times, and should return independent connections. +// The returned connection must be fully initialised: the org.freedesktop.DBus.Hello call must have succeeded, +// and any authentication should be handled by the function. +func NewConnection(dialBus func() (*dbus.Conn, error)) (*Conn, error) { + sysconn, err := dialBus() + if err != nil { + return nil, err + } + + sigconn, err := dialBus() + if err != nil { + sysconn.Close() + return nil, err + } + + c := &Conn{ + sysconn: sysconn, + sysobj: systemdObject(sysconn), + sigconn: sigconn, + sigobj: systemdObject(sigconn), + } + + c.subscriber.ignore = make(map[dbus.ObjectPath]int64) + c.jobListener.jobs = make(map[dbus.ObjectPath]chan<- string) + + // Setup the listeners on jobs so that we can get completions + c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, + "type='signal', interface='org.freedesktop.systemd1.Manager', member='JobRemoved'") + + c.dispatch() + return c, nil +} + +// GetManagerProperty returns the value of a property on the org.freedesktop.systemd1.Manager +// interface. The value is returned in its string representation, as defined at +// https://developer.gnome.org/glib/unstable/gvariant-text.html +func (c *Conn) GetManagerProperty(prop string) (string, error) { + variant, err := c.sysobj.GetProperty("org.freedesktop.systemd1.Manager." + prop) + if err != nil { + return "", err + } + return variant.String(), nil +} + +func dbusAuthConnection(createBus func() (*dbus.Conn, error)) (*dbus.Conn, error) { + conn, err := createBus() + if err != nil { + return nil, err + } + + // Only use EXTERNAL method, and hardcode the uid (not username) + // to avoid a username lookup (which requires a dynamically linked + // libc) + methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))} + + err = conn.Auth(methods) + if err != nil { + conn.Close() + return nil, err + } + + return conn, nil +} + +func dbusAuthHelloConnection(createBus func() (*dbus.Conn, error)) (*dbus.Conn, error) { + conn, err := dbusAuthConnection(createBus) + if err != nil { + return nil, err + } + + if err = conn.Hello(); err != nil { + conn.Close() + return nil, err + } + + return conn, nil +} + +func systemdObject(conn *dbus.Conn) dbus.BusObject { + return conn.Object("org.freedesktop.systemd1", dbus.ObjectPath("/org/freedesktop/systemd1")) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/methods.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/methods.go new file mode 100644 index 00000000..ab17f7cc --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/methods.go @@ -0,0 +1,565 @@ +// Copyright 2015 CoreOS, 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 dbus + +import ( + "errors" + "path" + "strconv" + + "github.com/godbus/dbus" +) + +func (c *Conn) jobComplete(signal *dbus.Signal) { + var id uint32 + var job dbus.ObjectPath + var unit string + var result string + dbus.Store(signal.Body, &id, &job, &unit, &result) + c.jobListener.Lock() + out, ok := c.jobListener.jobs[job] + if ok { + out <- result + delete(c.jobListener.jobs, job) + } + c.jobListener.Unlock() +} + +func (c *Conn) startJob(ch chan<- string, job string, args ...interface{}) (int, error) { + if ch != nil { + c.jobListener.Lock() + defer c.jobListener.Unlock() + } + + var p dbus.ObjectPath + err := c.sysobj.Call(job, 0, args...).Store(&p) + if err != nil { + return 0, err + } + + if ch != nil { + c.jobListener.jobs[p] = ch + } + + // ignore error since 0 is fine if conversion fails + jobID, _ := strconv.Atoi(path.Base(string(p))) + + return jobID, nil +} + +// StartUnit enqueues a start job and depending jobs, if any (unless otherwise +// specified by the mode string). +// +// Takes the unit to activate, plus a mode string. The mode needs to be one of +// replace, fail, isolate, ignore-dependencies, ignore-requirements. If +// "replace" the call will start the unit and its dependencies, possibly +// replacing already queued jobs that conflict with this. If "fail" the call +// will start the unit and its dependencies, but will fail if this would change +// an already queued job. If "isolate" the call will start the unit in question +// and terminate all units that aren't dependencies of it. If +// "ignore-dependencies" it will start a unit but ignore all its dependencies. +// If "ignore-requirements" it will start a unit but only ignore the +// requirement dependencies. It is not recommended to make use of the latter +// two options. +// +// If the provided channel is non-nil, a result string will be sent to it upon +// job completion: one of done, canceled, timeout, failed, dependency, skipped. +// done indicates successful execution of a job. canceled indicates that a job +// has been canceled before it finished execution. timeout indicates that the +// job timeout was reached. failed indicates that the job failed. dependency +// indicates that a job this job has been depending on failed and the job hence +// has been removed too. skipped indicates that a job was skipped because it +// didn't apply to the units current state. +// +// If no error occurs, the ID of the underlying systemd job will be returned. There +// does exist the possibility for no error to be returned, but for the returned job +// ID to be 0. In this case, the actual underlying ID is not 0 and this datapoint +// should not be considered authoritative. +// +// If an error does occur, it will be returned to the user alongside a job ID of 0. +func (c *Conn) StartUnit(name string, mode string, ch chan<- string) (int, error) { + return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartUnit", name, mode) +} + +// StopUnit is similar to StartUnit but stops the specified unit rather +// than starting it. +func (c *Conn) StopUnit(name string, mode string, ch chan<- string) (int, error) { + return c.startJob(ch, "org.freedesktop.systemd1.Manager.StopUnit", name, mode) +} + +// ReloadUnit reloads a unit. Reloading is done only if the unit is already running and fails otherwise. +func (c *Conn) ReloadUnit(name string, mode string, ch chan<- string) (int, error) { + return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadUnit", name, mode) +} + +// RestartUnit restarts a service. If a service is restarted that isn't +// running it will be started. +func (c *Conn) RestartUnit(name string, mode string, ch chan<- string) (int, error) { + return c.startJob(ch, "org.freedesktop.systemd1.Manager.RestartUnit", name, mode) +} + +// TryRestartUnit is like RestartUnit, except that a service that isn't running +// is not affected by the restart. +func (c *Conn) TryRestartUnit(name string, mode string, ch chan<- string) (int, error) { + return c.startJob(ch, "org.freedesktop.systemd1.Manager.TryRestartUnit", name, mode) +} + +// ReloadOrRestart attempts a reload if the unit supports it and use a restart +// otherwise. +func (c *Conn) ReloadOrRestartUnit(name string, mode string, ch chan<- string) (int, error) { + return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrRestartUnit", name, mode) +} + +// ReloadOrTryRestart attempts a reload if the unit supports it and use a "Try" +// flavored restart otherwise. +func (c *Conn) ReloadOrTryRestartUnit(name string, mode string, ch chan<- string) (int, error) { + return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrTryRestartUnit", name, mode) +} + +// StartTransientUnit() may be used to create and start a transient unit, which +// will be released as soon as it is not running or referenced anymore or the +// system is rebooted. name is the unit name including suffix, and must be +// unique. mode is the same as in StartUnit(), properties contains properties +// of the unit. +func (c *Conn) StartTransientUnit(name string, mode string, properties []Property, ch chan<- string) (int, error) { + return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartTransientUnit", name, mode, properties, make([]PropertyCollection, 0)) +} + +// KillUnit takes the unit name and a UNIX signal number to send. All of the unit's +// processes are killed. +func (c *Conn) KillUnit(name string, signal int32) { + c.sysobj.Call("org.freedesktop.systemd1.Manager.KillUnit", 0, name, "all", signal).Store() +} + +// ResetFailedUnit resets the "failed" state of a specific unit. +func (c *Conn) ResetFailedUnit(name string) error { + return c.sysobj.Call("org.freedesktop.systemd1.Manager.ResetFailedUnit", 0, name).Store() +} + +// getProperties takes the unit name and returns all of its dbus object properties, for the given dbus interface +func (c *Conn) getProperties(unit string, dbusInterface string) (map[string]interface{}, error) { + var err error + var props map[string]dbus.Variant + + path := unitPath(unit) + if !path.IsValid() { + return nil, errors.New("invalid unit name: " + unit) + } + + obj := c.sysconn.Object("org.freedesktop.systemd1", path) + err = obj.Call("org.freedesktop.DBus.Properties.GetAll", 0, dbusInterface).Store(&props) + if err != nil { + return nil, err + } + + out := make(map[string]interface{}, len(props)) + for k, v := range props { + out[k] = v.Value() + } + + return out, nil +} + +// GetUnitProperties takes the unit name and returns all of its dbus object properties. +func (c *Conn) GetUnitProperties(unit string) (map[string]interface{}, error) { + return c.getProperties(unit, "org.freedesktop.systemd1.Unit") +} + +func (c *Conn) getProperty(unit string, dbusInterface string, propertyName string) (*Property, error) { + var err error + var prop dbus.Variant + + path := unitPath(unit) + if !path.IsValid() { + return nil, errors.New("invalid unit name: " + unit) + } + + obj := c.sysconn.Object("org.freedesktop.systemd1", path) + err = obj.Call("org.freedesktop.DBus.Properties.Get", 0, dbusInterface, propertyName).Store(&prop) + if err != nil { + return nil, err + } + + return &Property{Name: propertyName, Value: prop}, nil +} + +func (c *Conn) GetUnitProperty(unit string, propertyName string) (*Property, error) { + return c.getProperty(unit, "org.freedesktop.systemd1.Unit", propertyName) +} + +// GetServiceProperty returns property for given service name and property name +func (c *Conn) GetServiceProperty(service string, propertyName string) (*Property, error) { + return c.getProperty(service, "org.freedesktop.systemd1.Service", propertyName) +} + +// GetUnitTypeProperties returns the extra properties for a unit, specific to the unit type. +// Valid values for unitType: Service, Socket, Target, Device, Mount, Automount, Snapshot, Timer, Swap, Path, Slice, Scope +// return "dbus.Error: Unknown interface" if the unitType is not the correct type of the unit +func (c *Conn) GetUnitTypeProperties(unit string, unitType string) (map[string]interface{}, error) { + return c.getProperties(unit, "org.freedesktop.systemd1."+unitType) +} + +// SetUnitProperties() may be used to modify certain unit properties at runtime. +// Not all properties may be changed at runtime, but many resource management +// settings (primarily those in systemd.cgroup(5)) may. The changes are applied +// instantly, and stored on disk for future boots, unless runtime is true, in which +// case the settings only apply until the next reboot. name is the name of the unit +// to modify. properties are the settings to set, encoded as an array of property +// name and value pairs. +func (c *Conn) SetUnitProperties(name string, runtime bool, properties ...Property) error { + return c.sysobj.Call("org.freedesktop.systemd1.Manager.SetUnitProperties", 0, name, runtime, properties).Store() +} + +func (c *Conn) GetUnitTypeProperty(unit string, unitType string, propertyName string) (*Property, error) { + return c.getProperty(unit, "org.freedesktop.systemd1."+unitType, propertyName) +} + +type UnitStatus struct { + Name string // The primary unit name as string + Description string // The human readable description string + LoadState string // The load state (i.e. whether the unit file has been loaded successfully) + ActiveState string // The active state (i.e. whether the unit is currently started or not) + SubState string // The sub state (a more fine-grained version of the active state that is specific to the unit type, which the active state is not) + Followed string // A unit that is being followed in its state by this unit, if there is any, otherwise the empty string. + Path dbus.ObjectPath // The unit object path + JobId uint32 // If there is a job queued for the job unit the numeric job id, 0 otherwise + JobType string // The job type as string + JobPath dbus.ObjectPath // The job object path +} + +type storeFunc func(retvalues ...interface{}) error + +func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) { + result := make([][]interface{}, 0) + err := f(&result) + if err != nil { + return nil, err + } + + resultInterface := make([]interface{}, len(result)) + for i := range result { + resultInterface[i] = result[i] + } + + status := make([]UnitStatus, len(result)) + statusInterface := make([]interface{}, len(status)) + for i := range status { + statusInterface[i] = &status[i] + } + + err = dbus.Store(resultInterface, statusInterface...) + if err != nil { + return nil, err + } + + return status, nil +} + +// ListUnits returns an array with all currently loaded units. Note that +// units may be known by multiple names at the same time, and hence there might +// be more unit names loaded than actual units behind them. +func (c *Conn) ListUnits() ([]UnitStatus, error) { + return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnits", 0).Store) +} + +// ListUnitsFiltered returns an array with units filtered by state. +// It takes a list of units' statuses to filter. +func (c *Conn) ListUnitsFiltered(states []string) ([]UnitStatus, error) { + return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsFiltered", 0, states).Store) +} + +// ListUnitsByPatterns returns an array with units. +// It takes a list of units' statuses and names to filter. +// Note that units may be known by multiple names at the same time, +// and hence there might be more unit names loaded than actual units behind them. +func (c *Conn) ListUnitsByPatterns(states []string, patterns []string) ([]UnitStatus, error) { + return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsByPatterns", 0, states, patterns).Store) +} + +// ListUnitsByNames returns an array with units. It takes a list of units' +// names and returns an UnitStatus array. Comparing to ListUnitsByPatterns +// method, this method returns statuses even for inactive or non-existing +// units. Input array should contain exact unit names, but not patterns. +func (c *Conn) ListUnitsByNames(units []string) ([]UnitStatus, error) { + return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsByNames", 0, units).Store) +} + +type UnitFile struct { + Path string + Type string +} + +func (c *Conn) listUnitFilesInternal(f storeFunc) ([]UnitFile, error) { + result := make([][]interface{}, 0) + err := f(&result) + if err != nil { + return nil, err + } + + resultInterface := make([]interface{}, len(result)) + for i := range result { + resultInterface[i] = result[i] + } + + files := make([]UnitFile, len(result)) + fileInterface := make([]interface{}, len(files)) + for i := range files { + fileInterface[i] = &files[i] + } + + err = dbus.Store(resultInterface, fileInterface...) + if err != nil { + return nil, err + } + + return files, nil +} + +// ListUnitFiles returns an array of all available units on disk. +func (c *Conn) ListUnitFiles() ([]UnitFile, error) { + return c.listUnitFilesInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitFiles", 0).Store) +} + +// ListUnitFilesByPatterns returns an array of all available units on disk matched the patterns. +func (c *Conn) ListUnitFilesByPatterns(states []string, patterns []string) ([]UnitFile, error) { + return c.listUnitFilesInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitFilesByPatterns", 0, states, patterns).Store) +} + +type LinkUnitFileChange EnableUnitFileChange + +// LinkUnitFiles() links unit files (that are located outside of the +// usual unit search paths) into the unit search path. +// +// It takes a list of absolute paths to unit files to link and two +// booleans. The first boolean controls whether the unit shall be +// enabled for runtime only (true, /run), or persistently (false, +// /etc). +// The second controls whether symlinks pointing to other units shall +// be replaced if necessary. +// +// This call returns a list of the changes made. The list consists of +// structures with three strings: the type of the change (one of symlink +// or unlink), the file name of the symlink and the destination of the +// symlink. +func (c *Conn) LinkUnitFiles(files []string, runtime bool, force bool) ([]LinkUnitFileChange, error) { + result := make([][]interface{}, 0) + err := c.sysobj.Call("org.freedesktop.systemd1.Manager.LinkUnitFiles", 0, files, runtime, force).Store(&result) + if err != nil { + return nil, err + } + + resultInterface := make([]interface{}, len(result)) + for i := range result { + resultInterface[i] = result[i] + } + + changes := make([]LinkUnitFileChange, len(result)) + changesInterface := make([]interface{}, len(changes)) + for i := range changes { + changesInterface[i] = &changes[i] + } + + err = dbus.Store(resultInterface, changesInterface...) + if err != nil { + return nil, err + } + + return changes, nil +} + +// EnableUnitFiles() may be used to enable one or more units in the system (by +// creating symlinks to them in /etc or /run). +// +// It takes a list of unit files to enable (either just file names or full +// absolute paths if the unit files are residing outside the usual unit +// search paths), and two booleans: the first controls whether the unit shall +// be enabled for runtime only (true, /run), or persistently (false, /etc). +// The second one controls whether symlinks pointing to other units shall +// be replaced if necessary. +// +// This call returns one boolean and an array with the changes made. The +// boolean signals whether the unit files contained any enablement +// information (i.e. an [Install]) section. The changes list consists of +// structures with three strings: the type of the change (one of symlink +// or unlink), the file name of the symlink and the destination of the +// symlink. +func (c *Conn) EnableUnitFiles(files []string, runtime bool, force bool) (bool, []EnableUnitFileChange, error) { + var carries_install_info bool + + result := make([][]interface{}, 0) + err := c.sysobj.Call("org.freedesktop.systemd1.Manager.EnableUnitFiles", 0, files, runtime, force).Store(&carries_install_info, &result) + if err != nil { + return false, nil, err + } + + resultInterface := make([]interface{}, len(result)) + for i := range result { + resultInterface[i] = result[i] + } + + changes := make([]EnableUnitFileChange, len(result)) + changesInterface := make([]interface{}, len(changes)) + for i := range changes { + changesInterface[i] = &changes[i] + } + + err = dbus.Store(resultInterface, changesInterface...) + if err != nil { + return false, nil, err + } + + return carries_install_info, changes, nil +} + +type EnableUnitFileChange struct { + Type string // Type of the change (one of symlink or unlink) + Filename string // File name of the symlink + Destination string // Destination of the symlink +} + +// DisableUnitFiles() may be used to disable one or more units in the system (by +// removing symlinks to them from /etc or /run). +// +// It takes a list of unit files to disable (either just file names or full +// absolute paths if the unit files are residing outside the usual unit +// search paths), and one boolean: whether the unit was enabled for runtime +// only (true, /run), or persistently (false, /etc). +// +// This call returns an array with the changes made. The changes list +// consists of structures with three strings: the type of the change (one of +// symlink or unlink), the file name of the symlink and the destination of the +// symlink. +func (c *Conn) DisableUnitFiles(files []string, runtime bool) ([]DisableUnitFileChange, error) { + result := make([][]interface{}, 0) + err := c.sysobj.Call("org.freedesktop.systemd1.Manager.DisableUnitFiles", 0, files, runtime).Store(&result) + if err != nil { + return nil, err + } + + resultInterface := make([]interface{}, len(result)) + for i := range result { + resultInterface[i] = result[i] + } + + changes := make([]DisableUnitFileChange, len(result)) + changesInterface := make([]interface{}, len(changes)) + for i := range changes { + changesInterface[i] = &changes[i] + } + + err = dbus.Store(resultInterface, changesInterface...) + if err != nil { + return nil, err + } + + return changes, nil +} + +type DisableUnitFileChange struct { + Type string // Type of the change (one of symlink or unlink) + Filename string // File name of the symlink + Destination string // Destination of the symlink +} + +// MaskUnitFiles masks one or more units in the system +// +// It takes three arguments: +// * list of units to mask (either just file names or full +// absolute paths if the unit files are residing outside +// the usual unit search paths) +// * runtime to specify whether the unit was enabled for runtime +// only (true, /run/systemd/..), or persistently (false, /etc/systemd/..) +// * force flag +func (c *Conn) MaskUnitFiles(files []string, runtime bool, force bool) ([]MaskUnitFileChange, error) { + result := make([][]interface{}, 0) + err := c.sysobj.Call("org.freedesktop.systemd1.Manager.MaskUnitFiles", 0, files, runtime, force).Store(&result) + if err != nil { + return nil, err + } + + resultInterface := make([]interface{}, len(result)) + for i := range result { + resultInterface[i] = result[i] + } + + changes := make([]MaskUnitFileChange, len(result)) + changesInterface := make([]interface{}, len(changes)) + for i := range changes { + changesInterface[i] = &changes[i] + } + + err = dbus.Store(resultInterface, changesInterface...) + if err != nil { + return nil, err + } + + return changes, nil +} + +type MaskUnitFileChange struct { + Type string // Type of the change (one of symlink or unlink) + Filename string // File name of the symlink + Destination string // Destination of the symlink +} + +// UnmaskUnitFiles unmasks one or more units in the system +// +// It takes two arguments: +// * list of unit files to mask (either just file names or full +// absolute paths if the unit files are residing outside +// the usual unit search paths) +// * runtime to specify whether the unit was enabled for runtime +// only (true, /run/systemd/..), or persistently (false, /etc/systemd/..) +func (c *Conn) UnmaskUnitFiles(files []string, runtime bool) ([]UnmaskUnitFileChange, error) { + result := make([][]interface{}, 0) + err := c.sysobj.Call("org.freedesktop.systemd1.Manager.UnmaskUnitFiles", 0, files, runtime).Store(&result) + if err != nil { + return nil, err + } + + resultInterface := make([]interface{}, len(result)) + for i := range result { + resultInterface[i] = result[i] + } + + changes := make([]UnmaskUnitFileChange, len(result)) + changesInterface := make([]interface{}, len(changes)) + for i := range changes { + changesInterface[i] = &changes[i] + } + + err = dbus.Store(resultInterface, changesInterface...) + if err != nil { + return nil, err + } + + return changes, nil +} + +type UnmaskUnitFileChange struct { + Type string // Type of the change (one of symlink or unlink) + Filename string // File name of the symlink + Destination string // Destination of the symlink +} + +// Reload instructs systemd to scan for and reload unit files. This is +// equivalent to a 'systemctl daemon-reload'. +func (c *Conn) Reload() error { + return c.sysobj.Call("org.freedesktop.systemd1.Manager.Reload", 0).Store() +} + +func unitPath(name string) dbus.ObjectPath { + return dbus.ObjectPath("/org/freedesktop/systemd1/unit/" + PathBusEscape(name)) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/properties.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/properties.go new file mode 100644 index 00000000..6c818958 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/properties.go @@ -0,0 +1,237 @@ +// Copyright 2015 CoreOS, 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 dbus + +import ( + "github.com/godbus/dbus" +) + +// From the systemd docs: +// +// The properties array of StartTransientUnit() may take many of the settings +// that may also be configured in unit files. Not all parameters are currently +// accepted though, but we plan to cover more properties with future release. +// Currently you may set the Description, Slice and all dependency types of +// units, as well as RemainAfterExit, ExecStart for service units, +// TimeoutStopUSec and PIDs for scope units, and CPUAccounting, CPUShares, +// BlockIOAccounting, BlockIOWeight, BlockIOReadBandwidth, +// BlockIOWriteBandwidth, BlockIODeviceWeight, MemoryAccounting, MemoryLimit, +// DevicePolicy, DeviceAllow for services/scopes/slices. These fields map +// directly to their counterparts in unit files and as normal D-Bus object +// properties. The exception here is the PIDs field of scope units which is +// used for construction of the scope only and specifies the initial PIDs to +// add to the scope object. + +type Property struct { + Name string + Value dbus.Variant +} + +type PropertyCollection struct { + Name string + Properties []Property +} + +type execStart struct { + Path string // the binary path to execute + Args []string // an array with all arguments to pass to the executed command, starting with argument 0 + UncleanIsFailure bool // a boolean whether it should be considered a failure if the process exits uncleanly +} + +// PropExecStart sets the ExecStart service property. The first argument is a +// slice with the binary path to execute followed by the arguments to pass to +// the executed command. See +// http://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart= +func PropExecStart(command []string, uncleanIsFailure bool) Property { + execStarts := []execStart{ + execStart{ + Path: command[0], + Args: command, + UncleanIsFailure: uncleanIsFailure, + }, + } + + return Property{ + Name: "ExecStart", + Value: dbus.MakeVariant(execStarts), + } +} + +// PropRemainAfterExit sets the RemainAfterExit service property. See +// http://www.freedesktop.org/software/systemd/man/systemd.service.html#RemainAfterExit= +func PropRemainAfterExit(b bool) Property { + return Property{ + Name: "RemainAfterExit", + Value: dbus.MakeVariant(b), + } +} + +// PropType sets the Type service property. See +// http://www.freedesktop.org/software/systemd/man/systemd.service.html#Type= +func PropType(t string) Property { + return Property{ + Name: "Type", + Value: dbus.MakeVariant(t), + } +} + +// PropDescription sets the Description unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit#Description= +func PropDescription(desc string) Property { + return Property{ + Name: "Description", + Value: dbus.MakeVariant(desc), + } +} + +func propDependency(name string, units []string) Property { + return Property{ + Name: name, + Value: dbus.MakeVariant(units), + } +} + +// PropRequires sets the Requires unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requires= +func PropRequires(units ...string) Property { + return propDependency("Requires", units) +} + +// PropRequiresOverridable sets the RequiresOverridable unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresOverridable= +func PropRequiresOverridable(units ...string) Property { + return propDependency("RequiresOverridable", units) +} + +// PropRequisite sets the Requisite unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requisite= +func PropRequisite(units ...string) Property { + return propDependency("Requisite", units) +} + +// PropRequisiteOverridable sets the RequisiteOverridable unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequisiteOverridable= +func PropRequisiteOverridable(units ...string) Property { + return propDependency("RequisiteOverridable", units) +} + +// PropWants sets the Wants unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Wants= +func PropWants(units ...string) Property { + return propDependency("Wants", units) +} + +// PropBindsTo sets the BindsTo unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#BindsTo= +func PropBindsTo(units ...string) Property { + return propDependency("BindsTo", units) +} + +// PropRequiredBy sets the RequiredBy unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredBy= +func PropRequiredBy(units ...string) Property { + return propDependency("RequiredBy", units) +} + +// PropRequiredByOverridable sets the RequiredByOverridable unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredByOverridable= +func PropRequiredByOverridable(units ...string) Property { + return propDependency("RequiredByOverridable", units) +} + +// PropWantedBy sets the WantedBy unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#WantedBy= +func PropWantedBy(units ...string) Property { + return propDependency("WantedBy", units) +} + +// PropBoundBy sets the BoundBy unit property. See +// http://www.freedesktop.org/software/systemd/main/systemd.unit.html#BoundBy= +func PropBoundBy(units ...string) Property { + return propDependency("BoundBy", units) +} + +// PropConflicts sets the Conflicts unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Conflicts= +func PropConflicts(units ...string) Property { + return propDependency("Conflicts", units) +} + +// PropConflictedBy sets the ConflictedBy unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#ConflictedBy= +func PropConflictedBy(units ...string) Property { + return propDependency("ConflictedBy", units) +} + +// PropBefore sets the Before unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Before= +func PropBefore(units ...string) Property { + return propDependency("Before", units) +} + +// PropAfter sets the After unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#After= +func PropAfter(units ...string) Property { + return propDependency("After", units) +} + +// PropOnFailure sets the OnFailure unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#OnFailure= +func PropOnFailure(units ...string) Property { + return propDependency("OnFailure", units) +} + +// PropTriggers sets the Triggers unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Triggers= +func PropTriggers(units ...string) Property { + return propDependency("Triggers", units) +} + +// PropTriggeredBy sets the TriggeredBy unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#TriggeredBy= +func PropTriggeredBy(units ...string) Property { + return propDependency("TriggeredBy", units) +} + +// PropPropagatesReloadTo sets the PropagatesReloadTo unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#PropagatesReloadTo= +func PropPropagatesReloadTo(units ...string) Property { + return propDependency("PropagatesReloadTo", units) +} + +// PropRequiresMountsFor sets the RequiresMountsFor unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresMountsFor= +func PropRequiresMountsFor(units ...string) Property { + return propDependency("RequiresMountsFor", units) +} + +// PropSlice sets the Slice unit property. See +// http://www.freedesktop.org/software/systemd/man/systemd.resource-control.html#Slice= +func PropSlice(slice string) Property { + return Property{ + Name: "Slice", + Value: dbus.MakeVariant(slice), + } +} + +// PropPids sets the PIDs field of scope units used in the initial construction +// of the scope only and specifies the initial PIDs to add to the scope object. +// See https://www.freedesktop.org/wiki/Software/systemd/ControlGroupInterface/#properties +func PropPids(pids ...uint32) Property { + return Property{ + Name: "PIDs", + Value: dbus.MakeVariant(pids), + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/set.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/set.go new file mode 100644 index 00000000..f92e6fbe --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/set.go @@ -0,0 +1,47 @@ +// Copyright 2015 CoreOS, 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 dbus + +type set struct { + data map[string]bool +} + +func (s *set) Add(value string) { + s.data[value] = true +} + +func (s *set) Remove(value string) { + delete(s.data, value) +} + +func (s *set) Contains(value string) (exists bool) { + _, exists = s.data[value] + return +} + +func (s *set) Length() int { + return len(s.data) +} + +func (s *set) Values() (values []string) { + for val, _ := range s.data { + values = append(values, val) + } + return +} + +func newSet() *set { + return &set{make(map[string]bool)} +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription.go new file mode 100644 index 00000000..99645144 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription.go @@ -0,0 +1,250 @@ +// Copyright 2015 CoreOS, 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 dbus + +import ( + "errors" + "time" + + "github.com/godbus/dbus" +) + +const ( + cleanIgnoreInterval = int64(10 * time.Second) + ignoreInterval = int64(30 * time.Millisecond) +) + +// Subscribe sets up this connection to subscribe to all systemd dbus events. +// This is required before calling SubscribeUnits. When the connection closes +// systemd will automatically stop sending signals so there is no need to +// explicitly call Unsubscribe(). +func (c *Conn) Subscribe() error { + c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, + "type='signal',interface='org.freedesktop.systemd1.Manager',member='UnitNew'") + c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, + "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'") + + err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Subscribe", 0).Store() + if err != nil { + return err + } + + return nil +} + +// Unsubscribe this connection from systemd dbus events. +func (c *Conn) Unsubscribe() error { + err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Unsubscribe", 0).Store() + if err != nil { + return err + } + + return nil +} + +func (c *Conn) dispatch() { + ch := make(chan *dbus.Signal, signalBuffer) + + c.sigconn.Signal(ch) + + go func() { + for { + signal, ok := <-ch + if !ok { + return + } + + if signal.Name == "org.freedesktop.systemd1.Manager.JobRemoved" { + c.jobComplete(signal) + } + + if c.subscriber.updateCh == nil { + continue + } + + var unitPath dbus.ObjectPath + switch signal.Name { + case "org.freedesktop.systemd1.Manager.JobRemoved": + unitName := signal.Body[2].(string) + c.sysobj.Call("org.freedesktop.systemd1.Manager.GetUnit", 0, unitName).Store(&unitPath) + case "org.freedesktop.systemd1.Manager.UnitNew": + unitPath = signal.Body[1].(dbus.ObjectPath) + case "org.freedesktop.DBus.Properties.PropertiesChanged": + if signal.Body[0].(string) == "org.freedesktop.systemd1.Unit" { + unitPath = signal.Path + } + } + + if unitPath == dbus.ObjectPath("") { + continue + } + + c.sendSubStateUpdate(unitPath) + } + }() +} + +// Returns two unbuffered channels which will receive all changed units every +// interval. Deleted units are sent as nil. +func (c *Conn) SubscribeUnits(interval time.Duration) (<-chan map[string]*UnitStatus, <-chan error) { + return c.SubscribeUnitsCustom(interval, 0, func(u1, u2 *UnitStatus) bool { return *u1 != *u2 }, nil) +} + +// SubscribeUnitsCustom is like SubscribeUnits but lets you specify the buffer +// size of the channels, the comparison function for detecting changes and a filter +// function for cutting down on the noise that your channel receives. +func (c *Conn) SubscribeUnitsCustom(interval time.Duration, buffer int, isChanged func(*UnitStatus, *UnitStatus) bool, filterUnit func(string) bool) (<-chan map[string]*UnitStatus, <-chan error) { + old := make(map[string]*UnitStatus) + statusChan := make(chan map[string]*UnitStatus, buffer) + errChan := make(chan error, buffer) + + go func() { + for { + timerChan := time.After(interval) + + units, err := c.ListUnits() + if err == nil { + cur := make(map[string]*UnitStatus) + for i := range units { + if filterUnit != nil && filterUnit(units[i].Name) { + continue + } + cur[units[i].Name] = &units[i] + } + + // add all new or changed units + changed := make(map[string]*UnitStatus) + for n, u := range cur { + if oldU, ok := old[n]; !ok || isChanged(oldU, u) { + changed[n] = u + } + delete(old, n) + } + + // add all deleted units + for oldN := range old { + changed[oldN] = nil + } + + old = cur + + if len(changed) != 0 { + statusChan <- changed + } + } else { + errChan <- err + } + + <-timerChan + } + }() + + return statusChan, errChan +} + +type SubStateUpdate struct { + UnitName string + SubState string +} + +// SetSubStateSubscriber writes to updateCh when any unit's substate changes. +// Although this writes to updateCh on every state change, the reported state +// may be more recent than the change that generated it (due to an unavoidable +// race in the systemd dbus interface). That is, this method provides a good +// way to keep a current view of all units' states, but is not guaranteed to +// show every state transition they go through. Furthermore, state changes +// will only be written to the channel with non-blocking writes. If updateCh +// is full, it attempts to write an error to errCh; if errCh is full, the error +// passes silently. +func (c *Conn) SetSubStateSubscriber(updateCh chan<- *SubStateUpdate, errCh chan<- error) { + c.subscriber.Lock() + defer c.subscriber.Unlock() + c.subscriber.updateCh = updateCh + c.subscriber.errCh = errCh +} + +func (c *Conn) sendSubStateUpdate(path dbus.ObjectPath) { + c.subscriber.Lock() + defer c.subscriber.Unlock() + + if c.shouldIgnore(path) { + return + } + + info, err := c.GetUnitProperties(string(path)) + if err != nil { + select { + case c.subscriber.errCh <- err: + default: + } + } + + name := info["Id"].(string) + substate := info["SubState"].(string) + + update := &SubStateUpdate{name, substate} + select { + case c.subscriber.updateCh <- update: + default: + select { + case c.subscriber.errCh <- errors.New("update channel full!"): + default: + } + } + + c.updateIgnore(path, info) +} + +// The ignore functions work around a wart in the systemd dbus interface. +// Requesting the properties of an unloaded unit will cause systemd to send a +// pair of UnitNew/UnitRemoved signals. Because we need to get a unit's +// properties on UnitNew (as that's the only indication of a new unit coming up +// for the first time), we would enter an infinite loop if we did not attempt +// to detect and ignore these spurious signals. The signal themselves are +// indistinguishable from relevant ones, so we (somewhat hackishly) ignore an +// unloaded unit's signals for a short time after requesting its properties. +// This means that we will miss e.g. a transient unit being restarted +// *immediately* upon failure and also a transient unit being started +// immediately after requesting its status (with systemctl status, for example, +// because this causes a UnitNew signal to be sent which then causes us to fetch +// the properties). + +func (c *Conn) shouldIgnore(path dbus.ObjectPath) bool { + t, ok := c.subscriber.ignore[path] + return ok && t >= time.Now().UnixNano() +} + +func (c *Conn) updateIgnore(path dbus.ObjectPath, info map[string]interface{}) { + c.cleanIgnore() + + // unit is unloaded - it will trigger bad systemd dbus behavior + if info["LoadState"].(string) == "not-found" { + c.subscriber.ignore[path] = time.Now().UnixNano() + ignoreInterval + } +} + +// without this, ignore would grow unboundedly over time +func (c *Conn) cleanIgnore() { + now := time.Now().UnixNano() + if c.subscriber.cleanIgnore < now { + c.subscriber.cleanIgnore = now + cleanIgnoreInterval + + for p, t := range c.subscriber.ignore { + if t < now { + delete(c.subscriber.ignore, p) + } + } + } +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_set.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_set.go new file mode 100644 index 00000000..5b408d58 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_set.go @@ -0,0 +1,57 @@ +// Copyright 2015 CoreOS, 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 dbus + +import ( + "time" +) + +// SubscriptionSet returns a subscription set which is like conn.Subscribe but +// can filter to only return events for a set of units. +type SubscriptionSet struct { + *set + conn *Conn +} + +func (s *SubscriptionSet) filter(unit string) bool { + return !s.Contains(unit) +} + +// Subscribe starts listening for dbus events for all of the units in the set. +// Returns channels identical to conn.SubscribeUnits. +func (s *SubscriptionSet) Subscribe() (<-chan map[string]*UnitStatus, <-chan error) { + // TODO: Make fully evented by using systemd 209 with properties changed values + return s.conn.SubscribeUnitsCustom(time.Second, 0, + mismatchUnitStatus, + func(unit string) bool { return s.filter(unit) }, + ) +} + +// NewSubscriptionSet returns a new subscription set. +func (conn *Conn) NewSubscriptionSet() *SubscriptionSet { + return &SubscriptionSet{newSet(), conn} +} + +// mismatchUnitStatus returns true if the provided UnitStatus objects +// are not equivalent. false is returned if the objects are equivalent. +// Only the Name, Description and state-related fields are used in +// the comparison. +func mismatchUnitStatus(u1, u2 *UnitStatus) bool { + return u1.Name != u2.Name || + u1.Description != u2.Description || + u1.LoadState != u2.LoadState || + u1.ActiveState != u2.ActiveState || + u1.SubState != u2.SubState +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util.go new file mode 100644 index 00000000..7828ce6f --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util.go @@ -0,0 +1,90 @@ +// Copyright 2015 CoreOS, 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 util contains utility functions related to systemd that applications +// can use to check things like whether systemd is running. Note that some of +// these functions attempt to manually load systemd libraries at runtime rather +// than linking against them. +package util + +import ( + "fmt" + "io/ioutil" + "os" + "strings" +) + +var ( + ErrNoCGO = fmt.Errorf("go-systemd built with CGO disabled") +) + +// GetRunningSlice attempts to retrieve the name of the systemd slice in which +// the current process is running. +// This function is a wrapper around the libsystemd C library; if it cannot be +// opened, an error is returned. +func GetRunningSlice() (string, error) { + return getRunningSlice() +} + +// RunningFromSystemService tries to detect whether the current process has +// been invoked from a system service. The condition for this is whether the +// process is _not_ a user process. User processes are those running in session +// scopes or under per-user `systemd --user` instances. +// +// To avoid false positives on systems without `pam_systemd` (which is +// responsible for creating user sessions), this function also uses a heuristic +// to detect whether it's being invoked from a session leader process. This is +// the case if the current process is executed directly from a service file +// (e.g. with `ExecStart=/this/cmd`). Note that this heuristic will fail if the +// command is instead launched in a subshell or similar so that it is not +// session leader (e.g. `ExecStart=/bin/bash -c "/this/cmd"`) +// +// This function is a wrapper around the libsystemd C library; if this is +// unable to successfully open a handle to the library for any reason (e.g. it +// cannot be found), an error will be returned. +func RunningFromSystemService() (bool, error) { + return runningFromSystemService() +} + +// CurrentUnitName attempts to retrieve the name of the systemd system unit +// from which the calling process has been invoked. It wraps the systemd +// `sd_pid_get_unit` call, with the same caveat: for processes not part of a +// systemd system unit, this function will return an error. +func CurrentUnitName() (string, error) { + return currentUnitName() +} + +// IsRunningSystemd checks whether the host was booted with systemd as its init +// system. This functions similarly to systemd's `sd_booted(3)`: internally, it +// checks whether /run/systemd/system/ exists and is a directory. +// http://www.freedesktop.org/software/systemd/man/sd_booted.html +func IsRunningSystemd() bool { + fi, err := os.Lstat("/run/systemd/system") + if err != nil { + return false + } + return fi.IsDir() +} + +// GetMachineID returns a host's 128-bit machine ID as a string. This functions +// similarly to systemd's `sd_id128_get_machine`: internally, it simply reads +// the contents of /etc/machine-id +// http://www.freedesktop.org/software/systemd/man/sd_id128_get_machine.html +func GetMachineID() (string, error) { + machineID, err := ioutil.ReadFile("/etc/machine-id") + if err != nil { + return "", fmt.Errorf("failed to read /etc/machine-id: %v", err) + } + return strings.TrimSpace(string(machineID)), nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util_cgo.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util_cgo.go new file mode 100644 index 00000000..22c0d609 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util_cgo.go @@ -0,0 +1,174 @@ +// Copyright 2016 CoreOS, 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. + +// +build cgo + +package util + +// #include +// #include +// #include +// +// int +// my_sd_pid_get_owner_uid(void *f, pid_t pid, uid_t *uid) +// { +// int (*sd_pid_get_owner_uid)(pid_t, uid_t *); +// +// sd_pid_get_owner_uid = (int (*)(pid_t, uid_t *))f; +// return sd_pid_get_owner_uid(pid, uid); +// } +// +// int +// my_sd_pid_get_unit(void *f, pid_t pid, char **unit) +// { +// int (*sd_pid_get_unit)(pid_t, char **); +// +// sd_pid_get_unit = (int (*)(pid_t, char **))f; +// return sd_pid_get_unit(pid, unit); +// } +// +// int +// my_sd_pid_get_slice(void *f, pid_t pid, char **slice) +// { +// int (*sd_pid_get_slice)(pid_t, char **); +// +// sd_pid_get_slice = (int (*)(pid_t, char **))f; +// return sd_pid_get_slice(pid, slice); +// } +// +// int +// am_session_leader() +// { +// return (getsid(0) == getpid()); +// } +import "C" +import ( + "fmt" + "syscall" + "unsafe" + + "github.com/coreos/pkg/dlopen" +) + +var libsystemdNames = []string{ + // systemd < 209 + "libsystemd-login.so.0", + "libsystemd-login.so", + + // systemd >= 209 merged libsystemd-login into libsystemd proper + "libsystemd.so.0", + "libsystemd.so", +} + +func getRunningSlice() (slice string, err error) { + var h *dlopen.LibHandle + h, err = dlopen.GetHandle(libsystemdNames) + if err != nil { + return + } + defer func() { + if err1 := h.Close(); err1 != nil { + err = err1 + } + }() + + sd_pid_get_slice, err := h.GetSymbolPointer("sd_pid_get_slice") + if err != nil { + return + } + + var s string + sl := C.CString(s) + defer C.free(unsafe.Pointer(sl)) + + ret := C.my_sd_pid_get_slice(sd_pid_get_slice, 0, &sl) + if ret < 0 { + err = fmt.Errorf("error calling sd_pid_get_slice: %v", syscall.Errno(-ret)) + return + } + + return C.GoString(sl), nil +} + +func runningFromSystemService() (ret bool, err error) { + var h *dlopen.LibHandle + h, err = dlopen.GetHandle(libsystemdNames) + if err != nil { + return + } + defer func() { + if err1 := h.Close(); err1 != nil { + err = err1 + } + }() + + sd_pid_get_owner_uid, err := h.GetSymbolPointer("sd_pid_get_owner_uid") + if err != nil { + return + } + + var uid C.uid_t + errno := C.my_sd_pid_get_owner_uid(sd_pid_get_owner_uid, 0, &uid) + serrno := syscall.Errno(-errno) + // when we're running from a unit file, sd_pid_get_owner_uid returns + // ENOENT (systemd <220) or ENXIO (systemd >=220) + switch { + case errno >= 0: + ret = false + case serrno == syscall.ENOENT, serrno == syscall.ENXIO: + // Since the implementation of sessions in systemd relies on + // the `pam_systemd` module, using the sd_pid_get_owner_uid + // heuristic alone can result in false positives if that module + // (or PAM itself) is not present or properly configured on the + // system. As such, we also check if we're the session leader, + // which should be the case if we're invoked from a unit file, + // but not if e.g. we're invoked from the command line from a + // user's login session + ret = C.am_session_leader() == 1 + default: + err = fmt.Errorf("error calling sd_pid_get_owner_uid: %v", syscall.Errno(-errno)) + } + return +} + +func currentUnitName() (unit string, err error) { + var h *dlopen.LibHandle + h, err = dlopen.GetHandle(libsystemdNames) + if err != nil { + return + } + defer func() { + if err1 := h.Close(); err1 != nil { + err = err1 + } + }() + + sd_pid_get_unit, err := h.GetSymbolPointer("sd_pid_get_unit") + if err != nil { + return + } + + var s string + u := C.CString(s) + defer C.free(unsafe.Pointer(u)) + + ret := C.my_sd_pid_get_unit(sd_pid_get_unit, 0, &u) + if ret < 0 { + err = fmt.Errorf("error calling sd_pid_get_unit: %v", syscall.Errno(-ret)) + return + } + + unit = C.GoString(u) + return +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util_stub.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util_stub.go new file mode 100644 index 00000000..477589e1 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/go-systemd/util/util_stub.go @@ -0,0 +1,23 @@ +// Copyright 2016 CoreOS, 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. + +// +build !cgo + +package util + +func getRunningSlice() (string, error) { return "", ErrNoCGO } + +func runningFromSystemService() (bool, error) { return false, ErrNoCGO } + +func currentUnitName() (string, error) { return "", ErrNoCGO } diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/LICENSE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/LICENSE new file mode 100644 index 00000000..e06d2081 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/NOTICE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/NOTICE new file mode 100644 index 00000000..b39ddfa5 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/NOTICE @@ -0,0 +1,5 @@ +CoreOS Project +Copyright 2014 CoreOS, Inc + +This product includes software developed at CoreOS, Inc. +(http://www.coreos.com/). diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/dlopen/dlopen.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/dlopen/dlopen.go new file mode 100644 index 00000000..23774f61 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/dlopen/dlopen.go @@ -0,0 +1,82 @@ +// Copyright 2016 CoreOS, 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 dlopen provides some convenience functions to dlopen a library and +// get its symbols. +package dlopen + +// #cgo LDFLAGS: -ldl +// #include +// #include +import "C" +import ( + "errors" + "fmt" + "unsafe" +) + +var ErrSoNotFound = errors.New("unable to open a handle to the library") + +// LibHandle represents an open handle to a library (.so) +type LibHandle struct { + Handle unsafe.Pointer + Libname string +} + +// GetHandle tries to get a handle to a library (.so), attempting to access it +// by the names specified in libs and returning the first that is successfully +// opened. Callers are responsible for closing the handler. If no library can +// be successfully opened, an error is returned. +func GetHandle(libs []string) (*LibHandle, error) { + for _, name := range libs { + libname := C.CString(name) + defer C.free(unsafe.Pointer(libname)) + handle := C.dlopen(libname, C.RTLD_LAZY) + if handle != nil { + h := &LibHandle{ + Handle: handle, + Libname: name, + } + return h, nil + } + } + return nil, ErrSoNotFound +} + +// GetSymbolPointer takes a symbol name and returns a pointer to the symbol. +func (l *LibHandle) GetSymbolPointer(symbol string) (unsafe.Pointer, error) { + sym := C.CString(symbol) + defer C.free(unsafe.Pointer(sym)) + + C.dlerror() + p := C.dlsym(l.Handle, sym) + e := C.dlerror() + if e != nil { + return nil, fmt.Errorf("error resolving symbol %q: %v", symbol, errors.New(C.GoString(e))) + } + + return p, nil +} + +// Close closes a LibHandle. +func (l *LibHandle) Close() error { + C.dlerror() + C.dlclose(l.Handle) + e := C.dlerror() + if e != nil { + return fmt.Errorf("error closing %v: %v", l.Libname, errors.New(C.GoString(e))) + } + + return nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/dlopen/dlopen_example.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/dlopen/dlopen_example.go new file mode 100644 index 00000000..48a66010 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/coreos/pkg/dlopen/dlopen_example.go @@ -0,0 +1,56 @@ +// Copyright 2015 CoreOS, 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. +// +// +build linux + +package dlopen + +// #include +// #include +// +// int +// my_strlen(void *f, const char *s) +// { +// size_t (*strlen)(const char *); +// +// strlen = (size_t (*)(const char *))f; +// return strlen(s); +// } +import "C" + +import ( + "fmt" + "unsafe" +) + +func strlen(libs []string, s string) (int, error) { + h, err := GetHandle(libs) + if err != nil { + return -1, fmt.Errorf(`couldn't get a handle to the library: %v`, err) + } + defer h.Close() + + f := "strlen" + cs := C.CString(s) + defer C.free(unsafe.Pointer(cs)) + + strlen, err := h.GetSymbolPointer(f) + if err != nil { + return -1, fmt.Errorf(`couldn't get symbol %q: %v`, f, err) + } + + len := C.my_strlen(strlen, cs) + + return int(len), nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/LICENSE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/LICENSE new file mode 100644 index 00000000..c7a3f0cf --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2013-2015 Docker, 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 + + https://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/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/NOTICE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/NOTICE new file mode 100644 index 00000000..6e6f469a --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/NOTICE @@ -0,0 +1,19 @@ +Docker +Copyright 2012-2015 Docker, Inc. + +This product includes software developed at Docker, Inc. (https://www.docker.com). + +This product contains software (https://github.com/kr/pty) developed +by Keith Rarick, licensed under the MIT License. + +The following is courtesy of our legal counsel: + + +Use and transfer of Docker may be subject to certain restrictions by the +United States and other governments. +It is your responsibility to ensure that your use and/or transfer does not +violate applicable laws. + +For more information, please see https://www.bis.doc.gov + +See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/contrib/syntax/vim/LICENSE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/contrib/syntax/vim/LICENSE new file mode 100644 index 00000000..e67cdabd --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/contrib/syntax/vim/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2013 Honza Pokorny +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. 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. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/docs/project/images/red_notice.png b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/docs/project/images/red_notice.png new file mode 100644 index 0000000000000000000000000000000000000000..8839723a376b4a58ef31b86eabf3d2c57d21ccc3 GIT binary patch literal 45387 zcmcG#Wl&u~vnaZ8hmE@vB)EHUcXtRI_aMPtHx7Z|uEE_MHW1ti?h@RB+vPj=)P3(& zovQci{+ZR)Yow>8dZxQ4QdL<74VefT005xL$x5mN05G)x0F)&n^ao~@ZaWSDsKb(z z6w~yCI$aaC(@-PnHO0)jW#j`_wDT?W$-$X?3C@heeS*s(A#q9V1c#8$Z=s-j0L4C2 zVRC3f#Poqul4Wx8#cDP#Fl}VeXpwzlH2SVN5uAqTde=Q;@dMlEqfmga&GWWR%B6E> z?hQy?LG}h+#`q8b01*TL06)HLNn&gEJab&kXrU3>6}SpO7yt#BI99sNki}l%N0EA2 z=mdQ*0RSMDRbpc*$pPdk{Le^O=Q7O<)E!VAfz*EuK-v8fbV&h*0;FMyp#lKG57Rq0 z!aC$=e^RTM5IzR~2lp`vEIXk0;`#DwZcqUw;xLY!&xLCR_syR`oIq+)8GYxm_@^s| zG3uWdM^*&D!!A*dp!3tv#Ia>ZwhYtDD_dy7V3N|>rstoUoHLW`oiq zEd@sWfQJ44m;Rk9+euLZDT3cB+)QEb(!kvIp3e7`xou>@nm?fSXZ3#V0^{@5t&yO`Ass|?y@f|WGCgHVmi3G9H`Y`^Yb~K3v_fGl z)rX+@QEjy_ijJW|^jOO6&u?oi)fB^LKFU%Wnb39KsvG#D z3$)51B~eVt_flotS=+Tr6R{gk$9cHv#w;Ex{N~I!jA=A&RqAK(i^=6n`*y^_pAR3G z;K>#C$CeVE(^s&re&lZtKE*c1xQCH0F7ut(<015}TJ!OID>7|AugDK-);Spo;x3=X805$ zr*gVq9nJ0C-t|7O&x>E6a>4G>Nic64|2=N8cq z*0#!1-geOuX|a+02g9#$ zK6c*uQs8+1zLE5D5mJ;^{Cky;;Ctd;{ z4`0Td51djPjLpj)x76>J;CmVeStIcEcrHm3(7Gyz=`*2AVZfNneet3q@}uCtQ`UkD4*RB!3?V#v0<;2j$eT6ajQ&LZ2&GychguBDjMbq1nS4p zFXS0!bvLI&SsOVPFvAuh_S*7QBe0-U&eK`F#+fNN-6Fc;aeTn9M{BzM2qN7KjPRS` z_M1@|O^oIJ8*g8XEe?mD<_<66Oeinj8*C39?>)VbFbZC-wPj@%an3jTW#3tV(W~1C zvP*B%LzoWC%Ba9noK686dn3nkp?d^8?dE$(HeW}gNZ`$M^U+^-SmGmU=%eRiyKD-ANdRRL!a-ojeO1`SykHVduiG#eMB!1v>hi=`(l zN3NI2&kQ^P&Q_vpsV=D4oXxE`4mgk21+#>`j_EYx56(;){fgP@v_Vk1Uo?I|RfZ{j zF-l^z`MUIFOq2DKC$$P!BDN;Lu&a8)d}yuj5E5?5tFLmcRw&Dr@hjIj!30-!)?SQB zM`sEFG*Vz9B+#hDt4EQkb}FtWt~ZotJpQ$U*EQIluQ+&rug{AyWei`>K5gdPOGByX zfP|^p?QIJ-Gr7)v7h9mCdK|!u?dWA)q1KYeQKL1zEVw-@f?m zI=IAoy1(!#`<=SYhkzZm04pc>iov_pBvyrX+$718-3Bd>49#qti zBENq#y)QC(D_TIOUH!&bp7x~*TG~hLa9ecL43~GyAx?2?$&gQ7q1xX7%*Qyi?qDu( zWBdSpog`vTf`%-446{9q^}M?pz;h;_uWC(I6}7_=Gi~eD!&8z90$uBbLh{$MU#Q$J zUl;sHG$o=iJ1g&SY<3LhB(#x5cj$?Ml98u;lu1l!h@t~E|c|Xw5YG!rRxEei6Of$s9!$J`!Iqq8xWcXSH^{#VFuNc zEU8o?2`ErUZXs0xh0;mR!l_xHl~uE;L0rm@pds^7u7D;p+m? z?vYbZGU=c2mJC9>Ia}+(M;GG2Q=ZbXK>fIHVsWf3wCG^cfi01dAMBUjznJ>t2^@bQ zp|?0+Zha!A0}9R}NH)Xcy4gx3?3Jt-ai-bm#lNXrU^rE4ci@QS!*#Fr9;O--zBF7l z5Ih$rM*~e!tU;9rSi$eI2wic^m2J_8k87c^oukFT7jh<8uP=&W3^;yj3CDC%qJT7gcAOfYu>>?3sn!xGAe8KUF<0J%m z_4~ux0%>)pCYt?+26yzmf0l}>jwoO~wxt5o!|D-uP)w2cfnteTM<)VThuGH%(WsnP z6Ct`^@SzqC3Gx{7UjD*67ywW~t^hX#oq`Nm&grO z-j;k!hUq)Kug$v3AP?Tv7{GXrkrY!F<%V-mp*aSlArcn!PgnSQ|7UgG3Awz{nTu%5 z574>wnkcGl2JWa&NAaPZB66^%E!yWqbhPkF(1dUrXM4z@sj1FNX3H;cACW1JUKzmn zR~qsbBK){pC{xJ^tEI1BHJq+`(1jv&niznELa6^_83_|2@|8!XUPLavBogQE;1Pm7 zTY{oy^S(uy<12l~j-U*A20&_ZGsx7qs9N-QTDTsI?+!GRasyAdsn2eSv9kpW&dEDx z2XU_%9WJGP28DjRD81Q=jyIb$tSEnffS+sW@pStm`m*{C4)u;;&`eHi-3bV|U0?dM zQD9qYj4dZ^B?X4dm4#(X-(1`C^4Iu-PvL={>>akp!9F)^AezOA)TpwQGeOm*E1`Ju zg7_P>Y^~f*(L)#;m%+Rno4|q7#wX51tH&^Vak4-w9~EA*$l;yUQSnTv852%~<*W6T z@<{x3ubJ$NB150$4F4-?A|a5PUWEmC{~2CzCz;51WxGL%EMM0F(Y-^+U;Yk$fHA*K zjRM^e0QvTB_qA%_(@Ek{5iA8#B|;g#nQ|9%h}5W2G&&~ObO77NpjdMO34-WLuxoDP z9#lq`e(vSWKYnz4n3EWwP%uC+DmmMIpL+9`G!v}>Mfb4n69fM{>X>78(|t+DPT#kV z{laH&F}`i+&+1Fmt`~XJ~}N`*{~V=-?KNs zQD9%Wl4R-tcM=w=Ej1|c7G+X)g5=N%+G^B)Y6`*b6j__8$v?a0!LanRTsr>45bpaAJ%-M zZMeIt*bf{RQPXLp1x}P7uLvhOCc!uEdB2)N3VBb}S z@jh777>R>Gz6lLtct;tbL;@6y5Swz(6oP$gB>-1Fk9i_&nK6hF_Jn)J8Znfw&P;|A zmM~YuO$lBXJbL@`{iC~NoD^mQ>rD(WN7fWR5o|%Pflvh|Sz3lQe-}YZY`RNgndrqv z{{c%W2N9TE#>bASMd@M_D@rZf7s=^0f3_M;S_>j*ArG$?eiZ`_r=E@c0g5bS(TWg4 zgRbWf0#r`21Ogv4sV{7%X7L`35x@xbUryq_ej28${nD_-YOF zTSs$hi9ek}zNQ2rKyIBj{p*$~G&{64xvi2eSbs*VRc`-U)PDZrM{ck?l~En?=Qh|~ z-DB9Dr>#mITwNm;HGAvEYNx@dMP*7TXUFf5O}P`eP-zD2G4PTAKavwl3qH-;mF29u z3>%;F;oCsop4=j^P)rk$8^&knU>z0|9YlZ!AJ;$uOoqv49{PifrXO&^Kq(P#zp==aB%jMcb`hV3qFPKI=a9cCY8OzM+~1GXlAlT+pB>QMaX!iv~FwA3LH&dx>ra5K;^w1kvsW zJSU+;S`Q?|{xC0{4d!M;Ip2P2HP#ChM26JN)s9u5IRYT86J5H8bAoU?A}=$OMzfdX zzArJ6pN7yO8T#z~IY+^&sr%kay+^Kee48w^vMv&!X++i4)PFCT=^5vobh8$cgV3ND zj?#SkGDi8TH24umrI2YRCm2KC5m*#O{4o8}!xWQ+n_34kbt0^wl%LA*1EQT}ys0<} zgP@>ZbG}T+r3AQ}qhQU{sC1>j-@+d27C;h-(Kf;=B_)e!?R3Fw*7NdhDhV@A154fm z_F>%8z1pBUQ|Wf0EH|J}3%D-F?K)MDKw03qW8pZ}_cAp3_=2yh^Xec@`Cz@yO8U#(4|+Xf7Wz#hvCGnid4=nlycb30^!r&i++P z+H7IGBHZj=-su;He6ovb$w$@Om&QjTF5y3A(NwNMF@zm`Zk8#83PXYj88CggRe)mO z`0WW9LD;#*Z-;)E7~|xq?rGdwfP$1BwA(~BqJh~lK<8niFNoRXgy^t4+g&wzlR=(3 zqA?;XzNw-wHdWk|J)5hkVX&7}`doBrbw*9bds8p$`7;sRzp+vn)8&X|UzD;@6>#9W ze+X5ui{Xs=#)iUti;S_DCK4Z_*VI_Qsra6)Gs6*AJZ-MA6oj`wC;8VprK}j$GEnQ2 zKr0icT-HJ+1un9(t_!qX)PC(qi^Ye~@GzQbm+Bm%oXnSV(3uP@v$1gh8#kXcECN5n0xL0;a8Yxcc@w=A1G zPD>2ouq7kTvrh)W>;+CRI&u@8B4=g3#J%>s!49>=-HHcpXL}EuVWL1N#$d>VBrEpb ze#To-2Y%=A<7|Xjs4TefrD>oVpOWCLUNk1?@K3c&pL%O|sKrj<2TeLPM}qjOOmCV9 z283raJAZidw?*RcdS3Ux76f`;JJ{l3H}JbV4HxHrthgw+G4;dO-Riq00lL<}SYgKp}SR*`iJ3kFy^A_LrjAX+R zx69`rO<(X!B0|~yuWnAel+-kO*aGF>gF1Q*2qACdR5P@p0c7J$ zhMyZ^(vnwf56E~Y=t}M6o1MtXBFXNOP6-E^?!2x9V-Uhm?+rIz9v+_~jU63~*aC*D z5Adj|Y&2#u36TU)L8z6ynWHAouTLrJ1G{K&t!cZOCns9k?gkN(G(y6;u4udRagpZw zF8vgi*oEP3;);?Gib;|0K51t?e`{GqD1jCAxhuvLw!lMIYZe>l=<}2z;ed8q$EEfn zYS2HY+U8(b z_J@JGDsFEB^W)u9-WX3?XNDxqvHsck?C<;~Y(r21@0zxWTADNj5XlePn`z8Qp|Y+F z{oaU_Wl<-Pll6g&G7ahBMQH3MBY}dsO{7Rsm^kZN4;0}Qti#P~vzZ$zQ3WS+skgi< z*(Gevv?k}IQo0RM;F=sTIP0FgiVQ;Hg%0{f98~~f%t-&0RCW&2-0d}Fyiwgs157;=% z3gkGcahwY9!*L`SEH+MI{7iuk3vCPB%_oAO$4rjzo|>+e)OA{RPNwv%+PdLfjtqyS z=ETEF??le`_ozyJ667mN27a)cpE8{>bAihoIK1neJ7t9dQkuJ*#)C)&gTdfmzMFmK zF3L=yWxb(br6H6263P(Iw#Yh~)4DAQs>I%b9h8r~QWeZuO|5qy;-f5B-=+cUM#g=A z8`D?<8M_UlIKUs|feUi!YH6crS+2f=UVP`-N}#c+5*8qDQSbcGgdc*EgwPJv)9V9Q ztrXn14$ZLUiQYyWNml@<0|4M!K$^0q*5}AQ-2VQ4XjHS!qXb+FeN+y@BskA zKe8C8>;M44M-qe$a{G~80dHQ^B-6+z;*KDbER|kFW+t@7iTd zCrf&B^$~SZAcB_ijtb>$f!mLC!DswLyrb#w_as(Mf5~<(r1XoV^wZ#`43@h713nGH zTxF71voPvZi}-#v^8MoJZ1H$k7*b1ce@OS*qJkj~zY|n!q&JD$$+^sGRoZiwrEb~b zZ^6HOpL?N)w9n~!0@>O4>S~Ao({#UZRLSm892fOk>~&vStD1@NpalOdneFsA649si zcg74!;^6+1bpiIFkrowyd--o}odW&38R6$OS{&M##uO{{g{O_H$%&cKc#e@`Yl~{m zf9GStG`xvPCx=ra8_K?V>^$qyyl2W9rsAq79ds!~{DLsU+5a>P{5{*5+y6?FP8{3j zpLv$*typH^cU%7R&!#_BTL)SAUF}Y26Vkq+EXa!cpaY+kIpX4{&mxih5}Fgwej7(T?);2YJC{c{AouYAcl0E zAIRtHNYJcVEyeig?Nj*2-=?(iEmwiz`4WdRH9bL!4ofTB^}2b709tyPO@7dq68(!d ziq-R40q%ifygdD18U05FI52bB4ctz5v9s7dYJ(w{{BQ5>ZXYPo&f+(Yz*YyySGDMD z?9aP|_HG2iWu>Eqa}G0urkj>wyq~otWil=Na3|)KtF<;2>p|WNj!x(AL^exg0WYg( zu~m0t$V?*>4e@?@?0YmPk<$@CtN(}_4oKel4$^CTns{ZcW>na0%pw2qy7^LKo$*YJ z0VFR%7!>C|R-sb0;sl~G5K_(6xu!M}(bEO>D3PYFfduZm zEeqL&e=i2A>$Y=jZ31FB`G#n_eeW#brc-`$Dk>I%rk~glofi#0)D+;ne=EV0^KNsw zJ!5u2_x574IV$?{xNgPT-5O_+_mFMnMCVb}(%pH>-yPHAdAT#vLBX=KvA$~Z{#Zl5 z`~J9fSL$I9pCkOT7k&}i?M?lb+41#!I%uiFBFSc~`C4xNb57L-yk@h7c}TQ8mB#9l z6}*B9M03GpRlQIydTPIe)IdRUXs{Mt7OL)#WAc{R9&0(9)l#0CY9V{~JXy5WGSlDX zNAq?}f~Kz6kpZ3SpHL+j?URS_kis)dZ^OC=TN}T>_+isg73^g}tut{I`c-oc^>sG6 z=e5P-F7UfXN8!6VC5h381_gkmG_2d#nh12CO5G=qRc$db)*|GT^u$2V9!v8*^b8oF zPTZ3+Tiw3)+k!QAe>X zJ~$bQ0QRz%Cq^0Z$D+|>pvAml6%qKKJeS7m8U`uYDx!(6>Zi5+C%gC|qCt2gq0N7v zw)mTTr3q_TOPOV3FbWnpDjX>G>@BwJ3CqBSs8w?@?dgAlLERgZfSoQSgXp-_+U2ff zZbZSe?=MdVtB#v7bviX@At!~(QWoo7%d>h_Z|5p?)-e%UkojLVFHG04MtDqpr9*|R z+z!!y>qIdQF9UVmeWRlH5G_)8kQFNEZR?xQ)Lv(KIIlXpHp(i-2)G-f#3br*JJixT zKUq^J%cE4waB3qAm`=KfbVQ_TXI^tJwKJA4l3}@rI7T~}#nTTpnuq3m8<828wvf_- zp7JxZTVrS@!rd0AT^(6jG%2wZ9-U;JEmlIIczZl&<{>zLo*4+CCC2UXdeMdk4fb5; zxnJnrR2aOx=RWl;8XLTnu6n#Rc-{ArzP-26A-ve|ChuQdhHgz26SKbUe!ua+aPd#O zu3G!h$Ac}(p?VH5jTv`FNqidO_IET~+J$QFQQh(S_hI%MIAD1SYf}VxN~4;_<#Z!M z?{Zn0nH)=0=$Gx9Z?YY$Lr52*d%4D+kH8GaptK5lI>C2&a5^XC&=3l4$XQ!jIGW!dD>M8 z=z9ZYmRY3QAmDIt8d_k+ndfjIpQY19eE74^@AEgJnoQM6yP=fREX(|XLiVcq%1rTh z%Bh4P-GC-emyq@|fyv*uzDMce#rekx1Q~@z6YcA@n7$*C^7A~FT=qd#3P>ik0x#b( zS;)emED*Z}%e!D9g|Qr80OQi6jL(0r*OwP5B$=_Um><9^)nl;BEkCG+xNgsOMfOoT zq2<fmA+}?`kB;j>BuO#T z*ru_&k1kbeDmNhBs;VOjF4IfiHxBL-HFy6+7CU{whwofsdw4Frc+4d~UjvY+1U}4N z_!Hp|)p+EPyj)yVKjWE%;)}fANPMtnBP3A7PY4S1nt}nD8m7cv<_}l=nlgblKp?Z5y3^!F~3F#tnraGmA26wI4?yZzFuVDxvfG|0Nn#{_C zn7&J^9-UVN_gpV6QJ(l3i^dpn@W%E&*Z(QA9+&IQoI1C4rDhH6Zr!dYE~{M;y9H+^ zJoEoxj5HT2u6sX@CAE3DRN8{;r)%^7I&*;;f&XpOYJ78FxeLIbMIa+t%9wdySDP^C_`!lwAt)Wli`RE zKLQ@0iUnTjZxD^6fLC}pl0iS(18IoAg5JfD*D@45; z09qp+?4tUWng}#S6JPf_&>0dxSp(sG6T+NtI+c959&IHc4JvVn&c~5Ni!>E41F~mH z!0#NzR2ShAr{F13KM$gDkto=@)rp3KV*X7K-0k)=zCRzw5lj;ONoiX_vpyYRH!50x zAYMpe7)^oVU^ zM;iE$yQzpQ^7{6r!^P>6wtjrAx4!WHHT85fBv%=FC#27Tr3MahF?`moOG$LB-LYw=B=?9bL{c@Vr{-o%rp)&Y~nPu&MB619NAN5 zM6qvN(sat#vgs=(D#8mer; z7m`^x@^wtotUfNu0GzQzX@6u7^6IvVj(aw?9R6N#E%ubJ7Lmy~Kod}+HqqUlkij1# zqM~9L?Cs;bUPXNOXl9VGCfZa30s7agIj)|>EoUu5h?0aY(E8<1q_K=02AJw90M{sQ+@8os5!#ZwDZ#k_%$hpM!WT@(o%9^HkmPC3+z69XIy5LsNN3i6_)cL zPs;D4Q>^5uYY9m!o$Wk>5A=}+bRC{MUc^{;^i``mq$5vZ|42uIG*jo^{}>2IBLWw9 z=bgO-kK-M2K(mXcz#%sPHY@(TzKo!WFcBD>eBAOGq^rNF)V^&F2R+o77_kB86afu` zro6)FV-k(~5H5;6lnPDD!SjE%bUxq)Upy7_k1)TJTUf+HVbGEsjNdPT2xJIbA}mm4 z%l{MNpXe&IwtP+QfpP-N0Z$U=~9EhDsVgf z8+F)g@EcwZ<*wiEz;5vAElKDFj>wjUZ5wsC(BPS0%c5CMBNxCiF%BSOS+LDdN~@%! zS}i9*G7B_u`Mh^TYE-G)2BKJSh<4FiK~S2JP>BuopP%-aRpJd1uD?Z@hTWhp0-fEe ziX1;Z4+?X1|2;4KQjQr%1#?A-y%O1!p+kV=ou3c&kD;TEE;5W{@>-WRkl>Zk=Tqg` zuBahhkY~#OwiRiL>Z>!i_e28g$_0`QA3YjrU zs3McFXmS`vp9zbCXiP%n4Lqnc4NRCl5``=7Z{^2$cvl324a{&S0oR2YKE-Uzu*m_y zR-uY~Hq(J5?%@UpC=gGbbl38|ESTv5$EVdC4hIjA%J!+fLg_|ht zrNdZ{_ZlT#pl&$llstomXw3eBUH@amrQw@2Q)EVF&OCCg)O?u#Xef>EAH1K#T;U78 zG&K>|)WdjCas4$Tq$1zm?;$LVeB2}9h+BeV4A@^G)s4nX5sF*i`%O^JMaU_J@TE!? z>BXQUrsceFeO8Cg$Wb8Ihe2r4X!x+? zw8%zv1=yJ4Y={yK@&lBG4(VxXrd1LIsZmeE!op4(hUTCCm-b^pvoGD>^^hx)3j|HL zf;853;teoN-hYW~_2FXp|1+b@S-%fxcYfbE$?f*LyZpTQRmYbu@9{=(%HR9nQv_=b zqY&AyRBW!q_(vv-oNVLy?d+xvrjEqFwh&J6o52aOkv*?8du9ERW!J^Cg^mRQ`53?3q8K;(NOt+G&O89-h`A zFewS0=QMSd*x)r5&%L~l3W3hLoKU;&R=FZA3Km`8`BkfBz0bLSyb~FtT7k5u27JRO zxPHgDMqq#2yB2BkoM}Y4_ni<7L!`R%DBuGvVD}=;MbrP3_-bx$mW6dU01L7=sQX-^ z$8z9W$rzITE$M7;>0&TL+e9sd+YocAcBiGnYCp;PA~|z-QhF!2*P_(EUBmhH_d`T8kNhY{ z(I1l6fItE|a?V#nlsLcGrGXJFG*F`(!P$#ZDQ65Fpl!(pQcWthqz!T|uD? z_HyPC6U6S}Uu*gSTJfwZ0lez}QHVC^I$drmTmxI8b=I6unP18Ypc1=f+5OpJdGx1U zhx%@si9ye_cU8^2udZO7qG{U|$7zQ|TnX850H~Y)=kh8Z6Na{Op1498Rz4qr-^4BFwjk+`y>qU4UbQ1Gc$_IXB8k;#MJf-aWXF9+SI{t{)f_>^Ba@||YNH`CqFHiNQu*3}%TX76lBY3wr zYvwkp=_gW47P_F;G4*ESl5=GBl6LFQUMb=FcC%c_T<#di=3S7p2GK&UDuh%X{}j~XYD=Du^e(C!m= z>|cEA)^A92gC*qL*5+R&*kBvwrle~VJvQ7Wbm8fLnv=LIHxauTm=C6<#I&L~ZWZXM z(pZowr5ya&iCwW()K&9Zq&|D0VxBFA+Tq;GwY&HtB$DRW<<3Tpywld|zbF(RAQ!Ob z9YL2W_OBEtSej0SC6JNf)#;VBX{2HpdC?_IOJP*p5%Pg z-&9}}rW0NDR8!AGU5F>jdgeBrZcYR0I{xpyXmWkie zh054jj~)m)IsudlU!n$5;6ZwmR^F>>+yJn36!3um)Z>2CBmdt7TYpfH0RXDeAFENQ zd{jvXegOaPN@&p)^Wiu(3iu$ln2mSej)cJ9QC(rhwO=O_Y!!XUFHi@jAao(RKWOAQ zz@OxP(EJyOOb%g4E$)pu5s_wX@|(Kj2Lv9r3xf|izll1i{ZW0_1?N zK!s;?(1j_04P4xXP*FvW_J)s=lVsOV!UDQP4>HKR%~Aa@i;?DV0$M{=fHq+|~*(5;)O z+~4@g67Vb^jc452E&A454n{B|c&LPImkv2bybHHH25d@5xW7F1Zp?BO-qYx{cNt9e z@JD^!vSC|(-Nw8@;6f@2uQ{Dc2ChMizBswG7b zdo&{MtI?+M(-O}lIc5y?@s1CM`-aRDuOM;gnz4x6KE_{s`#my+7J49oc1UA@NlaB1 z(3#&7nm#{m_8!0LD$%9#YpV2aXme9RCw9JTc5N2r7Z@b_LKn=9NK+~$#UhIn;}%rn-Z2X;*1H_3e)PPCXZoa}y_yHR%r7BW(JvuvVlpuR zL)W10n46=9f??)vUM)taYU${{JoAkad7_n@)lKSl9FEon^%FPgW42D}L|5H>FfRyd z5n>c8JU_{0F*Ri0!@yBZC2Z1M&yXLL{Qb*X|4pZDj)_+js!+@GfJIMvP}=enQJ{jg zx~%T;NW<_diX-&D-l+{N@iYBy`%___-3{g7acxVU=@O~x4b=OH7PTo={@h-PTdz3Z z4bLV~g{I8F)%$?=H%@rGQE> zmVhslMdf)y)7UlpO8;&}9_%OrFnz8*TZxP6ZRho?A0^IB6ydYC_;2y&s(HNlpTRk- zh=W*xp5B8IB79Up<|7=JH)LFESLG<)rR_a6S=+`oE4}v-L1++F+9jUxtxVxLK92dH zGdK>sHAfAdshsr29mr@oODQ`=T#d+n6jWU=q)IQ7n&5#kz&K(6#1}YseXG}E0p4vs z(v_c-I&I^wsjLK3*iM!kok6iX9bH#$awJhz^!e(VMb=ty>np2;*3M3pE_K-+1_zNU zD1DWNbs_cl+n(qs85|FHKT8W6 z6j45R-iDh{aKnV*%k=p1yb3r7{$OXayc*#_vf%Jm@eJQ=%de%n}sfuHu(-=DNPwcETw>-&Sx zu?e-G zNzC=eXN6LWKDC=F=9_u_92wVIAMWK!WXc_xVtJptKfv>l=^5g1}TRyW?KY zY#gz?RIMM<$`^$qOE;~BIYPuRw!K<8(SM2RZUC^>*DqiVEfFq+NEH+wGTBC0^I}RI zdP-fm1u^WxqAD;Dl4%k0PqA63Yteih>gws+?~_I+8CJ}1lu z#C7XTb$zm-dGM=571{tTyeizai=t~|xaSD^JIZFL)aB6Y%niDafKEcd{*(n5aQ!}z zTom^g!t6QDO)g+=Xr}WhD#D5aevG&Em^{^ znF0Ee_8E9L9J-yJ0GBBGe<-4r)>-}C`)l3J(LlwG_?oA|#9s;;3DjqB0>|yd_FRXC zLk+13jBiLEmbJqO4?$#QOOsdo{>96lHzY$uG)0z8T!jc|1`HC}F0oD-#cPybFViGf zA_S7}Fj#s3fTh5iuXoBKyc_WQ6o>7ew!GQWa}HeD`q}&_Bv{($;rvkxRj$L4tzVkj z=ek!%%OAuOQu|^JK8tpS+uI=)qL#+i=d3wp&59W#s)*JfD=ZL(=bB)82hNk)`y2)1 zx*Y^B9rCV2R)=BP z6v(eGNh_mMg>XrQ75?98j@8*OHHw(Y%ncFJQ-5NBE1Yt@->&{!7AO7-d?ee1+dA9U z!uy*Dc~EtT0;AMJ)`vr*ye2eM8JIXh+xK|DQgKhXxHQgic|UwAv>-|7`RZ*1dI2l=E9iSY1g*JGps(7y+_H zkr4K70K;>EX=AH{Qvyye|F-u-`;##{)i|(IgxU)ufBWOsqK5y(qFTl2yH5zRRtSfO zsQaO_VZc((L}%~sqR1CqK!biL>vnN4!R(7-_oVDvk>DrSbOU+TU9m)Mfw|L^VS+(h z*(yD5;Z3D#VEYLaYJ&i@z3c19cm&qHc0nYH@Jjdg7Qs+KehCs5BFhY%CuM>#Dtq-_ zm}dIEy@zrUvhVR4c^2l50+@guzr^@|j*HW8%>R9cWnZ+1&!13aNe@(U9Uod4ZOnbT z^+5*8{6&he(C>a@V{^Zu^jBcX4jGV3`LXM_7{aIl)k-0EMHBTic4cssoy=C~?MI*| zowAu}M=Ss=20PeAQZ2*#Hs4D*XbUEqpUh~QoLdrPL7amO1iyb1a%(`gejX4tmdZa-^n_#+`|+xBOBVWp0o2(A|yTz7ddUv)Qe^LJ7? z`q==(PPtLtX@9A5Vg^7HCHY&KAM~Sz=tTQbI558Dq&^_m;fr8W zX>~x2Ryd|_JS-%69qC|TG9?`?2A3Q$N!zjc88nwX*QLL$W8Em33^$Ow0nLe%Z35T{ zJ$7fcT+dmhckRnxOc8`Xst8ruZ!bY5F~<~0{zeCdjA5~l2^JMbx<5W}v9E#058r{= zLA#^0pnTzhrU-90_Y5-snat*V;Z-^DnXr=5|0q}NTOc+1)k`od3uYeHIl=B!WFc^p zIA5GrosGZyxT{d@o-eGBqrUH(zPhtbNX(1Bx3J;H9Yk33?!5zQ=OL$3M)<{rIptkL|p_% z^wYck$U;mu3ST{>>^PcMg?_uSkO*Ssm(>>GwOqXnk^f2g={Ms`iDhr6t4#n=t7~{l z>ml0CE$z5_i|=1mrmyY6+Utwq#fan!=X7ty5T>b#$nuML;i zxq!MSBp`Ou4>Ec$1w^3T@>-Dct|KES#$Q+))rZ|Ay7SdKYc29w~LbKktga5sLvKgT7wmp?F(iJ#XR0 zV+q#7f(xc!^MISIMR&P+T~H5#4A)5siCkVV7 zsuwhs><9?xA&9{gh{3J;U@ga;qv?maG{aH}JswaTDuRxiZ3MDY9BM45)R}n(S-WZD z;=qBXJC&K3qt~G>FMKqLtJ8tKeH;Il&`(Le+4T)rok}C3|1+aHxGd+5jMYv0Gvydu zI%t>)H;7ZlKT~&_CC(29<;o>t{9+4}8g&nHu<^SY0eeT<$|un#JS_H=hwKk3Dh^2J zf6?}rQE@fF8Ze4Wu)%`M;O_1&!QI{6-3c;Sumsl-Ah^53;2zxF-5oyObIFVn0>Zkte7by)`-Lp7FM9Sk=aRh#HzVRm8crXW!!cmsJ@DnwHOS!w_ zL^-!!hORt|rc}y!HX0c?`TG~v@o?$7hI?@Z!_c@w4S9?LKpPf}C;&zj2nSvCWPEAX z&0#!*r<5Ft*kXd{;w(B=@hDT#e~6Xpn5tJ_%j(EB=9-Dk=cWV7B##O`2AHN*cvvJ* zl(v;t5K(J;niHlNV`komMvwlk-pnLJ6+}Zrx+Q@Q_%fBRp|@r2mUtTMAKtYnxR zQ|wfI4IQ$m!#V7)i3<=YLq)MxQ>TB<#;mYa4U`>SGAd`lToq;ZLqp2yz5?SQ9b^Vw z7cD3*-yZnqru3fH8aCH#GU1ky8tnQ9tIHN-qY@w_ zP2>WxtR%GzWm!T-L)_(wavyh|u@fmR5OfSISw_Djlm@1>{T%G`(HD)moG|UZ5?@Q5 zp|6A3GP(!b;_mwy5Fd&^)%zMl1~YA~ob)xnb{D_7Ob4cK(u`v2IGJ1h-YxCnT&osX zH)ms_X>fB3i@>E=gNkWnR!#pAXq0 zRcce}_Ga+C2Wek}xU2smVJBs^GNGTQDO zv0O8qO2z0Q0q%b|ppCDHn@9gS+^uO;86|?`#!1H_D)W!wMWtF#|D!Z@8E?fuUtk>s5o=T^eqliT zG5C;PX^2VDb z5%K`ME%dxpTzK`)WUumVT(=d@-TjNy|EThCydzd#8^zk+2ryiG=Gv5Q$xeDSNZajH z+ZuP1{e`e!th4?iFtnn&JhV0!v^a}1%o-Re%%pgIj*jImjP1_33;Bgroj*;$^r5TG zA{$YU=RyVK;1FBzdwwI1Hv(^+&Df_OKg+Zj@1H+P(%{+mgBrxLO(0h0jY^bPy#f6| zfjhzNsZ?LxDzY5GH(X(?ZB3|*k^UIC2)QtAjNHd2v&{^_1SJcBocck%5q?xzy(JM+ zOmC)S@s0Z=J)w_5tBcP2uEOuZEn(8DLSc#5r@8xm6;Er#p00ZSdq#=;3th)rw%K|e z@G|M~#FKH8O#&YRH{j>hcthVA;*Snqmq&cRw_GlYg9X<~xphqbkb}aGK7w*raGKL- zOxq(YZ7$nG%c$G}p=-}EwAz|?>J{9cf7N6N`$#VyaOgXRsdybKinCS2x}G2 zwp_ygUZpY@DG`zZtuNO0G-+zH@5#Qc4T?F=W41xbzoczT%CB&0@G3djc8smuf6w!p zR-yYN1N%tlMQCV`>owEPH>Pp${^0dti}`zR-uyAL^qmjKQYq}7=9Ff4mWlXzJdoMQ z`nazCvi7gIE6TS0D9xSegpz(gdvy9r4_5J@B0x)I!)aOYN{mOxY(g8c%^;F4f-{#H~Zmr6tU6K@sZhW zad_NCacMRZG<)MlDt?-i#T_c<{~(Iw(;^mdIqY6h$^99An6Uy01Ls^q_wE2zda;e|cd;YdwvD4A4c#a=)S{dnNvZg}zEg7Je^{&cKa= z2n0&avgu*fj5Z={Ni@pCIJV&B}^Jm8}yq zUY5DS7_yvVQ^WU5ZeF`m={swUgZ5dDIbSsNX*l}fMpw4FZSURn`Jy{v_4m;*_bK_Zni6=gIQAtk<%WqU+l zD}S$|%!rHc7IpaE5F^y}gYT=X^hGg9RLRS`yvFx|65e|`*5w<;`gY0&leJAq~8{Vr>p=LQAX1~s=5 zUkZ1!D1>PkUABYITRg`6%$43crJJ=lpb5`IzB`9DMCIq%Veiy$7#3BV7dEyIKiuVX zj-Ps2IUjBmaKH481@h7$g?EGLdK~#4FToXAPu-UK4JS zdy~IUT1m}X@)Zb-J_;VUfe@IklRPS_t=1`~Xaw3{4U9OqtJ*C!UfR@{dNOU=gkWab zP@IyJ2bFVC`HT%Pa?vK(8nUpi;JFPWPIA}u>PjaBtI*IesJAM^)4TGt;;Nzq{5u@* zmT_b}BG)Ka)*l#>_9u32Pg;23{7IjC^+o{MMSx%F3g1*1t;R6e&A4{%Sn_dTwB!f}-2$fv%S<3%#{ha_vGKgMK# zS?(dNcMJLkq>(nQU0sJMcrg=p*OSOO+7j`oAME#ARfW}`ogP+ zYhLHi+EI>Y@7i=fHOv|rbv_%ZD#pNPGdsxhOS55b0g0ubfKI#z@d_C0ncAUqdWP3y zaW&?9mLje_RY~oX$C|x3a3h`u1vJFsjA+_gSdyu@#xIUbEK{iRb!2+4459wB>&1Ur z7_%4XXTu5)!Y~7A(Z5 z!XLVFYd%B+*nJl=@E<7gkEUiBQI8MALlTv#Sr!FMe|=l%Ao_b! z?JFfUN79mAet+ZJC63H$0Yxui=&=mgyB18QE;T>(e9?GHNUB@u?{ictHk4uOvENzLhjbMfxa9GZgI2r?Q7bdDKhr}tTgGH%iLX6DceFWS6EzlD zc-Vt^Ks+)ZLt2&J2ri3muaibiUGL9TxtCf$=JF9(nYgm1O{<_@Q>#qQG)ckLs6D>W z94eRQFr#QvnrXmHSs@-XGQ%3r5Mpzmiqsti#lv^~88I5Zx%q!a4AVbpPGdw{blR@57KCE-X zReL-@iO|w(jp~&tk*3cpM8?OdjFtP ziq+UMiXlFH_-t*9pH17Uw|QpS5GTTi{3cwlo)BI9B)k=#DvlabExul1A&_M;lZdX$~amPfdMC(D3lVn_}159%CbNYdr%S3(0t0d)?ba;6x1vY(YL z9#=^aCF~5XvD0Lu#Vf{*naq-6$e;uOIsAz3Q)u==h3SPPLN<*XB3X-;6_uFwk;}+# zShFv+qX=Xe56aJNgD`KVK(I1ydZ=1uu=icW%6|Aic6ay$RbM~}MlArua&B3zR11iz zV62rzzaB)WS%@@tB=c2Yp@I|N(+&-_N;RlRYnO$%vuerhk0yB5>F~}$oDx|_y9o}% zrAzJqCXly3XZPOFw(o@qQtL=F)Wl%TFFW}GEm(Ux+K_Aw5Th^@BI+Qf`PqNaS2y;~ zb7Q<6Z=5sPH`6XIzz;D`H(#VhR82_^W|Q#KF|7DWqY|b~B>a(&;4&jp*>_Sd|J4U& zgpPz1+&z3rUUBccZL)~O>Qd9r(G+SqYIko)Q_oHYA1=oH6}2Yo3APa&+Os+A)|7DC z#?$d9mScx#>?s?)NuDP?A-J)-$;NQ!r;Fob4SQB?5N$c_`YY_8laHur@Tp0U=UznyMDneJMgTBK!dYYs>+LsZPY2i(=_$sO{Gj1#}46#Kr+92@! zJAat=Ivem_Pe}l($4IR4vQ`jduLvj#>0(WoCmZZ_%x)dkv1nLDpm=jmLwR@+8kHFG zgZv;RCu=g5xI;%`hm8m|`iF@tn&-v{r=i)V3UlPVw_p_{v5&$8zX(@~gLGpvFC?1Loe7me5}ztC(x!qtMh2_LT0jv`#$s?J(`@!YAF zzUhWI$fU`D%5$hsaWc@RM|?ZKHP(@p3t7(T^U9(-!_kVksi6gYMpdm0#@6-8%h{B5 z-Ox8ZK=e0P9~}0Zv6PBmD|2uW5D58GbEQDOg{&8$LhVHpIPJ>y=(P#FhY&2isS|+{a%WhJRV$ zP=*1+*T+M6>^xQf&AZ2sPpEgwYd3i*iw7aSTvDW#Elq-LXZS+U)Ta||{^flw&OvV5 z7WLe1^0?hwX*>qyoh;$&agTBUcK8mywUCaw>Id#W0VQG7>v2RKyQUhE+J*tV@$%LoGY>bOI3?`Mm>sH7+5=$FdLL5)11V1%S z5<%5<2(#oz^<#JfQ#_*Bju4TaYJ~f&xMrxhPtk>v8qT2VZn3Gq;IDl&IZ$ZATjJ?y z(L6{D?lf@IZ#_{Q7bMS7C1Z*gR<2m4x9ui85F_;`j(g^03yWiW1c+T|Mb6Kw&In>t zt0DcXC%DBFRW+w`hyFLSOxXgmM@V|5qF9ij8Vn+M8vi-B*CP#yfEdFYM90d)Yx1dn-yUvfuuM(<1!+fsO>w5& zBy3y4rKg-btm0#`w;*qpJQXML`NobkfBSP=owaYoZj5(D{`4WpdCZRgI~Ld1wo~`9 z>CH>lQ>OIG;&7LEEFg!l1Q4X-+!^kcH>xbuGjBBtjK&ZgQSo>DD~yWi`d$$^I7QRn z{#&-`!JT%2G#o-mX6NRqjv?}C8ba#8wZO{Y7rE+h33OABSHjQPMYv*9A;_CcCJKY{ z+o!?&jd1m`oR3gL1|Gf3!_mLjTvvUIe?e>WP=4BJN;HAhR&OXW)9y9{R);un0f~%J=J6YgHq-7vyDV?=ekMQkgg?=~&m*gZ zlB+95(dFf}F9I;^^-L7RUDrE&)RsIGF!#VI@Iv)?P10{Sxj}pW-C<)T{=^B_plPJ1 zcXsy9$gFAH*k@47>;wMh?t!H`*0`Qi=cS7VffX1A5CfPVmsxk z{s{M8E_d8(V||X8_9(+G9{~Ur1#g-KU$(>qT9CsZsm=t;^`6ek_;UrGx~Tr|HHi~6 z7yLJ2fQxo9`z8(TrR;z{YX&fZaQOJL+rsQ zEcQnl*1J9|@b*=-RmXSZLR$@=#r!o~)x)#{aPQ@wqGzis&UsW1+G6x|($`*`DeF=! zh|LS^#_y+Y)O?N&=Jx8}TnoIs)ac4o-44U+h_LNC1`iIGaNfjNW)JJ>KV=nk&6(HQbrr40$b&C-I`$2e|dPs!tI#;HGzHL6XCEn~x&Ld0~AmVl&oj1k2eq}g(qBsW3cCUEsv=oJID)tEhQZN!W z?LOTjX=k$&3Z_^&-;T2O#rTw6VP<17n2NxYrr~}tBJ0)U>eOkVh1r*J-q)z-uT7X2 z-XpDb!E*S^-pQV&okYd84MR`j2nqaP%#YR9heLRVzF(&n1V5@U1t#LM<}(EBg@sU| z?BeCMEakq`ARi6Z=4?KS<@hdF*ohH#jH%wXTB-`9+{Y6I1LCdt-|Z+qA%!4zsvzN0 zU{t}IIGZt}Q2PzP#(MOL+$sgL<+c5uJjZD?@gqP1cq$z#D z-`DWtNasCwTOO0rM!GoM@XrObO~>ipkG?7$xQt3LtV&JhtmInVo3dID+>nFYHkDq4 z|KCy>GVRwB*10pA}-Q$OR!xA-qNhi-3S~2@Y0WQKm9J#Qf5I>O`=3U%e&|IxMY)(Jj zMeU*{aolKkzDZgNkgKTw=Qn%%T>cyB%CNC>H4&inkqht>U7h%- zM${g|KWiep7;p^*)+DZm0C}HvL2*C7)Ubmb6E%9yT({f`&kSEFFmgflo(vbZ)5-WA z7V3Av4%KsHf~#xW{q%3AY``;2QP-Xmy3v})D?RA{NF5-;v?)|q%oUuXu|M3z&;>Z~ zOWQR}WPz&&+S-Awy#L0om4^)hdRemkSw^eVSh5ZZzu%T!*(k<)_=Z)`P4CFSo=sG> z?_}V@bA3l@`luw%ySF4x%?`^m5luV&`&JxXrJ-X@jU7BX*g|(;iXoEHpLPPi8VaZA z$AS5mS-Z67373kk-VI)aPgV&CQm`<|qycX{+B%iPkdBXI!UFlpCdQ!8b4v`e=5>~k zt=AWeI`ami3jFN9iGJte%VvQG1rEI`UT0lEz-K}`gb1jIh)Bjrx@P{^b7J!MIi z!W%jyiaa{siqu@~Gs=XFtZC+}&WuOBhE@3+Oa(AdVG5#V4cfScH--%h$MBo!QmUyb zpiD8MB*+qFHi$uSvYY#jLd*8dQ$={~Z%avmHZz18RgS%8I}4s;>CPT*Cr&;!$g}}& zb_Bz}@Xs{KaomIk>HFBT>j^FkPzr7q4=$Mh?{zTXc?x&8m3CwhBde>QLE^+>>~{sX z<>uC?Zv%UtObfwiE5R!{ov44bswczXaSAH1TBF`SlSLs}|ED*f-I5!TY_=@JhZjE4 zC_fA>7Ya~>-x^a$b3##&yMDjnO28ODo7Z=DtEu**%E88}Z$SfpD~3#2^1MyQMcB8n zKEjPXeg9c@cUEQm;GpETBKTTYe}QIrhuQNtZm7uN6)u*4xn51Bv%s;*R`4sfLGV14 z#{`jBy&=63BtTs0*-+`XnA4HucXQ9RA8RO@U;nRT|C%7TWubVgmePj`tX^(BY)q4_ zSKpNZdvmT+BSyR-fFL|Ci5GKHy|a$7@rs#E=~Cc$ifXY5_om-6DXXnMW8$Qp43ZQ43IjMi2?L#O0KQg{N&G!YgIy~7frT}ioCxqU@GKh>mL{IjcfF+LLUf3^1Kf)Z+b z8q(eIPihn*VTpV$rlLEz4!*Y1YQg2<3p1T%9FM62cy-sf;VP(L1GVudo#$wK?V7C5 z5Hx`OWj}SKt$QT80OEu7z$csYJpvM(Jtq`Opyv#Sv#^*v?dJ67I3^0FfQ7RG-UaIn z`~Phe2xa;mHakJ&to8D*H9-KU{K}NhVH@cSIsFiQBqt;&wYA98d*b~y`Qk;p?znGt z%sBt3OqS?%++XQ#r6*;7d)h^kpIW130bz9!C1)w14`}=sTEZ(9r*sXkM9t%EzSnx^ zIsWMd(VgwMrDl5nUlbhbe)c)zvrR0}P>`R|$Le%s$mArb-RN5(3mCxcAx==gYHa;~ zWAu+OFJQ2P0Ta<`16PdN3)>}6&1D#4h9BZXmXrD&63S1i|hO=m^ZMf8nle)JM6mPC--=q0`C?GmtP5Q5&w}by_S0wgN z%wS2<4#70^cGV^@g^utx#ZT@@T)qY6?O+@I77&S6!=tIm0A(8S`6F386nOHxsY14F z+l~t1 zyC;LSi$jr@W0CTDeNx4dmC<1BjatsiU{N0DV%q-!b-q5?E`O;L9p>ejp8z=es?A&5 zuR@CHt0z5i+88>c1ixXWpe`NKgK~VPXzOA-)XhC?GMBn+TLfYA-x%gFd*eIwoy6CT zYoqr!;rA2h|7;ZLK&l^wT-c6;UEmi`5E#bIPL?Qf(vtKzSkC!rKj7ikz440shZ|le z*$+Rx7%HeLQT4!jGd<$(EUiQ_PeCvg+gBYbywjii(s9 z9nhusEVtBOdt$%frv*oY{B?oahm|nC`k@e!`S@zSNv&;3EWrhhQsXyn&)BW(;^5>z z7{gQ@xbGTo*&?TH1lk9L^)7B9b*PmAyK?i=Vw>Ou%wJno!QSLW{ynQi*zi;Il<8bM z{y5TM+|-7dLufwsH$cUJPb)75MNA+hG$GVh=m5EsG_LtQ-X|R0pCDsL|0(Fb?oj@H z$@WE5rqAt%VUk99f|C-@t2v1t|~X8Tkpb0n@?#(eDKR|u{6iPxv!PX_J9 zP-uVfo0=M)Z345<5mHf>M35g~S{dDq^_3s(X(2!>57Ep~c1}0G!SvA;wuGH!O|>qs zhY|8051V2Pp`LjkE3Y3LA4nH$|G65$kJ+`$t7k$fCH|M{ix5z(#9I<{xj!Ty(r~T5 zcvo!Lk!<}dF*jz`*5L?X?Liii@B~BcpZcR8)_CIp3S2hayKKnweG$7bYpOrw{Tg|- z1;ON4qr0_u!ac<#`^6#Jm^}7)_XVC+fc37p9EEm9p0ODxr2ou_kja`(utD0@RLu0S zX%gAP7Szp|qv}X3O6*i$D~Noc4b)qNFQaoob6xj3F{+|9}jjrVCiZQS6q!R65k1 zKPJ`_7wkt_#+zlcjtrV+f;N@@s#yNAHSw7t>`x*>DwWG>Hl%nZ2_CNv6xfwfnJ-@e zY9&>5T5$o&#uruy&KMYSzqg0{WcZ;@m~`v>@MRAv1{R!k$)T>9;h4wyi4@;rbz&|O zzntmV(@{;VgCrMf#m_w1+Z77b-GlM0c z3(U*9{=i!gT9Z`>ZXq)T-p&%T)t3$?l=y#1uKy58rD$jJwP}l6XwL5=YJ1KXr&ll( zPtTPW1BfehxM7&VaTmp%Sm|k>rby(K81luG2I@;n2jEM(h`+%hTR@qNxAyG|R^78L zq2^so$fH@EeDxrL5L!jcCxb?!{)p^6B^(o1}@VauFJTdPY2Iyy}BE*#*kwTBUbMdEEsj%zz1H z_=h;c;DR=SNi=X85>(4&E8CSB4b;{2m{WtAXL-e60`b9IzLj=#kizIPI|jeL>WoqJ zqlZ1|KsZ>tXx-O7wOLJsaQk{e8$6QmDN3tJ_Z?GXe%X&{UR}_N-Ex-=} zTvvzQZ)QtQ!UB!C5zp^=Ve8fJ-}=tik+AN!)EB?+zBRNDn2>pX`i1|bk-ocQmQXP5 zwFw*#E_qaqEJPr*@xOZ070czg^`y0-8j}F1T{=c#dxF`szd1pe>QBX7!w!zO57Zrm zET+NS=eXZw?OYvQ2nUzK12KEY_*gJpJ%7t}CLk)->XQx(Mf%_y5sQ2u$(~YM`cL_i zViK>yM$4S5YZ$UcYIw1k^6Jm2c#xAH9yZsN8A#G!|3sgaeWay{xzV-WDpw(zRuFoH z>`S(BtmX02?FdsqZBL>zfyEzZ$^UQ$?;NoXBEWfvOWq!_)nNDe@Gr4IJ1=>^X$0do zxpzBSr~Q~T3@2)f5Tt|_^7R}#wR;=9va~vdb|=T@6WA2!)Y@cmQKI;CPy(8r?-;b* ziy8FEkpAHRGo|&whXl3VK(qRyxHeR_YyZeC4GAE<*Tiq}bRz2zplXMeasxwbv(oE1 z;~QXDg=qVQvPvgf`u zpx|&m)1W}3jq)@JJo=`k!|2!0?nc5#_Y!ex1QHz%`bIjChHLVSFR@4~!R)n?x8kpK zQ6JnD`+x||#9q6#6Gf^zOPQhJAVrOKW%VWG?iDyuUQlmG9VjpWxKi2Bwaz_K6zU$V zf&k-&NBBpveDV9Mqw68gV;<`ejQ8qFI)f2W=S78vx9gfz2qqRsMUdCBb7+KD|mVB7a7eUwm= zav!D?68V=Ff?N15NDxX%&hk&t|C{~hC;W_M?XR)&4vn) z(qz`aWV$%MZ6kn!Sv~1Ky81}c-8&(Xq?`e2J02(EwR5X^|K$_euY!3{3+FBY zXJwGAr!G=x^hL48`@!I~dF!tsxGAqpklTQbUwo39MX2@>Jw9VQOj>{GzM^8{%0}=`Nyo zZRuTJ6U`K+*n02nC$j^`C5MWo_@YU&il+;On-e8B^iSke_?wPIjzGG;Fxd5t8Z#!;+D2(37UOxS)P|jw<9Vwp z(JeW$089TW@|Yjw<%hkjjPJY>IMC$bWCaZ4UGr~QN*9T}e6}RDgcm-H0mh53D0RoC z{aBh(-qFRl80hXsaX$5ebEAXvXND*j0H1P3+^_SuS(J96BNVx6+Y#h7%EJ zc&)-YH^U$f>&%vNtoQz)+zkR%K1XS*G6QC)K*fgWPK z9gcg}@GLl7`cm)aV74)@uO$bx3|1$6u%tu!;aCw*Y9e{6PJd~vLSDs-k+ksz`u_Y3 z`CJX!c1yc_%&#;*HFlV)m+sh2{PcI+ z?`v3PvRHJI4%|tUuT#Z7k8~;_DFLQ9IY!9IKI|TTPjnW z*J=yH8JH=o?N-^mKX5C|T*+dFU2!1^mEE$TVLlbQ&0PB1#WJV`^FNU~big3+t0ukz zTu0?lA114+pr_3 z$W1X!ZkrsM&IB4ky0W-R#x;c>fG>46V)ucAKN_)k|FV8+9w7r}XR>xCaH-6K#k{xQ z;yv)Uoh>{9!#T8RY9N%3=rq@e9CVXyOIyZcWR#=z&WnK1k+3`rI1K`qU8bG3$PzYv64zOqhAA`&DpzcGmA_+E`KAG%A{O@HhC;4{zH(8x6XH4#mUzTf$O`0T@ zg;2n0N86uD&yA*b5VKJu=?p?4rTPqEVL-C(KoZ7YH&j;5Itau6tx1*ZNqd=hNX}k@ z6L+fl5{v}8-?M2K(EPbtPDy>k)C9Ke<1V&_qJf&KuKJ zYc$B@5M}}q`BC}ITyOA)6xER^RNUG5NSVK0EwVKYh>8KO0MLYqeaFfY1G>mKvV6x- z77N=>7)_8jN>)P~Zh1nd5kTXP3T%H^59w;7oq!N=55@f~a7hXh{oKX<|MMmKXXVaN z+)u8R>TOauQGuhTNxwCUF1UrJ8NkwG>xND4Llrf!@n}uspk75-pfu=X&i0{L$+2`s zalmA$I&&=Oog0NdY5jKpq@$UU!JJj9>gBc-fAY7ZCC7$O5;O3<=E^YYH6Q$0Sfp;n z@Lm;V24LjESoT@=5&*WTy}Dm3+bdgbPYd&Yj=VS+>@1-GmToQeT<@N2z}W<iS0+H?Kz(Py&!Z`3mfU)j2Zv`Pnm9lsY3 zF4D~v10!w)J|=YNrFqz&Yo6$@Y9ra~etzwnWv=ZaqKsRX-LYarnO-BRI@n-r`>q2j zX-?4L#(<>M@DF(TzVcvb$iYg8DjvX_+bSF!C-rbNQ>+wpe&oiSyV~)*X5>NAQrS|u zp}X#L%^T!*0JP14=2E+G4(WUFWE|T;sc?2~SZWJ@%U0sz78c~85U>iv{TZ6ync^ON zbvy2CIz6T!{YKohleDsjRD7eMS>MEitsEMXPa)>wx8(9(tl8DjkVhBYcjU>_k)N2} z!4%fqk%Vi3V(TFg&DR0*{BJn}=_&N>*jpZD=itrkrecSJS@Y(b}Kv*vr=AHIY_x@W;PX_3i_YydP`{ zIy0^GlTvS;o4f98UyqPA6|nFAgi>l;@zwjqhRFV6H&D_NLw=_JhBaGG!o_Zz#`)tf z_3kbGw5r~62~nZMB9{04ejYG=@$5{t=!+3g-5lJLoKz^JWcrx8(o{Ky`e4zlQ1}vJ z=DfBgLGS2K2Kin#TKv+ZL`a;}@ySz%n$pZY!a91xb5EbpnkBNb^jOlV3H6Gw*%nO; z(YUZV^fZ)AP_MaBHM>i|G~x0Eh$BNWR-9sS;L5s!dODGkk15uZB8T|<*m*GDXI{E$ zpS`5~gkyoOi*MSS&t2C?i)nd=Z5Hhk4p>EAki_bX75yQ)R*aoBT?w3nn!QmJ?hg!* ze8sMn81ZW1;=-m+um~vt*m*-G6mHi=kvVH8kT?Q2}PNcc^UxFtclGQ!+zFB)oH;2rx z@^HFivrtre_Uz$`?9!#-{tW$L%Vd`Lrmr`P%fkz(^f#?k*j1!*D}z@ioUsOn?UW zb#t;*Dy*3s2sh7Hvn$@~CJ%x&uyY6@@ImJv^H>zA_0ZPniL*>k#DXSjoK}2rIp^V6 z_~$(b)p)$?yJ9Td06X>bU1B;5CTram$&q!q %xcyi~+)pK=#ICSZo9x@$=fruK} zV+IGh>FiZJ!)4k-vnZQ9jY4FD_8mvsc9yua+TS5wI8zb}VJk0y9;6cCBPPc*Hg!8H!VTnt) z<)-m@8T+iP$`G;3gT7{I7Vm6Q=n>Tk&j(*;*G5J+8Pin%*tQJ`D5d69T}1k^=~vdK zq_edzjp?M{v3~Si>U#kBc)R0w(Rs6sUC~qZG|NwNkp~;~ck(L;km?b-{Xol*z~I6wTVJ7U3Fmb=6SU*>eKupQPb)jm+# zfihYBW$e|pIaU;Lz84oUE%I|~q}G{ZC+B=J`qvH8aLsfetf(>)cYuLGD28Mm=+|#T zgWOnvQ$yir{%DC{*03JZL1StEEQGG2t-9VaRMPh+1BGAMrt^xcr!qa>KLPGKmAjQ; z%{*{9+yw+yZdIxk+Kuy|IqFdR(0CZehgGtd}V7HUtu+J zdb^zwZ~1!wKLT{br{2k#z`G?Ew3;p4OQQ?v40#_C5s9k(n~9(U`&dMfMzh`CruG-+ zt<#u>ZE6EY9aFL=@YA~Ka9nJVf)DF06wu-JY72fwKVugL*$)p@X9d@fjF^3w2yGZb zV7(?8+uiXPO%6in4>5t6%ily7JIxibD9~Y5byIJ!8j&c|G%h~=9GiN5u_9=Ke1b`` z7{^i#%%!mjvU&g?=E_c%A-q}FTFW?q+7zkl*km%bBl^g0#tJ@3wOz6%I`0n==>LGsZ4WhZ5BUEDTek2k% z=Y50a^F5ZwoZQ~`$={_(E~_e;-JXYRJ0pZMl`c>WXS7c@1K#_8jOb~SsK?t>&;tVn zuZDXH9=g>o9BWO@EwG0A*6lU7mvd;v1vw`wa~7ctQ8m3UTK~EiJ7w06BQ>947!5+qh!>ELu9wGMO#YLW+DvZTZ+!E4JWiHc zrWK>2kJl1Kh@KRHaI3u5)p8|5UJx$?liktubhKa4FrJ-#+P1(sfB3T5EdkQP{NChUn6q3PgtcAqKrufHeot}Z+K?JavQ679V61(hCN&tOlXW|Y(W||%>3CNzZrR`c@)s(9`z80xzxEl_5kPk0dIJ3uh*wtb5jA3u^(1Jw`9#-k^2p$P!+oIU&sQb@t58_sO3{l}xtCDvcj`|~ zlDa83^dk9rmO>xH-e5|4|3fcVSr0{!B%q|W|5|`*`pFTXSZO{i?jZ(OjG@YR_BVzT zV5*6msaP7lLP22pZzs3?p8d-1OKXSay9tS~F#c39LMm z5{b>OeNK|CSJh0IcdMddi(BfmN8zneUZsngqIR>q{*+`zc|!a0a9E+lg$o(p9OK6S z&TIvsD!+HHc*_=38N&f3FD7vIj5w3qVHkQszd_y(Q5d>T;;L7R`+`S5C zDc@hnTnaI;5=IWv_pZzrI27o#Cr}KwEJdk*`aads)1?fzezD2$9<5W`P`CWy zDn778;P1as-zv=}GrE;06w^)X*N4XjwrUzpxY>7+NznAgaY65OUqe94UkOmI zLOs4NmsQ!DkB(czd1!T+;wVs zHQBPjv^eO5I-{s-P8m|b1kPKfsjqZZb%t_7dnf_gSQn?aTis0W+R4J> z$|~{qx@+nA%id@-K0KtzyOk_Yqc@#7c`KuL#B&Y6J?Ax1R0<4M;F z&;QffTL#3{Yhk0MxD|)u9o$`u5AN<(26rozqQwV?VjYURbf8nbSaG-FUfkXN&fE8# zd(Zv-eLq)rcCwP4WGBzFR@S2gMc`Jdf0|815DmMQ_$zdzm%(T-2!BX7$G)q*kLAgh zvHmIP!|a1`yG&J!*ZMTMxIYykw~=>aWgD*#WlrtB$gwysdlQQ5t5-CMu@@-zjvhcZ ztuO++Uhq8+0PyTZr0Nb4u6J2G6@k)T7O3M~S68i$vW6b40{!KlU?w_n^;jL)6d)?L z7*H1}al*i|QX9h$Q6JMlQl(X#MFhONbGKU1N7=ya99z%yVf`FN`kXSzlmL%PPFZ8B z*LRDT!IHTt=$=Ry16|@P;zvt7B{X5jqO;tOSM%!L*;G6R)lTqE>oi~b_1$y(?JS+$ z>G1K55AtN#zD>>UO@iLUbbvSxBY#^#k3XHeIkH&}ey4fX}+9#t0**oSL*l~05 zDEO;e)8{dC^!uukEIm*KzEUH-T&0i^{@PoAOlAKEC2HZj7#uWhBq93_G0)e!#|tk-vZ$>yqJFr{J&8F1qFqZ=Xad{ zslVBzbY_2Wa4?2~I_QD>KKZZuH${klRm0vEnnk^0WTpG3Za|>@--duX1wIiF{MEG0 z>2EV(7U+x&@GQ+ID2o3ktUA;hmFduB-h?y!f6WGC^RmQNd3$@q(`6a|f9XnhJL9y9 zM_rhz|I;(%Pw7Fo>9w`BRJUE6EdSFrPCi~xMt z#6~z%0X=_jt+Aw4=Aq*iJ3`eN5%hGPQytWwG`j8Qu|^V#E79n8+0?f8bd(jTzG0qq zNFydy0{`%FA^X2KG37bwTc$-#LyuB>(*M*la+(I}vS-$!P^5FHZ*8tSyOyfC`nG82 z@#RS>-}IB_LM|+bn@eUaSS9Z0hmkXW#ujHwfDOgPMjS9Sga=YG9W(QrE=kipb0>vR zWwT;N#s|A$AuXBqTC&I60!yP$9ycN4btz=tvNlFM1!9PVz0IaqW&W2BCWgE{I)d;P zgaZ+t11!0}-b_5NOFY}TpQDl6h^E4(Qd3jAU4A_uyo+mo6LvH5l?kMeDm#PKuKTFZ1;gJ++BkEhm3rytOsG^Kblr+TIJp52=Rl zVHl3i4@p<1fwit%Cs?p{!q-a9LBerRb#BmO(U7d8D&M7OK2w&p@Q4Kl+0;aKWp2~C zeu}?!R{PzhI$;xv)L`6s&e3_KzeDTy1a?&)PN5Pbe0YQ2;OA|y4C_fZ4LD+!%P*9F zb{zKfupVyMKHIMo;pQ@m#|b+Az%k+^&R=cOqphjh{83dd#@q^sMZvd^s#=^?-HR?l zj|+(3537QMRwwv!_eRYvHL-b(~18!PwXnAtzsLsA?#lcbW9Nlhg2!h8xe|S12LFJt3D@ zkX5tti*LocpEfw)pwV)T{K$jKQ<8Dwh&u)2JSu&%r@dId=3VIQli3IdCHjDgo9DG?gPv? z+IWO3b{j>>y>9ZY-I*Xc9>SOIs#yD3z=dhkE)F8#uDGj0+#VSwg9U!%5;>c#+@mya zk-ru#pC$4wA?73xE#m78Y4VN;acE~_w{YpqDrw(d)4iEEx*~^9$F9onFV+>64|Zdn zTOs@g%2yu|EtPu&GG9;YOxDeGfgtEoMd^IW5ksGuB{kTyzfyXg+~pj#F0K-WysX)IWG&Lh^})|+ zP`x(oey3X5T<(pFHNLVG$lgw`V4?+mS}MIUvud5(LsIEHYV}3=1ajvW>-@XL(nSe@ z75rE7q}d1GRO!=}rlH)K&>Hp0m_yc+yt3+s%pNqXASS)FN&LF=e&dYkU`ORO zbZB{_yrOvOd!_AoK_;#-QA}CT6p5=MmI@Ek>OgM3u+76$USrzQA1Sw~+zgft{Bg{& zFIl+8j|9E%+vKSi29-w6gC<2>&)g_dnb;vB2Corm`21d5z2xuV`b zpIymgrqx6@Qv2TzA;cye40O63|b#<7s0`}UJlx>aDk?~nq(O) zNg!QOFX>mAZ*R_+`DwSD|Is!sQ9oMJSn;{&Y1 z`N!K=9Fk=g2iT_MWv;^&0T~h=HywL%)X#0wi>7xWdkP-MCtL*X=caCaVq)>^j4jJH zZ0%Jzy;ZT|M!Of}WKq&S%Rs)Y3=E-!h~LKFM2?b3h}2u#(J;!d06 zHj(-ec_Sq|Q=t?)Ux6~<^G-g`@t7Q8tg3pR$*|u3t^4_;?VUmR_)nJ?2wtMX0z-lw zJJ}yek`%(f!!J_n6CyY5E9-To!zTWChAuR);ndno=&2n>##`po7n*`^X@uw?I_!g9 zzmQhkPvANMGEgi@ zx6r^y(65-tYXjKR=_LbP%?tI=^LX+(%B&M~XJh7NLNMIlt{szutNow@6s7(DK;oKR zrj?`~vU!~KZ}AdN&tmpEEG+xOE%KY@5T=DhSXTzIEc+DMkTN-={+Ufq!O{}h!S5a9 zbQ_XX1`8IxTfh&9Q=0GIzyPAN$f~QSfjCD!<03y^s*S;ClY)(m_>zr*>LZCePIJZ4 zW~S&S;$W{hE&&|_qt&@XL>@|`MVE2T;4V7#!idcG_+p+iW(ikzeUWdR@!kwB-Y9Pq zHb0PFV)-NEHx}OA~>Y#h<$n%QlC%>TU`ueAfHlM)r{gsE|mFw2q7UP&}hUeK5|NDFG z>+RzV#1#6XRh0XzVyC_@Xr2g!^V>CNkr_SEl(NnY3k_B-tt0j z;nqGS-B-4ipMe_{=H$(zLZ|HoI78tLW{n=o1zjS{_xhm{6-FZAPV$_WQo5F%%(|T1 znBD=TN`Vl`um(OnB!J5lvB^nE6wQiDfgAQNRDgoslRER1Zz2GVWi$$fQqAcFqMOC0 z&X;;p_WF-lQ=X*v5Gim#L8CuxamRxp961P2@YG0K^SdM>HguxDyEw^tD|1f?Jf%Vu z6rvr0zW{Pg6#TI&C_9!+<#Qf?9TZ?C)%OQgYTOlFk8Fp8lIRjI_&qS<)P?awz6fso zAb5pq62P0%b1nKceeP%`MbwPMxT&OC>^#mQ_uHti5dxy+B?Ls`W5}I5jAoFMR6TB# z&?$-pNK@=y;&XIf);6@(1V!nJ+Led7<1NgKL?NEVy#Ah_(lX zK4!q(^iNF(tpyMJT>OD@E+*c{3zo=V12VWVGdjlQOhX>N%Gc-<7HB>D^4AxnA9W$^ z&g5s{cM5=mX^?fl9>(v@tUFTVzQ`~lfPbaxuv2d$kMwH43Q-2%bcY_kl7O#-BBzHf z4FvD@{Z|VfuN~})(Y4J&L~bdN$D0_r&&HZLJK1XL7xBVp=hJ@{-<_yyUUj#4!-M9d668 zZ0x?gY)aHVvWJE>JZ9p9PN!TV+m@evBIQ4%ulxx@3H<5V;71KxXu_d()Lb2&bUaeS z|E>nETGhYDk-*LLIxji4+n5a?Kv?n<>^K;$TI$OXAjl*WK9^0C0^`W4en?;r zz6N35IT8B-8OH~vViEm`&QU68#tO-WABUwj-tU3JAKS584Ztfp>@&)dn2*Q8-I5=j znS}-5w~$b$%eH7RyC(0Gj%%=D))TOC7;8`}@8QJGfYioBM0AT@{9#hOFx@)b#I3E2K>#cT`gfqgUdJ2WJm_h)D(KO8<-Yp)@&h&d+~A`NY>=zlsud^J3IrAs-G+|>|?Tr8lU6x zf5L}@3fiySC)_gb1T@UQ;-fCgxpkkoqjCHPOut0w-i*k339unq;SbI0lMJGxAj^;< zK?zEgsMQ$Z?3zNjVeaz7;){OFVq^8re9MbYV#A2xHZa}Oz5K>e1_&O{B_Ah~azp}T z%LM3DKR+Oa`P2l`MItQ{-dAMdh8Da)^Fsp;^<|PxRp#w%%-(D$G%rpgY8np{5m}In zZN2SsSR;#zi({x>02)DbDEloG7_#-#`Ov)bva+?=)Bqee9m(_Utlsj;zJ3S8yd+i^ zG~7kDVl-(H0Y=RH<;icDK4(B{>BJ)=W`jNOjZ^$FzKQ(&Vl51ivvx#oOrs0Cp#kk_ z#nbB&3YoN(kIwh`I9c(PP?EZSe{qsSC$M+RJB_KRw{!bMkJ9h(t@cxE95pduJAnLa&P_2 z!llh;yW`P5tZKep4gM&L2MC0q!QL9b11$eG0!(iUxMbnI?zB(uYv{07WBIm?upYk% z2lbb8KQGK{d=w&ObOFDO@tkUT7%F_5F*5T&SP*JQR zPiQR-7laj7AaFeP5DydVBa;dj8VFYa7p*>w!)b{UnNagrfVymV{jG+f?jwmV`&#}g zzNJV77Mhp{*QLSu3Ib&syA7}m;#Gig(j?|Mf7;6l;arvwMb|KyJ5-if?A~f! zZn<5h)yXk`-XZ)3ZU@DIE|XGMlf_J18qvWvL4ddgC%(iR2;S~{L~jgmXQIB?Y1$lK zfH-h*YD1&438eC#kbvFY7athw8I%jlbw+@wUa`xeCQ&pSq65mgL{L z>(vR`^()VAAFt6{?*^uD1V2bDEk4LJQ9+^NY)(hw@QNg?XW9e3&R0X5j+cRH$fLPC zK(IbE>@}Pk7nB9B6ri0d%YxZSe6Tt^qMuIm=&%H^LSj<1MX}>(ovh3-fF_gm#D!w3 z!LMa*bVM0AO}t%!CKu=LH=F_sn$5u1jqvsOSD%T!Bdy3dy8WMz4hTtKlg!xCX42u2 ze`0sXsSRm!L6v<%`=(&H8=HKV0TYy6l?8~X2h4oV4|_d?#bb*p`;VhdxB?ms+!fig zrIZ?XU|>*4{O49!enrRKvFQuM<28=_TB82q0@%IL5(4~Kft%2f$24B1!m_@_Qma$> zho1bQPU&}UD(>|c&`<}m^?U0UT8SU~YZqoWi`Lr--ql!F{ z6{Gq9%Q0Yc`#vkZd)L`fEXpCoo=8MGn^V6I=6%PD0!V`ro(?#tztt{x+Q#o(gDjmL zaLw0qTIgGqH?+o)yywcQ`8Lioro;;ncZUzQu>d(MRy8%S?0{<~dt@!LDlE}l;P2M| z^J2bmF{GQ0T!^8fWP@FYOoEjZdCg< zLl@68O1jr=TU-mtb5qdGeqb8SgUEBOMD|U;e1F-mqUVeKHlqG54-|5j`a>7_J^OLm zb4165BB#u(4*a&Ng=PEu+dGqA z8b(|#ddUwOx#$eh+~v|zn$;=MWYw`Bau8~fNvI+S> zKmuiU#n4>jH8} z<|$PD_q+`(YV!vg|czYNw8^noPV0V1FD4GY}nDt-i*cTg$7JHQ7XCp zyt`VdBRgDYsrj03Gefb4-}Bop5GJ>wmA7SxV4CUF`ZH#-ZeL@$OhpsFEYbMKa$4Cd z>}*i1_|2oO&~Xr~Qm=lkFID`Yns`Dun`C`N-KM zKrFeKs>(;JZD#YroW%xTRUM!1Yc+2YLt@i5kiHV6`=0yElc2DoGKbZqV^a;;B z3bg&@0$v;!ONMTxQwI%SkEl}>nsAOe&cOKsBgb{ydrn<+?9;88ZPHqx3Z>hd4kaOD zzV(qKUzbgJ&a2^?>=LsP0($mfi)J;ogvF6tg0+c9^2W!dy{9LFe*FaX8}+ShsuQfZ z&@09Dpqx^D)D^Pk+Gf{&K;Y&85(b>l$#MM?^y#vDKQfG0+D}>+#iMq6QEfWe2!odD z4Q(cS1|-i-)ZFjMPuMm^d;BTtrLdTXh&cv;Vbb;ftuTH)L6pex^1%aRv+>~e8_a)b zq`%Y)P1p9P$B?_?&7AEP_x-1K!2hsIoCGz3mfvSu4i65r_qhK1%KtDu|EEk-hcY@% z*YFxBFOW&zQY3xF&g*{4?0$}VUaQgFPF}c8r#!Rq0zXb_wFDSY@%@LHh$wjtOSh8) zLv@4uP3)(!S+jn9`V~dzdl|Wqfzb{H&k_SlKS$-=Nfnotxz6rOjdyuEjyb_3G?{Ic z8!eeVyq4*UE_eV2(UmvAMJAJm_lCoQMHfsG11#V8;-3cGchBeoFNc6ER=nQ3XBD*J z=Xk~G9o9@m5vEC`H;Y7@ z)S232(ew7Q`hC+U8A~xj4r%)izjk3{ph*>>2O4SMu0aCtX!i1+VZxZ2?`)ls=!5<* z-*kSoKIeNRIS-5&mY-jAjnilC$q>rog7Q$5C)zR7J2sa&)L1@&aY^bk{wj9Q7|l4- zGl-g3;kjE>pVc>Bx@HxMcFK$L5^qgO>QLL~dzT0#Lmh|N=v#hEp6_Bg-q^gJnCPqa zfq+#f#-Q9ZQc|}QrWj??z8|h|2%%P-u|D`43wWF-- z!q+`z^8q==tk+1%F}mac7aPV1ZmS?_U(x8_aFBd`OG^8LomJ&XPA{_n^4aaGRPKNlt)z9N8QQKHVVRekb~BR8o&ol3j0Q`>>D8m=ICLrWPSzG;PVo{r%Loms^ra zcCeOorNMrwNX#G!Jc@($1QH=Zfy&hPLzQUNU=Tx>mc42nlw8r3a-M}Vm!|@k%rYGR z)=?RN!?3h(YfJJQ9>Jo*;xY1sg~5Ql%o9kVA%7oml&wwsLd0F@7CigX(9uXm@Y=I6 zraB=XLW-egv&!Uz!dZ<<5I^6u9%5rNaAGCHy_X|dBu4y74hcY+VIvS36LLeVq7V(8!O4kPtlyTge=OS8L)Kqh_2TF zTjSp`N03`oI5!01h>epzy84%^@qdU`i@VF4>htjhy*^ilGvi@5DlojYWvQ%ei;AO{ zX`2QJ2V-b40!R{;)QS3IBQhN4OLi>D8E2lak}7t?zC2nvM)=*XYIWv*XasEWgcJ#o zLCX(nxOsxCIw$JP)P*1!iae+oq&}*3y}kHZ9r~$O6@II$W^&}=(oqa0y^T6YPTfLO z*l}H&hE4wC?;TkFG-F-8=tV{C8jxNjrJu>L`JG7VaSlje>}{yb9B-lZ>se!Bq%YW= zgY=76<9$T{FS~T?UH@3FC9d){!EVXcJGgRV&e1^m*^~4Wk915%rx?M=X}~wr)w#x z$=uwn%W3AM*nu-_}syKtbOAmTvv{tu7bJ5A^g$u^n%a8r@@LraawMV5kj_ay3bTIS;d}c z8nf%dMzy~71bat`tpDaSMHt~u^lo!QuMQFpNtybXG@Sxs%Vg9l4Y=hA3vbXR*BHkJ=GI91h zz&m{bpwp)9&97NRhnK0sHzY^KM8q*u&E>8a3e5z8s;1xCd*@8?1G61>(BsuqQN~VV z*nTf236qgQT)o(>f{{inWiIHu_f)X2Dc zG#rd^q`D80D*5obdT8aafteTfM^y7;l-3PM(Vfg98kuNkSYdUhtDA;{DliEtUplcL z1Qy851X~yAt?hoEz8_e9KhQq`Dh0FkINJ7Nl=+;x^)mVUP(rvJM5J074puLdkfkBH z0nT={ozKyh7)J%)I>-}aGhDB-$HlV5_wJk+PV?Ap(zx?7y3;n^rZc1V5R4UQZ_3~b zdNn_N5-&Nd>99vaDec;)e5AWvI_273ZK9M`?>-xw*`T>6s+oke9!((aA(FpVPVJd?E@mACXt-*1F9%AsIT2a=g&-{T z{zAFa&-A>)AlH%U0DskCi}e1jGs<25u2WJIiZLJ)FCHy5cclc0Q1A$PJzb1-7WX3b z=X<{0xwM^3a(7y+2r(S#);|`*EP>`@$K&1AEnWa#vC6B}cdxL$jkr)h;{kAWbdh8! z^u%It(ja?F1>-+X;WlPNUukJdM}_jyOoDmNf*1JNR7p`QaLven4(P;Yuxb?Z0}`&u zmy#JXK2Y-8kWM2{o{yCnqV#R`2smZGj2ii1Jzx)sMIFxP3=4XoRF*E3H~i>C_J%lq z3B{L**e;ED8^l8MnCUNRdSwrqm;6K_`Rj%WkfyMZhzn|bWu2-Syxl=;b@ui6qg4g^ zBq}ootSjVkif>C!O@JTU@N;1y0?|$@)-wtwUOZHbgsZxc%9~lkNzvCQ%tI(9lvNF^ zwYtGqauOA>vCLkg^?IqJ;8n;bdF0R`W<9g%I7eq&yXilcPXKYxcT%s?p{UMi19!tm zWp!?0rH~IwpP+4eP3y*wcxh9%GK5`K7hh_$9CR30t>f{(SuxgIfHz;z4Hq_Nnu9BZ zjJupa)B`yL7L;`Pqge$6#D!Zv6-?3k&1x#40${AOK80w!s1fjf~_cp*RS_mp=9 zox8T8SzseHZWPwHL}3O#Z<&;U;5gN84WDZIeN8nmCyh8=W)lQg@Ec-!si_>edk!X5 zNG5-S>aE1IGM{7x4_ogbKA3!KPbhh?!b!ZnCB*Y}V;#i%Dh}t}?b62nQZeplrpsh*)7!w%U_%3sc>}_JRw( z3Ok4S*tLsdL*?%I2AfMni0;)y%{BO2%?7byl0E(|9WmcwD*FBhvEzH}39-F$a-POb zOU{=}8Qo4=vQOL|?7mcK1A?z03xar{+vt%mXfWX4-}blQclbYAyFTLjaE-DP$24Xm zPrz{t3Lk_xWOlmDGBV+=RAD-Ks?+)0c{pUbZNBs%6z}LRGiYt+s=|V}#@1A*>2N%- z?h=lzdJt1C<>+DAdCFF}rwGPF$K}A^)2))3j zuY(T6)~l(2o8o*cUQ2>v=J|uRPF@^gB3MO}eoePeJXrLLODY#s5s3 zPhq$VB`RBMLodNAS9~|iVXx}|WzQdV=KWTk2xas*hOk!q;fVxsY=rTd15XqjSs=)@ zcZrr&iA;&)^<&8<|pzgPsQ|=aD68FP>a=sF* zxrE25VdlYZJ*-7UxX1E#ZUoFw%a;N1t-Jd0HN= zX4s^EnT?ae<%3W*!_a0-BVkNAP5S&%I^Gt{aaIl73wNA&=ud_G3!bJYiMWV;+))M7 z7aR@!Fjpm>!PrfDld$<|`I5ntCu=aplAnrpDD*DAwQOzLo11s@S7tN<)i7eP6XLE) zUJ0l@@FlHh5fpot>nmjs(ZK|g^SAd-ft5OQeevNKtC%3%3?)1kP7CYjEJH_oo1>6^%gPSRS>=cVv{ zO>n)woc^?k!#Lc1ltsJX1rxuHQMr!3mS*-_6QL!Z^d@cNK9q!%)jUDGy7WEbD9@4a zb*+Dh=3b`HmLFbaGkcczi6SmwXFXWx8FGT&oW)6RU2TRLe6xE}SeaGfZp*z(1bEtn z`DFhE1>o3#56sO6|3N9{e`Fru;(u&M-{6|DWya!4(En>n`j6=E4s32}x?iV$zKN80 z$h*V($M5g2q3OHH6g(X{?Pq>8_gbSC_w|Uo*ngo1crEYvQj?~58M|VAD@N)5=Kkj; zIla+LTj)NiIXCb4x> zaQr}87JK3m@^4N&5OLsBYS6W7>g>gZ1pa?j<-~X;L4CB`a(^B4eElpT^BVJ4gYjK2 R{Cd(Cin3}lmB4o){}0{H>gxai literal 0 HcmV?d00001 diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mflag/LICENSE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mflag/LICENSE new file mode 100644 index 00000000..ac74d8f0 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mflag/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014-2015 The Docker & Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags.go new file mode 100644 index 00000000..17dbd7a6 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags.go @@ -0,0 +1,69 @@ +package mount + +import ( + "strings" +) + +// Parse fstab type mount options into mount() flags +// and device specific data +func parseOptions(options string) (int, string) { + var ( + flag int + data []string + ) + + flags := map[string]struct { + clear bool + flag int + }{ + "defaults": {false, 0}, + "ro": {false, RDONLY}, + "rw": {true, RDONLY}, + "suid": {true, NOSUID}, + "nosuid": {false, NOSUID}, + "dev": {true, NODEV}, + "nodev": {false, NODEV}, + "exec": {true, NOEXEC}, + "noexec": {false, NOEXEC}, + "sync": {false, SYNCHRONOUS}, + "async": {true, SYNCHRONOUS}, + "dirsync": {false, DIRSYNC}, + "remount": {false, REMOUNT}, + "mand": {false, MANDLOCK}, + "nomand": {true, MANDLOCK}, + "atime": {true, NOATIME}, + "noatime": {false, NOATIME}, + "diratime": {true, NODIRATIME}, + "nodiratime": {false, NODIRATIME}, + "bind": {false, BIND}, + "rbind": {false, RBIND}, + "unbindable": {false, UNBINDABLE}, + "runbindable": {false, RUNBINDABLE}, + "private": {false, PRIVATE}, + "rprivate": {false, RPRIVATE}, + "shared": {false, SHARED}, + "rshared": {false, RSHARED}, + "slave": {false, SLAVE}, + "rslave": {false, RSLAVE}, + "relatime": {false, RELATIME}, + "norelatime": {true, RELATIME}, + "strictatime": {false, STRICTATIME}, + "nostrictatime": {true, STRICTATIME}, + } + + for _, o := range strings.Split(options, ",") { + // If the option does not exist in the flags table or the flag + // is not supported on the platform, + // then it is a data value for a specific fs type + if f, exists := flags[o]; exists && f.flag != 0 { + if f.clear { + flag &= ^f.flag + } else { + flag |= f.flag + } + } else { + data = append(data, o) + } + } + return flag, strings.Join(data, ",") +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_freebsd.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_freebsd.go new file mode 100644 index 00000000..f166cb2f --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_freebsd.go @@ -0,0 +1,48 @@ +// +build freebsd,cgo + +package mount + +/* +#include +*/ +import "C" + +const ( + // RDONLY will mount the filesystem as read-only. + RDONLY = C.MNT_RDONLY + + // NOSUID will not allow set-user-identifier or set-group-identifier bits to + // take effect. + NOSUID = C.MNT_NOSUID + + // NOEXEC will not allow execution of any binaries on the mounted file system. + NOEXEC = C.MNT_NOEXEC + + // SYNCHRONOUS will allow any I/O to the file system to be done synchronously. + SYNCHRONOUS = C.MNT_SYNCHRONOUS + + // NOATIME will not update the file access time when reading from a file. + NOATIME = C.MNT_NOATIME +) + +// These flags are unsupported. +const ( + BIND = 0 + DIRSYNC = 0 + MANDLOCK = 0 + NODEV = 0 + NODIRATIME = 0 + UNBINDABLE = 0 + RUNBINDABLE = 0 + PRIVATE = 0 + RPRIVATE = 0 + SHARED = 0 + RSHARED = 0 + SLAVE = 0 + RSLAVE = 0 + RBIND = 0 + RELATIVE = 0 + RELATIME = 0 + REMOUNT = 0 + STRICTATIME = 0 +) diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_linux.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_linux.go new file mode 100644 index 00000000..2f9f5c58 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_linux.go @@ -0,0 +1,85 @@ +package mount + +import ( + "syscall" +) + +const ( + // RDONLY will mount the file system read-only. + RDONLY = syscall.MS_RDONLY + + // NOSUID will not allow set-user-identifier or set-group-identifier bits to + // take effect. + NOSUID = syscall.MS_NOSUID + + // NODEV will not interpret character or block special devices on the file + // system. + NODEV = syscall.MS_NODEV + + // NOEXEC will not allow execution of any binaries on the mounted file system. + NOEXEC = syscall.MS_NOEXEC + + // SYNCHRONOUS will allow I/O to the file system to be done synchronously. + SYNCHRONOUS = syscall.MS_SYNCHRONOUS + + // DIRSYNC will force all directory updates within the file system to be done + // synchronously. This affects the following system calls: creat, link, + // unlink, symlink, mkdir, rmdir, mknod and rename. + DIRSYNC = syscall.MS_DIRSYNC + + // REMOUNT will attempt to remount an already-mounted file system. This is + // commonly used to change the mount flags for a file system, especially to + // make a readonly file system writeable. It does not change device or mount + // point. + REMOUNT = syscall.MS_REMOUNT + + // MANDLOCK will force mandatory locks on a filesystem. + MANDLOCK = syscall.MS_MANDLOCK + + // NOATIME will not update the file access time when reading from a file. + NOATIME = syscall.MS_NOATIME + + // NODIRATIME will not update the directory access time. + NODIRATIME = syscall.MS_NODIRATIME + + // BIND remounts a subtree somewhere else. + BIND = syscall.MS_BIND + + // RBIND remounts a subtree and all possible submounts somewhere else. + RBIND = syscall.MS_BIND | syscall.MS_REC + + // UNBINDABLE creates a mount which cannot be cloned through a bind operation. + UNBINDABLE = syscall.MS_UNBINDABLE + + // RUNBINDABLE marks the entire mount tree as UNBINDABLE. + RUNBINDABLE = syscall.MS_UNBINDABLE | syscall.MS_REC + + // PRIVATE creates a mount which carries no propagation abilities. + PRIVATE = syscall.MS_PRIVATE + + // RPRIVATE marks the entire mount tree as PRIVATE. + RPRIVATE = syscall.MS_PRIVATE | syscall.MS_REC + + // SLAVE creates a mount which receives propagation from its master, but not + // vice versa. + SLAVE = syscall.MS_SLAVE + + // RSLAVE marks the entire mount tree as SLAVE. + RSLAVE = syscall.MS_SLAVE | syscall.MS_REC + + // SHARED creates a mount which provides the ability to create mirrors of + // that mount such that mounts and unmounts within any of the mirrors + // propagate to the other mirrors. + SHARED = syscall.MS_SHARED + + // RSHARED marks the entire mount tree as SHARED. + RSHARED = syscall.MS_SHARED | syscall.MS_REC + + // RELATIME updates inode access times relative to modify or change time. + RELATIME = syscall.MS_RELATIME + + // STRICTATIME allows to explicitly request full atime updates. This makes + // it possible for the kernel to default to relatime or noatime but still + // allow userspace to override it. + STRICTATIME = syscall.MS_STRICTATIME +) diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_unsupported.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_unsupported.go new file mode 100644 index 00000000..a90d3d11 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/flags_unsupported.go @@ -0,0 +1,30 @@ +// +build !linux,!freebsd freebsd,!cgo + +package mount + +// These flags are unsupported. +const ( + BIND = 0 + DIRSYNC = 0 + MANDLOCK = 0 + NOATIME = 0 + NODEV = 0 + NODIRATIME = 0 + NOEXEC = 0 + NOSUID = 0 + UNBINDABLE = 0 + RUNBINDABLE = 0 + PRIVATE = 0 + RPRIVATE = 0 + SHARED = 0 + RSHARED = 0 + SLAVE = 0 + RSLAVE = 0 + RBIND = 0 + RELATIME = 0 + RELATIVE = 0 + REMOUNT = 0 + STRICTATIME = 0 + SYNCHRONOUS = 0 + RDONLY = 0 +) diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount.go new file mode 100644 index 00000000..ed7216e5 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount.go @@ -0,0 +1,74 @@ +package mount + +import ( + "time" +) + +// GetMounts retrieves a list of mounts for the current running process. +func GetMounts() ([]*Info, error) { + return parseMountTable() +} + +// Mounted looks at /proc/self/mountinfo to determine of the specified +// mountpoint has been mounted +func Mounted(mountpoint string) (bool, error) { + entries, err := parseMountTable() + if err != nil { + return false, err + } + + // Search the table for the mountpoint + for _, e := range entries { + if e.Mountpoint == mountpoint { + return true, nil + } + } + return false, nil +} + +// Mount will mount filesystem according to the specified configuration, on the +// condition that the target path is *not* already mounted. Options must be +// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See +// flags.go for supported option flags. +func Mount(device, target, mType, options string) error { + flag, _ := parseOptions(options) + if flag&REMOUNT != REMOUNT { + if mounted, err := Mounted(target); err != nil || mounted { + return err + } + } + return ForceMount(device, target, mType, options) +} + +// ForceMount will mount a filesystem according to the specified configuration, +// *regardless* if the target path is not already mounted. Options must be +// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See +// flags.go for supported option flags. +func ForceMount(device, target, mType, options string) error { + flag, data := parseOptions(options) + if err := mount(device, target, mType, uintptr(flag), data); err != nil { + return err + } + return nil +} + +// Unmount will unmount the target filesystem, so long as it is mounted. +func Unmount(target string) error { + if mounted, err := Mounted(target); err != nil || !mounted { + return err + } + return ForceUnmount(target) +} + +// ForceUnmount will force an unmount of the target filesystem, regardless if +// it is mounted or not. +func ForceUnmount(target string) (err error) { + // Simple retry logic for unmount + for i := 0; i < 10; i++ { + if err = unmount(target, 0); err == nil { + return nil + } + time.Sleep(100 * time.Millisecond) + } + return +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_freebsd.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_freebsd.go new file mode 100644 index 00000000..bb870e6f --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_freebsd.go @@ -0,0 +1,59 @@ +package mount + +/* +#include +#include +#include +#include +#include +#include +*/ +import "C" + +import ( + "fmt" + "strings" + "syscall" + "unsafe" +) + +func allocateIOVecs(options []string) []C.struct_iovec { + out := make([]C.struct_iovec, len(options)) + for i, option := range options { + out[i].iov_base = unsafe.Pointer(C.CString(option)) + out[i].iov_len = C.size_t(len(option) + 1) + } + return out +} + +func mount(device, target, mType string, flag uintptr, data string) error { + isNullFS := false + + xs := strings.Split(data, ",") + for _, x := range xs { + if x == "bind" { + isNullFS = true + } + } + + options := []string{"fspath", target} + if isNullFS { + options = append(options, "fstype", "nullfs", "target", device) + } else { + options = append(options, "fstype", mType, "from", device) + } + rawOptions := allocateIOVecs(options) + for _, rawOption := range rawOptions { + defer C.free(rawOption.iov_base) + } + + if errno := C.nmount(&rawOptions[0], C.uint(len(options)), C.int(flag)); errno != 0 { + reason := C.GoString(C.strerror(*C.__error())) + return fmt.Errorf("Failed to call nmount: %s", reason) + } + return nil +} + +func unmount(target string, flag int) error { + return syscall.Unmount(target, flag) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_linux.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_linux.go new file mode 100644 index 00000000..dd4280c7 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_linux.go @@ -0,0 +1,21 @@ +package mount + +import ( + "syscall" +) + +func mount(device, target, mType string, flag uintptr, data string) error { + if err := syscall.Mount(device, target, mType, flag, data); err != nil { + return err + } + + // If we have a bind mount or remount, remount... + if flag&syscall.MS_BIND == syscall.MS_BIND && flag&syscall.MS_RDONLY == syscall.MS_RDONLY { + return syscall.Mount(device, target, mType, flag|syscall.MS_REMOUNT, data) + } + return nil +} + +func unmount(target string, flag int) error { + return syscall.Unmount(target, flag) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_unsupported.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_unsupported.go new file mode 100644 index 00000000..eb93365e --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mounter_unsupported.go @@ -0,0 +1,11 @@ +// +build !linux,!freebsd freebsd,!cgo + +package mount + +func mount(device, target, mType string, flag uintptr, data string) error { + panic("Not implemented") +} + +func unmount(target string, flag int) error { + panic("Not implemented") +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo.go new file mode 100644 index 00000000..e3fc3535 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo.go @@ -0,0 +1,40 @@ +package mount + +// Info reveals information about a particular mounted filesystem. This +// struct is populated from the content in the /proc//mountinfo file. +type Info struct { + // ID is a unique identifier of the mount (may be reused after umount). + ID int + + // Parent indicates the ID of the mount parent (or of self for the top of the + // mount tree). + Parent int + + // Major indicates one half of the device ID which identifies the device class. + Major int + + // Minor indicates one half of the device ID which identifies a specific + // instance of device. + Minor int + + // Root of the mount within the filesystem. + Root string + + // Mountpoint indicates the mount point relative to the process's root. + Mountpoint string + + // Opts represents mount-specific options. + Opts string + + // Optional represents optional fields. + Optional string + + // Fstype indicates the type of filesystem, such as EXT3. + Fstype string + + // Source indicates filesystem specific information or "none". + Source string + + // VfsOpts represents per super block options. + VfsOpts string +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go new file mode 100644 index 00000000..4f32edcd --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go @@ -0,0 +1,41 @@ +package mount + +/* +#include +#include +#include +*/ +import "C" + +import ( + "fmt" + "reflect" + "unsafe" +) + +// Parse /proc/self/mountinfo because comparing Dev and ino does not work from +// bind mounts. +func parseMountTable() ([]*Info, error) { + var rawEntries *C.struct_statfs + + count := int(C.getmntinfo(&rawEntries, C.MNT_WAIT)) + if count == 0 { + return nil, fmt.Errorf("Failed to call getmntinfo") + } + + var entries []C.struct_statfs + header := (*reflect.SliceHeader)(unsafe.Pointer(&entries)) + header.Cap = count + header.Len = count + header.Data = uintptr(unsafe.Pointer(rawEntries)) + + var out []*Info + for _, entry := range entries { + var mountinfo Info + mountinfo.Mountpoint = C.GoString(&entry.f_mntonname[0]) + mountinfo.Source = C.GoString(&entry.f_mntfromname[0]) + mountinfo.Fstype = C.GoString(&entry.f_fstypename[0]) + out = append(out, &mountinfo) + } + return out, nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux.go new file mode 100644 index 00000000..be69fee1 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux.go @@ -0,0 +1,95 @@ +// +build linux + +package mount + +import ( + "bufio" + "fmt" + "io" + "os" + "strings" +) + +const ( + /* 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue + (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) + + (1) mount ID: unique identifier of the mount (may be reused after umount) + (2) parent ID: ID of parent (or of self for the top of the mount tree) + (3) major:minor: value of st_dev for files on filesystem + (4) root: root of the mount within the filesystem + (5) mount point: mount point relative to the process's root + (6) mount options: per mount options + (7) optional fields: zero or more fields of the form "tag[:value]" + (8) separator: marks the end of the optional fields + (9) filesystem type: name of filesystem of the form "type[.subtype]" + (10) mount source: filesystem specific information or "none" + (11) super options: per super block options*/ + mountinfoFormat = "%d %d %d:%d %s %s %s %s" +) + +// Parse /proc/self/mountinfo because comparing Dev and ino does not work from +// bind mounts +func parseMountTable() ([]*Info, error) { + f, err := os.Open("/proc/self/mountinfo") + if err != nil { + return nil, err + } + defer f.Close() + + return parseInfoFile(f) +} + +func parseInfoFile(r io.Reader) ([]*Info, error) { + var ( + s = bufio.NewScanner(r) + out = []*Info{} + ) + + for s.Scan() { + if err := s.Err(); err != nil { + return nil, err + } + + var ( + p = &Info{} + text = s.Text() + optionalFields string + ) + + if _, err := fmt.Sscanf(text, mountinfoFormat, + &p.ID, &p.Parent, &p.Major, &p.Minor, + &p.Root, &p.Mountpoint, &p.Opts, &optionalFields); err != nil { + return nil, fmt.Errorf("Scanning '%s' failed: %s", text, err) + } + // Safe as mountinfo encodes mountpoints with spaces as \040. + index := strings.Index(text, " - ") + postSeparatorFields := strings.Fields(text[index+3:]) + if len(postSeparatorFields) < 3 { + return nil, fmt.Errorf("Error found less than 3 fields post '-' in %q", text) + } + + if optionalFields != "-" { + p.Optional = optionalFields + } + + p.Fstype = postSeparatorFields[0] + p.Source = postSeparatorFields[1] + p.VfsOpts = strings.Join(postSeparatorFields[2:], " ") + out = append(out, p) + } + return out, nil +} + +// PidMountInfo collects the mounts for a specific process ID. If the process +// ID is unknown, it is better to use `GetMounts` which will inspect +// "/proc/self/mountinfo" instead. +func PidMountInfo(pid int) ([]*Info, error) { + f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid)) + if err != nil { + return nil, err + } + defer f.Close() + + return parseInfoFile(f) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go new file mode 100644 index 00000000..8245f01d --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go @@ -0,0 +1,12 @@ +// +build !linux,!freebsd freebsd,!cgo + +package mount + +import ( + "fmt" + "runtime" +) + +func parseMountTable() ([]*Info, error) { + return nil, fmt.Errorf("mount.parseMountTable is not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go new file mode 100644 index 00000000..47303bbc --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go @@ -0,0 +1,70 @@ +// +build linux + +package mount + +// MakeShared ensures a mounted filesystem has the SHARED mount option enabled. +// See the supported options in flags.go for further reference. +func MakeShared(mountPoint string) error { + return ensureMountedAs(mountPoint, "shared") +} + +// MakeRShared ensures a mounted filesystem has the RSHARED mount option enabled. +// See the supported options in flags.go for further reference. +func MakeRShared(mountPoint string) error { + return ensureMountedAs(mountPoint, "rshared") +} + +// MakePrivate ensures a mounted filesystem has the PRIVATE mount option enabled. +// See the supported options in flags.go for further reference. +func MakePrivate(mountPoint string) error { + return ensureMountedAs(mountPoint, "private") +} + +// MakeRPrivate ensures a mounted filesystem has the RPRIVATE mount option +// enabled. See the supported options in flags.go for further reference. +func MakeRPrivate(mountPoint string) error { + return ensureMountedAs(mountPoint, "rprivate") +} + +// MakeSlave ensures a mounted filesystem has the SLAVE mount option enabled. +// See the supported options in flags.go for further reference. +func MakeSlave(mountPoint string) error { + return ensureMountedAs(mountPoint, "slave") +} + +// MakeRSlave ensures a mounted filesystem has the RSLAVE mount option enabled. +// See the supported options in flags.go for further reference. +func MakeRSlave(mountPoint string) error { + return ensureMountedAs(mountPoint, "rslave") +} + +// MakeUnbindable ensures a mounted filesystem has the UNBINDABLE mount option +// enabled. See the supported options in flags.go for further reference. +func MakeUnbindable(mountPoint string) error { + return ensureMountedAs(mountPoint, "unbindable") +} + +// MakeRUnbindable ensures a mounted filesystem has the RUNBINDABLE mount +// option enabled. See the supported options in flags.go for further reference. +func MakeRUnbindable(mountPoint string) error { + return ensureMountedAs(mountPoint, "runbindable") +} + +func ensureMountedAs(mountPoint, options string) error { + mounted, err := Mounted(mountPoint) + if err != nil { + return err + } + + if !mounted { + if err := Mount(mountPoint, mountPoint, "none", "bind,rw"); err != nil { + return err + } + } + mounted, err = Mounted(mountPoint) + if err != nil { + return err + } + + return ForceMount("", mountPoint, "none", options) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/LICENSE.APACHE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/LICENSE.APACHE new file mode 100644 index 00000000..9e4bd4db --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/LICENSE.APACHE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2014-2015 Docker, 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. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/LICENSE.BSD b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/LICENSE.BSD new file mode 100644 index 00000000..ac74d8f0 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/LICENSE.BSD @@ -0,0 +1,27 @@ +Copyright (c) 2014-2015 The Docker & Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/README.md b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/README.md new file mode 100644 index 00000000..0d1dbb70 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/README.md @@ -0,0 +1,5 @@ +Package symlink implements EvalSymlinksInScope which is an extension of filepath.EvalSymlinks +from the [Go standard library](https://golang.org/pkg/path/filepath). + +The code from filepath.EvalSymlinks has been adapted in fs.go. +Please read the LICENSE.BSD file that governs fs.go and LICENSE.APACHE for fs_test.go. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/fs.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/fs.go new file mode 100644 index 00000000..b4bdff24 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/symlink/fs.go @@ -0,0 +1,131 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE.BSD file. + +// This code is a modified version of path/filepath/symlink.go from the Go standard library. + +package symlink + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "strings" +) + +// FollowSymlinkInScope is a wrapper around evalSymlinksInScope that returns an absolute path +func FollowSymlinkInScope(path, root string) (string, error) { + path, err := filepath.Abs(path) + if err != nil { + return "", err + } + root, err = filepath.Abs(root) + if err != nil { + return "", err + } + return evalSymlinksInScope(path, root) +} + +// evalSymlinksInScope will evaluate symlinks in `path` within a scope `root` and return +// a result guaranteed to be contained within the scope `root`, at the time of the call. +// Symlinks in `root` are not evaluated and left as-is. +// Errors encountered while attempting to evaluate symlinks in path will be returned. +// Non-existing paths are valid and do not constitute an error. +// `path` has to contain `root` as a prefix, or else an error will be returned. +// Trying to break out from `root` does not constitute an error. +// +// Example: +// If /foo/bar -> /outside, +// FollowSymlinkInScope("/foo/bar", "/foo") == "/foo/outside" instead of "/oustide" +// +// IMPORTANT: it is the caller's responsibility to call evalSymlinksInScope *after* relevant symlinks +// are created and not to create subsequently, additional symlinks that could potentially make a +// previously-safe path, unsafe. Example: if /foo/bar does not exist, evalSymlinksInScope("/foo/bar", "/foo") +// would return "/foo/bar". If one makes /foo/bar a symlink to /baz subsequently, then "/foo/bar" should +// no longer be considered safely contained in "/foo". +func evalSymlinksInScope(path, root string) (string, error) { + root = filepath.Clean(root) + if path == root { + return path, nil + } + if !strings.HasPrefix(path, root) { + return "", errors.New("evalSymlinksInScope: " + path + " is not in " + root) + } + const maxIter = 255 + originalPath := path + // given root of "/a" and path of "/a/b/../../c" we want path to be "/b/../../c" + path = path[len(root):] + if root == string(filepath.Separator) { + path = string(filepath.Separator) + path + } + if !strings.HasPrefix(path, string(filepath.Separator)) { + return "", errors.New("evalSymlinksInScope: " + path + " is not in " + root) + } + path = filepath.Clean(path) + // consume path by taking each frontmost path element, + // expanding it if it's a symlink, and appending it to b + var b bytes.Buffer + // b here will always be considered to be the "current absolute path inside + // root" when we append paths to it, we also append a slash and use + // filepath.Clean after the loop to trim the trailing slash + for n := 0; path != ""; n++ { + if n > maxIter { + return "", errors.New("evalSymlinksInScope: too many links in " + originalPath) + } + + // find next path component, p + i := strings.IndexRune(path, filepath.Separator) + var p string + if i == -1 { + p, path = path, "" + } else { + p, path = path[:i], path[i+1:] + } + + if p == "" { + continue + } + + // this takes a b.String() like "b/../" and a p like "c" and turns it + // into "/b/../c" which then gets filepath.Cleaned into "/c" and then + // root gets prepended and we Clean again (to remove any trailing slash + // if the first Clean gave us just "/") + cleanP := filepath.Clean(string(filepath.Separator) + b.String() + p) + if cleanP == string(filepath.Separator) { + // never Lstat "/" itself + b.Reset() + continue + } + fullP := filepath.Clean(root + cleanP) + + fi, err := os.Lstat(fullP) + if os.IsNotExist(err) { + // if p does not exist, accept it + b.WriteString(p) + b.WriteRune(filepath.Separator) + continue + } + if err != nil { + return "", err + } + if fi.Mode()&os.ModeSymlink == 0 { + b.WriteString(p + string(filepath.Separator)) + continue + } + + // it's a symlink, put it at the front of path + dest, err := os.Readlink(fullP) + if err != nil { + return "", err + } + if filepath.IsAbs(dest) { + b.Reset() + } + path = dest + string(filepath.Separator) + path + } + + // see note above on "fullP := ..." for why this is double-cleaned and + // what's happening here + return filepath.Clean(root + filepath.Clean(string(filepath.Separator)+b.String())), nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/tc_linux_cgo.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/tc_linux_cgo.go new file mode 100644 index 00000000..d47cf59b --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/tc_linux_cgo.go @@ -0,0 +1,48 @@ +// +build linux,cgo + +package term + +import ( + "syscall" + "unsafe" +) + +// #include +import "C" + +type Termios syscall.Termios + +// MakeRaw put the terminal connected to the given file descriptor into raw +// mode and returns the previous state of the terminal so that it can be +// restored. +func MakeRaw(fd uintptr) (*State, error) { + var oldState State + if err := tcget(fd, &oldState.termios); err != 0 { + return nil, err + } + + newState := oldState.termios + + C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) + newState.Oflag = newState.Oflag | C.OPOST + if err := tcset(fd, &newState); err != 0 { + return nil, err + } + return &oldState, nil +} + +func tcget(fd uintptr, p *Termios) syscall.Errno { + ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) + if ret != 0 { + return err.(syscall.Errno) + } + return 0 +} + +func tcset(fd uintptr, p *Termios) syscall.Errno { + ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) + if ret != 0 { + return err.(syscall.Errno) + } + return 0 +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/tc_other.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/tc_other.go new file mode 100644 index 00000000..266039ba --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/tc_other.go @@ -0,0 +1,19 @@ +// +build !windows +// +build !linux !cgo + +package term + +import ( + "syscall" + "unsafe" +) + +func tcget(fd uintptr, p *Termios) syscall.Errno { + _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(p))) + return err +} + +func tcset(fd uintptr, p *Termios) syscall.Errno { + _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(p))) + return err +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/term.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/term.go new file mode 100644 index 00000000..b945a3dc --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/term.go @@ -0,0 +1,118 @@ +// +build !windows + +package term + +import ( + "errors" + "io" + "os" + "os/signal" + "syscall" + "unsafe" +) + +var ( + ErrInvalidState = errors.New("Invalid terminal state") +) + +type State struct { + termios Termios +} + +type Winsize struct { + Height uint16 + Width uint16 + x uint16 + y uint16 +} + +func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { + return os.Stdin, os.Stdout, os.Stderr +} + +func GetFdInfo(in interface{}) (uintptr, bool) { + var inFd uintptr + var isTerminalIn bool + if file, ok := in.(*os.File); ok { + inFd = file.Fd() + isTerminalIn = IsTerminal(inFd) + } + return inFd, isTerminalIn +} + +func GetWinsize(fd uintptr) (*Winsize, error) { + ws := &Winsize{} + _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(ws))) + // Skipp errno = 0 + if err == 0 { + return ws, nil + } + return ws, err +} + +func SetWinsize(fd uintptr, ws *Winsize) error { + _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws))) + // Skipp errno = 0 + if err == 0 { + return nil + } + return err +} + +// IsTerminal returns true if the given file descriptor is a terminal. +func IsTerminal(fd uintptr) bool { + var termios Termios + return tcget(fd, &termios) == 0 +} + +// Restore restores the terminal connected to the given file descriptor to a +// previous state. +func RestoreTerminal(fd uintptr, state *State) error { + if state == nil { + return ErrInvalidState + } + if err := tcset(fd, &state.termios); err != 0 { + return err + } + return nil +} + +func SaveState(fd uintptr) (*State, error) { + var oldState State + if err := tcget(fd, &oldState.termios); err != 0 { + return nil, err + } + + return &oldState, nil +} + +func DisableEcho(fd uintptr, state *State) error { + newState := state.termios + newState.Lflag &^= syscall.ECHO + + if err := tcset(fd, &newState); err != 0 { + return err + } + handleInterrupt(fd, state) + return nil +} + +func SetRawTerminal(fd uintptr) (*State, error) { + oldState, err := MakeRaw(fd) + if err != nil { + return nil, err + } + handleInterrupt(fd, oldState) + return oldState, err +} + +func handleInterrupt(fd uintptr, state *State) { + sigchan := make(chan os.Signal, 1) + signal.Notify(sigchan, os.Interrupt) + + go func() { + _ = <-sigchan + RestoreTerminal(fd, state) + os.Exit(0) + }() +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/term_windows.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/term_windows.go new file mode 100644 index 00000000..f7fa1b3a --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/term_windows.go @@ -0,0 +1,139 @@ +// +build windows + +package term + +import ( + "io" + "os" + + "github.com/Sirupsen/logrus" + "github.com/docker/docker/pkg/term/winconsole" +) + +// State holds the console mode for the terminal. +type State struct { + mode uint32 +} + +// Winsize is used for window size. +type Winsize struct { + Height uint16 + Width uint16 + x uint16 + y uint16 +} + +func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { + switch { + case os.Getenv("ConEmuANSI") == "ON": + // The ConEmu shell emulates ANSI well by default. + return os.Stdin, os.Stdout, os.Stderr + case os.Getenv("MSYSTEM") != "": + // MSYS (mingw) does not emulate ANSI well. + return winconsole.WinConsoleStreams() + default: + return winconsole.WinConsoleStreams() + } +} + +// GetFdInfo returns file descriptor and bool indicating whether the file is a terminal. +func GetFdInfo(in interface{}) (uintptr, bool) { + return winconsole.GetHandleInfo(in) +} + +// GetWinsize retrieves the window size of the terminal connected to the passed file descriptor. +func GetWinsize(fd uintptr) (*Winsize, error) { + info, err := winconsole.GetConsoleScreenBufferInfo(fd) + if err != nil { + return nil, err + } + + // TODO(azlinux): Set the pixel width / height of the console (currently unused by any caller) + return &Winsize{ + Width: uint16(info.Window.Right - info.Window.Left + 1), + Height: uint16(info.Window.Bottom - info.Window.Top + 1), + x: 0, + y: 0}, nil +} + +// SetWinsize sets the size of the given terminal connected to the passed file descriptor. +func SetWinsize(fd uintptr, ws *Winsize) error { + // TODO(azlinux): Implement SetWinsize + logrus.Debugf("[windows] SetWinsize: WARNING -- Unsupported method invoked") + return nil +} + +// IsTerminal returns true if the given file descriptor is a terminal. +func IsTerminal(fd uintptr) bool { + return winconsole.IsConsole(fd) +} + +// RestoreTerminal restores the terminal connected to the given file descriptor to a +// previous state. +func RestoreTerminal(fd uintptr, state *State) error { + return winconsole.SetConsoleMode(fd, state.mode) +} + +// SaveState saves the state of the terminal connected to the given file descriptor. +func SaveState(fd uintptr) (*State, error) { + mode, e := winconsole.GetConsoleMode(fd) + if e != nil { + return nil, e + } + return &State{mode}, nil +} + +// DisableEcho disables echo for the terminal connected to the given file descriptor. +// -- See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx +func DisableEcho(fd uintptr, state *State) error { + mode := state.mode + mode &^= winconsole.ENABLE_ECHO_INPUT + mode |= winconsole.ENABLE_PROCESSED_INPUT | winconsole.ENABLE_LINE_INPUT + // TODO(azlinux): Core code registers a goroutine to catch os.Interrupt and reset the terminal state. + return winconsole.SetConsoleMode(fd, mode) +} + +// SetRawTerminal puts the terminal connected to the given file descriptor into raw +// mode and returns the previous state of the terminal so that it can be +// restored. +func SetRawTerminal(fd uintptr) (*State, error) { + state, err := MakeRaw(fd) + if err != nil { + return nil, err + } + // TODO(azlinux): Core code registers a goroutine to catch os.Interrupt and reset the terminal state. + return state, err +} + +// MakeRaw puts the terminal connected to the given file descriptor into raw +// mode and returns the previous state of the terminal so that it can be +// restored. +func MakeRaw(fd uintptr) (*State, error) { + state, err := SaveState(fd) + if err != nil { + return nil, err + } + + // See + // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx + // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx + mode := state.mode + + // Disable these modes + mode &^= winconsole.ENABLE_ECHO_INPUT + mode &^= winconsole.ENABLE_LINE_INPUT + mode &^= winconsole.ENABLE_MOUSE_INPUT + mode &^= winconsole.ENABLE_WINDOW_INPUT + mode &^= winconsole.ENABLE_PROCESSED_INPUT + + // Enable these modes + mode |= winconsole.ENABLE_EXTENDED_FLAGS + mode |= winconsole.ENABLE_INSERT_MODE + mode |= winconsole.ENABLE_QUICK_EDIT_MODE + + err = winconsole.SetConsoleMode(fd, mode) + if err != nil { + return nil, err + } + return state, nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_darwin.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_darwin.go new file mode 100644 index 00000000..11cd70d1 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_darwin.go @@ -0,0 +1,65 @@ +package term + +import ( + "syscall" + "unsafe" +) + +const ( + getTermios = syscall.TIOCGETA + setTermios = syscall.TIOCSETA + + IGNBRK = syscall.IGNBRK + PARMRK = syscall.PARMRK + INLCR = syscall.INLCR + IGNCR = syscall.IGNCR + ECHONL = syscall.ECHONL + CSIZE = syscall.CSIZE + ICRNL = syscall.ICRNL + ISTRIP = syscall.ISTRIP + PARENB = syscall.PARENB + ECHO = syscall.ECHO + ICANON = syscall.ICANON + ISIG = syscall.ISIG + IXON = syscall.IXON + BRKINT = syscall.BRKINT + INPCK = syscall.INPCK + OPOST = syscall.OPOST + CS8 = syscall.CS8 + IEXTEN = syscall.IEXTEN +) + +type Termios struct { + Iflag uint64 + Oflag uint64 + Cflag uint64 + Lflag uint64 + Cc [20]byte + Ispeed uint64 + Ospeed uint64 +} + +// MakeRaw put the terminal connected to the given file descriptor into raw +// mode and returns the previous state of the terminal so that it can be +// restored. +func MakeRaw(fd uintptr) (*State, error) { + var oldState State + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { + return nil, err + } + + newState := oldState.termios + newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) + newState.Oflag &^= OPOST + newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN) + newState.Cflag &^= (CSIZE | PARENB) + newState.Cflag |= CS8 + newState.Cc[syscall.VMIN] = 1 + newState.Cc[syscall.VTIME] = 0 + + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 { + return nil, err + } + + return &oldState, nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_freebsd.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_freebsd.go new file mode 100644 index 00000000..ed365957 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_freebsd.go @@ -0,0 +1,65 @@ +package term + +import ( + "syscall" + "unsafe" +) + +const ( + getTermios = syscall.TIOCGETA + setTermios = syscall.TIOCSETA + + IGNBRK = syscall.IGNBRK + PARMRK = syscall.PARMRK + INLCR = syscall.INLCR + IGNCR = syscall.IGNCR + ECHONL = syscall.ECHONL + CSIZE = syscall.CSIZE + ICRNL = syscall.ICRNL + ISTRIP = syscall.ISTRIP + PARENB = syscall.PARENB + ECHO = syscall.ECHO + ICANON = syscall.ICANON + ISIG = syscall.ISIG + IXON = syscall.IXON + BRKINT = syscall.BRKINT + INPCK = syscall.INPCK + OPOST = syscall.OPOST + CS8 = syscall.CS8 + IEXTEN = syscall.IEXTEN +) + +type Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]byte + Ispeed uint32 + Ospeed uint32 +} + +// MakeRaw put the terminal connected to the given file descriptor into raw +// mode and returns the previous state of the terminal so that it can be +// restored. +func MakeRaw(fd uintptr) (*State, error) { + var oldState State + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { + return nil, err + } + + newState := oldState.termios + newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) + newState.Oflag &^= OPOST + newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN) + newState.Cflag &^= (CSIZE | PARENB) + newState.Cflag |= CS8 + newState.Cc[syscall.VMIN] = 1 + newState.Cc[syscall.VTIME] = 0 + + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 { + return nil, err + } + + return &oldState, nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_linux.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_linux.go new file mode 100644 index 00000000..024187ff --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/termios_linux.go @@ -0,0 +1,46 @@ +// +build !cgo + +package term + +import ( + "syscall" + "unsafe" +) + +const ( + getTermios = syscall.TCGETS + setTermios = syscall.TCSETS +) + +type Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]byte + Ispeed uint32 + Ospeed uint32 +} + +// MakeRaw put the terminal connected to the given file descriptor into raw +// mode and returns the previous state of the terminal so that it can be +// restored. +func MakeRaw(fd uintptr) (*State, error) { + var oldState State + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { + return nil, err + } + + newState := oldState.termios + + newState.Iflag &^= (syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON) + newState.Oflag &^= syscall.OPOST + newState.Lflag &^= (syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN) + newState.Cflag &^= (syscall.CSIZE | syscall.PARENB) + newState.Cflag |= syscall.CS8 + + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 { + return nil, err + } + return &oldState, nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/console_windows.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/console_windows.go new file mode 100644 index 00000000..ce40a931 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/console_windows.go @@ -0,0 +1,1053 @@ +// +build windows + +package winconsole + +import ( + "bytes" + "fmt" + "io" + "os" + "strconv" + "strings" + "sync" + "syscall" + "unsafe" + + "github.com/Sirupsen/logrus" +) + +const ( + // Consts for Get/SetConsoleMode function + // -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx + ENABLE_PROCESSED_INPUT = 0x0001 + ENABLE_LINE_INPUT = 0x0002 + ENABLE_ECHO_INPUT = 0x0004 + ENABLE_WINDOW_INPUT = 0x0008 + ENABLE_MOUSE_INPUT = 0x0010 + ENABLE_INSERT_MODE = 0x0020 + ENABLE_QUICK_EDIT_MODE = 0x0040 + ENABLE_EXTENDED_FLAGS = 0x0080 + + // If parameter is a screen buffer handle, additional values + ENABLE_PROCESSED_OUTPUT = 0x0001 + ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 + + //http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes + FOREGROUND_BLUE = 1 + FOREGROUND_GREEN = 2 + FOREGROUND_RED = 4 + FOREGROUND_INTENSITY = 8 + FOREGROUND_MASK_SET = 0x000F + FOREGROUND_MASK_UNSET = 0xFFF0 + + BACKGROUND_BLUE = 16 + BACKGROUND_GREEN = 32 + BACKGROUND_RED = 64 + BACKGROUND_INTENSITY = 128 + BACKGROUND_MASK_SET = 0x00F0 + BACKGROUND_MASK_UNSET = 0xFF0F + + COMMON_LVB_REVERSE_VIDEO = 0x4000 + COMMON_LVB_UNDERSCORE = 0x8000 + + // http://man7.org/linux/man-pages/man4/console_codes.4.html + // ECMA-48 Set Graphics Rendition + ANSI_ATTR_RESET = 0 + ANSI_ATTR_BOLD = 1 + ANSI_ATTR_DIM = 2 + ANSI_ATTR_UNDERLINE = 4 + ANSI_ATTR_BLINK = 5 + ANSI_ATTR_REVERSE = 7 + ANSI_ATTR_INVISIBLE = 8 + + ANSI_ATTR_UNDERLINE_OFF = 24 + ANSI_ATTR_BLINK_OFF = 25 + ANSI_ATTR_REVERSE_OFF = 27 + ANSI_ATTR_INVISIBLE_OFF = 8 + + ANSI_FOREGROUND_BLACK = 30 + ANSI_FOREGROUND_RED = 31 + ANSI_FOREGROUND_GREEN = 32 + ANSI_FOREGROUND_YELLOW = 33 + ANSI_FOREGROUND_BLUE = 34 + ANSI_FOREGROUND_MAGENTA = 35 + ANSI_FOREGROUND_CYAN = 36 + ANSI_FOREGROUND_WHITE = 37 + ANSI_FOREGROUND_DEFAULT = 39 + + ANSI_BACKGROUND_BLACK = 40 + ANSI_BACKGROUND_RED = 41 + ANSI_BACKGROUND_GREEN = 42 + ANSI_BACKGROUND_YELLOW = 43 + ANSI_BACKGROUND_BLUE = 44 + ANSI_BACKGROUND_MAGENTA = 45 + ANSI_BACKGROUND_CYAN = 46 + ANSI_BACKGROUND_WHITE = 47 + ANSI_BACKGROUND_DEFAULT = 49 + + ANSI_MAX_CMD_LENGTH = 256 + + MAX_INPUT_EVENTS = 128 + MAX_INPUT_BUFFER = 1024 + DEFAULT_WIDTH = 80 + DEFAULT_HEIGHT = 24 +) + +// http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx +const ( + VK_PRIOR = 0x21 // PAGE UP key + VK_NEXT = 0x22 // PAGE DOWN key + VK_END = 0x23 // END key + VK_HOME = 0x24 // HOME key + VK_LEFT = 0x25 // LEFT ARROW key + VK_UP = 0x26 // UP ARROW key + VK_RIGHT = 0x27 // RIGHT ARROW key + VK_DOWN = 0x28 // DOWN ARROW key + VK_SELECT = 0x29 // SELECT key + VK_PRINT = 0x2A // PRINT key + VK_EXECUTE = 0x2B // EXECUTE key + VK_SNAPSHOT = 0x2C // PRINT SCREEN key + VK_INSERT = 0x2D // INS key + VK_DELETE = 0x2E // DEL key + VK_HELP = 0x2F // HELP key + VK_F1 = 0x70 // F1 key + VK_F2 = 0x71 // F2 key + VK_F3 = 0x72 // F3 key + VK_F4 = 0x73 // F4 key + VK_F5 = 0x74 // F5 key + VK_F6 = 0x75 // F6 key + VK_F7 = 0x76 // F7 key + VK_F8 = 0x77 // F8 key + VK_F9 = 0x78 // F9 key + VK_F10 = 0x79 // F10 key + VK_F11 = 0x7A // F11 key + VK_F12 = 0x7B // F12 key +) + +var kernel32DLL = syscall.NewLazyDLL("kernel32.dll") + +var ( + setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode") + getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo") + setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition") + setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") + fillConsoleOutputCharacterProc = kernel32DLL.NewProc("FillConsoleOutputCharacterW") + writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW") + readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW") + getNumberOfConsoleInputEventsProc = kernel32DLL.NewProc("GetNumberOfConsoleInputEvents") + getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo") + setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo") + setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo") + setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize") +) + +// types for calling various windows API +// see http://msdn.microsoft.com/en-us/library/windows/desktop/ms682093(v=vs.85).aspx +type ( + SHORT int16 + BOOL int32 + WORD uint16 + WCHAR uint16 + DWORD uint32 + + SMALL_RECT struct { + Left SHORT + Top SHORT + Right SHORT + Bottom SHORT + } + + COORD struct { + X SHORT + Y SHORT + } + + CONSOLE_SCREEN_BUFFER_INFO struct { + Size COORD + CursorPosition COORD + Attributes WORD + Window SMALL_RECT + MaximumWindowSize COORD + } + + CONSOLE_CURSOR_INFO struct { + Size DWORD + Visible BOOL + } + + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms684166(v=vs.85).aspx + KEY_EVENT_RECORD struct { + KeyDown BOOL + RepeatCount WORD + VirtualKeyCode WORD + VirtualScanCode WORD + UnicodeChar WCHAR + ControlKeyState DWORD + } + + INPUT_RECORD struct { + EventType WORD + KeyEvent KEY_EVENT_RECORD + } + + CHAR_INFO struct { + UnicodeChar WCHAR + Attributes WORD + } +) + +// TODO(azlinux): Basic type clean-up +// -- Convert all uses of uintptr to syscall.Handle to be consistent with Windows syscall +// -- Convert, as appropriate, types to use defined Windows types (e.g., DWORD instead of uint32) + +// Implements the TerminalEmulator interface +type WindowsTerminal struct { + outMutex sync.Mutex + inMutex sync.Mutex + inputBuffer []byte + inputSize int + inputEvents []INPUT_RECORD + screenBufferInfo *CONSOLE_SCREEN_BUFFER_INFO + inputEscapeSequence []byte +} + +func getStdHandle(stdhandle int) uintptr { + handle, err := syscall.GetStdHandle(stdhandle) + if err != nil { + panic(fmt.Errorf("could not get standard io handle %d", stdhandle)) + } + return uintptr(handle) +} + +func WinConsoleStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { + handler := &WindowsTerminal{ + inputBuffer: make([]byte, MAX_INPUT_BUFFER), + inputEscapeSequence: []byte(KEY_ESC_CSI), + inputEvents: make([]INPUT_RECORD, MAX_INPUT_EVENTS), + } + + if IsConsole(os.Stdin.Fd()) { + stdIn = &terminalReader{ + wrappedReader: os.Stdin, + emulator: handler, + command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), + fd: getStdHandle(syscall.STD_INPUT_HANDLE), + } + } else { + stdIn = os.Stdin + } + + if IsConsole(os.Stdout.Fd()) { + stdoutHandle := getStdHandle(syscall.STD_OUTPUT_HANDLE) + + // Save current screen buffer info + screenBufferInfo, err := GetConsoleScreenBufferInfo(stdoutHandle) + if err != nil { + // If GetConsoleScreenBufferInfo returns a nil error, it usually means that stdout is not a TTY. + // However, this is in the branch where stdout is a TTY, hence the panic. + panic("could not get console screen buffer info") + } + handler.screenBufferInfo = screenBufferInfo + + buffer = make([]CHAR_INFO, screenBufferInfo.MaximumWindowSize.X*screenBufferInfo.MaximumWindowSize.Y) + + stdOut = &terminalWriter{ + wrappedWriter: os.Stdout, + emulator: handler, + command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), + fd: stdoutHandle, + } + } else { + stdOut = os.Stdout + } + + if IsConsole(os.Stderr.Fd()) { + stdErr = &terminalWriter{ + wrappedWriter: os.Stderr, + emulator: handler, + command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), + fd: getStdHandle(syscall.STD_ERROR_HANDLE), + } + } else { + stdErr = os.Stderr + } + + return stdIn, stdOut, stdErr +} + +// GetHandleInfo returns file descriptor and bool indicating whether the file is a console. +func GetHandleInfo(in interface{}) (uintptr, bool) { + var inFd uintptr + var isTerminalIn bool + + switch t := in.(type) { + case *terminalReader: + in = t.wrappedReader + case *terminalWriter: + in = t.wrappedWriter + } + + if file, ok := in.(*os.File); ok { + inFd = file.Fd() + isTerminalIn = IsConsole(inFd) + } + return inFd, isTerminalIn +} + +func getError(r1, r2 uintptr, lastErr error) error { + // If the function fails, the return value is zero. + if r1 == 0 { + if lastErr != nil { + return lastErr + } + return syscall.EINVAL + } + return nil +} + +// GetConsoleMode gets the console mode for given file descriptor +// http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx +func GetConsoleMode(handle uintptr) (uint32, error) { + var mode uint32 + err := syscall.GetConsoleMode(syscall.Handle(handle), &mode) + return mode, err +} + +// SetConsoleMode sets the console mode for given file descriptor +// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx +func SetConsoleMode(handle uintptr, mode uint32) error { + return getError(setConsoleModeProc.Call(handle, uintptr(mode), 0)) +} + +// SetCursorVisible sets the cursor visbility +// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx +func SetCursorVisible(handle uintptr, isVisible BOOL) (bool, error) { + var cursorInfo *CONSOLE_CURSOR_INFO = &CONSOLE_CURSOR_INFO{} + if err := getError(getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0)); err != nil { + return false, err + } + cursorInfo.Visible = isVisible + if err := getError(setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0)); err != nil { + return false, err + } + return true, nil +} + +// SetWindowSize sets the size of the console window. +func SetWindowSize(handle uintptr, width, height, max SHORT) (bool, error) { + window := SMALL_RECT{Left: 0, Top: 0, Right: width - 1, Bottom: height - 1} + coord := COORD{X: width - 1, Y: max} + if err := getError(setConsoleWindowInfoProc.Call(handle, uintptr(1), uintptr(unsafe.Pointer(&window)))); err != nil { + return false, err + } + if err := getError(setConsoleScreenBufferSizeProc.Call(handle, marshal(coord))); err != nil { + return false, err + } + return true, nil +} + +// GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer. +// http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx +func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) { + var info CONSOLE_SCREEN_BUFFER_INFO + if err := getError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)); err != nil { + return nil, err + } + return &info, nil +} + +// setConsoleTextAttribute sets the attributes of characters written to the +// console screen buffer by the WriteFile or WriteConsole function, +// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx +func setConsoleTextAttribute(handle uintptr, attribute WORD) error { + return getError(setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0)) +} + +func writeConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) (bool, error) { + if err := getError(writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), marshal(bufferSize), marshal(bufferCoord), uintptr(unsafe.Pointer(writeRegion)))); err != nil { + return false, err + } + return true, nil +} + +// http://msdn.microsoft.com/en-us/library/windows/desktop/ms682663(v=vs.85).aspx +func fillConsoleOutputCharacter(handle uintptr, fillChar byte, length uint32, writeCord COORD) (bool, error) { + out := int64(0) + if err := getError(fillConsoleOutputCharacterProc.Call(handle, uintptr(fillChar), uintptr(length), marshal(writeCord), uintptr(unsafe.Pointer(&out)))); err != nil { + return false, err + } + return true, nil +} + +// Gets the number of space characters to write for "clearing" the section of terminal +func getNumberOfChars(fromCoord COORD, toCoord COORD, screenSize COORD) uint32 { + // must be valid cursor position + if fromCoord.X < 0 || fromCoord.Y < 0 || toCoord.X < 0 || toCoord.Y < 0 { + return 0 + } + if fromCoord.X >= screenSize.X || fromCoord.Y >= screenSize.Y || toCoord.X >= screenSize.X || toCoord.Y >= screenSize.Y { + return 0 + } + // can't be backwards + if fromCoord.Y > toCoord.Y { + return 0 + } + // same line + if fromCoord.Y == toCoord.Y { + return uint32(toCoord.X-fromCoord.X) + 1 + } + // spans more than one line + if fromCoord.Y < toCoord.Y { + // from start till end of line for first line + from start of line till end + retValue := uint32(screenSize.X-fromCoord.X) + uint32(toCoord.X) + 1 + // don't count first and last line + linesBetween := toCoord.Y - fromCoord.Y - 1 + if linesBetween > 0 { + retValue = retValue + uint32(linesBetween*screenSize.X) + } + return retValue + } + return 0 +} + +var buffer []CHAR_INFO + +func clearDisplayRect(handle uintptr, attributes WORD, fromCoord COORD, toCoord COORD) (uint32, error) { + var writeRegion SMALL_RECT + writeRegion.Left = fromCoord.X + writeRegion.Top = fromCoord.Y + writeRegion.Right = toCoord.X + writeRegion.Bottom = toCoord.Y + + // allocate and initialize buffer + width := toCoord.X - fromCoord.X + 1 + height := toCoord.Y - fromCoord.Y + 1 + size := uint32(width) * uint32(height) + if size > 0 { + buffer := make([]CHAR_INFO, size) + for i := range buffer { + buffer[i] = CHAR_INFO{WCHAR(' '), attributes} + } + + // Write to buffer + r, err := writeConsoleOutput(handle, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, &writeRegion) + if !r { + if err != nil { + return 0, err + } + return 0, syscall.EINVAL + } + } + return uint32(size), nil +} + +func clearDisplayRange(handle uintptr, attributes WORD, fromCoord COORD, toCoord COORD) (uint32, error) { + nw := uint32(0) + // start and end on same line + if fromCoord.Y == toCoord.Y { + return clearDisplayRect(handle, attributes, fromCoord, toCoord) + } + // TODO(azlinux): if full screen, optimize + + // spans more than one line + if fromCoord.Y < toCoord.Y { + // from start position till end of line for first line + n, err := clearDisplayRect(handle, attributes, fromCoord, COORD{X: toCoord.X, Y: fromCoord.Y}) + if err != nil { + return nw, err + } + nw += n + // lines between + linesBetween := toCoord.Y - fromCoord.Y - 1 + if linesBetween > 0 { + n, err = clearDisplayRect(handle, attributes, COORD{X: 0, Y: fromCoord.Y + 1}, COORD{X: toCoord.X, Y: toCoord.Y - 1}) + if err != nil { + return nw, err + } + nw += n + } + // lines at end + n, err = clearDisplayRect(handle, attributes, COORD{X: 0, Y: toCoord.Y}, toCoord) + if err != nil { + return nw, err + } + nw += n + } + return nw, nil +} + +// setConsoleCursorPosition sets the console cursor position +// Note The X and Y are zero based +// If relative is true then the new position is relative to current one +func setConsoleCursorPosition(handle uintptr, isRelative bool, column int16, line int16) error { + screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) + if err != nil { + return err + } + var position COORD + if isRelative { + position.X = screenBufferInfo.CursorPosition.X + SHORT(column) + position.Y = screenBufferInfo.CursorPosition.Y + SHORT(line) + } else { + position.X = SHORT(column) + position.Y = SHORT(line) + } + return getError(setConsoleCursorPositionProc.Call(handle, marshal(position), 0)) +} + +// http://msdn.microsoft.com/en-us/library/windows/desktop/ms683207(v=vs.85).aspx +func getNumberOfConsoleInputEvents(handle uintptr) (uint16, error) { + var n DWORD + if err := getError(getNumberOfConsoleInputEventsProc.Call(handle, uintptr(unsafe.Pointer(&n)))); err != nil { + return 0, err + } + return uint16(n), nil +} + +//http://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx +func readConsoleInputKey(handle uintptr, inputBuffer []INPUT_RECORD) (int, error) { + var nr DWORD + if err := getError(readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&inputBuffer[0])), uintptr(len(inputBuffer)), uintptr(unsafe.Pointer(&nr)))); err != nil { + return 0, err + } + return int(nr), nil +} + +func getWindowsTextAttributeForAnsiValue(originalFlag WORD, defaultValue WORD, ansiValue int16) (WORD, error) { + flag := WORD(originalFlag) + if flag == 0 { + flag = defaultValue + } + switch ansiValue { + case ANSI_ATTR_RESET: + flag &^= COMMON_LVB_UNDERSCORE + flag &^= BACKGROUND_INTENSITY + flag = flag | FOREGROUND_INTENSITY + case ANSI_ATTR_INVISIBLE: + // TODO: how do you reset reverse? + case ANSI_ATTR_UNDERLINE: + flag = flag | COMMON_LVB_UNDERSCORE + case ANSI_ATTR_BLINK: + // seems like background intenisty is blink + flag = flag | BACKGROUND_INTENSITY + case ANSI_ATTR_UNDERLINE_OFF: + flag &^= COMMON_LVB_UNDERSCORE + case ANSI_ATTR_BLINK_OFF: + // seems like background intenisty is blink + flag &^= BACKGROUND_INTENSITY + case ANSI_ATTR_BOLD: + flag = flag | FOREGROUND_INTENSITY + case ANSI_ATTR_DIM: + flag &^= FOREGROUND_INTENSITY + case ANSI_ATTR_REVERSE, ANSI_ATTR_REVERSE_OFF: + // swap forground and background bits + foreground := flag & FOREGROUND_MASK_SET + background := flag & BACKGROUND_MASK_SET + flag = (flag & BACKGROUND_MASK_UNSET & FOREGROUND_MASK_UNSET) | (foreground << 4) | (background >> 4) + + // FOREGROUND + case ANSI_FOREGROUND_DEFAULT: + flag = (flag & FOREGROUND_MASK_UNSET) | (defaultValue & FOREGROUND_MASK_SET) + case ANSI_FOREGROUND_BLACK: + flag = flag ^ (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE) + case ANSI_FOREGROUND_RED: + flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED + case ANSI_FOREGROUND_GREEN: + flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_GREEN + case ANSI_FOREGROUND_YELLOW: + flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_GREEN + case ANSI_FOREGROUND_BLUE: + flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_BLUE + case ANSI_FOREGROUND_MAGENTA: + flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_BLUE + case ANSI_FOREGROUND_CYAN: + flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_GREEN | FOREGROUND_BLUE + case ANSI_FOREGROUND_WHITE: + flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + + // Background + case ANSI_BACKGROUND_DEFAULT: + // Black with no intensity + flag = (flag & BACKGROUND_MASK_UNSET) | (defaultValue & BACKGROUND_MASK_SET) + case ANSI_BACKGROUND_BLACK: + flag = (flag & BACKGROUND_MASK_UNSET) + case ANSI_BACKGROUND_RED: + flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED + case ANSI_BACKGROUND_GREEN: + flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_GREEN + case ANSI_BACKGROUND_YELLOW: + flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_GREEN + case ANSI_BACKGROUND_BLUE: + flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_BLUE + case ANSI_BACKGROUND_MAGENTA: + flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_BLUE + case ANSI_BACKGROUND_CYAN: + flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_GREEN | BACKGROUND_BLUE + case ANSI_BACKGROUND_WHITE: + flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE + } + return flag, nil +} + +// HandleOutputCommand interpretes the Ansi commands and then makes appropriate Win32 calls +func (term *WindowsTerminal) HandleOutputCommand(handle uintptr, command []byte) (n int, err error) { + // always consider all the bytes in command, processed + n = len(command) + + parsedCommand := parseAnsiCommand(command) + logrus.Debugf("[windows] HandleOutputCommand: %v", parsedCommand) + + // console settings changes need to happen in atomic way + term.outMutex.Lock() + defer term.outMutex.Unlock() + + switch parsedCommand.Command { + case "m": + // [Value;...;Valuem + // Set Graphics Mode: + // Calls the graphics functions specified by the following values. + // These specified functions remain active until the next occurrence of this escape sequence. + // Graphics mode changes the colors and attributes of text (such as bold and underline) displayed on the screen. + screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) + if err != nil { + return n, err + } + flag := screenBufferInfo.Attributes + for _, e := range parsedCommand.Parameters { + value, _ := strconv.ParseInt(e, 10, 16) // base 10, 16 bit + if value == ANSI_ATTR_RESET { + flag = term.screenBufferInfo.Attributes // reset + } else { + flag, err = getWindowsTextAttributeForAnsiValue(flag, term.screenBufferInfo.Attributes, int16(value)) + if err != nil { + return n, err + } + } + } + if err := setConsoleTextAttribute(handle, flag); err != nil { + return n, err + } + case "H", "f": + // [line;columnH + // [line;columnf + // Moves the cursor to the specified position (coordinates). + // If you do not specify a position, the cursor moves to the home position at the upper-left corner of the screen (line 0, column 0). + screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) + if err != nil { + return n, err + } + line, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) + if err != nil { + return n, err + } + if line > int16(screenBufferInfo.Window.Bottom) { + line = int16(screenBufferInfo.Window.Bottom) + 1 + } + column, err := parseInt16OrDefault(parsedCommand.getParam(1), 1) + if err != nil { + return n, err + } + if column > int16(screenBufferInfo.Window.Right) { + column = int16(screenBufferInfo.Window.Right) + 1 + } + // The numbers are not 0 based, but 1 based + logrus.Debugf("[windows] HandleOutputCommmand: Moving cursor to (%v,%v)", column-1, line-1) + if err := setConsoleCursorPosition(handle, false, column-1, line-1); err != nil { + return n, err + } + + case "A": + // [valueA + // Moves the cursor up by the specified number of lines without changing columns. + // If the cursor is already on the top line, ignores this sequence. + value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) + if err != nil { + return len(command), err + } + if err := setConsoleCursorPosition(handle, true, 0, -value); err != nil { + return n, err + } + case "B": + // [valueB + // Moves the cursor down by the specified number of lines without changing columns. + // If the cursor is already on the bottom line, ignores this sequence. + value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) + if err != nil { + return n, err + } + if err := setConsoleCursorPosition(handle, true, 0, value); err != nil { + return n, err + } + case "C": + // [valueC + // Moves the cursor forward by the specified number of columns without changing lines. + // If the cursor is already in the rightmost column, ignores this sequence. + value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) + if err != nil { + return n, err + } + if err := setConsoleCursorPosition(handle, true, value, 0); err != nil { + return n, err + } + case "D": + // [valueD + // Moves the cursor back by the specified number of columns without changing lines. + // If the cursor is already in the leftmost column, ignores this sequence. + value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) + if err != nil { + return n, err + } + if err := setConsoleCursorPosition(handle, true, -value, 0); err != nil { + return n, err + } + case "J": + // [J Erases from the cursor to the end of the screen, including the cursor position. + // [1J Erases from the beginning of the screen to the cursor, including the cursor position. + // [2J Erases the complete display. The cursor does not move. + // Clears the screen and moves the cursor to the home position (line 0, column 0). + value, err := parseInt16OrDefault(parsedCommand.getParam(0), 0) + if err != nil { + return n, err + } + var start COORD + var cursor COORD + var end COORD + screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) + if err != nil { + return n, err + } + switch value { + case 0: + start = screenBufferInfo.CursorPosition + // end of the buffer + end.X = screenBufferInfo.Size.X - 1 + end.Y = screenBufferInfo.Size.Y - 1 + // cursor + cursor = screenBufferInfo.CursorPosition + case 1: + + // start of the screen + start.X = 0 + start.Y = 0 + // end of the screen + end = screenBufferInfo.CursorPosition + // cursor + cursor = screenBufferInfo.CursorPosition + case 2: + // start of the screen + start.X = 0 + start.Y = 0 + // end of the buffer + end.X = screenBufferInfo.Size.X - 1 + end.Y = screenBufferInfo.Size.Y - 1 + // cursor + cursor.X = 0 + cursor.Y = 0 + } + if _, err := clearDisplayRange(uintptr(handle), term.screenBufferInfo.Attributes, start, end); err != nil { + return n, err + } + // remember the the cursor position is 1 based + if err := setConsoleCursorPosition(handle, false, int16(cursor.X), int16(cursor.Y)); err != nil { + return n, err + } + + case "K": + // [K + // Clears all characters from the cursor position to the end of the line (including the character at the cursor position). + // [K Erases from the cursor to the end of the line, including the cursor position. + // [1K Erases from the beginning of the line to the cursor, including the cursor position. + // [2K Erases the complete line. + value, err := parseInt16OrDefault(parsedCommand.getParam(0), 0) + var start COORD + var cursor COORD + var end COORD + screenBufferInfo, err := GetConsoleScreenBufferInfo(uintptr(handle)) + if err != nil { + return n, err + } + switch value { + case 0: + // start is where cursor is + start = screenBufferInfo.CursorPosition + // end of line + end.X = screenBufferInfo.Size.X - 1 + end.Y = screenBufferInfo.CursorPosition.Y + // cursor remains the same + cursor = screenBufferInfo.CursorPosition + + case 1: + // beginning of line + start.X = 0 + start.Y = screenBufferInfo.CursorPosition.Y + // until cursor + end = screenBufferInfo.CursorPosition + // cursor remains the same + cursor = screenBufferInfo.CursorPosition + case 2: + // start of the line + start.X = 0 + start.Y = screenBufferInfo.CursorPosition.Y - 1 + // end of the line + end.X = screenBufferInfo.Size.X - 1 + end.Y = screenBufferInfo.CursorPosition.Y - 1 + // cursor + cursor.X = 0 + cursor.Y = screenBufferInfo.CursorPosition.Y - 1 + } + if _, err := clearDisplayRange(uintptr(handle), term.screenBufferInfo.Attributes, start, end); err != nil { + return n, err + } + // remember the the cursor position is 1 based + if err := setConsoleCursorPosition(uintptr(handle), false, int16(cursor.X), int16(cursor.Y)); err != nil { + return n, err + } + + case "l": + for _, value := range parsedCommand.Parameters { + switch value { + case "?25", "25": + SetCursorVisible(uintptr(handle), BOOL(0)) + case "?1049", "1049": + // TODO (azlinux): Restore terminal + case "?1", "1": + // If the DECCKM function is reset, then the arrow keys send ANSI cursor sequences to the host. + term.inputEscapeSequence = []byte(KEY_ESC_CSI) + } + } + case "h": + for _, value := range parsedCommand.Parameters { + switch value { + case "?25", "25": + SetCursorVisible(uintptr(handle), BOOL(1)) + case "?1049", "1049": + // TODO (azlinux): Save terminal + case "?1", "1": + // If the DECCKM function is set, then the arrow keys send application sequences to the host. + // DECCKM (default off): When set, the cursor keys send an ESC O prefix, rather than ESC [. + term.inputEscapeSequence = []byte(KEY_ESC_O) + } + } + + case "]": + /* + TODO (azlinux): + Linux Console Private CSI Sequences + + The following sequences are neither ECMA-48 nor native VT102. They are + native to the Linux console driver. Colors are in SGR parameters: 0 = + black, 1 = red, 2 = green, 3 = brown, 4 = blue, 5 = magenta, 6 = cyan, + 7 = white. + + ESC [ 1 ; n ] Set color n as the underline color + ESC [ 2 ; n ] Set color n as the dim color + ESC [ 8 ] Make the current color pair the default attributes. + ESC [ 9 ; n ] Set screen blank timeout to n minutes. + ESC [ 10 ; n ] Set bell frequency in Hz. + ESC [ 11 ; n ] Set bell duration in msec. + ESC [ 12 ; n ] Bring specified console to the front. + ESC [ 13 ] Unblank the screen. + ESC [ 14 ; n ] Set the VESA powerdown interval in minutes. + + */ + } + return n, nil +} + +// WriteChars writes the bytes to given writer. +func (term *WindowsTerminal) WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) { + if len(p) == 0 { + return 0, nil + } + return w.Write(p) +} + +const ( + CAPSLOCK_ON = 0x0080 //The CAPS LOCK light is on. + ENHANCED_KEY = 0x0100 //The key is enhanced. + LEFT_ALT_PRESSED = 0x0002 //The left ALT key is pressed. + LEFT_CTRL_PRESSED = 0x0008 //The left CTRL key is pressed. + NUMLOCK_ON = 0x0020 //The NUM LOCK light is on. + RIGHT_ALT_PRESSED = 0x0001 //The right ALT key is pressed. + RIGHT_CTRL_PRESSED = 0x0004 //The right CTRL key is pressed. + SCROLLLOCK_ON = 0x0040 //The SCROLL LOCK light is on. + SHIFT_PRESSED = 0x0010 // The SHIFT key is pressed. +) + +const ( + KEY_CONTROL_PARAM_2 = ";2" + KEY_CONTROL_PARAM_3 = ";3" + KEY_CONTROL_PARAM_4 = ";4" + KEY_CONTROL_PARAM_5 = ";5" + KEY_CONTROL_PARAM_6 = ";6" + KEY_CONTROL_PARAM_7 = ";7" + KEY_CONTROL_PARAM_8 = ";8" + KEY_ESC_CSI = "\x1B[" + KEY_ESC_N = "\x1BN" + KEY_ESC_O = "\x1BO" +) + +var keyMapPrefix = map[WORD]string{ + VK_UP: "\x1B[%sA", + VK_DOWN: "\x1B[%sB", + VK_RIGHT: "\x1B[%sC", + VK_LEFT: "\x1B[%sD", + VK_HOME: "\x1B[1%s~", // showkey shows ^[[1 + VK_END: "\x1B[4%s~", // showkey shows ^[[4 + VK_INSERT: "\x1B[2%s~", + VK_DELETE: "\x1B[3%s~", + VK_PRIOR: "\x1B[5%s~", + VK_NEXT: "\x1B[6%s~", + VK_F1: "", + VK_F2: "", + VK_F3: "\x1B[13%s~", + VK_F4: "\x1B[14%s~", + VK_F5: "\x1B[15%s~", + VK_F6: "\x1B[17%s~", + VK_F7: "\x1B[18%s~", + VK_F8: "\x1B[19%s~", + VK_F9: "\x1B[20%s~", + VK_F10: "\x1B[21%s~", + VK_F11: "\x1B[23%s~", + VK_F12: "\x1B[24%s~", +} + +var arrowKeyMapPrefix = map[WORD]string{ + VK_UP: "%s%sA", + VK_DOWN: "%s%sB", + VK_RIGHT: "%s%sC", + VK_LEFT: "%s%sD", +} + +func getControlStateParameter(shift, alt, control, meta bool) string { + if shift && alt && control { + return KEY_CONTROL_PARAM_8 + } + if alt && control { + return KEY_CONTROL_PARAM_7 + } + if shift && control { + return KEY_CONTROL_PARAM_6 + } + if control { + return KEY_CONTROL_PARAM_5 + } + if shift && alt { + return KEY_CONTROL_PARAM_4 + } + if alt { + return KEY_CONTROL_PARAM_3 + } + if shift { + return KEY_CONTROL_PARAM_2 + } + return "" +} + +func getControlKeys(controlState DWORD) (shift, alt, control bool) { + shift = 0 != (controlState & SHIFT_PRESSED) + alt = 0 != (controlState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) + control = 0 != (controlState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) + return shift, alt, control +} + +func charSequenceForKeys(key WORD, controlState DWORD, escapeSequence []byte) string { + i, ok := arrowKeyMapPrefix[key] + if ok { + shift, alt, control := getControlKeys(controlState) + modifier := getControlStateParameter(shift, alt, control, false) + return fmt.Sprintf(i, escapeSequence, modifier) + } + + i, ok = keyMapPrefix[key] + if ok { + shift, alt, control := getControlKeys(controlState) + modifier := getControlStateParameter(shift, alt, control, false) + return fmt.Sprintf(i, modifier) + } + + return "" +} + +// mapKeystokeToTerminalString maps the given input event record to string +func mapKeystokeToTerminalString(keyEvent *KEY_EVENT_RECORD, escapeSequence []byte) string { + _, alt, control := getControlKeys(keyEvent.ControlKeyState) + if keyEvent.UnicodeChar == 0 { + return charSequenceForKeys(keyEvent.VirtualKeyCode, keyEvent.ControlKeyState, escapeSequence) + } + if control { + // TODO(azlinux): Implement following control sequences + // -D Signals the end of input from the keyboard; also exits current shell. + // -H Deletes the first character to the left of the cursor. Also called the ERASE key. + // -Q Restarts printing after it has been stopped with -s. + // -S Suspends printing on the screen (does not stop the program). + // -U Deletes all characters on the current line. Also called the KILL key. + // -E Quits current command and creates a core + + } + // +Key generates ESC N Key + if !control && alt { + return KEY_ESC_N + strings.ToLower(string(keyEvent.UnicodeChar)) + } + return string(keyEvent.UnicodeChar) +} + +// getAvailableInputEvents polls the console for availble events +// The function does not return until at least one input record has been read. +func getAvailableInputEvents(handle uintptr, inputEvents []INPUT_RECORD) (n int, err error) { + // TODO(azlinux): Why is there a for loop? Seems to me, that `n` cannot be negative. - tibor + for { + // Read number of console events available + n, err = readConsoleInputKey(handle, inputEvents) + if err != nil || n >= 0 { + return n, err + } + } +} + +// getTranslatedKeyCodes converts the input events into the string of characters +// The ansi escape sequence are used to map key strokes to the strings +func getTranslatedKeyCodes(inputEvents []INPUT_RECORD, escapeSequence []byte) string { + var buf bytes.Buffer + for i := 0; i < len(inputEvents); i++ { + input := inputEvents[i] + if input.EventType == KEY_EVENT && input.KeyEvent.KeyDown != 0 { + keyString := mapKeystokeToTerminalString(&input.KeyEvent, escapeSequence) + buf.WriteString(keyString) + } + } + return buf.String() +} + +// ReadChars reads the characters from the given reader +func (term *WindowsTerminal) ReadChars(fd uintptr, r io.Reader, p []byte) (n int, err error) { + for term.inputSize == 0 { + nr, err := getAvailableInputEvents(fd, term.inputEvents) + if nr == 0 && nil != err { + return n, err + } + if nr > 0 { + keyCodes := getTranslatedKeyCodes(term.inputEvents[:nr], term.inputEscapeSequence) + term.inputSize = copy(term.inputBuffer, keyCodes) + } + } + n = copy(p, term.inputBuffer[:term.inputSize]) + term.inputSize -= n + return n, nil +} + +// HandleInputSequence interprets the input sequence command +func (term *WindowsTerminal) HandleInputSequence(fd uintptr, command []byte) (n int, err error) { + return 0, nil +} + +func marshal(c COORD) uintptr { + return uintptr(*((*DWORD)(unsafe.Pointer(&c)))) +} + +// IsConsole returns true if the given file descriptor is a terminal. +// -- The code assumes that GetConsoleMode will return an error for file descriptors that are not a console. +func IsConsole(fd uintptr) bool { + _, e := GetConsoleMode(fd) + return e == nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/term_emulator.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/term_emulator.go new file mode 100644 index 00000000..2d5edc03 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/term_emulator.go @@ -0,0 +1,234 @@ +package winconsole + +import ( + "fmt" + "io" + "strconv" + "strings" +) + +// http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html +const ( + ANSI_ESCAPE_PRIMARY = 0x1B + ANSI_ESCAPE_SECONDARY = 0x5B + ANSI_COMMAND_FIRST = 0x40 + ANSI_COMMAND_LAST = 0x7E + ANSI_PARAMETER_SEP = ";" + ANSI_CMD_G0 = '(' + ANSI_CMD_G1 = ')' + ANSI_CMD_G2 = '*' + ANSI_CMD_G3 = '+' + ANSI_CMD_DECPNM = '>' + ANSI_CMD_DECPAM = '=' + ANSI_CMD_OSC = ']' + ANSI_CMD_STR_TERM = '\\' + ANSI_BEL = 0x07 + KEY_EVENT = 1 +) + +// Interface that implements terminal handling +type terminalEmulator interface { + HandleOutputCommand(fd uintptr, command []byte) (n int, err error) + HandleInputSequence(fd uintptr, command []byte) (n int, err error) + WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) + ReadChars(fd uintptr, w io.Reader, p []byte) (n int, err error) +} + +type terminalWriter struct { + wrappedWriter io.Writer + emulator terminalEmulator + command []byte + inSequence bool + fd uintptr +} + +type terminalReader struct { + wrappedReader io.ReadCloser + emulator terminalEmulator + command []byte + inSequence bool + fd uintptr +} + +// http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html +func isAnsiCommandChar(b byte) bool { + switch { + case ANSI_COMMAND_FIRST <= b && b <= ANSI_COMMAND_LAST && b != ANSI_ESCAPE_SECONDARY: + return true + case b == ANSI_CMD_G1 || b == ANSI_CMD_OSC || b == ANSI_CMD_DECPAM || b == ANSI_CMD_DECPNM: + // non-CSI escape sequence terminator + return true + case b == ANSI_CMD_STR_TERM || b == ANSI_BEL: + // String escape sequence terminator + return true + } + return false +} + +func isCharacterSelectionCmdChar(b byte) bool { + return (b == ANSI_CMD_G0 || b == ANSI_CMD_G1 || b == ANSI_CMD_G2 || b == ANSI_CMD_G3) +} + +func isXtermOscSequence(command []byte, current byte) bool { + return (len(command) >= 2 && command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_CMD_OSC && current != ANSI_BEL) +} + +// Write writes len(p) bytes from p to the underlying data stream. +// http://golang.org/pkg/io/#Writer +func (tw *terminalWriter) Write(p []byte) (n int, err error) { + if len(p) == 0 { + return 0, nil + } + if tw.emulator == nil { + return tw.wrappedWriter.Write(p) + } + // Emulate terminal by extracting commands and executing them + totalWritten := 0 + start := 0 // indicates start of the next chunk + end := len(p) + for current := 0; current < end; current++ { + if tw.inSequence { + // inside escape sequence + tw.command = append(tw.command, p[current]) + if isAnsiCommandChar(p[current]) { + if !isXtermOscSequence(tw.command, p[current]) { + // found the last command character. + // Now we have a complete command. + nchar, err := tw.emulator.HandleOutputCommand(tw.fd, tw.command) + totalWritten += nchar + if err != nil { + return totalWritten, err + } + + // clear the command + // don't include current character again + tw.command = tw.command[:0] + start = current + 1 + tw.inSequence = false + } + } + } else { + if p[current] == ANSI_ESCAPE_PRIMARY { + // entering escape sequnce + tw.inSequence = true + // indicates end of "normal sequence", write whatever you have so far + if len(p[start:current]) > 0 { + nw, err := tw.emulator.WriteChars(tw.fd, tw.wrappedWriter, p[start:current]) + totalWritten += nw + if err != nil { + return totalWritten, err + } + } + // include the current character as part of the next sequence + tw.command = append(tw.command, p[current]) + } + } + } + // note that so far, start of the escape sequence triggers writing out of bytes to console. + // For the part _after_ the end of last escape sequence, it is not written out yet. So write it out + if !tw.inSequence { + // assumption is that we can't be inside sequence and therefore command should be empty + if len(p[start:]) > 0 { + nw, err := tw.emulator.WriteChars(tw.fd, tw.wrappedWriter, p[start:]) + totalWritten += nw + if err != nil { + return totalWritten, err + } + } + } + return totalWritten, nil + +} + +// Read reads up to len(p) bytes into p. +// http://golang.org/pkg/io/#Reader +func (tr *terminalReader) Read(p []byte) (n int, err error) { + //Implementations of Read are discouraged from returning a zero byte count + // with a nil error, except when len(p) == 0. + if len(p) == 0 { + return 0, nil + } + if nil == tr.emulator { + return tr.readFromWrappedReader(p) + } + return tr.emulator.ReadChars(tr.fd, tr.wrappedReader, p) +} + +// Close the underlying stream +func (tr *terminalReader) Close() (err error) { + return tr.wrappedReader.Close() +} + +func (tr *terminalReader) readFromWrappedReader(p []byte) (n int, err error) { + return tr.wrappedReader.Read(p) +} + +type ansiCommand struct { + CommandBytes []byte + Command string + Parameters []string + IsSpecial bool +} + +func parseAnsiCommand(command []byte) *ansiCommand { + if isCharacterSelectionCmdChar(command[1]) { + // Is Character Set Selection commands + return &ansiCommand{ + CommandBytes: command, + Command: string(command), + IsSpecial: true, + } + } + // last char is command character + lastCharIndex := len(command) - 1 + + retValue := &ansiCommand{ + CommandBytes: command, + Command: string(command[lastCharIndex]), + IsSpecial: false, + } + // more than a single escape + if lastCharIndex != 0 { + start := 1 + // skip if double char escape sequence + if command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_ESCAPE_SECONDARY { + start++ + } + // convert this to GetNextParam method + retValue.Parameters = strings.Split(string(command[start:lastCharIndex]), ANSI_PARAMETER_SEP) + } + return retValue +} + +func (c *ansiCommand) getParam(index int) string { + if len(c.Parameters) > index { + return c.Parameters[index] + } + return "" +} + +func (ac *ansiCommand) String() string { + return fmt.Sprintf("0x%v \"%v\" (\"%v\")", + bytesToHex(ac.CommandBytes), + ac.Command, + strings.Join(ac.Parameters, "\",\"")) +} + +func bytesToHex(b []byte) string { + hex := make([]string, len(b)) + for i, ch := range b { + hex[i] = fmt.Sprintf("%X", ch) + } + return strings.Join(hex, "") +} + +func parseInt16OrDefault(s string, defaultValue int16) (n int16, err error) { + if s == "" { + return defaultValue, nil + } + parsedValue, err := strconv.ParseInt(s, 10, 16) + if err != nil { + return defaultValue, err + } + return int16(parsedValue), nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/LICENSE b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/LICENSE new file mode 100644 index 00000000..b55b37bc --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Docker, 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 + + https://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/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/README.md b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/README.md new file mode 100644 index 00000000..f1d46d16 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/README.md @@ -0,0 +1,11 @@ +# Introduction + +go-units is a library to transform human friendly measurements into machine friendly values. + +## Usage + +See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation. + +## License + +go-units is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text. diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/duration.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/duration.go new file mode 100644 index 00000000..c219a8a9 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/duration.go @@ -0,0 +1,33 @@ +// Package units provides helper function to parse and print size and time units +// in human-readable format. +package units + +import ( + "fmt" + "time" +) + +// HumanDuration returns a human-readable approximation of a duration +// (eg. "About a minute", "4 hours ago", etc.). +func HumanDuration(d time.Duration) string { + if seconds := int(d.Seconds()); seconds < 1 { + return "Less than a second" + } else if seconds < 60 { + return fmt.Sprintf("%d seconds", seconds) + } else if minutes := int(d.Minutes()); minutes == 1 { + return "About a minute" + } else if minutes < 60 { + return fmt.Sprintf("%d minutes", minutes) + } else if hours := int(d.Hours()); hours == 1 { + return "About an hour" + } else if hours < 48 { + return fmt.Sprintf("%d hours", hours) + } else if hours < 24*7*2 { + return fmt.Sprintf("%d days", hours/24) + } else if hours < 24*30*3 { + return fmt.Sprintf("%d weeks", hours/24/7) + } else if hours < 24*365*2 { + return fmt.Sprintf("%d months", hours/24/30) + } + return fmt.Sprintf("%d years", int(d.Hours())/24/365) +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/size.go b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/size.go new file mode 100644 index 00000000..3b59daff --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/docker/go-units/size.go @@ -0,0 +1,95 @@ +package units + +import ( + "fmt" + "regexp" + "strconv" + "strings" +) + +// See: http://en.wikipedia.org/wiki/Binary_prefix +const ( + // Decimal + + KB = 1000 + MB = 1000 * KB + GB = 1000 * MB + TB = 1000 * GB + PB = 1000 * TB + + // Binary + + KiB = 1024 + MiB = 1024 * KiB + GiB = 1024 * MiB + TiB = 1024 * GiB + PiB = 1024 * TiB +) + +type unitMap map[string]int64 + +var ( + decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB} + binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB} + sizeRegex = regexp.MustCompile(`^(\d+)([kKmMgGtTpP])?[bB]?$`) +) + +var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} +var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} + +// CustomSize returns a human-readable approximation of a size +// using custom format. +func CustomSize(format string, size float64, base float64, _map []string) string { + i := 0 + for size >= base { + size = size / base + i++ + } + return fmt.Sprintf(format, size, _map[i]) +} + +// HumanSize returns a human-readable approximation of a size +// capped at 4 valid numbers (eg. "2.746 MB", "796 KB"). +func HumanSize(size float64) string { + return CustomSize("%.4g %s", size, 1000.0, decimapAbbrs) +} + +// BytesSize returns a human-readable size in bytes, kibibytes, +// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB"). +func BytesSize(size float64) string { + return CustomSize("%.4g %s", size, 1024.0, binaryAbbrs) +} + +// FromHumanSize returns an integer from a human-readable specification of a +// size using SI standard (eg. "44kB", "17MB"). +func FromHumanSize(size string) (int64, error) { + return parseSize(size, decimalMap) +} + +// RAMInBytes parses a human-readable string representing an amount of RAM +// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and +// returns the number of bytes, or -1 if the string is unparseable. +// Units are case-insensitive, and the 'b' suffix is optional. +func RAMInBytes(size string) (int64, error) { + return parseSize(size, binaryMap) +} + +// Parses the human-readable size string into the amount it represents. +func parseSize(sizeStr string, uMap unitMap) (int64, error) { + matches := sizeRegex.FindStringSubmatch(sizeStr) + if len(matches) != 3 { + return -1, fmt.Errorf("invalid size: '%s'", sizeStr) + } + + size, err := strconv.ParseInt(matches[1], 10, 0) + if err != nil { + return -1, err + } + + unitPrefix := strings.ToLower(matches[2]) + if mul, ok := uMap[unitPrefix]; ok { + size *= mul + } + + return size, nil +} diff --git a/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/CONTRIBUTING.md b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/CONTRIBUTING.md new file mode 100644 index 00000000..c88f9b2b --- /dev/null +++ b/vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# How to Contribute + +## Getting Started + +- Fork the repository on GitHub +- Read the [README](README.markdown) for build and test instructions +- Play with the project, submit bugs, submit patches! + +## Contribution Flow + +This is a rough outline of what a contributor's workflow looks like: + +- Create a topic branch from where you want to base your work (usually master). +- Make commits of logical units. +- Make sure your commit messages are in the proper format (see below). +- Push your changes to a topic branch in your fork of the repository. +- Make sure the tests pass, and add any new tests as appropriate. +- Submit a pull request to the original repository. + +Thanks for your contributions! + +### Format of the Commit Message + +We follow a rough convention for commit messages that is designed to answer two +questions: what changed and why. The subject line should feature the what and +the body of the commit should describe the why. + +``` +scripts: add the test-cluster command + +this uses tmux to setup a test cluster that you can easily kill and +start for debugging. + +Fixes #38 +``` + +The format can be described more formally as follows: + +``` +: + + + +