From 58a4a40b0cdc6ad9620d31fb34be07c2c7ad35a8 Mon Sep 17 00:00:00 2001 From: sathyaseelan Date: Tue, 30 Apr 2019 16:40:01 +0530 Subject: [PATCH] chore[cleanup]: remove unused files (#606) Signed-off-by: nsathyaseelan --- Gopkg.lock | 95 - Gopkg.toml | 38 - apps/jupyter/deployers/jupyter_openebs.yml | 57 - apps/jupyter/deployers/run_litmus_test.yml | 44 - apps/jupyter/deployers/test.yml | 40 - apps/jupyter/deployers/test_vars.yml | 7 - apps/minio/tests/deploy_minio/README.md | 21 - .../tests/deploy_minio/application_launch.yml | 76 - apps/minio/tests/deploy_minio/e2e.feature | 19 - apps/minio/tests/deploy_minio/e2e_test.go | 274 -- .../tests/deploy_minio/run_litmus_test.yml | 123 - .../tests/mysql_data_persistence/README.md | 28 - .../tests/mysql_data_persistence/mysql.yml | 73 - .../run_litmus_test.yml | 32 - .../tests/mysql_data_persistence/test.yml | 148 - .../mysql_data_persistence/test_cleanup.yml | 43 - .../mysql_data_persistence/test_vars.yml | 11 - .../tests/mysql_storage_benchmark/README.md | 54 - .../tests/mysql_storage_benchmark/mysql.yml | 74 - .../run_litmus_test.yml | 31 - .../tests/mysql_storage_benchmark/test.yml | 131 - .../mysql_storage_benchmark/test_cleanup.yml | 51 - .../mysql_storage_benchmark/test_vars.yml | 17 - .../tests/mysql_storage_benchmark/tpcc.conf | 9 - docs/litmus_deep_dive.md | 15 - docs/running_test_suite.md | 24 - executor/README.md | 5 - executor/ansible/README.md | 18 - executor/ansible/all.csv | 4 - executor/ansible/ansible.cfg | 363 -- executor/ansible/execute.sh | 23 - executor/ansible/inventory/group_vars/all.yml | 21 - .../ansible/inventory/host_vars/localhost.yml | 3 - executor/ansible/inventory/hosts | 2 - executor/ansible/litmus_playbook.yml | 24 - executor/ansible/plugins/callback/README.md | 6 - .../ansible/plugins/callback/actionable.py | 94 - executor/ansible/plugins/callback/log_ara.py | 372 -- executor/ansible/plugins/callback/openebs.py | 63 - .../ansible/plugins/callback/timestamp.py | 127 - executor/ansible/provider/README.md | 10 - executor/ansible/provider/local-pv/README.md | 11 - .../provider/local-pv/setup-local-pv.yaml | 8 - .../provider/local-pv/templates/pv.yaml | 22 - .../local-pv/templates/storage_class.yaml | 7 - .../roles/k8s-local-pv/defaults/main.yml | 3 - .../ansible/roles/k8s-local-pv/tasks/main.yml | 51 - executor/ansible/utils/execute.yml | 47 - executor/ansible/utils/getFiles.yaml | 21 - executor/ansible/utils/runTest.yaml | 44 - hack/godog.sh | 10 - hack/minikube.sh | 68 - pkg/exec/exec.go | 64 - pkg/exec/exec_mock.go | 46 - pkg/exec/exec_test.go | 45 - pkg/kubectl/kubectl.go | 344 -- pkg/kubectl/kubectl_mock.go | 82 - pkg/kubectl/kubectl_test.go | 578 ---- pkg/time/time.go | 43 - pkg/time/time_test.go | 72 - pkg/util/envs.go | 73 - pkg/verify/verify.go | 672 ---- tools/godog-runner/Dockerfile | 22 - vendor/github.com/DATA-DOG/godog/.gitignore | 2 - vendor/github.com/DATA-DOG/godog/.travis.yml | 23 - vendor/github.com/DATA-DOG/godog/CHANGELOG.md | 85 - vendor/github.com/DATA-DOG/godog/LICENSE | 28 - vendor/github.com/DATA-DOG/godog/Makefile | 32 - vendor/github.com/DATA-DOG/godog/README.md | 341 -- vendor/github.com/DATA-DOG/godog/ast.go | 31 - vendor/github.com/DATA-DOG/godog/builder.go | 337 -- .../DATA-DOG/godog/builder_go110.go | 409 --- .../DATA-DOG/godog/colors/ansi_others.go | 18 - .../DATA-DOG/godog/colors/ansi_windows.go | 417 --- .../DATA-DOG/godog/colors/colors.go | 59 - .../DATA-DOG/godog/colors/no_colors.go | 57 - .../DATA-DOG/godog/colors/writer.go | 41 - vendor/github.com/DATA-DOG/godog/flags.go | 192 -- vendor/github.com/DATA-DOG/godog/fmt.go | 513 --- .../github.com/DATA-DOG/godog/fmt_cucumber.go | 332 -- .../github.com/DATA-DOG/godog/fmt_events.go | 269 -- vendor/github.com/DATA-DOG/godog/fmt_junit.go | 208 -- .../github.com/DATA-DOG/godog/fmt_pretty.go | 456 --- .../github.com/DATA-DOG/godog/fmt_progress.go | 121 - vendor/github.com/DATA-DOG/godog/gherkin.go | 36 - .../github.com/DATA-DOG/godog/gherkin/LICENSE | 21 - .../DATA-DOG/godog/gherkin/README.md | 3 - .../github.com/DATA-DOG/godog/gherkin/ast.go | 97 - .../DATA-DOG/godog/gherkin/astbuilder.go | 378 --- .../DATA-DOG/godog/gherkin/dialect.go | 47 - .../godog/gherkin/dialects_builtin.go | 2988 ----------------- .../DATA-DOG/godog/gherkin/gherkin.go | 137 - .../DATA-DOG/godog/gherkin/matcher.go | 270 -- .../DATA-DOG/godog/gherkin/parser.go | 2270 ------------- vendor/github.com/DATA-DOG/godog/godog.go | 42 - vendor/github.com/DATA-DOG/godog/logo.png | Bin 48144 -> 0 bytes vendor/github.com/DATA-DOG/godog/options.go | 59 - vendor/github.com/DATA-DOG/godog/run.go | 232 -- .../github.com/DATA-DOG/godog/stacktrace.go | 141 - vendor/github.com/DATA-DOG/godog/stepdef.go | 211 -- vendor/github.com/DATA-DOG/godog/suite.go | 804 ----- .../DATA-DOG/godog/suite_context.go | 489 --- vendor/github.com/DATA-DOG/godog/utils.go | 30 - vendor/github.com/davecgh/go-spew/LICENSE | 15 - .../github.com/davecgh/go-spew/spew/bypass.go | 145 - .../davecgh/go-spew/spew/bypasssafe.go | 38 - .../github.com/davecgh/go-spew/spew/common.go | 341 -- .../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 --- .../github.com/davecgh/go-spew/spew/format.go | 419 --- .../github.com/davecgh/go-spew/spew/spew.go | 148 - vendor/github.com/ghodss/yaml/.gitignore | 20 - vendor/github.com/ghodss/yaml/.travis.yml | 7 - vendor/github.com/ghodss/yaml/LICENSE | 50 - vendor/github.com/ghodss/yaml/README.md | 121 - vendor/github.com/ghodss/yaml/fields.go | 501 --- vendor/github.com/ghodss/yaml/yaml.go | 277 -- vendor/github.com/golang/mock/AUTHORS | 12 - vendor/github.com/golang/mock/CONTRIBUTORS | 37 - vendor/github.com/golang/mock/LICENSE | 202 -- vendor/github.com/golang/mock/gomock/call.go | 428 --- .../github.com/golang/mock/gomock/callset.go | 108 - .../golang/mock/gomock/controller.go | 217 -- .../github.com/golang/mock/gomock/matchers.go | 99 - vendor/github.com/pkg/errors/.gitignore | 24 - vendor/github.com/pkg/errors/.travis.yml | 11 - vendor/github.com/pkg/errors/LICENSE | 23 - vendor/github.com/pkg/errors/README.md | 52 - vendor/github.com/pkg/errors/appveyor.yml | 32 - vendor/github.com/pkg/errors/errors.go | 269 -- vendor/github.com/pkg/errors/stack.go | 178 - vendor/github.com/pmezard/go-difflib/LICENSE | 27 - .../pmezard/go-difflib/difflib/difflib.go | 772 ----- vendor/github.com/stretchr/testify/LICENSE | 22 - .../testify/assert/assertion_format.go | 484 --- .../testify/assert/assertion_format.go.tmpl | 5 - .../testify/assert/assertion_forward.go | 956 ------ .../testify/assert/assertion_forward.go.tmpl | 5 - .../stretchr/testify/assert/assertions.go | 1394 -------- .../github.com/stretchr/testify/assert/doc.go | 45 - .../stretchr/testify/assert/errors.go | 10 - .../testify/assert/forward_assertions.go | 16 - .../testify/assert/http_assertions.go | 143 - .../stretchr/testify/require/doc.go | 28 - .../testify/require/forward_requirements.go | 16 - .../stretchr/testify/require/require.go | 1227 ------- .../stretchr/testify/require/require.go.tmpl | 6 - .../testify/require/require_forward.go | 957 ------ .../testify/require/require_forward.go.tmpl | 5 - .../stretchr/testify/require/requirements.go | 29 - vendor/golang.org/x/net/AUTHORS | 3 - vendor/golang.org/x/net/CONTRIBUTORS | 3 - vendor/golang.org/x/net/LICENSE | 27 - vendor/golang.org/x/net/PATENTS | 22 - vendor/golang.org/x/net/context/context.go | 56 - vendor/golang.org/x/net/context/go17.go | 72 - vendor/golang.org/x/net/context/go19.go | 20 - vendor/golang.org/x/net/context/pre_go17.go | 300 -- vendor/golang.org/x/net/context/pre_go19.go | 109 - vendor/gopkg.in/yaml.v2/.travis.yml | 12 - vendor/gopkg.in/yaml.v2/LICENSE | 201 -- vendor/gopkg.in/yaml.v2/LICENSE.libyaml | 31 - vendor/gopkg.in/yaml.v2/NOTICE | 13 - vendor/gopkg.in/yaml.v2/README.md | 133 - vendor/gopkg.in/yaml.v2/apic.go | 739 ---- vendor/gopkg.in/yaml.v2/decode.go | 775 ----- vendor/gopkg.in/yaml.v2/emitterc.go | 1685 ---------- vendor/gopkg.in/yaml.v2/encode.go | 362 -- vendor/gopkg.in/yaml.v2/go.mod | 5 - vendor/gopkg.in/yaml.v2/parserc.go | 1095 ------ vendor/gopkg.in/yaml.v2/readerc.go | 412 --- vendor/gopkg.in/yaml.v2/resolve.go | 258 -- vendor/gopkg.in/yaml.v2/scannerc.go | 2696 --------------- vendor/gopkg.in/yaml.v2/sorter.go | 113 - vendor/gopkg.in/yaml.v2/writerc.go | 26 - vendor/gopkg.in/yaml.v2/yaml.go | 466 --- vendor/gopkg.in/yaml.v2/yamlh.go | 738 ---- vendor/gopkg.in/yaml.v2/yamlprivateh.go | 173 - 179 files changed, 38721 deletions(-) delete mode 100644 Gopkg.lock delete mode 100644 Gopkg.toml delete mode 100644 apps/jupyter/deployers/jupyter_openebs.yml delete mode 100644 apps/jupyter/deployers/run_litmus_test.yml delete mode 100644 apps/jupyter/deployers/test.yml delete mode 100644 apps/jupyter/deployers/test_vars.yml delete mode 100644 apps/minio/tests/deploy_minio/README.md delete mode 100644 apps/minio/tests/deploy_minio/application_launch.yml delete mode 100644 apps/minio/tests/deploy_minio/e2e.feature delete mode 100644 apps/minio/tests/deploy_minio/e2e_test.go delete mode 100644 apps/minio/tests/deploy_minio/run_litmus_test.yml delete mode 100644 apps/percona/tests/mysql_data_persistence/README.md delete mode 100644 apps/percona/tests/mysql_data_persistence/mysql.yml delete mode 100644 apps/percona/tests/mysql_data_persistence/run_litmus_test.yml delete mode 100644 apps/percona/tests/mysql_data_persistence/test.yml delete mode 100644 apps/percona/tests/mysql_data_persistence/test_cleanup.yml delete mode 100644 apps/percona/tests/mysql_data_persistence/test_vars.yml delete mode 100644 apps/percona/tests/mysql_storage_benchmark/README.md delete mode 100644 apps/percona/tests/mysql_storage_benchmark/mysql.yml delete mode 100644 apps/percona/tests/mysql_storage_benchmark/run_litmus_test.yml delete mode 100644 apps/percona/tests/mysql_storage_benchmark/test.yml delete mode 100644 apps/percona/tests/mysql_storage_benchmark/test_cleanup.yml delete mode 100644 apps/percona/tests/mysql_storage_benchmark/test_vars.yml delete mode 100644 apps/percona/tests/mysql_storage_benchmark/tpcc.conf delete mode 100644 docs/litmus_deep_dive.md delete mode 100644 docs/running_test_suite.md delete mode 100644 executor/README.md delete mode 100644 executor/ansible/README.md delete mode 100644 executor/ansible/all.csv delete mode 100644 executor/ansible/ansible.cfg delete mode 100644 executor/ansible/execute.sh delete mode 100644 executor/ansible/inventory/group_vars/all.yml delete mode 100644 executor/ansible/inventory/host_vars/localhost.yml delete mode 100644 executor/ansible/inventory/hosts delete mode 100644 executor/ansible/litmus_playbook.yml delete mode 100644 executor/ansible/plugins/callback/README.md delete mode 100644 executor/ansible/plugins/callback/actionable.py delete mode 100644 executor/ansible/plugins/callback/log_ara.py delete mode 100644 executor/ansible/plugins/callback/openebs.py delete mode 100644 executor/ansible/plugins/callback/timestamp.py delete mode 100644 executor/ansible/provider/README.md delete mode 100644 executor/ansible/provider/local-pv/README.md delete mode 100644 executor/ansible/provider/local-pv/setup-local-pv.yaml delete mode 100644 executor/ansible/provider/local-pv/templates/pv.yaml delete mode 100644 executor/ansible/provider/local-pv/templates/storage_class.yaml delete mode 100644 executor/ansible/roles/k8s-local-pv/defaults/main.yml delete mode 100644 executor/ansible/roles/k8s-local-pv/tasks/main.yml delete mode 100644 executor/ansible/utils/execute.yml delete mode 100644 executor/ansible/utils/getFiles.yaml delete mode 100644 executor/ansible/utils/runTest.yaml delete mode 100644 hack/godog.sh delete mode 100644 hack/minikube.sh delete mode 100644 pkg/exec/exec.go delete mode 100644 pkg/exec/exec_mock.go delete mode 100644 pkg/exec/exec_test.go delete mode 100644 pkg/kubectl/kubectl.go delete mode 100644 pkg/kubectl/kubectl_mock.go delete mode 100644 pkg/kubectl/kubectl_test.go delete mode 100644 pkg/time/time.go delete mode 100644 pkg/time/time_test.go delete mode 100644 pkg/util/envs.go delete mode 100644 pkg/verify/verify.go delete mode 100644 tools/godog-runner/Dockerfile delete mode 100644 vendor/github.com/DATA-DOG/godog/.gitignore delete mode 100644 vendor/github.com/DATA-DOG/godog/.travis.yml delete mode 100644 vendor/github.com/DATA-DOG/godog/CHANGELOG.md delete mode 100644 vendor/github.com/DATA-DOG/godog/LICENSE delete mode 100644 vendor/github.com/DATA-DOG/godog/Makefile delete mode 100644 vendor/github.com/DATA-DOG/godog/README.md delete mode 100644 vendor/github.com/DATA-DOG/godog/ast.go delete mode 100644 vendor/github.com/DATA-DOG/godog/builder.go delete mode 100644 vendor/github.com/DATA-DOG/godog/builder_go110.go delete mode 100644 vendor/github.com/DATA-DOG/godog/colors/ansi_others.go delete mode 100644 vendor/github.com/DATA-DOG/godog/colors/ansi_windows.go delete mode 100644 vendor/github.com/DATA-DOG/godog/colors/colors.go delete mode 100644 vendor/github.com/DATA-DOG/godog/colors/no_colors.go delete mode 100644 vendor/github.com/DATA-DOG/godog/colors/writer.go delete mode 100644 vendor/github.com/DATA-DOG/godog/flags.go delete mode 100644 vendor/github.com/DATA-DOG/godog/fmt.go delete mode 100644 vendor/github.com/DATA-DOG/godog/fmt_cucumber.go delete mode 100644 vendor/github.com/DATA-DOG/godog/fmt_events.go delete mode 100644 vendor/github.com/DATA-DOG/godog/fmt_junit.go delete mode 100644 vendor/github.com/DATA-DOG/godog/fmt_pretty.go delete mode 100644 vendor/github.com/DATA-DOG/godog/fmt_progress.go delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin.go delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/LICENSE delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/README.md delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/ast.go delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/astbuilder.go delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/dialect.go delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/dialects_builtin.go delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/gherkin.go delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/matcher.go delete mode 100644 vendor/github.com/DATA-DOG/godog/gherkin/parser.go delete mode 100644 vendor/github.com/DATA-DOG/godog/godog.go delete mode 100644 vendor/github.com/DATA-DOG/godog/logo.png delete mode 100644 vendor/github.com/DATA-DOG/godog/options.go delete mode 100644 vendor/github.com/DATA-DOG/godog/run.go delete mode 100644 vendor/github.com/DATA-DOG/godog/stacktrace.go delete mode 100644 vendor/github.com/DATA-DOG/godog/stepdef.go delete mode 100644 vendor/github.com/DATA-DOG/godog/suite.go delete mode 100644 vendor/github.com/DATA-DOG/godog/suite_context.go delete mode 100644 vendor/github.com/DATA-DOG/godog/utils.go delete mode 100644 vendor/github.com/davecgh/go-spew/LICENSE delete mode 100644 vendor/github.com/davecgh/go-spew/spew/bypass.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/bypasssafe.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/common.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/config.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/doc.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/dump.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/format.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/spew.go delete mode 100644 vendor/github.com/ghodss/yaml/.gitignore delete mode 100644 vendor/github.com/ghodss/yaml/.travis.yml delete mode 100644 vendor/github.com/ghodss/yaml/LICENSE delete mode 100644 vendor/github.com/ghodss/yaml/README.md delete mode 100644 vendor/github.com/ghodss/yaml/fields.go delete mode 100644 vendor/github.com/ghodss/yaml/yaml.go delete mode 100644 vendor/github.com/golang/mock/AUTHORS delete mode 100644 vendor/github.com/golang/mock/CONTRIBUTORS delete mode 100644 vendor/github.com/golang/mock/LICENSE delete mode 100644 vendor/github.com/golang/mock/gomock/call.go delete mode 100644 vendor/github.com/golang/mock/gomock/callset.go delete mode 100644 vendor/github.com/golang/mock/gomock/controller.go delete mode 100644 vendor/github.com/golang/mock/gomock/matchers.go delete mode 100644 vendor/github.com/pkg/errors/.gitignore delete mode 100644 vendor/github.com/pkg/errors/.travis.yml delete mode 100644 vendor/github.com/pkg/errors/LICENSE delete mode 100644 vendor/github.com/pkg/errors/README.md delete mode 100644 vendor/github.com/pkg/errors/appveyor.yml delete mode 100644 vendor/github.com/pkg/errors/errors.go delete mode 100644 vendor/github.com/pkg/errors/stack.go delete mode 100644 vendor/github.com/pmezard/go-difflib/LICENSE delete mode 100644 vendor/github.com/pmezard/go-difflib/difflib/difflib.go delete mode 100644 vendor/github.com/stretchr/testify/LICENSE delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_format.go delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_forward.go delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/assert/assertions.go delete mode 100644 vendor/github.com/stretchr/testify/assert/doc.go delete mode 100644 vendor/github.com/stretchr/testify/assert/errors.go delete mode 100644 vendor/github.com/stretchr/testify/assert/forward_assertions.go delete mode 100644 vendor/github.com/stretchr/testify/assert/http_assertions.go delete mode 100644 vendor/github.com/stretchr/testify/require/doc.go delete mode 100644 vendor/github.com/stretchr/testify/require/forward_requirements.go delete mode 100644 vendor/github.com/stretchr/testify/require/require.go delete mode 100644 vendor/github.com/stretchr/testify/require/require.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/require/require_forward.go delete mode 100644 vendor/github.com/stretchr/testify/require/require_forward.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/require/requirements.go delete mode 100644 vendor/golang.org/x/net/AUTHORS delete mode 100644 vendor/golang.org/x/net/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/net/LICENSE delete mode 100644 vendor/golang.org/x/net/PATENTS delete mode 100644 vendor/golang.org/x/net/context/context.go delete mode 100644 vendor/golang.org/x/net/context/go17.go delete mode 100644 vendor/golang.org/x/net/context/go19.go delete mode 100644 vendor/golang.org/x/net/context/pre_go17.go delete mode 100644 vendor/golang.org/x/net/context/pre_go19.go delete mode 100644 vendor/gopkg.in/yaml.v2/.travis.yml delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE.libyaml delete mode 100644 vendor/gopkg.in/yaml.v2/NOTICE delete mode 100644 vendor/gopkg.in/yaml.v2/README.md delete mode 100644 vendor/gopkg.in/yaml.v2/apic.go delete mode 100644 vendor/gopkg.in/yaml.v2/decode.go delete mode 100644 vendor/gopkg.in/yaml.v2/emitterc.go delete mode 100644 vendor/gopkg.in/yaml.v2/encode.go delete mode 100644 vendor/gopkg.in/yaml.v2/go.mod delete mode 100644 vendor/gopkg.in/yaml.v2/parserc.go delete mode 100644 vendor/gopkg.in/yaml.v2/readerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/resolve.go delete mode 100644 vendor/gopkg.in/yaml.v2/scannerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/sorter.go delete mode 100644 vendor/gopkg.in/yaml.v2/writerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/yaml.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlh.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlprivateh.go diff --git a/Gopkg.lock b/Gopkg.lock deleted file mode 100644 index 2c2285175..000000000 --- a/Gopkg.lock +++ /dev/null @@ -1,95 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:63e35f61c1d659416dc2d27d873689a9aef81701fd077fa4686e3d6edccac3dc" - name = "github.com/DATA-DOG/godog" - packages = [ - ".", - "colors", - "gherkin", - ] - pruneopts = "UT" - revision = "0371765570d36374bef4ab9f62ed0491f0862a3c" - version = "v0.7.6" - -[[projects]] - digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" - name = "github.com/davecgh/go-spew" - packages = ["spew"] - pruneopts = "UT" - revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" - version = "v1.1.1" - -[[projects]] - digest = "1:2cd7915ab26ede7d95b8749e6b1f933f1c6d5398030684e6505940a10f31cfda" - name = "github.com/ghodss/yaml" - packages = ["."] - pruneopts = "UT" - revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7" - version = "v1.0.0" - -[[projects]] - digest = "1:bc38c7c481812e178d85160472e231c5e1c9a7f5845d67e23ee4e706933c10d8" - name = "github.com/golang/mock" - packages = ["gomock"] - pruneopts = "UT" - revision = "c34cdb4725f4c3844d095133c6e40e448b86589b" - version = "v1.1.1" - -[[projects]] - digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747" - name = "github.com/pkg/errors" - packages = ["."] - pruneopts = "UT" - revision = "645ef00459ed84a119197bfb8d8205042c6df63d" - version = "v0.8.0" - -[[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - pruneopts = "UT" - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - digest = "1:c40d65817cdd41fac9aa7af8bed56927bb2d6d47e4fea566a74880f5c2b1c41e" - name = "github.com/stretchr/testify" - packages = [ - "assert", - "require", - ] - pruneopts = "UT" - revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686" - version = "v1.2.2" - -[[projects]] - branch = "master" - digest = "1:76ee51c3f468493aff39dbacc401e8831fbb765104cbf613b89bef01cf4bad70" - name = "golang.org/x/net" - packages = ["context"] - pruneopts = "UT" - revision = "04a2e542c03f1d053ab3e4d6e5abcd4b66e2be8e" - -[[projects]] - digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" - name = "gopkg.in/yaml.v2" - packages = ["."] - pruneopts = "UT" - revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" - version = "v2.2.1" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/DATA-DOG/godog", - "github.com/DATA-DOG/godog/gherkin", - "github.com/ghodss/yaml", - "github.com/golang/mock/gomock", - "github.com/pkg/errors", - "github.com/stretchr/testify/require", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml deleted file mode 100644 index 9b044905c..000000000 --- a/Gopkg.toml +++ /dev/null @@ -1,38 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - name = "github.com/DATA-DOG/godog" - version = "0.7.6" - -[prune] - go-tests = true - unused-packages = true - -[[constraint]] - name = "github.com/golang/mock" - version = "1.1.1" diff --git a/apps/jupyter/deployers/jupyter_openebs.yml b/apps/jupyter/deployers/jupyter_openebs.yml deleted file mode 100644 index 6823e3a0f..000000000 --- a/apps/jupyter/deployers/jupyter_openebs.yml +++ /dev/null @@ -1,57 +0,0 @@ -apiVersion: apps/v1beta1 -kind: Deployment -metadata: - name: jupyter-server -spec: - replicas: 1 - template: - metadata: - labels: - lkey: lvalue - spec: - containers: - - name: jupyter-server - imagePullPolicy: Always - image: satyamz/docker-jupyter:v0.4 - ports: - - containerPort: 8888 - env: - - name: GIT_REPO - value: https://github.com/vharsh/plot-demo.git - volumeMounts: - - name: data-vol - mountPath: /mnt/data - volumes: - - name: data-vol - persistentVolumeClaim: - claimName: testclaim ---- -kind: PersistentVolumeClaim -apiVersion: v1 -metadata: - name: testclaim -spec: - storageClassName: testclass - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 5G ---- -apiVersion: v1 -kind: Service -metadata: - name: jupyter-service - labels: - lkey: lvalue -spec: - ports: - - name: ui - port: 8888 - nodePort: 32424 - protocol: TCP - selector: - lkey: lvalue - sessionAffinity: None - type: NodePort - diff --git a/apps/jupyter/deployers/run_litmus_test.yml b/apps/jupyter/deployers/run_litmus_test.yml deleted file mode 100644 index e0a757475..000000000 --- a/apps/jupyter/deployers/run_litmus_test.yml +++ /dev/null @@ -1,44 +0,0 @@ ---- -apiVersion: batch/v1 -kind: Job -metadata: - generateName: litmus-jupyter- - namespace: litmus -spec: - template: - metadata: - name: litmus - labels: - app: jupyter-deployment-litmus - - spec: - serviceAccountName: litmus - restartPolicy: Never - containers: - - name: ansibletest - image: openebs/ansible-runner:ci - imagePullPolicy: Always - - env: - - name: ANSIBLE_STDOUT_CALLBACK - #value: log_plays, actionable, default - value: default - - - name: PROVIDER_STORAGE_CLASS - # Supported values: openebs-standard, local-storage - value: openebs-standard - - - name: APP_PVC - value: jupyter-data-vol-claim - - # Application label - - name: APP_LABEL - value: 'app=jupyter-server' - - # Application namespace - - name: APP_NAMESPACE - value: app-jupyter-ns - - command: ["/bin/bash"] - args: ["-c", "ansible-playbook ./jupyter/deployers/test.yml -i /etc/ansible/hosts -v; exit 0"] - diff --git a/apps/jupyter/deployers/test.yml b/apps/jupyter/deployers/test.yml deleted file mode 100644 index 54f91313e..000000000 --- a/apps/jupyter/deployers/test.yml +++ /dev/null @@ -1,40 +0,0 @@ ---- -- hosts: localhost - connection: local - - vars_files: - - test_vars.yml - - tasks: - - block: - - ## Generating the testname for deployment - - include_tasks: /common/utils/create_testname.yml - - ## RECORD START-OF-TEST IN LITMUS RESULT CR - - include_tasks: /common/utils/update_litmus_result_resource.yml - vars: - status: 'SOT' - - ## Actual Test to deploy Jupyter NoteBook on k8s - ## Creating namespaces and making the application for deployment - - include_tasks: /common/utils/pre_create_app_deploy.yml - - ## Deploying the application - - include_tasks: /common/utils/deploy_single_app.yml - vars: - delay: 60 - retries: 20 - - - set_fact: - flag: "Pass" - - rescue: - - set_fact: - - flag: "Fail" - always: - ## RECORD END-OF-TEST IN LITMUS RESULT CR - - include_tasks: /common/utils/update_litmus_result_resource.yml - vars: - status: 'EOT' \ No newline at end of file diff --git a/apps/jupyter/deployers/test_vars.yml b/apps/jupyter/deployers/test_vars.yml deleted file mode 100644 index ded827e99..000000000 --- a/apps/jupyter/deployers/test_vars.yml +++ /dev/null @@ -1,7 +0,0 @@ -# Test-specific parametres - -application_deployment: jupyter_openebs.yml -app_ns: "{{ lookup('env','APP_NAMESPACE') }}" -app_label: "{{ lookup('env','APP_LABEL') }}" -test_name: jupyter-deployment -application_name: "jupyter_Notebook" diff --git a/apps/minio/tests/deploy_minio/README.md b/apps/minio/tests/deploy_minio/README.md deleted file mode 100644 index 6aad78912..000000000 --- a/apps/minio/tests/deploy_minio/README.md +++ /dev/null @@ -1,21 +0,0 @@ -### Test Minio deployment in Kubernetes - -#### Use-Case -Feature: Test deployment of Minio on Kubernetes PV - In order to test deployment of Minio on Kubernetes PV - As an end user - I need to be able to launch Minio on Kubernetes PV - -#### Implementation -- Step 1: Describe the scenario(s) in **e2e.feature** file -- Step 2: Run **godog e2e.feature** -- Step 3: Implement undefined steps (also referred to as snippets) in **e2e_test.go** file -- Step 4: Re-Run **godog e2e.feature** - -#### Best Practices -- 1: Make use of standard go practices -- 2: Transform the usecase into structure(s) & its properties -- 3: Now fit the godog generated function snippets into above structure' methods - -#### References -- https://github.com/DATA-DOG/godog diff --git a/apps/minio/tests/deploy_minio/application_launch.yml b/apps/minio/tests/deploy_minio/application_launch.yml deleted file mode 100644 index e764ffd4b..000000000 --- a/apps/minio/tests/deploy_minio/application_launch.yml +++ /dev/null @@ -1,76 +0,0 @@ -# For k8s versions before 1.9.0 use apps/v1beta2 and before 1.8.0 use extensions/v1beta1 -apiVersion: apps/v1beta2 -kind: Deployment -metadata: - # This name uniquely identifies the Deployment - name: odm-minio - namespace: litmus -spec: - selector: - matchLabels: - app: minio - strategy: - type: Recreate - template: - metadata: - labels: - # Label is used as selector in the service. - app: minio - spec: - # Refer to the PVC - volumes: - - name: storage - persistentVolumeClaim: - # Name of the PVC created earlier - claimName: odm-minio - containers: - - name: minio - # Pulls the default Minio image from Docker Hub - image: minio/minio:latest - args: - - server - - /storage - env: - # Minio access key and secret key - - name: MINIO_ACCESS_KEY - value: "minio" - - name: MINIO_SECRET_KEY - value: "minio123" - ports: - - containerPort: 9000 - hostPort: 9000 - # Mount the volume into the pod - volumeMounts: - - name: storage # must match the volume name, above - mountPath: "/home/username" ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: odm-minio - namespace: litmus - labels: - app: minio-storage-claim -spec: - storageClassName: openebs-standalone - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 10G ---- -apiVersion: v1 -kind: Service -metadata: - name: odm-minio - namespace: litmus -spec: - type: LoadBalancer - ports: - - port: 9000 - nodePort: 32701 - protocol: TCP - selector: - app: minio - sessionAffinity: None - type: NodePort diff --git a/apps/minio/tests/deploy_minio/e2e.feature b/apps/minio/tests/deploy_minio/e2e.feature deleted file mode 100644 index 2b1328598..000000000 --- a/apps/minio/tests/deploy_minio/e2e.feature +++ /dev/null @@ -1,19 +0,0 @@ -Feature: Test deployment of Minio on Kubernetes PV - In order to test deployment of Minio on Kubernetes PV - As an end user - I need to be able to launch Minio on Kubernetes PV - - Scenario: launch Minio on PV - Given I have a kubernetes cluster with volume operator installed - When I launch minio application on volume - Then wait for "180s" - And verify minio application is launched successfully on volume - And verify PVC is bound - And verify PV is deployed - - Scenario: delete Minio instance - Given minio application is launched successfully on volume - When I delete minio instance along with volume - Then wait for "60s" - And verify minio application is deleted - And verify PV is deleted diff --git a/apps/minio/tests/deploy_minio/e2e_test.go b/apps/minio/tests/deploy_minio/e2e_test.go deleted file mode 100644 index 7f6a598e1..000000000 --- a/apps/minio/tests/deploy_minio/e2e_test.go +++ /dev/null @@ -1,274 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package main - -import ( - "fmt" - - "github.com/DATA-DOG/godog" - "github.com/DATA-DOG/godog/gherkin" - "github.com/openebs/litmus/pkg/kubectl" - "github.com/openebs/litmus/pkg/time" - "github.com/openebs/litmus/pkg/verify" -) - -// errorIdentity is a type to set error identities -type errorIdentity string - -const ( - // OperatorVerifyFileEI stores the actual error during load of volume - // operator verify file - OperatorVerifyFileEI errorIdentity = "operator-verify-file-err" - // ApplicationVerifyFileEI stores the actual error during load of application - // verify file - ApplicationVerifyFileEI errorIdentity = "application-verify-file-err" - // VolumeVerifyFileEI stores the actual error during load of volume verify - // file - VolumeVerifyFileEI errorIdentity = "volume-verify-file-err" -) - -const ( - // OperatorMF enables litmus to run checks & actions based on this volume - // operator verify file - OperatorMF verify.VerifyFile = "/etc/e2e/operator-verify/operator-verify.yaml" - // ApplicationMF enables litmus to run checks & actions based on this application - // verify file - ApplicationMF verify.VerifyFile = "/etc/e2e/application-verify/application-verify.yaml" - // VolumeMF enables litmus to run checks & actions based on this volume verify - // file - VolumeMF verify.VerifyFile = "/etc/e2e/volume-verify/volume-verify.yaml" -) - -const ( - // ApplicationKF is launched via kubectl - ApplicationKF kubectl.KubectlFile = "/etc/e2e/application-launch/application-launch.yaml" -) - -const ( - // PVCAlias is the alias name given to a application's pvc - // - // This is the text which is typically understood by the end user. This text - // which will be set in the verify file against a particular component. - // Verification logic will filter the component based on this alias & run - // various checks &/or actions - PVCAlias string = "pvc" -) - -type MinioLaunch struct { - // appVerifier instance enables verification of application components - appVerifier verify.AllVerifier - // volVerifier instance enables verification of persistent volume components - volVerifier verify.AllVerifier - // operatorVerifier instance enables verification of volume operator components - operatorVerifier verify.DeployRunVerifier - // errors hold the previous error(s) - errors map[errorIdentity]error -} - -func (e2e *MinioLaunch) withOperatorVerifier(f *gherkin.Feature) { - o, err := verify.NewKubeInstallVerify(OperatorMF) - if err != nil { - e2e.errors[OperatorVerifyFileEI] = err - return - } - e2e.operatorVerifier = o -} - -func (e2e *MinioLaunch) withApplicationVerifier(f *gherkin.Feature) { - a, err := verify.NewKubeInstallVerify(ApplicationMF) - if err != nil { - e2e.errors[ApplicationVerifyFileEI] = err - return - } - e2e.appVerifier = a -} - -func (e2e *MinioLaunch) withVolumeVerifier(f *gherkin.Feature) { - v, err := verify.NewKubeInstallVerify(VolumeMF) - if err != nil { - e2e.errors[VolumeVerifyFileEI] = err - return - } - e2e.volVerifier = v -} - -func (e2e *MinioLaunch) tearDown(f *gherkin.Feature) { - kubectl.New().Run([]string{"delete", "-f", string(ApplicationKF)}) -} - -func (e2e *MinioLaunch) iHaveAKubernetesClusterWithVolumeOperatorInstalled() (err error) { - kconnVerifier := verify.NewKubeConnectionVerify() - // checks if kubernetes cluster is available & is connected - _, err = kconnVerifier.IsConnected() - if err != nil { - return - } - - if e2e.operatorVerifier == nil { - err = fmt.Errorf("nil operator verifier: possible error '%s'", e2e.errors[OperatorVerifyFileEI]) - return - } - - // checks if operator is deployed - _, err = e2e.operatorVerifier.IsDeployed() - if err != nil { - return - } - - // checks if operator is running - _, err = e2e.operatorVerifier.IsRunning() - - return -} - -func (e2e *MinioLaunch) waitFor(duration string) (err error) { - err = time.WaitFor(duration) - return -} - -func (e2e *MinioLaunch) iLaunchMinioApplicationOnVolume() (err error) { - // do a kubectl apply of application yaml - _, err = kubectl.New().Run([]string{"apply", "-f", string(ApplicationKF)}) - return -} - -func (e2e *MinioLaunch) verifyMinioApplicationIsLaunchedSuccessfullyOnVolume() (err error) { - err = e2e.verifyApplicationIsRunning() - if err != nil { - return - } - - // check if volume is running - return e2e.verifyAllVolumeReplicasAreRunning() -} - -func (e2e *MinioLaunch) verifyApplicationIsRunning() (err error) { - if e2e.appVerifier == nil { - err = fmt.Errorf("nil application verifier: possible error '%s'", e2e.errors[ApplicationVerifyFileEI]) - return - } - - // is application deployed - _, err = e2e.appVerifier.IsDeployed() - if err != nil { - return - } - - // is application running - _, err = e2e.appVerifier.IsRunning() - return -} - -func (e2e *MinioLaunch) verifyAllVolumeReplicasAreRunning() (err error) { - if e2e.volVerifier == nil { - err = fmt.Errorf("nil volume verifier: possible error '%s'", e2e.errors[VolumeVerifyFileEI]) - return - } - - // is volume deployed - _, err = e2e.volVerifier.IsDeployed() - if err != nil { - return - } - - // is volume running - _, err = e2e.volVerifier.IsRunning() - return -} - -func (e2e *MinioLaunch) minioApplicationIsLaunchedSuccessfullyOnVolume() (err error) { - // check if application is running - return e2e.verifyMinioApplicationIsLaunchedSuccessfullyOnVolume() -} - -func (e2e *MinioLaunch) verifyPVCIsBound() (err error) { - if e2e.appVerifier == nil { - err = fmt.Errorf("nil application verifier: possible error '%s'", e2e.errors[ApplicationVerifyFileEI]) - return - } - - // is condition satisfied - _, err = e2e.appVerifier.IsCondition(PVCAlias, verify.PVCBoundCond) - return -} - -func (e2e *MinioLaunch) verifyPVIsDeployed() (err error) { - if e2e.volVerifier == nil { - err = fmt.Errorf("nil volume verifier: possible error '%s'", e2e.errors[VolumeVerifyFileEI]) - return - } - - // is volume deployed - _, err = e2e.volVerifier.IsDeployed() - if err != nil { - return - } - - // is volume running - _, err = e2e.volVerifier.IsRunning() - return -} - -func (e2e *MinioLaunch) iDeleteMinioInstanceAlongWithVolume() (err error) { - kubectl.New().Run([]string{"delete", "-f", string(ApplicationKF)}) - return -} - -func (e2e *MinioLaunch) verifyMinioApplicationIsDeleted() (err error) { - if e2e.appVerifier == nil { - err = fmt.Errorf("nil application verifier: possible error '%s'", e2e.errors[ApplicationVerifyFileEI]) - return - } - - // is application deleted - _, err = e2e.appVerifier.IsDeleted() - return -} - -func (e2e *MinioLaunch) verifyPVIsDeleted() (err error) { - if e2e.volVerifier == nil { - err = fmt.Errorf("nil volume verifier: possible error '%s'", e2e.errors[VolumeVerifyFileEI]) - return - } - - // is volume deployed - _, err = e2e.volVerifier.IsDeleted() - return -} - -func FeatureContext(s *godog.Suite) { - e2e := &MinioLaunch{ - errors: map[errorIdentity]error{}, - } - - s.BeforeFeature(e2e.withOperatorVerifier) - s.BeforeFeature(e2e.withApplicationVerifier) - s.BeforeFeature(e2e.withVolumeVerifier) - - s.AfterFeature(e2e.tearDown) - - s.Step(`^I have a kubernetes cluster with volume operator installed$`, e2e.iHaveAKubernetesClusterWithVolumeOperatorInstalled) - s.Step(`^wait for "([^"]*)"$`, e2e.waitFor) - s.Step(`^I launch minio application on volume$`, e2e.iLaunchMinioApplicationOnVolume) - s.Step(`^verify minio application is launched successfully on volume$`, e2e.verifyMinioApplicationIsLaunchedSuccessfullyOnVolume) - s.Step(`^verify PVC is bound$`, e2e.verifyPVCIsBound) - s.Step(`^verify PV is deployed$`, e2e.verifyPVIsDeployed) - s.Step(`^I delete minio instance along with volume$`, e2e.iDeleteMinioInstanceAlongWithVolume) - s.Step(`^verify minio application is deleted$`, e2e.verifyMinioApplicationIsDeleted) - s.Step(`^verify PV is deleted$`, e2e.verifyPVIsDeleted) - s.Step(`^minio application is launched successfully on volume$`, e2e.minioApplicationIsLaunchedSuccessfullyOnVolume) -} diff --git a/apps/minio/tests/deploy_minio/run_litmus_test.yml b/apps/minio/tests/deploy_minio/run_litmus_test.yml deleted file mode 100644 index 33a258835..000000000 --- a/apps/minio/tests/deploy_minio/run_litmus_test.yml +++ /dev/null @@ -1,123 +0,0 @@ ---- -apiVersion: v1 -kind: ConfigMap -metadata: - generateName: odm-operator-verify- - namespace: litmus - labels: - name: odm-operator-verify - test: deploy-minio -data: - config: |- - components: - - kind: serviceaccount - name: openebs-maya-operator - namespace: default - - kind: clusterrole - name: openebs-maya-operator - namespace: default - - kind: clusterrolebinding - name: openebs-maya-operator - namespace: default - - kind: pod - labels: name=maya-apiserver - namespace: default - - kind: service - name: maya-apiserver-service - namespace: default - - kind: pod - labels: name=openebs-provisioner - namespace: default - - kind: sc - name: openebs-standalone ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: odm-application-verify - namespace: litmus - labels: - name: odm-application-verify - test: deploy-minio -data: - config: |- - components: - - kind: service - name: odm-minio - - kind: deploy - name: odm-minio - - kind: pod - labels: app=minio - - kind: pvc - name: odm-minio - alias: pvc ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: odm-volume-verify - namespace: litmus - labels: - name: odm-volume-verify - test: deploy-minio -data: - config: |- - components: - - kind: pod - labels: openebs/controller=jiva-controller - - kind: pod - labels: openebs/replica=jiva-replica ---- -apiVersion: batch/v1 -kind: Job -metadata: - #name: odm-test-the-feature - name: litmus - namespace: litmus - labels: - #name: odm-test-the-feature - name: litmus - test: deploy-minio -spec: - template: - spec: - serviceAccountName: litmus - containers: - - name: odm-test-the-feature - image: openebs/godog-runner:ci - command: ["/bin/sh", "./hack/godog.sh", "./tests/minio/deploy_minio"] - volumeMounts: - - mountPath: /etc/e2e/operator-verify - name: odm-operator-verify - - mountPath: /etc/e2e/application-verify - name: odm-application-verify - - mountPath: /etc/e2e/volume-verify - name: odm-volume-verify - - mountPath: /etc/e2e/application-launch - name: odm-application-launch - volumes: - - name: odm-operator-verify - configMap: - name: odm-operator-verify - items: - - key: config - path: operator-verify.yaml - - name: odm-application-verify - configMap: - name: odm-application-verify - items: - - key: config - path: application-verify.yaml - - name: odm-volume-verify - configMap: - name: odm-volume-verify - items: - - key: config - path: volume-verify.yaml - - name: odm-application-launch - configMap: - name: odm-application-launch - items: - - key: config - path: application-launch.yaml - restartPolicy: Never diff --git a/apps/percona/tests/mysql_data_persistence/README.md b/apps/percona/tests/mysql_data_persistence/README.md deleted file mode 100644 index c63009eb7..000000000 --- a/apps/percona/tests/mysql_data_persistence/README.md +++ /dev/null @@ -1,28 +0,0 @@ -## Checking MySQL data persistence upon forced reschedule (eviction) - -### Objective - -- This test checks MySQL data persistence with a specified storage solution after the application is subjected to -different types of failures, induced via "chaos" operations. Currently, the following chaos types are supported by the test job: - - - APP_POD_KILL/PUMBA : The MySQL pod is terminated abruptly (via SIGKILL) , multiple times, over a perdiod of 120s using Pumba - - APP_POD_EVICT/KUBECTL : The MySQL and other pods on the application node are forcefully evicted by Kubernetes via resource taints - - APP_NODE_DRAIN/KUBECTL : The application node is taken down gracefully via cordon & drain process - -### Considerations - -- This test requires a multi-node Kubernetes cluster - *Note:* The min. count depends on individual storage solution's HA policies. For example OpenEBS needs 3-node cluster -- This test simulates node loss, with original cluster state being reverted to at the end of test -- The application reschedule time is also impacted by the amount of delay between disk attach and mount attempts by Kubernetes - -### Steps to Run - -[Pre-Requisites](https://github.com/openebs/litmus#running-a-specific-test) -- View the following test info on the litmus node at /mnt/mysql_data_persistence : - - - Pod logs at "Logstash__.tar - - Playbook run logs at "hosts/127.0.0.1" - - Result at "result.json" - - diff --git a/apps/percona/tests/mysql_data_persistence/mysql.yml b/apps/percona/tests/mysql_data_persistence/mysql.yml deleted file mode 100644 index 7bbd5473a..000000000 --- a/apps/percona/tests/mysql_data_persistence/mysql.yml +++ /dev/null @@ -1,73 +0,0 @@ ---- -apiVersion: apps/v1beta1 -kind: Deployment -metadata: - name: percona - labels: - name: percona -spec: - replicas: 1 - selector: - matchLabels: - name: percona - template: - metadata: - labels: - name: percona - spec: - affinity: - podAntiAffinity: - requiredDuringSchedulingIgnoredDuringExecution: - - labelSelector: - matchLabels: - name: litmus - topologyKey: kubernetes.io/hostname - containers: - - resources: - limits: - cpu: 0.5 - name: percona - image: percona - imagePullPolicy: IfNotPresent - args: - - "--ignore-db-dir" - - "lost+found" - env: - - name: MYSQL_ROOT_PASSWORD - value: k8sDem0 - ports: - - containerPort: 3306 - name: percona - volumeMounts: - - mountPath: /var/lib/mysql - name: data-vol - volumes: - - name: data-vol - persistentVolumeClaim: - claimName: testClaim ---- -kind: PersistentVolumeClaim -apiVersion: v1 -metadata: - name: testClaim -spec: - storageClassName: testClass - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 5G ---- -apiVersion: v1 -kind: Service -metadata: - name: percona-mysql - labels: - name: percona-mysql -spec: - ports: - - port: 3306 - targetPort: 3306 - selector: - name: percona - diff --git a/apps/percona/tests/mysql_data_persistence/run_litmus_test.yml b/apps/percona/tests/mysql_data_persistence/run_litmus_test.yml deleted file mode 100644 index a3d1e9d2d..000000000 --- a/apps/percona/tests/mysql_data_persistence/run_litmus_test.yml +++ /dev/null @@ -1,32 +0,0 @@ ---- -apiVersion: batch/v1 -kind: Job -metadata: - generateName: litmus-mysql-data-persistence- - namespace: litmus -spec: - template: - metadata: - labels: - name: litmus - spec: - serviceAccountName: litmus - restartPolicy: Never - containers: - - name: ansibletest - image: openebs/ansible-runner:ci - env: - - name: ANSIBLE_STDOUT_CALLBACK - #value: log_plays - value: default - - - name: PROVIDER_STORAGE_CLASS - # Supported values: openebs-standard, local-storage - value: openebs-standard - - - name: CHAOS_TYPE - # Supported values : APP_POD_EVICT/KUBECTL, APP_NODE_DRAIN/KUBECTL, APP_POD_KILL/PUMBA - value: "APP_POD_KILL/PUMBA" - - command: ["/bin/bash"] - args: ["-c", "ansible-playbook ./percona/tests/mysql_data_persistence/test.yml -i /etc/ansible/hosts -v; exit 0"] diff --git a/apps/percona/tests/mysql_data_persistence/test.yml b/apps/percona/tests/mysql_data_persistence/test.yml deleted file mode 100644 index 911762b2c..000000000 --- a/apps/percona/tests/mysql_data_persistence/test.yml +++ /dev/null @@ -1,148 +0,0 @@ -# TODO -# Change pod status checks to container status checks (containerStatuses) -# O/P result - -- hosts: localhost - connection: local - - vars_files: - - test_vars.yml - - tasks: - - block: - - ## VERIFY AVAILABILITY OF SELECTED TEST JOB PARAMS - - - name: Check whether the provider storageclass is applied - shell: kubectl get sc {{ lookup('env','PROVIDER_STORAGE_CLASS') }} - args: - executable: /bin/bash - register: result - - - name: Get the chaos type from test job - set_fact: - chaos_util: "{{ lookup('env','CHAOS_TYPE') }}" - - - name: Verify if chaos type is supported by the test - fail: - msg: "Unsupported chaos type" - when: "chaos_util not in supported_chaos_types" - - ## PRE-CONDITION THE APPLICATION DEPLOYMENT SPECS WITH TEST PARAMS - - - name: Replace the pvc placeholder with test param - replace: - path: "{{ pod_yaml_alias }}" - regexp: "testClaim" - replace: "{{ test_name }}" - - - name: Replace the storageclass placeholder with provider - replace: - path: "{{ pod_yaml_alias }}" - regexp: "testClass" - replace: "{{ lookup('env','PROVIDER_STORAGE_CLASS') }}" - - ## RUN APPLICATION PERSISTENCE TEST - - - name: Deploy percona mysql pod - shell: kubectl apply -f {{ pod_yaml_alias }} -n litmus - args: - executable: /bin/bash - - - name: Confirm mysql pod status is running - shell: > - kubectl get pods -l name=percona -n litmus - --no-headers - args: - executable: /bin/bash - register: result - until: "'percona' and 'Running' in result.stdout" - delay: 60 - retries: 15 - - - name: Obtain name of mysql pod - set_fact: - percona_pod_name: "{{ result.stdout.split()[0] }}" - - - name: Check for successful database init - shell: > - kubectl logs {{ percona_pod_name }} -n litmus - | grep 'ready for connections' | wc -l - args: - executable: /bin/bash - register: result - until: result.stdout == "2" - delay: 10 - retries: 30 - - - name: Create some test data in the mysql database - include_tasks: "/common/utils/mysql_data_persistence.yml" - vars: - status: 'LOAD' - ns: 'litmus' - pod_name: "{{ percona_pod_name }}" - dbuser: 'root' - dbpassword: 'k8sDem0' - dbname: 'tdb' - - - include: /chaoslib/kubectl/pod_evict_by_taint.yaml - app: "{{ percona_pod_name }}" - app_ns: 'litmus' - taint: "node.kubernetes.io/out-of-disk" - when: chaos_util == "APP_POD_EVICT/KUBECTL" - - - include: /chaoslib/kubectl/cordon_drain_node.yaml - app: "{{ percona_pod_name }}" - app_ns: 'litmus' - when: chaos_util == "APP_NODE_DRAIN/KUBECTL" - - - include_tasks: /chaoslib/pumba/pod_failure_by_sigkill.yaml - vars: - action: "killapp" - app_pod: "{{ percona_pod_name }}" - namespace: 'litmus' - when: chaos_util == "APP_POD_KILL/PUMBA" - - - name: Confirm mysql pod status is running - shell: > - kubectl get pods -l name=percona -n litmus - --no-headers - args: - executable: /bin/bash - register: result - until: "'percona' and 'Running' in result.stdout" - delay: 30 - retries: 20 - - - name: Obtain name of mysql pod - set_fact: - percona_pod_name: "{{ result.stdout.split()[0] }}" - - - name: Verify mysql data persistence - include_tasks: "/common/utils/mysql_data_persistence.yml" - vars: - status: 'VERIFY' - ns: 'litmus' - pod_name: "{{ percona_pod_name }}" - dbuser: 'root' - dbpassword: 'k8sDem0' - dbname: 'tdb' - - - - set_fact: - flag: "Pass" - - rescue: - - set_fact: - flag: "Fail" - - always: - - - name: Create results file - lineinfile: - create: yes - state: present - path: '/var/log/ansible/result.json' - line: '{ "Testname" : {{ test_name | to_json }}, "status" : {{ flag | to_json }} }' - - - include: test_cleanup.yml diff --git a/apps/percona/tests/mysql_data_persistence/test_cleanup.yml b/apps/percona/tests/mysql_data_persistence/test_cleanup.yml deleted file mode 100644 index 949c07142..000000000 --- a/apps/percona/tests/mysql_data_persistence/test_cleanup.yml +++ /dev/null @@ -1,43 +0,0 @@ ---- -- name: Get pvc name to verify successful pvc deletion - shell: > - kubectl get pvc {{ test_name }} - -o custom-columns=:spec.volumeName -n litmus - --no-headers - args: - executable: /bin/bash - register: pv - -- name: Delete percona mysql pod - shell: > - source ~/.profile; kubectl delete -f {{ pod_yaml_alias }} - -n litmus - args: - executable: /bin/bash - -- name: Confirm percona pod has been deleted - shell: source ~/.profile; kubectl get pods -n litmus - args: - executable: /bin/bash - register: result - until: "'percona' not in result.stdout" - delay: 30 - retries: 12 - -- block: - - name: Confirm pvc pod has been deleted - shell: > - kubectl get pods -n litmus | grep {{ pv.stdout }} - args: - executable: /bin/bash - register: result - failed_when: "'pvc' and 'Running' in result.stdout" - delay: 30 - retries: 12 - when: "'openebs-standard' in lookup('env','PROVIDER_STORAGE_CLASS')" - -- include_tasks: /chaoslib/pumba/pod_failure_by_sigkill.yaml - vars: - action: "deletepumba" - namespace: 'litmus' - when: chaos_util == "APP_POD_KILL/PUMBA" diff --git a/apps/percona/tests/mysql_data_persistence/test_vars.yml b/apps/percona/tests/mysql_data_persistence/test_vars.yml deleted file mode 100644 index e6233fce6..000000000 --- a/apps/percona/tests/mysql_data_persistence/test_vars.yml +++ /dev/null @@ -1,11 +0,0 @@ ---- -## TEST-SPECIFIC PARAMS - -test_name: mysql-data-persistence -pod_yaml_alias: mysql.yml -supported_chaos_types: - - APP_POD_EVICT/KUBECTL - - APP_NODE_DRAIN/KUBECTL - - APP_POD_KILL/PUMBA - - diff --git a/apps/percona/tests/mysql_storage_benchmark/README.md b/apps/percona/tests/mysql_storage_benchmark/README.md deleted file mode 100644 index 4b0529361..000000000 --- a/apps/percona/tests/mysql_storage_benchmark/README.md +++ /dev/null @@ -1,54 +0,0 @@ -This is a sample test to illustrate/templatize how scenarios can be coded using ansible in Litmus. - -### Understanding the ansible-based litmus test - -- Objective: Obtain a TPC-C benchmark against a MySQL (percona) database created on specified kubernetes storage solution - -- Components: The ansible-based litmus test has the following pieces:- - - - The test code itself - constructed as playbooks (`test.yaml`). Most steps are simple kubectl commands. - - - The auxiliary taskfiles invoked in the main playbook - such as `test_vars.yaml`, `test_cleanup.yaml` - - Note: Tests may also include additional taskfile such as `test_prerequisites.yaml` - - - Deployment/statefulset specification used in the test scenario (`mysql.yaml`). By default, this consists of a placeholder -for the storageClass which will be replaced with the desired provider as part of test execution - - - Test kubernetes job: The actual "test artifact" which is deployed to run the litmus test (`run_litmus_test.yaml`). -This job runs the `ansible-runner` container which executes the aforementioned test code with a `logger sidecar`. - - Notes: - - - By default, the OpenEBS storage class is passed as an ENV variable to the `ansible_runner` container. Replace with SC of -desired storage provider. However, ensure the provider is already setup on the cluster - - - Update the application node selector ENV variable to schedule the app on node with desired disk resources. In case of -local persistent volumes, ensure that the node selected also has the PV created. - - - The test folder may also contain several `setup_*.yaml` config maps as necessary inputs to the test job - -It is rcommended that the naming conventions of the test playbooks, setup config maps & test kubernetes jobs are maintained -as described above in order to aid batch runs of all the litmus tests by the executor frameworks - -### Running the test - -[Pre-Requisites](https://github.com/openebs/litmus#running-a-specific-test) - -The test can be run using the following command: - -`kubectl create -f run_litmus_test.yaml` - -### Viewing test results & logs - -The test is completed upon the kubernetes job completion. at the end of which the `ansible_runner` & `logger pods` are deleted. - -Currently, the test results and logs are available in the `/mnt` folder of the node in which the job is scheduled. These include -the test result, pod logs, playbook logs & node's systemd (kubelet) logs if available. - - -### Considerations - -All the litmus tests harness the enormous potential of `kubectl` which we believe is more than just a CLI tool - - diff --git a/apps/percona/tests/mysql_storage_benchmark/mysql.yml b/apps/percona/tests/mysql_storage_benchmark/mysql.yml deleted file mode 100644 index d38bcee34..000000000 --- a/apps/percona/tests/mysql_storage_benchmark/mysql.yml +++ /dev/null @@ -1,74 +0,0 @@ -############################################################################## -# This YAML runs a TPC-C workload against a percona database container # -# Obtain the TransactionsPerMinuteCount (TpmC) using the given command # -# # -# kubectl logs percona -c tpcc-bench | awk '/TpmC/ && !/^/{print $0}' # -# # -############################################################################## ---- -apiVersion: v1 -kind: Pod -metadata: - name: percona - labels: - name: percona -spec: - - ## Ensures the pod enters "completed" state after - ## the tpcc-workload test duration - restartPolicy: Never - - ## Ensures the pod is scheduled on desired node - nodeSelector: - kubernetes.io/hostname: testNode - - containers: - - # Runs latest percona database container - - name: percona - image: openebs/tests-custom-percona:latest - args: - - "--ignore-db-dir" - - "lost+found" - env: - - name: MYSQL_ROOT_PASSWORD - value: k8sDem0 - ports: - - containerPort: 3306 - name: percona - volumeMounts: - - mountPath: /var/lib/mysql - name: mysql-path - - # Runs a sample tpc-c workload sidecar container - # Wait for 90s to wait for MySQL to accept connections - - name: tpcc-bench - image: openebs/tests-tpcc-client - command: ["/bin/bash"] - args: ["-c", "./tpcc-runner.sh 127.0.0.1 tpcc.conf; exit 0"] - volumeMounts: - - name: tpcc-configmap - mountPath: /tpcc-mysql/tpcc.conf - subPath: tpcc.conf - tty: true - - volumes: - - name: mysql-path - persistentVolumeClaim: - claimName: testClaim - - name: tpcc-configmap - configMap: - name: tpcc-config - ---- -kind: PersistentVolumeClaim -apiVersion: v1 -metadata: - name: testClaim -spec: - storageClassName: testClass - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 5G diff --git a/apps/percona/tests/mysql_storage_benchmark/run_litmus_test.yml b/apps/percona/tests/mysql_storage_benchmark/run_litmus_test.yml deleted file mode 100644 index 9969f0f69..000000000 --- a/apps/percona/tests/mysql_storage_benchmark/run_litmus_test.yml +++ /dev/null @@ -1,31 +0,0 @@ ---- -apiVersion: batch/v1 -kind: Job -metadata: - generateName: litmus-mysql-storage-benchmark- - namespace: litmus -spec: - template: - metadata: - labels: - name: litmus - spec: - serviceAccountName: litmus - restartPolicy: Never - containers: - - name: ansibletest - image: openebs/ansible-runner:ci - env: - - name: ANSIBLE_STDOUT_CALLBACK - #value: log_plays - value: default - - - name: PROVIDER_STORAGE_CLASS - value: openebs-standard - #value: local-storage - - - name: APP_NODE_SELECTOR - value: kubeminion-01 - - command: ["/bin/bash"] - args: ["-c", "ansible-playbook ./percona/tests/mysql_storage_benchmark/test.yml -i /etc/ansible/hosts -v; exit 0"] diff --git a/apps/percona/tests/mysql_storage_benchmark/test.yml b/apps/percona/tests/mysql_storage_benchmark/test.yml deleted file mode 100644 index 6ae532c44..000000000 --- a/apps/percona/tests/mysql_storage_benchmark/test.yml +++ /dev/null @@ -1,131 +0,0 @@ -# TODO -# Change pod status checks to container status checks (containerStatuses) -# O/P result - -- hosts: localhost - connection: local - - vars_files: - - test_vars.yml - - tasks: - - block: - - ## VERIFY AVAILABILITY OF SELECTED STORAGE CLASS - - - name: Check whether the provider storageclass is applied - shell: kubectl get sc {{ lookup('env','PROVIDER_STORAGE_CLASS') }} - args: - executable: /bin/bash - register: result - - ## PERFORM PROVIDER SPECIFIC CHECKS FOR PRE-REQUISITES - - - block: - - name: OpenEBS - Check whether operator pods are running - shell: > - kubectl get pod -l name={{ item }} --no-headers - -o custom-columns=:status.phase --all-namespaces - args: - executable: /bin/bash - register: result - until: "result.stdout == 'Running'" - delay: 10 - retries: 12 - with_items: "{{ openebs_operator }}" - when: "'openebs-standard' in lookup('env','PROVIDER_STORAGE_CLASS')" - - - block: - - name: Local PV - Check whether the local volume is created - shell: > - kubectl get pv {{ local_pv_name }} --no-headers - -o custom-columns=:spec.local - args: - executable: /bin/bash - register: local_volume_path - when: "'local-storage' in lookup('env','PROVIDER_STORAGE_CLASS')" - - ## PRE-CONDITION THE APPLICATION DEPLOYMENT SPECS WITH TEST PARAMS - - - name: Replace the app node placeholder with perf-intensive node - replace: - path: "{{ pod_yaml_alias }}" - regexp: "testNode" - replace: "{{ lookup('env','APP_NODE_SELECTOR') }}" - - - name: Replace the pvc placeholder with test param - replace: - path: "{{ pod_yaml_alias }}" - regexp: "testClaim" - replace: "{{ test_name }}" - - - name: Replace the storageclass placeholder with provider - replace: - path: "{{ pod_yaml_alias }}" - regexp: "testClass" - replace: "{{ lookup('env','PROVIDER_STORAGE_CLASS') }}" - - ## RUN APPLICATION WORKLOAD TEST - - - name: Display TPCC parameters - shell: cat tpcc.conf - register: result - - - name: Obtain TPCC run duration from config - set_fact: - mysql_load_duration: "{{ (result.stdout | from_json).run_duration }}" - - - name: Create config map for TPCC properties - shell: > - kubectl create configmap tpcc-config --from-file=tpcc.conf - -n litmus - args: - executable: /bin/bash - - - name: Deploy percona mysql pod - shell: kubectl apply -f {{ pod_yaml_alias }} -n litmus - args: - executable: /bin/bash - - - name: Confirm pod status is running - shell: > - kubectl get pods -l name=percona -n litmus - --no-headers -o custom-columns=:status.phase - args: - executable: /bin/bash - register: result - until: "result.stdout == 'Running'" - delay: 120 - retries: 15 - - - name: Wait for I/O completion - wait_for: - timeout: "{{ mysql_load_duration }}" - - - name: Confirm pod status is completed - shell: > - kubectl get pods -l name=percona -n litmus - --no-headers - args: - executable: /bin/bash - register: result - until: "'Completed' in result.stdout" - delay: 120 - retries: 15 - - - set_fact: - flag: "Pass" - - rescue: - - set_fact: - flag: "Fail" - - always: - - name: Create results file - lineinfile: - create: yes - state: present - path: '/var/log/ansible/result.json' - line: '{ "Testname" : {{ test_name | to_json }}, "status" : {{ flag | to_json }} }' - - - include: test_cleanup.yaml diff --git a/apps/percona/tests/mysql_storage_benchmark/test_cleanup.yml b/apps/percona/tests/mysql_storage_benchmark/test_cleanup.yml deleted file mode 100644 index b072b448e..000000000 --- a/apps/percona/tests/mysql_storage_benchmark/test_cleanup.yml +++ /dev/null @@ -1,51 +0,0 @@ ---- -- name: Get pvc name to verify successful pvc deletion - shell: > - kubectl get pvc {{ test_name }} - -o custom-columns=:spec.volumeName -n litmus - --no-headers - args: - executable: /bin/bash - register: pv - -- name: Delete percona mysql pod - shell: > - source ~/.profile; kubectl delete -f {{ pod_yaml_alias }} - -n litmus - args: - executable: /bin/bash - -- name: Delete the TPCC config map - shell: kubectl delete cm tpcc-config -n litmus - args: - executable: /bin/bash - -- name: Confirm percona pod has been deleted - shell: source ~/.profile; kubectl get pods -n litmus - args: - executable: /bin/bash - register: result - until: "'percona' not in result.stdout" - delay: 30 - retries: 12 - -- block: - - name: Confirm pvc pod has been deleted - shell: > - kubectl get pods -n litmus | grep {{ pv.stdout }} - args: - executable: /bin/bash - register: result - failed_when: "'pvc' and 'Running' in result.stdout" - delay: 30 - retries: 12 - when: "'openebs-standard' in lookup('env','PROVIDER_STORAGE_CLASS')" - -- block: - - name: Remove the local persistent volume - shell: kubectl delete pv {{ pv.stdout }} - args: - executable: /bin/bash - register: result - failed_when: "'persistentvolume' and 'deleted' not in result.stdout" - when: "'local-storage' in lookup('env','PROVIDER_STORAGE_CLASS')" diff --git a/apps/percona/tests/mysql_storage_benchmark/test_vars.yml b/apps/percona/tests/mysql_storage_benchmark/test_vars.yml deleted file mode 100644 index 465b8dc9a..000000000 --- a/apps/percona/tests/mysql_storage_benchmark/test_vars.yml +++ /dev/null @@ -1,17 +0,0 @@ ---- -## TEST-SPECIFIC PARAMS - -test_name: mysql-benchmark -pod_yaml_alias: mysql.yml - -## PROVIDER-SPECIFIC PARARMS - -# OpenEBS - -openebs_operator: - - maya-apiserver - - openebs-provisioner - -# Local Volume - -local_pv_name: local-pv diff --git a/apps/percona/tests/mysql_storage_benchmark/tpcc.conf b/apps/percona/tests/mysql_storage_benchmark/tpcc.conf deleted file mode 100644 index eef9163c8..000000000 --- a/apps/percona/tests/mysql_storage_benchmark/tpcc.conf +++ /dev/null @@ -1,9 +0,0 @@ -{ - "db_user": "root", - "db_password": "k8sDem0", - "warehouses": "1", - "connections": "16", - "warmup_period": "10", - "run_duration": "120", - "interval": "2" -} diff --git a/docs/litmus_deep_dive.md b/docs/litmus_deep_dive.md deleted file mode 100644 index 06801bb25..000000000 --- a/docs/litmus_deep_dive.md +++ /dev/null @@ -1,15 +0,0 @@ -# Litmus Deep Dive - -Litmus tests range from initial setup and configuration validation to deploying and running workloads under various conditions and failures. - -Litmus comprises the following major components: -- **Deployments** that help in setting up different types of Kubernetes Clusters like on-premise, cloud, OpenShift, etc. The default is that the deployment scripts to provision and configure OpenEBS storage, however, these deployments are easily extended to support other storage. -- **Framework** for test execution that includes: - * Defining and running test suites - * Capturing logs and generating reports about the test runs - * Fault/Error injection tools that help to perform chaos tests - * Examples that demonstrate how to integrate these test pipelines with Slack notifications -- **Test modules** that can be triggered from within a Kubernetes cluster. Think of these as containerized tests. For instance, the **_mysql-client_** can be launched as a pod to validate the MySQL resiliency while the underlying nodes and the connected storage are subjected to chaos engineering. -- **Tests** that themselves are written in easy to understand formats, either in plain English (thanks Godog!) or in Ansible Playbooks. These tests primarily interact with the Kubernetes cluster via **_kubectl_** making them highly portable. - -Litmus can be used to test a given workload in a variety of Kubernetes environments, for example, a developer minikube or a GKE cluster with a specific storage solution or as a part of a full-fledged CI setup. diff --git a/docs/running_test_suite.md b/docs/running_test_suite.md deleted file mode 100644 index f0a75e444..000000000 --- a/docs/running_test_suite.md +++ /dev/null @@ -1,24 +0,0 @@ -# Running a Complete Test Suite - -The Litmus test suite can be run on a Kubernetes cluster using an Ansible-based executor framework. -This involves: - -- Setting up Ansible on any Linux machine (Ansible test harness), with SSH access to the Kubernetes cluster -- Generating the ansible inventory file with host information (master/control node & hosts) -- Modifying a global variables file to: - - - Set Provider and storage class - - Select test Category (call or subset) - - Enable/Disable some services like log collection, notifications etc.., - -Follow the executor/README for detailed instructions on how to perform the above steps. Once these pre-requisites -have been met, execute the following on the Ansible test harness: - -``` -./litmus/executor/ansible/run-litmus.sh -``` - -The above script will verify that it has all the details required for it to proceed and provides you with -test task execution status. - -*Litmus may take a while to show a reaction as it puts the system through rigorous scrutiny!* diff --git a/executor/README.md b/executor/README.md deleted file mode 100644 index cc0316d2a..000000000 --- a/executor/README.md +++ /dev/null @@ -1,5 +0,0 @@ -This folder will contain the code that can help execute all or a subset of tests. There can be many -different ways of executing a series of tests, for example, Ansible is one of the ways to execute the tests. - -The executor helps with performing batch execution of Litmus tests with ability to select/skip tests & -consolidate results or for dashboarding purposes. diff --git a/executor/ansible/README.md b/executor/ansible/README.md deleted file mode 100644 index c6c732a92..000000000 --- a/executor/ansible/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Litmus Executer - Litmus executor runs the litmusbook sequentially as order is defined in all.csv file. -**In order to run executer perform the following steps:** -- Update the **all.csv** present in ```/executer/ansible/``` in this manner: **[test-type]:[test-path]:[litmus-job-label]** -**Example:** -``` -deployers:/apps/percona/deployers/run_litmus_test.yml:percona-deployment-litmus -loadgen:/apps/percona/workload/run_litmus_test.yml:percona-loadgen-litmus -chaos:apps/percona/chaos/openebs_replica_network_delay:openebs-replica-network-delay-litmus -``` -- Then simply run the bash file **execute.sh** present in ```/executer/ansible/```. -**Example:** -```bash execute.sh``` - -# NOTE -**Following things should be considered before running the executer:** -1. No spaces are allowed in all.csv file. -2. The label for litmus job should be like:**[test-name]-litmus**. diff --git a/executor/ansible/all.csv b/executor/ansible/all.csv deleted file mode 100644 index c4c361879..000000000 --- a/executor/ansible/all.csv +++ /dev/null @@ -1,4 +0,0 @@ -deployers:/apps/percona/deployers/run_litmus_test.yml:percona-deployment-litmus -loadgen:/apps/percona/workload/run_litmus_test.yml:percona-loadgen-litmus -chaos:apps/percona/chaos/openebs_replica_network_delay:openebs-replica-network-delay-litmus - diff --git a/executor/ansible/ansible.cfg b/executor/ansible/ansible.cfg deleted file mode 100644 index 3ab7a0418..000000000 --- a/executor/ansible/ansible.cfg +++ /dev/null @@ -1,363 +0,0 @@ -# config file for ansible -- http://ansible.com/ -# ============================================== - -# nearly all parameters can be overridden in ansible-playbook -# or with command line flags. ansible will read ANSIBLE_CONFIG, -# ansible.cfg in the current working directory, .ansible.cfg in -# the home directory or /etc/ansible/ansible.cfg, whichever it -# finds first - -[defaults] - -# some basic default values... - -inventory = ./inventory/hosts -callback_plugins = ./plugins/callback -stdout_callback = openebs -#library = /usr/share/my_modules/ -#remote_tmp = ~/.ansible/tmp -#local_tmp = ~/.ansible/tmp -#forks = 5 -#poll_interval = 15 -#sudo_user = root -#ask_sudo_pass = True -#ask_pass = True -#transport = smart -#remote_port = 22 -#module_lang = C -#module_set_locale = False - -# plays will gather facts by default, which contain information about -# the remote system. -# -# smart - gather by default, but don't regather if already gathered -# implicit - gather by default, turn off with gather_facts: False -# explicit - do not gather by default, must say gather_facts: True -#gathering = implicit - -# by default retrieve all facts subsets -# all - gather all subsets -# network - gather min and network facts -# hardware - gather hardware facts (longest facts to retrieve) -# virtual - gather min and virtual facts -# facter - import facts from facter -# ohai - import facts from ohai -# You can combine them using comma (ex: network,virtual) -# You can negate them using ! (ex: !hardware,!facter,!ohai) -# A minimal set of facts is always gathered. -#gather_subset = all - -# some hardware related facts are collected -# with a maximum timeout of 10 seconds. This -# option lets you increase or decrease that -# timeout to something more suitable for the -# environment. -# gather_timeout = 10 - -# additional paths to search for roles in, colon separated -roles_path = ./roles/ - -# uncomment this to disable SSH key host checking -#host_key_checking = False - -# change the default callback -#stdout_callback = skippy -# enable additional callbacks -#callback_whitelist = timer, mail - -# Determine whether includes in tasks and handlers are "static" by -# default. As of 2.0, includes are dynamic by default. Setting these -# values to True will make includes behave more like they did in the -# 1.x versions. -#task_includes_static = True -#handler_includes_static = True - -# Controls if a missing handler for a notification event is an error or a warning -#error_on_missing_handler = True - -# change this for alternative sudo implementations -#sudo_exe = sudo - -# What flags to pass to sudo -# WARNING: leaving out the defaults might create unexpected behaviours -#sudo_flags = -H -S -n - -# SSH timeout -#timeout = 10 - -# default user to use for playbooks if user is not specified -# (/usr/bin/ansible will use current user as default) -#remote_user = root - -# logging is off by default unless this path is defined -# if so defined, consider logrotate -#log_path = /var/log/ansible.log - -# default module name for /usr/bin/ansible -#module_name = command - -# use this shell for commands executed under sudo -# you may need to change this to bin/bash in rare instances -# if sudo is constrained -#executable = /bin/sh - -# if inventory variables overlap, does the higher precedence one win -# or are hash values merged together? The default is 'replace' but -# this can also be set to 'merge'. -#hash_behaviour = replace - -# by default, variables from roles will be visible in the global variable -# scope. To prevent this, the following option can be enabled, and only -# tasks and handlers within the role will see the variables there -#private_role_vars = yes - -# list any Jinja2 extensions to enable here: -#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n - -# if set, always use this private key file for authentication, same as -# if passing --private-key to ansible or ansible-playbook -#private_key_file = /path/to/file - -# If set, configures the path to the Vault password file as an alternative to -# specifying --vault-password-file on the command line. -#vault_password_file = /path/to/vault_password_file - -# format of string {{ ansible_managed }} available within Jinja2 -# templates indicates to users editing templates files will be replaced. -# replacing {file}, {host} and {uid} and strftime codes with proper values. -#ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host} -# {file}, {host}, {uid}, and the timestamp can all interfere with idempotence -# in some situations so the default is a static string: -#ansible_managed = Ansible managed - -# by default, ansible-playbook will display "Skipping [host]" if it determines a task -# should not be run on a host. Set this to "False" if you don't want to see these "Skipping" -# messages. NOTE: the task header will still be shown regardless of whether or not the -# task is skipped. -#display_skipped_hosts = True - -# by default, if a task in a playbook does not include a name: field then -# ansible-playbook will construct a header that includes the task's action but -# not the task's args. This is a security feature because ansible cannot know -# if the *module* considers an argument to be no_log at the time that the -# header is printed. If your environment doesn't have a problem securing -# stdout from ansible-playbook (or you have manually specified no_log in your -# playbook on all of the tasks where you have secret information) then you can -# safely set this to True to get more informative messages. -#display_args_to_stdout = False - -# by default (as of 1.3), Ansible will raise errors when attempting to dereference -# Jinja2 variables that are not set in templates or action lines. Uncomment this line -# to revert the behavior to pre-1.3. -#error_on_undefined_vars = False - -# by default (as of 1.6), Ansible may display warnings based on the configuration of the -# system running ansible itself. This may include warnings about 3rd party packages or -# other conditions that should be resolved if possible. -# to disable these warnings, set the following value to False: -#system_warnings = True - -# by default (as of 1.4), Ansible may display deprecation warnings for language -# features that should no longer be used and will be removed in future versions. -# to disable these warnings, set the following value to False: -#deprecation_warnings = True - -# (as of 1.8), Ansible can optionally warn when usage of the shell and -# command module appear to be simplified by using a default Ansible module -# instead. These warnings can be silenced by adjusting the following -# setting or adding warn=yes or warn=no to the end of the command line -# parameter string. This will for example suggest using the git module -# instead of shelling out to the git command. -# command_warnings = False - - -# set plugin path directories here, separate with colons -#action_plugins = /usr/share/ansible/plugins/action -#cache_plugins = /usr/share/ansible/plugins/cache -#callback_plugins = /usr/share/ansible/plugins/callback -#connection_plugins = /usr/share/ansible/plugins/connection -#lookup_plugins = /usr/share/ansible/plugins/lookup -#inventory_plugins = /usr/share/ansible/plugins/inventory -#vars_plugins = /usr/share/ansible/plugins/vars -#filter_plugins = /usr/share/ansible/plugins/filter -#test_plugins = /usr/share/ansible/plugins/test -#strategy_plugins = /usr/share/ansible/plugins/strategy - -# by default callbacks are not loaded for /bin/ansible, enable this if you -# want, for example, a notification or logging callback to also apply to -# /bin/ansible runs -#bin_ansible_callbacks = False - - -# don't like cows? that's unfortunate. -# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1 -#nocows = 1 - -# set which cowsay stencil you'd like to use by default. When set to 'random', -# a random stencil will be selected for each task. The selection will be filtered -# against the `cow_whitelist` option below. -#cow_selection = default -#cow_selection = random - -# when using the 'random' option for cowsay, stencils will be restricted to this list. -# it should be formatted as a comma-separated list with no spaces between names. -# NOTE: line continuations here are for formatting purposes only, as the INI parser -# in python does not support them. -#cow_whitelist=bud-frogs,bunny,cheese,daemon,default,dragon,elephant-in-snake,elephant,eyes,\ -# hellokitty,kitty,luke-koala,meow,milk,moofasa,moose,ren,sheep,small,stegosaurus,\ -# stimpy,supermilker,three-eyes,turkey,turtle,tux,udder,vader-koala,vader,www - -# don't like colors either? -# set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1 -#nocolor = 1 - -# if set to a persistent type (not 'memory', for example 'redis') fact values -# from previous runs in Ansible will be stored. This may be useful when -# wanting to use, for example, IP information from one group of servers -# without having to talk to them in the same playbook run to get their -# current IP information. -#fact_caching = memory - - -# retry files -# When a playbook fails by default a .retry file will be created in ~/ -# You can disable this feature by setting retry_files_enabled to False -# and you can change the location of the files by setting retry_files_save_path - -retry_files_enabled = False -#retry_files_save_path = ~/.ansible-retry - -# squash actions -# Ansible can optimise actions that call modules with list parameters -# when looping. Instead of calling the module once per with_ item, the -# module is called once with all items at once. Currently this only works -# under limited circumstances, and only with parameters named 'name'. -#squash_actions = apk,apt,dnf,homebrew,package,pacman,pkgng,yum,zypper - -# prevents logging of task data, off by default -#no_log = False - -# prevents logging of tasks, but only on the targets, data is still logged on the master/controller -#no_target_syslog = False - -# controls whether Ansible will raise an error or warning if a task has no -# choice but to create world readable temporary files to execute a module on -# the remote machine. This option is False by default for security. Users may -# turn this on to have behaviour more like Ansible prior to 2.1.x. See -# https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user -# for more secure ways to fix this than enabling this option. -#allow_world_readable_tmpfiles = False - -# controls the compression level of variables sent to -# worker processes. At the default of 0, no compression -# is used. This value must be an integer from 0 to 9. -#var_compression_level = 9 - -# controls what compression method is used for new-style ansible modules when -# they are sent to the remote system. The compression types depend on having -# support compiled into both the controller's python and the client's python. -# The names should match with the python Zipfile compression types: -# * ZIP_STORED (no compression. available everywhere) -# * ZIP_DEFLATED (uses zlib, the default) -# These values may be set per host via the ansible_module_compression inventory -# variable -#module_compression = 'ZIP_DEFLATED' - -# This controls the cutoff point (in bytes) on --diff for files -# set to 0 for unlimited (RAM may suffer!). -#max_diff_size = 1048576 - -[privilege_escalation] -#become=True -#become_method=sudo -#become_user=root -#become_ask_pass=False - -[paramiko_connection] - -# uncomment this line to cause the paramiko connection plugin to not record new host -# keys encountered. Increases performance on new host additions. Setting works independently of the -# host key checking setting above. -#record_host_keys=False - -# by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this -# line to disable this behaviour. -#pty=False - -[ssh_connection] - -# ssh arguments to use -# Leaving off ControlPersist will result in poor performance, so use -# paramiko on older platforms rather than removing it, -C controls compression use -#ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s - -# The path to use for the ControlPath sockets. This defaults to -# "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with -# very long hostnames or very long path names (caused by long user names or -# deeply nested home directories) this can exceed the character limit on -# file socket names (108 characters for most platforms). In that case, you -# may wish to shorten the string below. -# -# Example: -# control_path = %(directory)s/%%h-%%r -#control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r - -# Enabling pipelining reduces the number of SSH operations required to -# execute a module on the remote server. This can result in a significant -# performance improvement when enabled, however when using "sudo:" you must -# first disable 'requiretty' in /etc/sudoers -# -# By default, this option is disabled to preserve compatibility with -# sudoers configurations that have requiretty (the default on many distros). -# -#pipelining = False - -# Control the mechanism for transferring files -# * smart = try sftp and then try scp [default] -# * True = use scp only -# * False = use sftp only -#scp_if_ssh = smart - -# if False, sftp will not use batch mode to transfer files. This may cause some -# types of file transfer failures impossible to catch however, and should -# only be disabled if your sftp version has problems with batch mode -#sftp_batch_mode = False - -[accelerate] -#accelerate_port = 5099 -#accelerate_timeout = 30 -#accelerate_connect_timeout = 5.0 - -# The daemon timeout is measured in minutes. This time is measured -# from the last activity to the accelerate daemon. -#accelerate_daemon_timeout = 30 - -# If set to yes, accelerate_multi_key will allow multiple -# private keys to be uploaded to it, though each user must -# have access to the system via SSH to add a new key. The default -# is "no". -#accelerate_multi_key = yes - -[selinux] -# file systems that require special treatment when dealing with security context -# the default behaviour that copies the existing context or uses the user default -# needs to be changed to use the file system dependent context. -#special_context_filesystems=nfs,vboxsf,fuse,ramfs - -# Set this to yes to allow libvirt_lxc connections to work without SELinux. -#libvirt_lxc_noseclabel = yes - -[colors] -#highlight = white -#verbose = blue -#warn = bright purple -#error = red -#debug = dark gray -#deprecate = purple -#skip = cyan -#unreachable = red -#ok = green -#changed = yellow -#diff_add = green -#diff_remove = red -#diff_lines = cyan diff --git a/executor/ansible/execute.sh b/executor/ansible/execute.sh deleted file mode 100644 index f0a963215..000000000 --- a/executor/ansible/execute.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash -file=./all.csv -var=0; - -update_file() -{ -while IFS=':' read -r col1 col2 col3; do - echo "$col2:$col3" - test="${col3%-*}" - ansible-playbook ./utils/execute.yml -e "LABEL="$col3" PATH="$col2" TYPE="$col1" TESTNAME="$test"" -vv -done < $file -} - -if [ ! -e $file ]; then - echo Unable to find CSV file -else - touch result.csv - update_file - var="$(cat result.csv | grep Pass | wc -l)" - echo "Number of test Passed: $var" >> result.csv - cat result.csv - rm result.csv -fi diff --git a/executor/ansible/inventory/group_vars/all.yml b/executor/ansible/inventory/group_vars/all.yml deleted file mode 100644 index 012d3197d..000000000 --- a/executor/ansible/inventory/group_vars/all.yml +++ /dev/null @@ -1,21 +0,0 @@ ---- -######################################### -# Ansible Runtime Specifications # -######################################### - -#Provider storage class -#Supported providers(openebs, local-pv) -storage_class: openebs-standard - -#Option to enable slack notifications to specified channel -#Accepted entries(true, false): default:true -slack_notify: true - -#Select the desired application -#Supported applications(percona, tba, all) -application: - - percona - - fio - -litmus_dir: "{{ ansible_env.HOME }}/git/litmus" - diff --git a/executor/ansible/inventory/host_vars/localhost.yml b/executor/ansible/inventory/host_vars/localhost.yml deleted file mode 100644 index e2edbbe98..000000000 --- a/executor/ansible/inventory/host_vars/localhost.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- -ansible_connection: local -ansible_become_pass: "{{ lookup('env','LOCAL_USER_PASSWORD') }}" diff --git a/executor/ansible/inventory/hosts b/executor/ansible/inventory/hosts deleted file mode 100644 index 36a16bae5..000000000 --- a/executor/ansible/inventory/hosts +++ /dev/null @@ -1,2 +0,0 @@ -localhost ansible_connection=local - ansible_become_pass="{{ lookup('env','LOCAL_USER_PASSWORD') }}" diff --git a/executor/ansible/litmus_playbook.yml b/executor/ansible/litmus_playbook.yml deleted file mode 100644 index 29785e4cc..000000000 --- a/executor/ansible/litmus_playbook.yml +++ /dev/null @@ -1,24 +0,0 @@ ---- -- hosts: localhost - gather_facts: yes - - vars: - testfile: "{{ playbook_dir }}/tests.out" - - tasks: - - - name: Clear existing test lists - file: - path: "{{ testfile }}" - state: absent - - - name: Obtain list of Kubernetes test job specifications - include: utils/getFiles.yaml - dir="{{ litmus_dir }}/apps/{{ item }}/tests" - expr="^run_litmus" - tfile="{{ testfile }}" - with_items: "{{ application }}" - - - name: Run the Kubernetes test jobs on selected storage providers - include: utils/runTest.yaml - with_lines: cat {{ testfile }} diff --git a/executor/ansible/plugins/callback/README.md b/executor/ansible/plugins/callback/README.md deleted file mode 100644 index 385643927..000000000 --- a/executor/ansible/plugins/callback/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Ansible Plugins ------------------ - -Contains custom plugins that can be integrated into Ansible. Currently holds the callback plugin which has been modified -to hide/suppress certain messages during failed retries in a loop-execution. - diff --git a/executor/ansible/plugins/callback/actionable.py b/executor/ansible/plugins/callback/actionable.py deleted file mode 100644 index 5ddcdc5a5..000000000 --- a/executor/ansible/plugins/callback/actionable.py +++ /dev/null @@ -1,94 +0,0 @@ -# (c) 2015, Andrew Gaffney -# (c) 2017 Ansible Project -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - -# Make coding more python3-ish -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - -DOCUMENTATION = ''' - callback: actionable - type: stdout - short_description: shows only items that need attention - description: - - Use this callback when you dont care about OK nor Skipped. - - This callback suppresses any non Failed or Changed status. - version_added: "2.1" - extends_documentation_fragment: - - default_callback - requirements: - - set as stdout callback in configuration -''' - -from ansible.plugins.callback.default import CallbackModule as CallbackModule_default - - -class CallbackModule(CallbackModule_default): - - CALLBACK_VERSION = 2.0 - CALLBACK_TYPE = 'stdout' - CALLBACK_NAME = 'actionable' - - def __init__(self): - self.super_ref = super(CallbackModule, self) - self.super_ref.__init__() - self.last_task = None - self.shown_title = False - - def v2_playbook_on_handler_task_start(self, task): - self.super_ref.v2_playbook_on_handler_task_start(task) - self.shown_title = True - - def v2_playbook_on_task_start(self, task, is_conditional): - self.last_task = task - self.shown_title = False - - def display_task_banner(self): - if not self.shown_title: - self.super_ref.v2_playbook_on_task_start(self.last_task, None) - self.shown_title = True - - def v2_runner_on_failed(self, result, ignore_errors=False): - self.display_task_banner() - self.super_ref.v2_runner_on_failed(result, ignore_errors) - - def v2_runner_on_ok(self, result): - if result._result.get('changed', False): - self.display_task_banner() - #self.super_ref.v2_runner_on_ok(result) - - def v2_runner_on_unreachable(self, result): - self.display_task_banner() - self.super_ref.v2_runner_on_unreachable(result) - - def v2_runner_on_skipped(self, result): - pass - - def v2_playbook_on_include(self, included_file): - pass - - def v2_runner_item_on_ok(self, result): - if result._result.get('changed', False): - self.display_task_banner() - #self.super_ref.v2_runner_item_on_ok(result) - - def v2_runner_item_on_skipped(self, result): - pass - - def v2_runner_item_on_failed(self, result): - self.display_task_banner() - self.super_ref.v2_runner_item_on_failed(result) - - def v2_runner_retry(self, result): - task_name = result.task_name or result._task - final_result = result._result['retries'] - result._result['attempts'] - msg = "FAILED - RETRYING: %s (%d retries left)." % (task_name, - final_result) - display_verbosity = self._display.verbosity - required_result = '_ansible_verbose_always' - if (display_verbosity > 2 or required_result in result._result): - if required_result not in result._result: - msg += "Result was: %s" % self._dump_results(result._result) - self._display.v('%s' % (msg)) - - diff --git a/executor/ansible/plugins/callback/log_ara.py b/executor/ansible/plugins/callback/log_ara.py deleted file mode 100644 index 95b9154d1..000000000 --- a/executor/ansible/plugins/callback/log_ara.py +++ /dev/null @@ -1,372 +0,0 @@ -# Copyright (c) 2017 Red Hat, Inc. -# -# This file is part of ARA: Ansible Run Analysis. -# -# ARA is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ARA is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ARA. If not, see . - -from __future__ import (absolute_import, division, print_function) - -import flask -import itertools -import logging -import os - -from ansible import __version__ as ansible_version -from ansible.plugins.callback import CallbackBase -from ara import models -from ara.models import db -from ara.webapp import create_app -from datetime import datetime -from distutils.version import LooseVersion -from oslo_serialization import jsonutils - -# To retrieve Ansible CLI options -try: - from __main__ import cli -except ImportError: - cli = None - -LOG = logging.getLogger('ara.callback') -app = create_app() - - -class IncludeResult(object): - """ - This is used by the v2_playbook_on_include callback to synthesize a task - result for calling log_task. - """ - def __init__(self, host, path): - self._host = host - self._result = {'included_file': path} - - -class CallbackModule(CallbackBase): - """ - Saves data from an Ansible run into a database - """ - CALLBACK_VERSION = 2.0 - CALLBACK_TYPE = 'notification' - CALLBACK_NAME = 'ara' - - def __init__(self): - super(CallbackModule, self).__init__() - - if not flask.current_app: - ctx = app.app_context() - ctx.push() - - self.taskresult = None - self.task = None - self.play = None - self.playbook = None - self.stats = None - self.loop_items = [] - - self.play_counter = itertools.count() - self.task_counter = itertools.count() - - if cli: - self._options = cli.options - else: - self._options = None - - def get_or_create_host(self, hostname): - try: - host = (models.Host.query - .filter_by(name=hostname) - .filter_by(playbook_id=self.playbook.id) - .one()) - except models.NoResultFound: - host = models.Host(name=hostname, playbook=self.playbook) - db.session.add(host) - db.session.commit() - - return host - - def get_or_create_file(self, path): - try: - if self.playbook.id: - file_ = (models.File.query - .filter_by(path=path) - .filter_by(playbook_id=self.playbook.id) - .one()) - return file_ - except models.NoResultFound: - pass - - file_ = models.File(path=path, playbook=self.playbook) - db.session.add(file_) - db.session.commit() - - try: - with open(path, 'r') as fd: - data = fd.read() - sha1 = models.content_sha1(data) - content = models.FileContent.query.get(sha1) - - if content is None: - content = models.FileContent(content=data) - - file_.content = content - except IOError: - LOG.warn('failed to open %s for reading', path) - - return file_ - - def log_task(self, result, status, **kwargs): - """ - 'log_task' is called when an individual task instance on a single - host completes. It is responsible for logging a single - 'TaskResult' record to the database. - """ - LOG.debug('logging task result for task %s (%s), host %s', - self.task.name, self.task.id, result._host.get_name()) - - # An include_role task might end up putting an IncludeRole object - # inside the result object which we don't need - # https://github.com/ansible/ansible/issues/30385 - if 'include_role' in result._result: - del result._result['include_role'] - - result.task_start = self.task.time_start - result.task_end = datetime.now() - host = self.get_or_create_host(result._host.get_name()) - - # Use Ansible's CallbackBase._dump_results in order to strip internal - # keys, respect no_log directive, etc. - if self.loop_items: - # NOTE (dmsimard): There is a known issue in which Ansible can send - # callback hooks out of order and "exit" the task before all items - # have returned, this can cause one of the items to be missing - # from the task result in ARA. - # https://github.com/ansible/ansible/issues/24207 - results = [self._dump_results(result._result)] - for item in self.loop_items: - results.append(self._dump_results(item._result)) - results = jsonutils.loads(jsonutils.dumps(results)) - else: - results = jsonutils.loads(self._dump_results(result._result)) - - # Ignore errors can be "yes" instead of a proper boolean in <2.3 - # for some reason - ignore_errors = kwargs.get('ignore_errors', False) - if LooseVersion(ansible_version) < LooseVersion('2.3.0'): - if not isinstance(ignore_errors, bool): - ignore_errors = True if ignore_errors == "yes" else False - - self.taskresult = models.TaskResult( - task=self.task, - host=host, - time_start=result.task_start, - time_end=result.task_end, - result=jsonutils.dumps(results), - status=status, - changed=result._result.get('changed', False), - failed=result._result.get('failed', False), - skipped=result._result.get('skipped', False), - unreachable=result._result.get('unreachable', False), - ignore_errors=ignore_errors, - ) - - db.session.add(self.taskresult) - db.session.commit() - - if self.task.action == 'setup' and 'ansible_facts' in result._result: - values = jsonutils.dumps(result._result['ansible_facts']) - facts = models.HostFacts(values=values) - host.facts = facts - - db.session.add(facts) - db.session.commit() - - def log_stats(self, stats): - """ - Logs playbook statistics to the database. - """ - LOG.debug('logging stats') - hosts = sorted(stats.processed.keys()) - for hostname in hosts: - host = self.get_or_create_host(hostname) - host_stats = stats.summarize(hostname) - db.session.add(models.Stats( - playbook=self.playbook, - host=host, - changed=host_stats['changed'], - unreachable=host_stats['unreachable'], - failed=host_stats['failures'], - ok=host_stats['ok'], - skipped=host_stats['skipped'] - )) - db.session.commit() - - def close_task(self): - """ - Marks the completion time of the currently active task. - """ - if self.task is not None: - LOG.debug('closing task %s (%s)', - self.task.name, - self.task.id) - self.task.stop() - db.session.add(self.task) - db.session.commit() - - self.task = None - self.loop_items = [] - - def close_play(self): - """ - Marks the completion time of the currently active play. - """ - if self.play is not None: - LOG.debug('closing play %s (%s)', self.play.name, self.play.id) - self.play.stop() - db.session.add(self.play) - db.session.commit() - - self.play = None - - def close_playbook(self): - """ - Marks the completion time of the currently active playbook. - """ - if self.playbook is not None: - LOG.debug('closing playbook %s', self.playbook.path) - self.playbook.stop() - self.playbook.complete = True - db.session.add(self.playbook) - db.session.commit() - - def v2_runner_item_on_ok(self, result): - self.loop_items.append(result) - - def v2_runner_item_on_failed(self, result): - self.loop_items.append(result) - - def v2_runner_item_on_skipped(self, result): - self.loop_items.append(result) - - def v2_runner_retry(self, result): - self.loop_items.append(result) - - def v2_runner_on_ok(self, result, **kwargs): - self.log_task(result, 'ok', **kwargs) - - def v2_runner_on_unreachable(self, result, **kwargs): - self.log_task(result, 'unreachable', **kwargs) - - def v2_runner_on_failed(self, result, **kwargs): - self.log_task(result, 'failed', **kwargs) - - def v2_runner_on_skipped(self, result, **kwargs): - self.log_task(result, 'skipped', **kwargs) - - def v2_playbook_on_task_start(self, task, is_conditional, - is_handler=False): - self.close_task() - - LOG.debug('starting task %s (action %s)', - task.name, task.action) - pathspec = task.get_path() - if pathspec: - path, lineno = pathspec.split(':', 1) - lineno = int(lineno) - file_ = self.get_or_create_file(path) - else: - path = self.playbook.path - lineno = 1 - file_ = self.get_or_create_file(self.playbook.path) - - self.task = models.Task( - name=task.get_name(), - sortkey=next(self.task_counter), - action=task.action, - play=self.play, - playbook=self.playbook, - tags=jsonutils.dumps(task._attributes['tags']), - file=file_, - lineno=lineno, - is_handler=is_handler) - - self.task.start() - db.session.add(self.task) - db.session.commit() - - def v2_playbook_on_handler_task_start(self, task): - self.v2_playbook_on_task_start(task, False, is_handler=True) - - def v2_playbook_on_start(self, playbook): - path = os.path.abspath(playbook._file_name) - if self._options is not None: - options = self._options.__dict__.copy() - else: - options = {} - - # Potentially sanitize some user-specified keys - for parameter in app.config['ARA_IGNORE_PARAMETERS']: - if parameter in options: - msg = "Parameter not saved by ARA due to configuration" - options[parameter] = msg - - LOG.debug('starting playbook %s', path) - self.playbook = models.Playbook( - ansible_version=ansible_version, - path=path, - options=options - ) - - self.playbook.start() - db.session.add(self.playbook) - db.session.commit() - - file_ = self.get_or_create_file(path) - file_.is_playbook = True - - # We need to persist the playbook id so it can be used by the modules - data = { - 'playbook': { - 'id': self.playbook.id - } - } - tmpfile = os.path.join(app.config['ARA_TMP_DIR'], 'ara.json') - with open(tmpfile, 'w') as file: - file.write(jsonutils.dumps(data)) - - def v2_playbook_on_play_start(self, play): - self.close_task() - self.close_play() - - LOG.debug('starting play %s', play.name) - if self.play is not None: - self.play.stop() - - self.play = models.Play( - name=play.name, - sortkey=next(self.play_counter), - playbook=self.playbook - ) - - self.play.start() - db.session.add(self.play) - db.session.commit() - - def v2_playbook_on_stats(self, stats): - self.log_stats(stats) - - self.close_task() - self.close_play() - self.close_playbook() - - LOG.debug('closing database') - db.session.close() diff --git a/executor/ansible/plugins/callback/openebs.py b/executor/ansible/plugins/callback/openebs.py deleted file mode 100644 index 381bdcb6d..000000000 --- a/executor/ansible/plugins/callback/openebs.py +++ /dev/null @@ -1,63 +0,0 @@ -# Make coding more python3-ish -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - - -from ansible.plugins.callback.default import ( - CallbackModule as CallbackModule_default -) -from ansible import constants as C - -"""Implementation of Custom Class that inherits the 'default' stdout_callback -plugin and overrides the v2_runner_retry api for displaying the 'FAILED - -RETRYING' only during verbose mode.""" - - -class CallbackModule(CallbackModule_default): - - CALLBACK_VERSION = 2.0 - CALLBACK_TYPE = 'stdout' - CALLBACK_NAME = 'openebs' - CALLBACK_NEEDS_WHITELIST = False - - def v2_runner_retry(self, result): - task_name = result.task_name or result._task - final_result = result._result['retries'] - result._result['attempts'] - msg = "FAILED - RETRYING: %s (%d retries left)." % (task_name, - final_result) - display_verbosity = self._display.verbosity - required_result = '_ansible_verbose_always' - if (display_verbosity > 2 or required_result in result._result): - if required_result not in result._result: - msg += "Result was: %s" % self._dump_results(result._result) - self._display.v('%s' % (msg)) - - def v2_runner_on_skipped(self, result): - my_result = result._result - required_result = '_ansible_verbose_always' - - if C.DISPLAY_SKIPPED_HOSTS: - if (self._display.verbosity > 0 or required_result in my_result): - if required_result not in my_result: - dumped_results = self._dump_results(my_result) - msg = "skipping: [%s] => %s" % (result._host.get_name(), - dumped_results) - self._display.display(msg, color=C.COLOR_SKIP) - - else: - self._display.display("skipping task..", color=C.COLOR_SKIP) - - def v2_runner_item_on_skipped(self, result): - my_result = result._result - required_result = '_ansible_verbose_always' - - if C.DISPLAY_SKIPPED_HOSTS: - if (self._display.verbosity > 0 or required_result in my_result): - if required_result not in my_result: - required_item = self._get_item(my_result) - dumped_result = self._dump_results(my_result) - result_host = result._host.get_name() - msg = "skipping: [%s] => (item=%s) => %s" % (result_host, - required_item, - dumped_result) - self._display.display(msg, color=C.COLOR_SKIP) diff --git a/executor/ansible/plugins/callback/timestamp.py b/executor/ansible/plugins/callback/timestamp.py deleted file mode 100644 index 411b66047..000000000 --- a/executor/ansible/plugins/callback/timestamp.py +++ /dev/null @@ -1,127 +0,0 @@ -# (C) 2012-2013, Michael DeHaan, - -# This file is part of Ansible -# -# Ansible is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Ansible is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Ansible. If not, see . - -from ansible.plugins.callback import CallbackBase -import datetime - -# define start time -t0 = tn = datetime.datetime.utcnow() - -def filled(msg, fchar="*"): - - if len(msg) == 0: - width = 79 - else: - msg = "%s " % msg - width = 79 - len(msg) - if width < 3: - width = 3 - filler = fchar * width - return "%s%s " % (msg, filler) - -def timestamp(): - - global tn - time_current = datetime.datetime.utcnow() - time_elapsed = (time_current - tn).total_seconds() - time_total_elapsed = (time_current - t0).total_seconds() - print( filled( '%s (delta: %s) %s elapsed: %s' % (time_current.isoformat(), - time_elapsed, ' ' * 7, time_total_elapsed ))) - tn = datetime.datetime.utcnow() - - - -class CallbackModule(CallbackBase): - - """ - this is an example ansible callback file that does nothing. You can drop - other classes in the same directory to define your own handlers. Methods - you do not use can be omitted. - - example uses include: logging, emailing, storing info, etc - """ - - - def on_any(self, *args, **kwargs): - pass - - def runner_on_failed(self, host, res, ignore_errors=False): - pass - - def runner_on_ok(self, host, res): - pass - - def runner_on_error(self, host, msg): - pass - - def runner_on_skipped(self, host, item=None): - pass - - def runner_on_unreachable(self, host, res): - pass - - def runner_on_no_hosts(self): - pass - - def runner_on_async_poll(self, host, res, jid, clock): - pass - - def runner_on_async_ok(self, host, res, jid): - pass - - def runner_on_async_failed(self, host, res, jid): - pass - - def playbook_on_start(self): - pass - - def playbook_on_notify(self, host, handler): - pass - - def playbook_on_no_hosts_matched(self): - pass - - def playbook_on_no_hosts_remaining(self): - pass - - def playbook_on_task_start(self, name, is_conditional): - timestamp() - pass - - def playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None): - pass - - def playbook_on_setup(self): - timestamp() - pass - - def playbook_on_import_for_host(self, host, imported_file): - pass - - def playbook_on_not_import_for_host(self, host, missing_file): - pass - - def playbook_on_play_start(self, pattern): - timestamp() - self._display.display(filled("", fchar="=")) - pass - - def playbook_on_stats(self, stats): - timestamp() - self._display.display(filled("", fchar="=")) - pass - diff --git a/executor/ansible/provider/README.md b/executor/ansible/provider/README.md deleted file mode 100644 index bb54f1589..000000000 --- a/executor/ansible/provider/README.md +++ /dev/null @@ -1,10 +0,0 @@ -The provider contains playbooks to setup storage providers on the Kubernetes cluster. This may involve installing Operators, -static provisioning of disk resources (say, Kubernetes Local Persistent Volume), or cloud storage (Google persistent disks). - -The playbook may be self-contained, i.e., consist of all steps required to setup the storage provider or can invoke a role -created for that purpose - - - - - diff --git a/executor/ansible/provider/local-pv/README.md b/executor/ansible/provider/local-pv/README.md deleted file mode 100644 index 4f4c5cddd..000000000 --- a/executor/ansible/provider/local-pv/README.md +++ /dev/null @@ -1,11 +0,0 @@ -### Setting up local disk resources - -- Manually discover, format and mount the disk on desired node -- Update templates/pv.yaml with appropriate node and disk mount location - -#### Note: - -- The local PV is beta in Kubernetes 1.10. -- The standard PersistentVolumeReclaim policy is "Retain", "Delete" is yet to be supported in all types of clusters - - diff --git a/executor/ansible/provider/local-pv/setup-local-pv.yaml b/executor/ansible/provider/local-pv/setup-local-pv.yaml deleted file mode 100644 index 809faf711..000000000 --- a/executor/ansible/provider/local-pv/setup-local-pv.yaml +++ /dev/null @@ -1,8 +0,0 @@ ---- -- hosts: kubernetes-kubemasters - roles: - - role: k8s-local-pv - template_path: "{{ playbook_dir }}/templates" - local_storage_class: storage_class.yaml - local_pv: pv.yaml - diff --git a/executor/ansible/provider/local-pv/templates/pv.yaml b/executor/ansible/provider/local-pv/templates/pv.yaml deleted file mode 100644 index 790d61ce9..000000000 --- a/executor/ansible/provider/local-pv/templates/pv.yaml +++ /dev/null @@ -1,22 +0,0 @@ ---- -apiVersion: v1 -kind: PersistentVolume -metadata: - name: local-pv -spec: - capacity: - storage: 5G - accessModes: - - ReadWriteOnce - persistentVolumeReclaimPolicy: Retain - storageClassName: local-storage - local: - path: /mnt/disks/vol1 - nodeAffinity: - required: - nodeSelectorTerms: - - matchExpressions: - - key: kubernetes.io/hostname - operator: In - values: - - kubeminion-01 diff --git a/executor/ansible/provider/local-pv/templates/storage_class.yaml b/executor/ansible/provider/local-pv/templates/storage_class.yaml deleted file mode 100644 index f9d1d6a1f..000000000 --- a/executor/ansible/provider/local-pv/templates/storage_class.yaml +++ /dev/null @@ -1,7 +0,0 @@ ---- -kind: StorageClass -apiVersion: storage.k8s.io/v1 -metadata: - name: local-storage -provisioner: kubernetes.io/no-provisioner -volumeBindingMode: WaitForFirstConsumer diff --git a/executor/ansible/roles/k8s-local-pv/defaults/main.yml b/executor/ansible/roles/k8s-local-pv/defaults/main.yml deleted file mode 100644 index 741b3e073..000000000 --- a/executor/ansible/roles/k8s-local-pv/defaults/main.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- -local_storageclass_yaml: local-storage-sc.yaml - diff --git a/executor/ansible/roles/k8s-local-pv/tasks/main.yml b/executor/ansible/roles/k8s-local-pv/tasks/main.yml deleted file mode 100644 index d016a0ea3..000000000 --- a/executor/ansible/roles/k8s-local-pv/tasks/main.yml +++ /dev/null @@ -1,51 +0,0 @@ ---- -- name: Get kubernetes master name - shell: hostname - args: - executable: /bin/bash - register: result - -- name: Get kubernetes master status - shell: source ~/.profile; kubectl get nodes | grep {{ result.stdout.lower()}} | awk '{print $2}' - args: - executable: /bin/bash - register: result - until: result.stdout == 'Ready' - delay: 60 - retries: 10 - ignore_errors: true - -- name: - debug: - msg: "Ending play, K8S Master NOT READY" - when: result.stdout != "Ready" - -- name: Ending Playbook Run - K8S master is NOT READY - meta: end_play - when: result.stdout != "Ready" - -- name: Copy local-storage artifacts to kube-master - copy: - src: "{{ item }}" - dest: "{{ ansible_env.HOME }}" - with_items: - - "{{ template_path }}/{{ local_storage_class }}" - - "{{ template_path }}/{{ local_pv }}" - -- name: Deploy the local-pv storageclass - shell: > - source ~/.profile; - kubectl apply -f {{ ansible_env.HOME }}/{{ local_storage_class }} - args: - executable: /bin/bash - register: result - failed_when: "'storageclass' and ('created' or 'configured') not in result.stdout" - -- name: Create the local persistent volume - shell: > - source ~/.profile; - kubectl apply -f {{ ansible_env.HOME }}/{{ local_pv }} - args: - executable: /bin/bash - register: result - failed_when: "'persistentvolume' and ('created' or 'configured') not in result.stdout" diff --git a/executor/ansible/utils/execute.yml b/executor/ansible/utils/execute.yml deleted file mode 100644 index cbeccb929..000000000 --- a/executor/ansible/utils/execute.yml +++ /dev/null @@ -1,47 +0,0 @@ ---- -- hosts: localhost - connection: local - - tasks: - - block: - - - name: Running the defined application - shell: kubectl create -f {{ PATH }} - - - name: Getting status of JOB - shell: kubectl get pod -n litmus -l app={{ LABEL }} -o jsonpath='{.items[0].status.phase}' - register: status - until: "'Succeeded' in status.stdout" - delay: 30 - retries: 30 - - - name: Checking the status of Ansible-test container - shell: kubectl get pod -n litmus -l app={{ LABEL }} -o jsonpath='{.items[0].status.containerStatuses[0].ready}' - register: container_status - until: "'false' in container_status.stdout" - - - name: Getting result CR - shell: kubectl get lr {{ TESTNAME }} -o jsonpath='{.spec.testStatus.result}' - register: result - until: "'none' not in result.stdout" - delay: 20 - retries: 10 - - - name: Updating the test-result csv - lineinfile: - path: /executor/ansible/result.csv - state: present - line: '{{ TYPE }} : {{ TESTNAME }} : {{ result.stdout }}' - - rescue: - - set_fact: - flag: "Fail" - - - name: Updating the test-result csv - lineinfile: - path: /executor/ansible/result.csv - state: present - line: '{{ TYPE }} : {{ TESTNAME }} : {{ flag }}' - - - diff --git a/executor/ansible/utils/getFiles.yaml b/executor/ansible/utils/getFiles.yaml deleted file mode 100644 index 446853a3d..000000000 --- a/executor/ansible/utils/getFiles.yaml +++ /dev/null @@ -1,21 +0,0 @@ ---- -- name: Obtain list of Kubernetes test job specifications - find: - paths: "{{ dir }}" - patterns: "{{ expr }}" - recurse: yes - use_regex: yes - register: result - -- debug: - msg: "{{ item.path }}" - with_items: "{{ result.files }}" - -- name: Create test path list - lineinfile: - path: "{{ tfile }}" - line: "{{ item.path }}" - state: present - create: yes - with_items: "{{ result.files }}" - diff --git a/executor/ansible/utils/runTest.yaml b/executor/ansible/utils/runTest.yaml deleted file mode 100644 index fe1e16c97..000000000 --- a/executor/ansible/utils/runTest.yaml +++ /dev/null @@ -1,44 +0,0 @@ ---- -- name: Get the Test item from Test Job List - set_fact: - test: "{{ item }}" - -- block: - - - name: Replace the storage class based on provider - replace: - path: "{{ test }}" - regexp: "openebs-standard" - replace: "{{ storage_class }}" - - - name: Run the test Kubernetes job YAML - shell: source ~/.profile; kubectl create -f run_litmus_test.yaml - args: - executable: /bin/bash - delegate_to: "{{groups['kubernetes-kubemasters'].0}}" - - - name: Verify the test Kubernetes job is Successful - # This is a placeholder task that waits 30m for job complete - shell: > - source ~/.profile; - kubectl get job litmus --no-headers - -n litmus -o custom-columns=:status.succeeded - args: - executable: /bin/bash - register: result - delegate_to: "{{groups['kubernetes-kubemasters'].0}}" - until: "result.stdout|int == 1" - delay: 120 - retries: 15 - - ## TODO: Result CR parse, slack notify if applicable - - rescue: - - name: Handle job failure - debug: - msg: "Unable to complete test, please examine the job spec for {{ test }}" - - always: - - name: Message b/w test job runs - debug: - msg: "Moving to next test..." diff --git a/hack/godog.sh b/hack/godog.sh deleted file mode 100644 index 65b8a6268..000000000 --- a/hack/godog.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env sh - -set -o errexit -set -o nounset - -CURDIR=`pwd` - -cd "$1" && godog --stop-on-failure e2e.feature - -cd ${CURDIR} diff --git a/hack/minikube.sh b/hack/minikube.sh deleted file mode 100644 index 67480bd76..000000000 --- a/hack/minikube.sh +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env sh - -set -o errexit -set -o nounset - -CURDIR=`pwd` - -#Install latest minikube -ls /usr/local/bin/minikube || \ -(curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 \ -&& chmod +x minikube \ -&& sudo mv minikube /usr/local/bin/) - -#Install latest kubectl -ls /usr/local/bin/kubectl || \ -(curl -Lo kubectl https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl \ -&& chmod +x kubectl \ -&& sudo mv kubectl /usr/local/bin/) - -#Setup minikube -mkdir -p $HOME/.minikube -mkdir -p $HOME/.kube -touch $HOME/.kube/config - -# Push these ENV k:v to $HOME/.profile to start/restart minikube. -grep "MINIKUBE_WANTUPDATENOTIFICATION=false" $HOME/.profile || \ - echo "MINIKUBE_WANTUPDATENOTIFICATION=false" >> $HOME/.profile - -grep "MINIKUBE_WANTREPORTERRORPROMPT=false" $HOME/.profile || \ - echo "MINIKUBE_WANTREPORTERRORPROMPT=false" >> $HOME/.profile - -grep "MINIKUBE_HOME=$HOME" $HOME/.profile || \ - echo "MINIKUBE_HOME=$HOME" >> $HOME/.profile - -grep "CHANGE_MINIKUBE_NONE_USER=true" $HOME/.profile || \ - echo "CHANGE_MINIKUBE_NONE_USER=true" >> $HOME/.profile - -grep "KUBECONFIG=$HOME/.kube/config" $HOME/.profile || \ - echo "KUBECONFIG=$HOME/.kube/config" >> $HOME/.profile - -# Export above as well for `minikube start` to work -# in the same session of `vagrant up` -export MINIKUBE_WANTUPDATENOTIFICATION=false -export MINIKUBE_WANTREPORTERRORPROMPT=false -export MINIKUBE_HOME=$HOME -export CHANGE_MINIKUBE_NONE_USER=true -export KUBECONFIG=$HOME/.kube/config - -# Permissions -sudo chown -R $USER $HOME/.kube -sudo chgrp -R $USER $HOME/.kube - -sudo chown -R $USER $HOME/.minikube -sudo chgrp -R $USER $HOME/.minikube - -# Start minikube on this host itself with RBAC enabled -sudo -E minikube start --vm-driver=none --extra-config=apiserver.Authorization.Mode=RBAC - -# Wait for Kubernetes to be up and ready. -JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}'; until kubectl get nodes -o jsonpath="$JSONPATH" 2>&1 | grep -q "Ready=True"; do sleep 1; done - -echo "" -echo "================================================" -echo "Congrats!! minikube apiserver is running" -echo "================================================" -echo "" - -cd ${CURDIR} diff --git a/pkg/exec/exec.go b/pkg/exec/exec.go deleted file mode 100644 index 00affc3bf..000000000 --- a/pkg/exec/exec.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -//go:generate mockgen -package exec -source=exec.go -destination exec_mock.go -package exec - -import ( - "bytes" - "fmt" - osexec "os/exec" - "strings" -) - -// Executor acts as a contract for various execution based logic -type Executor interface { - Output(args []string) (output string, err error) -} - -// ShellExec is a shell based struct that implements Executor interface -type ShellExec struct { - binary string -} - -// NewShellExec returns a new instance of shellExec -// based on the provided binary name -func NewShellExec(binary string) *ShellExec { - return &ShellExec{ - binary: binary, - } -} - -// Output executes the shell command and returns the output or error -func (e *ShellExec) Output(args []string) (output string, err error) { - var out bytes.Buffer - var stderr bytes.Buffer - - cmd := osexec.Command(e.binary, args...) - cmd.Stdout = &out - cmd.Stderr = &stderr - - err = cmd.Run() - if err != nil { - err = fmt.Errorf("failed to run cmd '%s': %s: %s", cmd.Args, fmt.Sprint(err), stderr.String()) - return - } - - // This removes the beginning & trailing single quotes from the output - // It has been observed that kubectl execution results in such single quotes - output = strings.Trim(out.String(), "'") - return -} diff --git a/pkg/exec/exec_mock.go b/pkg/exec/exec_mock.go deleted file mode 100644 index 430555035..000000000 --- a/pkg/exec/exec_mock.go +++ /dev/null @@ -1,46 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: exec.go - -// Package exec is a generated GoMock package. -package exec - -import ( - gomock "github.com/golang/mock/gomock" - reflect "reflect" -) - -// MockExecutor is a mock of Executor interface -type MockExecutor struct { - ctrl *gomock.Controller - recorder *MockExecutorMockRecorder -} - -// MockExecutorMockRecorder is the mock recorder for MockExecutor -type MockExecutorMockRecorder struct { - mock *MockExecutor -} - -// NewMockExecutor creates a new mock instance -func NewMockExecutor(ctrl *gomock.Controller) *MockExecutor { - mock := &MockExecutor{ctrl: ctrl} - mock.recorder = &MockExecutorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockExecutor) EXPECT() *MockExecutorMockRecorder { - return m.recorder -} - -// Output mocks base method -func (m *MockExecutor) Output(args []string) (string, error) { - ret := m.ctrl.Call(m, "Output", args) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Output indicates an expected call of Output -func (mr *MockExecutorMockRecorder) Output(args interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Output", reflect.TypeOf((*MockExecutor)(nil).Output), args) -} diff --git a/pkg/exec/exec_test.go b/pkg/exec/exec_test.go deleted file mode 100644 index 475be1288..000000000 --- a/pkg/exec/exec_test.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package exec - -import ( - "testing" -) - -func TestNewShellExec(t *testing.T) { - testCases := map[string]struct { - binary string - expectValue *ShellExec - }{ - "String Empty": { - binary: "", - expectValue: &ShellExec{binary: ""}, - }, - "Present string value": { - binary: "_MY_PRESENT_STRING_", - expectValue: &ShellExec{binary: "_MY_PRESENT_STRING_"}, - }, - } - for k, v := range testCases { - t.Run(k, func(t *testing.T) { - - if v.binary != v.expectValue.binary { - t.Errorf("expected %s got %s", v.expectValue.binary, v.binary) - } - }) - } -} diff --git a/pkg/kubectl/kubectl.go b/pkg/kubectl/kubectl.go deleted file mode 100644 index a075fd170..000000000 --- a/pkg/kubectl/kubectl.go +++ /dev/null @@ -1,344 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -//go:generate mockgen -package kubectl -source=kubectl.go -destination kubectl_mock.go - -package kubectl - -import ( - "fmt" - "strings" - - "github.com/openebs/litmus/pkg/exec" - "github.com/openebs/litmus/pkg/util" -) - -// KubectlFile is the type to hold various yaml file paths -// that can be applied by kubectl -type KubectlFile string - -const ( - // KubectlPath is the expected location where kubectl executable may be found - KubectlPath = "/usr/local/bin/kubectl" -) - -const ( - // DefaultLitmusNamespace is the default namespace where kubectl operations - // will be executed - DefaultLitmusNamespace = "litmus" -) - -// kubectlArgs builds the arguments required to execute any kubectl command -// -// This has been borrowed from https://github.com/CanopyTax/ckube -func kubectlArgs(args []string, namespace string, context string, labels string) []string { - if len(namespace) != 0 { - args = append(args, fmt.Sprintf("--namespace=%v", strings.TrimSpace(namespace))) - } - if len(context) != 0 { - args = append(args, fmt.Sprintf("--context=%v", strings.TrimSpace(context))) - } - if len(labels) != 0 { - args = append(args, fmt.Sprintf("--selector=%v", strings.TrimSpace(labels))) - } - return args -} - -// KubeRunner interface provides the contract i.e. method signature to -// invoke commands at kubernetes cluster -type KubeRunner interface { - // Run executes the kubectl command - Run(args []string) (output string, err error) -} - -// Kubectl holds the properties required to execute any kubectl command. -// Kubectl is an implementation of following interfaces: -// 1. KubeRunner -type Kubectl struct { - // namespace where this kubectl command will be run - namespace string - // labels to be used during kubectl execution - labels string - // context where this kubectl command will be run - context string - // args are provided to kubectl command during its run - args []string - // executor does actual kubectl execution - executor exec.Executor -} - -// GetKubectlPath gets the location where kubectl executable is -// expected to be present -func GetKubectlPath() string { - // get from environment variable - kpath := util.KubectlPathENV() - if len(kpath) == 0 { - // else use the constant - kpath = KubectlPath - } - - return kpath -} - -// New returns a new instance of kubectl based on defaults -func New() *Kubectl { - return &Kubectl{ - namespace: DefaultLitmusNamespace, - executor: exec.NewShellExec(GetKubectlPath()), - } -} - -// Namespace sets the namespace to be used during kubectl run -func (k *Kubectl) Namespace(namespace string) *Kubectl { - if len(namespace) == 0 { - return k - } - k.namespace = namespace - return k -} - -// Labels sets the labels to be used during kubectl run -func (k *Kubectl) Labels(labels string) *Kubectl { - k.labels = labels - return k -} - -// Context sets the context to be used during kubectl run -func (k *Kubectl) Context(context string) *Kubectl { - k.context = context - return k -} - -// Args sets the args to be used during kubectl run -func (k *Kubectl) Args(args []string) *Kubectl { - k.args = args - return k -} - -// Run will execute the kubectl command & provide output or error -func (k *Kubectl) Run(args []string) (output string, err error) { - k.args = kubectlArgs(args, k.namespace, k.context, k.labels) - - output, err = k.executor.Output(k.args) - return -} - -// IsPod flags if the provided kind is a kubernetes pod or is related -// to a pod -func IsPod(kind string) (yes bool) { - switch kind { - case "po", "pod", "pods", "deploy", "deployment", "deployments", "job", "jobs", "sts", "statefulset", "statefulsets", "ds", "daemonset", "daemonsets": - yes = true - default: - yes = false - } - - return -} - -// ArePodsRunning returns true if all the pod(s) are running, false otherwise -// -// An example of kubectl get pods & its state: -// This makes use of status.containerStatuses[*].state.*.reason -// -// $ kubectl get po -n kube-system --selector=k8s-app=kube-dns -o jsonpath='{.items[*].status.containerStatuses[*].state.*.reason}' -// CrashLoopBackOff CrashLoopBackOff -// -// Another example of kubectl get pods & its state: -// This makes use of status.containerStatuses[*].ready -// -// $ kubectl get pods -n kube-system --selector=k8s-app=kube-dns -o jsonpath='{.items[*].status.containerStatuses[*].ready}' -// true false true -func ArePodsRunning(k KubeRunner) (yes bool, err error) { - isReady, err := k.Run([]string{"get", "pods", "-o", "jsonpath='{.items[*].status.containerStatuses[*].ready}'"}) - if err != nil { - return - } - - // split the output by space - isReadyArr := strings.Split(isReady, " ") - - if contains(isReadyArr, "false") { - err = fmt.Errorf("pod(s) are not running: '%#v'", isReadyArr) - return - } - - // double check - if contains(isReadyArr, "true") { - yes = true - } else { - err = fmt.Errorf("status of pod(s) could not be determined: '%#v'", isReadyArr) - } - - return -} - -// IsPodRunning returns true if the specified pod is running, false otherwise -// -// An example of kubectl get pods & its state: -// This makes use of status.containerStatuses[*].state.*.reason -// -// $ kubectl get po -n kube-system my-pod -o jsonpath='{.status.containerStatuses[*].state.*.reason}' -// CrashLoopBackOff CrashLoopBackOff -// -// Another example of kubectl get pods & its state: -// This makes use of status.containerStatuses[*].ready -// -// $ kubectl get pods -n kube-system my-pod -o jsonpath='{.status.containerStatuses[*].ready}' -// true false true -func IsPodRunning(k KubeRunner, name string) (yes bool, err error) { - if len(name) == 0 { - err = fmt.Errorf("unable to determine pod running status: pod name is missing") - return - } - - isReady, err := k.Run([]string{"get", "pods", name, "-o", "jsonpath='{.status.containerStatuses[*].ready}'"}) - if err != nil { - return - } - - // split the output by space - isReadyArr := strings.Split(isReady, " ") - - if contains(isReadyArr, "false") { - err = fmt.Errorf("pod '%s' is not running: '%#v'", name, isReadyArr) - return - } - - // double check - if contains(isReadyArr, "true") { - yes = true - } else { - err = fmt.Errorf("status of pod '%s' could not be determined: received output '%#v'", name, isReadyArr) - } - - return -} - -// GetPodNodes fetches the nodes that hosts the pods. Pods are referred to -// via the provided labels -func GetPodNodes(k KubeRunner) (nodes []string, err error) { - n, err := k.Run([]string{"get", "pods", "-o", "jsonpath='{.items[*].spec.nodeName}'"}) - if err != nil { - return - } - - // split the output by space - nodes = strings.Split(n, " ") - return -} - -// GetPods fetches the pods based on the provided labels -func GetPods(k KubeRunner) (pods []string, err error) { - p, err := k.Run([]string{"get", "pods", "-o", "jsonpath='{.items[*].metadata.name}'"}) - if err != nil { - return - } - - // split the output by space - pods = strings.Split(p, " ") - - return -} - -// GetRunningPods fetches the pods which are running based on the provided labels -// -// Sample code to do this: -// -// $ JSONPATH='{range .items[*]}{@.metadata.name}::{@.status.containerStatuses[*].ready}::::{end}' && kubectl get po -n kube-system -o jsonpath="$JSONPATH" -// kube-addon-manager-amit-thinkpad-l470::true::::kube-dns-54cccfbdf8-q7v2c::false false true::::kubernetes-dashboard-77d8b98585-cwbjq::false::::storage-provisioner::true::::tiller-deploy-5b48764ff7-g9qz7::true:::: -func GetRunningPods(k KubeRunner) (pods []string, err error) { - // fetch pods - o, err := k.Run([]string{"get", "pods", "-o", "jsonpath='{range .items[*]}{@.metadata.name}::{@.status.containerStatuses[*].ready}::::{end}'"}) - if err != nil { - return - } - - // split the output by the splitter used in above command - firstSplit := strings.Split(o, "::::") - for _, fs := range firstSplit { - if len(fs) == 0 { - continue - } - - secondSplit := strings.Split(fs, "::") - // ignore if pod is not running - if strings.Contains(secondSplit[1], "false") { - continue - } - - // add the running pod to the list - if strings.Contains(secondSplit[1], "true") { - pods = append(pods, secondSplit[0]) - } - } - - return -} - -// GetOldestRunningPod fetches the oldest running pod based on the provided labels -// and sorted based on their age -// -// Sample code to do this: -// -// $ JSONPATH='{range .items[*]}{@.metadata.name}::{@.status.containerStatuses[*].ready}::::{end}' && kubectl get po -n kube-system --sort-by=.metadata.creationTimestamp -o jsonpath="$JSONPATH" -// kube-addon-manager-amit-thinkpad-l470::true::::kube-dns-54cccfbdf8-q7v2c::false false true::::kubernetes-dashboard-77d8b98585-cwbjq::false::::storage-provisioner::true::::tiller-deploy-5b48764ff7-g9qz7::true:::: -func GetOldestRunningPod(k KubeRunner) (pod string, err error) { - // fetch pods sorted by creation timestamp - o, err := k.Run([]string{"get", "pods", "-o", "--sort-by=.metadata.creationTimestamp", "jsonpath='{range .items[*]}{@.metadata.name}::{@.status.containerStatuses[*].ready}::::{end}'"}) - if err != nil { - return - } - - // split the output by the splitter used in above command - firstSplit := strings.Split(o, "::::") - for _, fs := range firstSplit { - if len(fs) == 0 { - continue - } - - secondSplit := strings.Split(fs, "::") - // ignore if pod is not running - if strings.Contains(secondSplit[1], "false") { - continue - } - - // return the first running pod - if strings.Contains(secondSplit[1], "true") { - pod = secondSplit[0] - return - } - } - - return -} - -// DeletePod deletes the specified pod -func DeletePod(k KubeRunner, name string) (err error) { - _, err = k.Run([]string{"delete", "pods", name}) - return -} - -// contains verifies if a specific element is present in the provided array -func contains(s []string, e string) bool { - for _, a := range s { - a = strings.TrimSpace(a) - if a == e { - return true - } - } - return false -} diff --git a/pkg/kubectl/kubectl_mock.go b/pkg/kubectl/kubectl_mock.go deleted file mode 100644 index f1adc8167..000000000 --- a/pkg/kubectl/kubectl_mock.go +++ /dev/null @@ -1,82 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: kubectl.go - -// Package kubectl is a generated GoMock package. -package kubectl - -import ( - gomock "github.com/golang/mock/gomock" - reflect "reflect" -) - -// MockKubeRunner is a mock of KubeRunner interface -type MockKubeRunner struct { - ctrl *gomock.Controller - recorder *MockKubeRunnerMockRecorder -} - -// MockKubeRunnerMockRecorder is the mock recorder for MockKubeRunner -type MockKubeRunnerMockRecorder struct { - mock *MockKubeRunner -} - -// NewMockKubeRunner creates a new mock instance -func NewMockKubeRunner(ctrl *gomock.Controller) *MockKubeRunner { - mock := &MockKubeRunner{ctrl: ctrl} - mock.recorder = &MockKubeRunnerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockKubeRunner) EXPECT() *MockKubeRunnerMockRecorder { - return m.recorder -} - -// Run mocks base method -func (m *MockKubeRunner) Run(args []string) (string, error) { - ret := m.ctrl.Call(m, "Run", args) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Run indicates an expected call of Run -func (mr *MockKubeRunnerMockRecorder) Run(args interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*MockKubeRunner)(nil).Run), args) -} - -// MockKubeCtlRunner is a mock of KubeCtlRunner interface -type MockKubeCtlRunner struct { - ctrl *gomock.Controller - recorder *MockKubeCtlRunnerMockRecorder -} - -// MockKubeCtlRunnerMockRecorder is the mock recorder for MockKubeCtlRunner -type MockKubeCtlRunnerMockRecorder struct { - mock *MockKubeCtlRunner -} - -// NewMockKubeCtlRunner creates a new mock instance -func NewMockKubeCtlRunner(ctrl *gomock.Controller) *MockKubeCtlRunner { - mock := &MockKubeCtlRunner{ctrl: ctrl} - mock.recorder = &MockKubeCtlRunnerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockKubeCtlRunner) EXPECT() *MockKubeCtlRunnerMockRecorder { - return m.recorder -} - -// Run mocks base method -func (m *MockKubeCtlRunner) Run(args []string) (string, error) { - ret := m.ctrl.Call(m, "Run", args) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Run indicates an expected call of Run -func (mr *MockKubeCtlRunnerMockRecorder) Run(args interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*MockKubeCtlRunner)(nil).Run), args) -} diff --git a/pkg/kubectl/kubectl_test.go b/pkg/kubectl/kubectl_test.go deleted file mode 100644 index bfa160d3e..000000000 --- a/pkg/kubectl/kubectl_test.go +++ /dev/null @@ -1,578 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -package kubectl - -import ( - "fmt" - "os" - "reflect" - "testing" - - "github.com/golang/mock/gomock" - "github.com/pkg/errors" - - "github.com/openebs/litmus/pkg/exec" -) - -func TestGetKubectlPath(t *testing.T) { - - const kubectlPathENVK = "LITMUS_IO_KUBECTL_PATH" - - tests := map[string]struct { - fn func() - expected string - }{ - "test 101": {fn: func() {}, expected: KubectlPath}, - "test 102": {fn: func() { os.Setenv(kubectlPathENVK, "someVal") }, expected: "someVal"}, - } - - for name, mock := range tests { - t.Run(name, func(t *testing.T) { - - mock.fn() - - path := GetKubectlPath() - - if path != mock.expected { - t.Fatalf("test '%s' failed: expected value: %s, actual value: %s", name, mock.expected, path) - } - - if path != KubectlPath { - os.Unsetenv(kubectlPathENVK) - } - - }) - - } - -} - -func TestKubectl_Namespace(t *testing.T) { - - const someNS = "someNS" - - tests := map[string]struct { - namespace string - expected string - }{ - "test 101": {expected: "litmus"}, - "test 102": {namespace: someNS, expected: someNS}, - } - - for name, mock := range tests { - - t.Run(name, func(t *testing.T) { - - kubeCtl := New() - - if mock.expected != kubeCtl.Namespace(mock.namespace).namespace { - t.Fatalf("test '%s' failed: expected value: %s, actual value %s", "101", mock.expected, kubeCtl.namespace) - } - - }) - - } - -} - -func TestKubectl_Labels(t *testing.T) { - - labels := "someLabel" - - kubeCtl := New() - - if labels != kubeCtl.Labels(labels).labels { - t.Fatalf("test '%s' failed: expected value: %s, actual value %s", "101", labels, kubeCtl.labels) - } - -} - -func TestKubectl_Context(t *testing.T) { - - ctx := "someCtx" - - kubeCtl := New() - - if ctx != kubeCtl.Context(ctx).context { - t.Fatalf("test '%s' failed: expected value: %s, actual value %s", "101", ctx, kubeCtl.context) - } - -} - -func TestKubectl_Args(t *testing.T) { - - args := []string{"something"} - - kubeCtl := New() - - if !reflect.DeepEqual(args, kubeCtl.Args(args).args) { - t.Fatalf("test '%s' failed: expected value: %s, actual value %s", "101", args, kubeCtl.args) - } - -} - -func TestKubectl_Run(t *testing.T) { - - const ( - namespace = "--namespace=litmus" - context = "someCtx" - labels = "someLabels" - ) - - type expected struct { - output string - err error - } - - tests := map[string]struct { - args []string - expected *expected - }{ - "test 101": { - args: []string{context, labels, namespace}, - expected: &expected{ - output: "--namespace=litmus--context=someCtx--selector=someLabels", - }, - }, - "test 201": { - args: []string{context, labels}, - expected: &expected{ - output: "--namespace=litmus--context=someCtx--selector=someLabels", - err: errors.New("some output error"), - }, - }, - } - - for name, mock := range tests { - t.Run(name, func(t *testing.T) { - - ctrl := gomock.NewController(t) - - defer ctrl.Finish() - - mockExecutor := exec.NewMockExecutor(ctrl) - mockExecutor.EXPECT().Output(mock.args).Return(mock.expected.output, mock.expected.err) - - ctl := New() - ctl.executor = mockExecutor - - output, err := ctl.Run(mock.args[:len(mock.args)-1]) - - if err != mock.expected.err { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.expected.err, err) - } - - if output != mock.expected.output { - t.Fatalf("test '%s' failed: expected value: %s, actual value %s", name, mock.expected.output, output) - } - - }) - - } - -} - -func TestIsPod(t *testing.T) { - - tests := map[string]struct { - pod string - expected bool - }{ - "test 101": {pod: "po", expected: true}, - "test 102": {pod: "pod", expected: true}, - "test 103": {pod: "pods", expected: true}, - "test 104": {pod: "deploy", expected: true}, - "test 105": {pod: "deployment", expected: true}, - "test 106": {pod: "deployments", expected: true}, - "test 107": {pod: "job", expected: true}, - "test 108": {pod: "jobs", expected: true}, - "test 109": {pod: "sts", expected: true}, - "test 110": {pod: "statefulset", expected: true}, - "test 111": {pod: "statefulsets", expected: true}, - "test 112": {pod: "ds", expected: true}, - "test 113": {pod: "daemonset", expected: true}, - "test 114": {pod: "daemonsets", expected: true}, - "test 201": {}, - } - - for name, mock := range tests { - t.Run(name, func(t *testing.T) { - - isPod := IsPod(mock.pod) - - if mock.expected != isPod { - t.Fatalf("test '%s' failed: expected value: %t, actual value: %t", name, mock.expected, isPod) - } - - }) - - } - -} - -func TestArePodsRunning(t *testing.T) { - - args := []string{"get", "pods", "-o", "jsonpath='{.items[*].status.containerStatuses[*].ready}'"} - - type expected struct { - runningBool bool - runningString string - runErr error - err error - } - - tests := map[string]struct { - expected *expected - }{ - "test 101": { - expected: &expected{ - runningString: "true", - runningBool: true, - }, - }, - "test 201": { - expected: &expected{ - runErr: errors.New("some running err"), - runningString: "false", - }, - }, - "test 202": { - expected: &expected{ - err: fmt.Errorf("pod(s) are not running: '%#v'", []string{"true", "false"}), - runningString: "true false", - }, - }, - "test 203": { - expected: &expected{err: fmt.Errorf("status of pod(s) could not be determined: '%#v'", []string{""})}, - }, - } - - for name, mock := range tests { - t.Run(name, func(t *testing.T) { - - ctrl := gomock.NewController(t) - - defer ctrl.Finish() - - mockRunner := NewMockKubeRunner(ctrl) - - mockRunner.EXPECT().Run(args).Return(mock.expected.runningString, mock.expected.runErr).AnyTimes() - - running, err := ArePodsRunning(mockRunner) - - if mock.expected.runErr != nil && err != mock.expected.runErr { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.expected.runErr, err) - } else if mock.expected.err != nil && err.Error() != mock.expected.err.Error() { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.expected.err, err) - } - - if running != mock.expected.runningBool { - t.Fatalf("test '%s' failed: expected value: %t, actual value: %t", name, mock.expected.runningBool, running) - } - - }) - - } - -} - -func TestIsPodRunning(t *testing.T) { - - const someName = "someName" - - args := []string{"get", "pods", "", "-o", "jsonpath='{.status.containerStatuses[*].ready}'"} - - type expected struct { - runningBool bool - runningString string - runErr error - err error - } - - tests := map[string]struct { - name string - expected *expected - }{ - "test 101": { - name: someName, - expected: &expected{ - runningBool: true, - runningString: "true", - }, - }, - "test 201": { - name: "", - expected: &expected{ - runningString: "false", - err: errors.New("unable to determine pod running status: pod name is missing"), - }, - }, - "test 202": { - name: someName, - expected: &expected{ - runningString: "false", - runErr: errors.New("some running err"), - }, - }, - "test 203": { - name: someName, - expected: &expected{ - runningString: "false", - err: fmt.Errorf("pod '%s' is not running: '%#v'", someName, []string{"false"}), - }, - }, - "test 204": { - name: someName, - expected: &expected{err: fmt.Errorf("status of pod '%s' could not be determined: received output '%#v'", someName, []string{""})}, - }, - } - - for name, mock := range tests { - t.Run(name, func(t *testing.T) { - - args[2] = mock.name - - ctrl := gomock.NewController(t) - - defer ctrl.Finish() - - mockRunner := NewMockKubeRunner(ctrl) - - mockRunner.EXPECT().Run(args).Return(mock.expected.runningString, mock.expected.runErr).AnyTimes() - - isRunning, err := IsPodRunning(mockRunner, mock.name) - - if mock.expected.runErr != nil && err != mock.expected.runErr { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.expected.runErr, err) - } else if mock.expected.err != nil && err.Error() != mock.expected.err.Error() { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.expected.err, err) - } - - if isRunning != mock.expected.runningBool { - t.Fatalf("test '%s' failed: expected value %t, actual value %t", name, mock.expected.runningBool, isRunning) - } - - }) - - } - -} - -func TestGetPodNodes(t *testing.T) { - - args := []string{"get", "pods", "-o", "jsonpath='{.items[*].spec.nodeName}'"} - - type expected struct { - err error - nodes []string - } - - tests := map[string]struct { - input string - expected *expected - }{ - "test 101": { - input: "some stuff", - expected: &expected{nodes: []string{"some", "stuff"}}, - }, - "test 201": { - expected: &expected{err: errors.New("some running err")}, - }, - } - - for name, mock := range tests { - t.Run(name, func(t *testing.T) { - - ctrl := gomock.NewController(t) - - defer ctrl.Finish() - - mockRunner := NewMockKubeRunner(ctrl) - - mockRunner.EXPECT().Run(args).Return(mock.input, mock.expected.err).AnyTimes() - - nodes, err := GetPodNodes(mockRunner) - - if err != mock.expected.err { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.expected.err, err) - } - - if !reflect.DeepEqual(nodes, mock.expected.nodes) { - t.Fatalf("test '%s' failed: expected value %v, actual value %v", name, mock.expected.nodes, nodes) - } - - }) - } - -} - -func TestGetPods(t *testing.T) { - - args := []string{"get", "pods", "-o", "jsonpath='{.items[*].metadata.name}'"} - - type expected struct { - err error - nodes []string - } - - tests := map[string]struct { - input string - expected *expected - }{ - "test 101": { - input: "some stuff", - expected: &expected{nodes: []string{"some", "stuff"}}, - }, - "test 201": { - expected: &expected{err: errors.New("some running err")}, - }, - } - - for name, mock := range tests { - t.Run(name, func(t *testing.T) { - - ctrl := gomock.NewController(t) - - defer ctrl.Finish() - - mockRunner := NewMockKubeRunner(ctrl) - - mockRunner.EXPECT().Run(args).Return(mock.input, mock.expected.err).AnyTimes() - - nodes, err := GetPods(mockRunner) - - if err != mock.expected.err { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.expected.err, err) - } - - if !reflect.DeepEqual(nodes, mock.expected.nodes) { - t.Fatalf("test '%s' failed: expected value %v, actual value %v", name, mock.expected.nodes, nodes) - } - }) - } - -} - -func TestGetRunningPods(t *testing.T) { - - args := []string{"get", "pods", "-o", "jsonpath='{range .items[*]}{@.metadata.name}::{@.status.containerStatuses[*].ready}::::{end}'"} - - tests := map[string]struct { - err error - output []string - input string - }{ - "test 101": {}, - "test 102": {input: "true::false::::true::false"}, - "test 103": {input: "false::true::::true::true", output: []string{"false", "true"}}, - "test 201": {err: errors.New("some running err")}, - } - - for name, mock := range tests { - - t.Run(name, func(t *testing.T) { - - ctrl := gomock.NewController(t) - - defer ctrl.Finish() - - mockRunner := NewMockKubeRunner(ctrl) - - mockRunner.EXPECT().Run(args).Return(mock.input, mock.err).AnyTimes() - - output, err := GetRunningPods(mockRunner) - - if err != mock.err { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.err, err) - } - - if !reflect.DeepEqual(output, mock.output) { - t.Fatalf("test '%s' failed: expected value %v, actual value %v", name, mock.output, output) - } - - }) - } - -} - -func TestGetOldestRunningPod(t *testing.T) { - - args := []string{"get", "pods", "-o", "--sort-by=.metadata.creationTimestamp", "jsonpath='{range .items[*]}{@.metadata.name}::{@.status.containerStatuses[*].ready}::::{end}'"} - - tests := map[string]struct { - err error - output string - input string - }{ - "test 101": {}, - "test 102": {input: "true::false::::true::false"}, - "test 103": {input: "true::true::::true::false", output: "true"}, - "test 201": {err: errors.New("some running err")}, - } - - for name, mock := range tests { - - t.Run(name, func(t *testing.T) { - - ctrl := gomock.NewController(t) - - defer ctrl.Finish() - - mockRunner := NewMockKubeRunner(ctrl) - - mockRunner.EXPECT().Run(args).Return(mock.input, mock.err).AnyTimes() - - output, err := GetOldestRunningPod(mockRunner) - - if err != mock.err { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.err, err) - } - - if output != mock.output { - t.Fatalf("test '%s' failed: expected value %v, actual value %v", name, mock.output, output) - } - - }) - } - -} - -func TestDeletePod(t *testing.T) { - - args := []string{"delete", "pods", "someName"} - const somename = "someName" - - tests := map[string]struct { - err error - }{ - "test 101": {}, - "test 102": {err: errors.New("some runnign err")}, - } - - for name, mock := range tests { - - ctrl := gomock.NewController(t) - - defer ctrl.Finish() - - mockRunner := NewMockKubeRunner(ctrl) - - mockRunner.EXPECT().Run(args).Return("", mock.err).AnyTimes() - - if err := DeletePod(mockRunner, somename); err != mock.err { - t.Fatalf("test '%s' failed: expected error: %s, actual error: %s", name, mock.err, err) - } - - } - -} diff --git a/pkg/time/time.go b/pkg/time/time.go deleted file mode 100644 index 64f631404..000000000 --- a/pkg/time/time.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package time - -import ( - "time" -) - -// WaitFor pauses the current goroutine for the provided time. -// This function is modelled using time.ParseDuration. -// -// time.ParseDuration parses a duration string. -// A duration string is a possibly signed sequence of -// decimal numbers, each with optional fraction and a unit suffix, -// such as "300ms", "-1.5h" or "2h45m". -// -// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". -func WaitFor(duration string) (err error) { - // sleep interval - interval, err := time.ParseDuration(duration) - if err != nil { - return - } - - sleep(interval) - return -} - -var sleep = time.Sleep diff --git a/pkg/time/time_test.go b/pkg/time/time_test.go deleted file mode 100644 index 904b81416..000000000 --- a/pkg/time/time_test.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package time - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -func TestWaitFor(t *testing.T) { - tests := []struct { - name string - argDuration string - wantSleep time.Duration - wantErr bool - }{ - {"nanosecond", "1ns", time.Nanosecond, false}, - {"microsecond", "1us", time.Microsecond, false}, - {"millisecond", "1ms", time.Millisecond, false}, - {"second", "1s", time.Second, false}, - {"minute", "1m", time.Minute, false}, - {"hour", "1h", time.Hour, false}, - {"negative", "-1s", -time.Second, false}, - {"fraction", "1.5s", 1500 * time.Millisecond, false}, - {"combo", "1h45m", 105 * time.Minute, false}, - {"error", "1a", 0, true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var gotSleep time.Duration - defer swapSleep(func(d time.Duration) { gotSleep = d })() - - err := WaitFor(tt.argDuration) - if tt.wantErr { - require.Error(t, err) - } else { - require.NoError(t, err) - require.Equal(t, tt.wantSleep, gotSleep) - } - }) - } - - t.Run("real sleep is called", func(t *testing.T) { - start := time.Now() - err := WaitFor("100ms") - require.NoError(t, err) - require.Condition(t, func() bool { return time.Since(start) > 100*time.Millisecond }) - }) -} - -func swapSleep(newSleep func(time.Duration)) func() { - oldSleep := sleep - sleep = newSleep - return func() { sleep = oldSleep } -} diff --git a/pkg/util/envs.go b/pkg/util/envs.go deleted file mode 100644 index 57e7dd296..000000000 --- a/pkg/util/envs.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package util - -import ( - "os" - "strings" -) - -// ENVKey is a typed variable that holds all environment -// variables -type ENVKey string - -const ( - // KubeNamespaceENVK is the ENV key to fetch the - // namespace where LITMUS operations will be executed - KubeNamespaceENVK ENVKey = "LITMUS_IO_KUBE_NAMESPACE" - - // KubeContextENVK is the ENV key to fetch the - // kubernetes context where LITMUS operations will be executed - KubeContextENVK ENVKey = "LITMUS_IO_KUBE_CONTEXT" - - // KubeConfigENVK is the ENV key to fetch the kubeconfig file path - // This kubeconfig will be used to connect to target kubernetes cluster - KubeConfigENVK ENVKey = "LITMUS_IO_KUBE_CONFIG" - - // KubectlPathENVK is the ENV key to fetch kubectl executable location - KubectlPathENVK ENVKey = "LITMUS_IO_KUBECTL_PATH" -) - -// KubectlPathENV gets the kubectl executable location from ENV -func KubectlPathENV() string { - val := getEnv(KubectlPathENVK) - return val -} - -// KubeNamespaceENV gets the kubernetes namespace from ENV -func KubeNamespaceENV() string { - val := getEnv(KubeNamespaceENVK) - return val -} - -// KubeContextENV gets the kubernetes context from ENV -func KubeContextENV() string { - val := getEnv(KubeContextENVK) - return val -} - -// KubeConfigENV gets the kubeconfig file path from ENV -func KubeConfigENV() string { - val := getEnv(KubeConfigENVK) - return val -} - -// getEnv fetches the environment variable value from the machine's -// environment -func getEnv(envKey ENVKey) string { - return strings.TrimSpace(os.Getenv(string(envKey))) -} diff --git a/pkg/verify/verify.go b/pkg/verify/verify.go deleted file mode 100644 index 2f3499122..000000000 --- a/pkg/verify/verify.go +++ /dev/null @@ -1,672 +0,0 @@ -/* -Copyright 2018 The OpenEBS Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package verify - -import ( - "fmt" - "io/ioutil" - "strings" - - "github.com/ghodss/yaml" - "github.com/openebs/litmus/pkg/kubectl" -) - -// VerifyFile type defines a yaml file path that represents an installation -// and is used for various verification purposes -// -// A verify file is a yaml version of Installation struct -type VerifyFile string - -// Condition type defines a condition that can be applied against a component -// or a set of components -type Condition string - -const ( - // UniqueNodeCond is a condition to check uniqueness of node - UniqueNodeCond Condition = "is-unique-node" - // ThreeReplicasCond is a condition to check if replica count is 3 - ThreeReplicasCond Condition = "is-three-replicas" - // PVCBoundCond is a condition to check if PVC is bound - PVCBoundCond Condition = "is-pvc-bound" - // PVCUnBoundCond is a condition to check if PVC is unbound - PVCUnBoundCond Condition = "is-pvc-unbound" -) - -// Action type defines a action that can be applied against a component -// or a set of components -type Action string - -const ( - // DeleteAnyPodAction is an action to delete any pod - DeleteAnyPodAction Action = "delete-any-pod" - // DeleteOldestPodAction is an action to delete the oldest pod - DeleteOldestPodAction Action = "delete-oldest-pod" -) - -// DeleteVerifier provides contract(s) i.e. method signature(s) to evaluate -// if an installation was deleted successfully -type DeleteVerifier interface { - IsDeleted() (yes bool, err error) -} - -// DeployVerifier provides contract(s) i.e. method signature(s) to evaluate -// if an installation was deployed successfully -type DeployVerifier interface { - IsDeployed() (yes bool, err error) -} - -// ConnectVerifier provides contract(s) i.e. method signature(s) to evaluate -// if a connection is possible or not -type ConnectVerifier interface { - IsConnected() (yes bool, err error) -} - -// RunVerifier provides contract(s) i.e. method signature(s) to evaluate -// if an entity is in a running state or not -type RunVerifier interface { - IsRunning() (yes bool, err error) -} - -// ConditionVerifier provides contract(s) i.e. method signature(s) to evaluate -// if specific entities passes the condition -type ConditionVerifier interface { - IsCondition(alias string, condition Condition) (yes bool, err error) -} - -// ActionVerifier provides contract(s) i.e. method signature(s) to evaluate -// if specific entities passes the action -type ActionVerifier interface { - IsAction(alias string, action Action) (yes bool, err error) -} - -// DeployRunVerifier provides contract(s) i.e. method signature(s) to -// evaluate: -// -// 1/ if an entity is deployed &, -// 2/ if the entity is running -type DeployRunVerifier interface { - // DeployVerifier will check if the instance has been deployed or not - DeployVerifier - // RunVerifier will check if the instance is in a running state or not - RunVerifier -} - -// AllVerifier provides contract(s) i.e. method signature(s) to -// evaluate: -// -// - if an entity is deleted, -// - if an entity is deployed, -// - if the entity is running, -// - if the entity satisfies the provided condition & -// - if the entity satisfies the provided action -type AllVerifier interface { - // DeleteVerifier will check if the instance has been deleted or not - DeleteVerifier - // DeployVerifier will check if the instance has been deployed or not - DeployVerifier - // RunVerifier will check if the instance is in a running state or not - RunVerifier - // ConditionVerifier will check if the instance satisfies the provided - // condition - ConditionVerifier - // ActionVerifier will check if the instance satisfies the provided action - ActionVerifier -} - -// Installation represents a set of components that represent an installation -// e.g. an operator represented by its CRDs, RBACs and Deployments forms an -// installation -// -// NOTE: -// Installation struct is accepted as a yaml file that is meant to be verified. -// In addition this file allows the testing logic to take appropriate actions -// as directed in the .feature file. -type Installation struct { - // VerifyID is an identifier that is used to tie together related installations - // meant to be verified - VerifyID string `json:"verifyID"` - // Version of this installation, operator etc - Version string `json:"version"` - // Components of this installation - Components []Component `json:"components"` -} - -// Component is the information about a particular component -// e.g. a Kubernetes Deployment, or a Kubernetes Pod, etc can be -// a component in the overall installation -type Component struct { - // Name of the component - Name string `json:"name"` - // Namespace of the component - Namespace string `json:"namespace"` - // Kind name of the component - // e.g. pods, deployments, services, etc - Kind string `json:"kind"` - // APIVersion of the component - APIVersion string `json:"apiVersion"` - // Labels of the component that is used for filtering the components - // - // Following are some valid sample values for labels: - // - // labels: name=app - // labels: name=app,env=prod - Labels string `json:"labels"` - // Alias provides a user understood description used for filtering the - // components. This is a single word setting. - // - // NOTE: - // Ensure unique alias values in an installation - // - // DETAILS: - // This is the text which is typically understood by the end user. This text - // which will be set in the installation file against a particular component. - // Verification logic will filter the component based on this alias & run - // various checks &/or actions - Alias string `json:"alias"` -} - -// unmarshal takes the raw yaml data and unmarshals it into Installation -func unmarshal(data []byte) (installation *Installation, err error) { - installation = &Installation{} - - err = yaml.Unmarshal(data, installation) - return -} - -// load converts a verify file into an instance of *Installation -func load(file VerifyFile) (installation *Installation, err error) { - if len(file) == 0 { - err = fmt.Errorf("failed to load: verify file is not provided") - return - } - - d, err := ioutil.ReadFile(string(file)) - if err != nil { - return - } - - return unmarshal(d) -} - -// KubeInstallVerify provides methods that handles verification related logic of -// an installation within kubernetes e.g. application, deployment, operator, etc -type KubeInstallVerify struct { - // installation is the set of components that determine the install - installation *Installation -} - -// NewKubeInstallVerify provides a new instance of NewKubeInstallVerify based on -// the provided kubernetes runner & verify file -func NewKubeInstallVerify(file VerifyFile) (*KubeInstallVerify, error) { - i, err := load(file) - if err != nil { - return nil, err - } - - return &KubeInstallVerify{ - installation: i, - }, nil -} - -// IsDeployed evaluates if all components of the installation are deployed -func (v *KubeInstallVerify) IsDeployed() (yes bool, err error) { - if v.installation == nil { - err = fmt.Errorf("failed to check IsDeployed: installation object is nil") - return - } - - for _, component := range v.installation.Components { - yes, err = v.isComponentDeployed(component) - if err != nil { - break - } - } - - return -} - -// IsDeleted evaluates if all components of the installation are deleted -func (v *KubeInstallVerify) IsDeleted() (yes bool, err error) { - if v.installation == nil { - err = fmt.Errorf("failed to check IsDeleted: installation object is nil") - return - } - - for _, component := range v.installation.Components { - yes, err = v.isComponentDeleted(component) - if err != nil { - break - } - } - - return -} - -// IsRunning evaluates if all components of the installation are running -func (v *KubeInstallVerify) IsRunning() (yes bool, err error) { - if v.installation == nil { - err = fmt.Errorf("failed to check IsRunning: installation object is nil") - return - } - - for _, component := range v.installation.Components { - if component.Kind != "pod" { - continue - } - - yes, err = v.isPodComponentRunning(component) - if err != nil { - break - } - } - - return -} - -// IsCondition evaluates if specific components satisfies the condition -func (v *KubeInstallVerify) IsCondition(alias string, condition Condition) (yes bool, err error) { - switch condition { - case UniqueNodeCond: - return v.isEachComponentOnUniqueNode(alias) - case ThreeReplicasCond: - return v.hasComponentThreeReplicas(alias) - case PVCBoundCond: - return v.isPVCBound(alias) - case PVCUnBoundCond: - return v.isPVCUnBound(alias) - default: - err = fmt.Errorf("condition '%s' is not supported", condition) - } - return -} - -// IsAction evaluates if specific components satisfies the action -func (v *KubeInstallVerify) IsAction(alias string, action Action) (yes bool, err error) { - switch action { - case DeleteAnyPodAction: - return v.isDeleteAnyRunningPod(alias) - case DeleteOldestPodAction: - return v.isDeleteOldestRunningPod(alias) - default: - err = fmt.Errorf("action '%s' is not supported", action) - } - return -} - -// isDeleteAnyPod deletes a pod based on the alias -func (v *KubeInstallVerify) isDeleteAnyRunningPod(alias string) (yes bool, err error) { - var pods = []string{} - - c, err := v.getMatchingPodComponent(alias) - if err != nil { - return - } - - if len(strings.TrimSpace(c.Labels)) == 0 { - err = fmt.Errorf("unable to fetch component '%s': component labels are missing '%s'", c.Kind, alias) - return - } - - k := kubectl.New().Namespace(c.Namespace).Labels(c.Labels) - pods, err = kubectl.GetRunningPods(k) - if err != nil { - return - } - - if len(pods) == 0 { - err = fmt.Errorf("failed to delete any running pod: pods with alias '%s' and running state are not found", alias) - return - } - - // delete any running pod - k = kubectl.New().Namespace(c.Namespace) - err = kubectl.DeletePod(k, pods[0]) - if err != nil { - return - } - - yes = true - return -} - -// isDeleteOldestRunningPod deletes the oldset pod based on the alias -func (v *KubeInstallVerify) isDeleteOldestRunningPod(alias string) (yes bool, err error) { - var pod string - - c, err := v.getMatchingPodComponent(alias) - if err != nil { - return - } - - // check for presence of labels - if len(strings.TrimSpace(c.Labels)) == 0 { - err = fmt.Errorf("unable to fetch component '%s': component labels are missing '%s'", c.Kind, alias) - return - } - - // fetch oldest running pod - k := kubectl.New().Namespace(c.Namespace).Labels(c.Labels) - pod, err = kubectl.GetOldestRunningPod(k) - if err != nil { - return - } - - if len(pod) == 0 { - err = fmt.Errorf("failed to delete oldest running pod: pod with alias '%s' and running state is not found", alias) - return - } - - // delete oldest running pod - k = kubectl.New().Namespace(c.Namespace) - err = kubectl.DeletePod(k, pod) - if err != nil { - return - } - - yes = true - return -} - -func (v *KubeInstallVerify) getMatchingPodComponent(alias string) (comp Component, err error) { - var filtered = []Component{} - - // filter the components that are pods & match with the provided alias - for _, c := range v.installation.Components { - if c.Alias == alias && kubectl.IsPod(c.Kind) { - filtered = append(filtered, c) - } - } - - if len(filtered) == 0 { - err = fmt.Errorf("component not found for alias '%s'", alias) - return - } - - // there should be only one component that matches the alias - if len(filtered) > 1 { - err = fmt.Errorf("multiple components found for alias '%s': alias should be unique in an install", alias) - return - } - - return filtered[0], nil -} - -// isComponentDeleted flags if a particular component is deleted -func (v *KubeInstallVerify) isComponentDeleted(component Component) (yes bool, err error) { - var op string - - if len(strings.TrimSpace(component.Kind)) == 0 { - err = fmt.Errorf("unable to verify component delete status: component kind is missing") - return - } - - // either name or labels is required - if len(strings.TrimSpace(component.Name)) == 0 && len(strings.TrimSpace(component.Labels)) == 0 { - err = fmt.Errorf("unable to verify component delete status: either component name or its labels is required") - return - } - - // check via name - if len(strings.TrimSpace(component.Name)) != 0 { - op, err = kubectl.New(). - Namespace(component.Namespace). - Run([]string{"get", component.Kind, component.Name}) - - if err == nil { - err = fmt.Errorf("component '%#v' is not deleted: output '%s'", component, op) - return - } - - if strings.Contains(err.Error(), "(NotFound)") { - // yes, it is deleted - yes = true - // We wanted to make sure that this component was deleted. - // Hence the get operation is expected to result in NotFound error - // from server. Now we can reset the err to nil to let the flow - // continue - err = nil - return - } - - err = fmt.Errorf("unable to verify delete status of component '%#v': output '%s'", component, op) - return - } - - // or check via labels - op, err = kubectl.New(). - Namespace(component.Namespace). - Labels(component.Labels). - Run([]string{"get", component.Kind}) - - if err != nil { - return - } - - if len(strings.TrimSpace(op)) == 0 || strings.Contains(op, "No resources found") { - // yes, it is deleted - yes = true - return - } - - err = fmt.Errorf("unable to verify delete status of component '%#v': output '%s'", component, op) - return -} - -// isComponentDeployed flags if a particular component is deployed -func (v *KubeInstallVerify) isComponentDeployed(component Component) (yes bool, err error) { - var op string - - if len(strings.TrimSpace(component.Kind)) == 0 { - err = fmt.Errorf("unable to verify component deploy status: component kind is missing") - return - } - - // either name or labels is required - if len(strings.TrimSpace(component.Name)) == 0 && len(strings.TrimSpace(component.Labels)) == 0 { - err = fmt.Errorf("unable to verify component deploy status: either component name or its labels is required") - return - } - - // check via name - if len(strings.TrimSpace(component.Name)) != 0 { - op, err = kubectl.New(). - Namespace(component.Namespace). - Run([]string{"get", component.Kind, component.Name, "-o", "jsonpath='{.metadata.name}'"}) - - if err == nil && len(strings.TrimSpace(op)) != 0 { - // yes, it is deployed - yes = true - } - return - } - - // or check via labels - op, err = kubectl.New(). - Namespace(component.Namespace). - Labels(component.Labels). - Run([]string{"get", component.Kind, "-o", "jsonpath='{.items[*].metadata.name}'"}) - - if err == nil && len(strings.TrimSpace(op)) != 0 { - // yes, it is deployed - yes = true - } - return -} - -// isPodComponentRunning flags if a particular component is running -func (v *KubeInstallVerify) isPodComponentRunning(component Component) (yes bool, err error) { - // either name or labels is required - if len(strings.TrimSpace(component.Name)) == 0 && len(strings.TrimSpace(component.Labels)) == 0 { - err = fmt.Errorf("unable to verify pod component running status: either name or its labels is required") - return - } - - // check via name - if len(strings.TrimSpace(component.Name)) != 0 { - k := kubectl.New().Namespace(component.Namespace) - return kubectl.IsPodRunning(k, component.Name) - } - - // or check via labels - k := kubectl.New(). - Namespace(component.Namespace). - Labels(component.Labels) - return kubectl.ArePodsRunning(k) -} - -// hasComponentThreeReplicas flags if a component has three replicas -func (v *KubeInstallVerify) hasComponentThreeReplicas(alias string) (yes bool, err error) { - err = fmt.Errorf("hasComponentThreeReplicas is not implemented") - return -} - -// getPVCVolume fetches the PVC's volume -func (v *KubeInstallVerify) getPVCVolume(alias string) (op string, err error) { - var filtered = []Component{} - - // filter the components based on the provided alias - for _, c := range v.installation.Components { - if c.Alias == alias { - filtered = append(filtered, c) - } - } - - if len(filtered) == 0 { - err = fmt.Errorf("unable to check pvc bound status: no component with alias '%s'", alias) - return - } - - if len(filtered) > 1 { - err = fmt.Errorf("unable to check pvc bound status: more than one components found with alias '%s'", alias) - return - } - - if len(filtered[0].Name) == 0 { - err = fmt.Errorf("unable to check pvc bound status: component name is required: '%#v'", filtered[0]) - return - } - - if filtered[0].Kind != "pvc" { - err = fmt.Errorf("unable to check pvc bound status: component is not a pvc resource: '%#v'", filtered[0]) - return - } - - op, err = kubectl.New(). - Namespace(filtered[0].Namespace). - Run([]string{"get", "pvc", filtered[0].Name, "-o", "jsonpath='{.spec.volumeName}'"}) - - return -} - -// isPVCBound flags if a PVC component is bound -func (v *KubeInstallVerify) isPVCBound(alias string) (yes bool, err error) { - var vol string - vol, err = v.getPVCVolume(alias) - if err != nil { - return - } - - // if no vol then pvc is not bound - if len(strings.TrimSpace(vol)) == 0 { - err = fmt.Errorf("pvc component is not bound") - return - } - - yes = true - return -} - -// isPVCUnBound flags if a PVC component is unbound -func (v *KubeInstallVerify) isPVCUnBound(alias string) (yes bool, err error) { - var vol string - vol, err = v.getPVCVolume(alias) - if err != nil { - return - } - - // if no vol then pvc is not bound - if len(strings.TrimSpace(vol)) != 0 { - err = fmt.Errorf("pvc component is bound") - return - } - - yes = true - return -} - -// isEachComponentOnUniqueNode flags if each component is placed on unique node -func (v *KubeInstallVerify) isEachComponentOnUniqueNode(alias string) (bool, error) { - var filtered = []Component{} - var nodes = []string{} - - // filter the components based on the provided alias - for _, c := range v.installation.Components { - if c.Alias == alias { - filtered = append(filtered, c) - } - } - - // get the node of each filtered component - for _, f := range filtered { - // skip for non pod components - if !kubectl.IsPod(f.Kind) { - continue - } - - // if pod then get the node on which it is running - if len(strings.TrimSpace(f.Labels)) == 0 { - return false, fmt.Errorf("unable to fetch component '%s' node: component labels are required", f.Kind) - } - - k := kubectl.New().Namespace(f.Namespace).Labels(f.Labels) - n, err := kubectl.GetPodNodes(k) - if err != nil { - return false, err - } - - nodes = append(nodes, n...) - } - - // check if condition is satisfied i.e. no duplicate nodes - exists := map[string]string{} - for _, n := range nodes { - if _, ok := exists[n]; ok { - return false, nil - } - exists[n] = "tracked" - } - - return true, nil -} - -// KubeConnectionVerify provides methods that verifies connection to a kubernetes -// environment -type KubeConnectionVerify struct{} - -// NewKubeConnectionVerify provides a new instance of KubeConnectionVerify -func NewKubeConnectionVerify() *KubeConnectionVerify { - return &KubeConnectionVerify{} -} - -// IsConnected verifies if kubectl can connect to the target Kubernetes cluster -func (k *KubeConnectionVerify) IsConnected() (yes bool, err error) { - _, err = kubectl.New().Run([]string{"get", "pods"}) - if err == nil { - yes = true - } - return -} diff --git a/tools/godog-runner/Dockerfile b/tools/godog-runner/Dockerfile deleted file mode 100644 index a1b561e42..000000000 --- a/tools/godog-runner/Dockerfile +++ /dev/null @@ -1,22 +0,0 @@ -FROM golang:latest - -MAINTAINER AmitD - -# Install kubectl -ENV KUBE_LATEST_VERSION="v1.12.0" - -RUN curl -L https://storage.googleapis.com/kubernetes-release/release/${KUBE_LATEST_VERSION}/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl \ - && chmod +x /usr/local/bin/kubectl \ - && kubectl version --client - -# Install go tools -RUN go get github.com/DATA-DOG/godog/cmd/godog -RUN go get -u github.com/golang/dep/cmd/dep - -# Add source code -RUN mkdir -p /go/src/github.com/openebs/litmus -ADD . /go/src/github.com/openebs/litmus/ -WORKDIR /go/src/github.com/openebs/litmus/ - -# Go dep -RUN dep ensure diff --git a/vendor/github.com/DATA-DOG/godog/.gitignore b/vendor/github.com/DATA-DOG/godog/.gitignore deleted file mode 100644 index 703729939..000000000 --- a/vendor/github.com/DATA-DOG/godog/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/cmd/godog/godog -/example/example diff --git a/vendor/github.com/DATA-DOG/godog/.travis.yml b/vendor/github.com/DATA-DOG/godog/.travis.yml deleted file mode 100644 index e8904acde..000000000 --- a/vendor/github.com/DATA-DOG/godog/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -language: go -go: - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - -go_import_path: github.com/DATA-DOG/godog - -install: go install github.com/DATA-DOG/godog/cmd/godog - -script: - - go vet github.com/DATA-DOG/godog - - go vet github.com/DATA-DOG/godog/gherkin - - go vet github.com/DATA-DOG/godog/colors - - test -z "$(go fmt ./...)" # fail if not formatted properly - - godog -f progress - - go test -v -race -coverprofile=coverage.txt -covermode=atomic - -after_success: - - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/DATA-DOG/godog/CHANGELOG.md b/vendor/github.com/DATA-DOG/godog/CHANGELOG.md deleted file mode 100644 index 4c2cb6e53..000000000 --- a/vendor/github.com/DATA-DOG/godog/CHANGELOG.md +++ /dev/null @@ -1,85 +0,0 @@ -# Change LOG - -**2018-03-04** -- support go1.10 new compiler and linker changes for **godog** command. - -**2017-08-31** -- added **BeforeFeature** and **AfterFeature** hooks. -- failed multistep error is now prepended with a parent step text in order - to determine failed nested step. -- pretty format now removes the step definition location package name in - comment next to step if the step definition matches tested package. If - step definition is imported from other package, full package name will - be printed. - -**2017-05-04** -- added **--strict** option in order to fail suite when there are pending - or undefined steps. By default, suite passes and treats pending or - undefined steps as TODOs. - -**2017-04-29** - **v0.7.0** -- added support for nested steps. From now on, it is possible to return - **godog.Steps** instead of an **error** in the step definition func. - This change introduced few minor changes in **Formatter** interface. Be - sure to adapt the changes if you have custom formatters. - -**2017-04-27** -- added an option to randomize scenario execution order, so we could - ensure that scenarios do not depend on global state. -- godog was manually sorting feature files by name. Now it just runs them - in given order, you may sort them anyway you like. For example `godog - $(find . -name '*.feature' | sort)` - -**2016-10-30** - **v0.6.0** -- added experimental **events** format, this might be used for unified - cucumber formats. But should be not adapted widely, since it is highly - possible that specification will change. -- added **RunWithOptions** method which allows to easily run godog from - **TestMain** without needing to simulate flag arguments. These options - now allows to configure output writer. -- added flag **-o, --output=runner.binary** which only compiles the test - runner executable, but does not execute it. -- **FlagSet** initialization now takes io.Writer as output for help text - output. It was not showing nice colors on windows before. - **--no-colors** option only applies to test run output. - -**2016-06-14** - **v0.5.0** -- godog now uses **go tool compile** and **go tool link** to support - vendor directory dependencies. It also compiles test executable the same - way as standard **go test** utility. With this change, only go - versions from **1.5** are now supported. - -**2016-06-01** -- parse flags in main command, to show version and help without needing - to compile test package and buildable go sources. - -**2016-05-28** -- show nicely formatted called step func name and file path - -**2016-05-26** -- pack gherkin dependency in a subpackage to prevent compatibility - conflicts in the future. If recently upgraded, probably you will need to - reference gherkin as `github.com/DATA-DOG/godog/gherkin` instead. - -**2016-05-25** -- refactored test suite build tooling in order to use standard **go test** - tool. Which allows to compile package with godog runner script in **go** - idiomatic way. It also supports all build environment options as usual. -- **godog.Run** now returns an **int** exit status. It was not returning - anything before, so there is no compatibility breaks. - -**2016-03-04** -- added **junit** compatible output formatter, which prints **xml** - results to **os.Stdout** -- fixed #14 which skipped printing background steps when there was - scenario outline in feature. - -**2015-07-03** -- changed **godog.Suite** from interface to struct. Context registration should be updated accordingly. The reason -for change: since it exports the same methods and there is no need to mock a function in tests, there is no -obvious reason to keep an interface. -- in order to support running suite concurrently, needed to refactor an entry point of application. The **Run** method -now is a func of godog package which initializes and run the suite (or more suites). Method **New** is removed. This -change made godog a little cleaner. -- renamed **RegisterFormatter** func to **Format** to be more consistent. - diff --git a/vendor/github.com/DATA-DOG/godog/LICENSE b/vendor/github.com/DATA-DOG/godog/LICENSE deleted file mode 100644 index 4a27bd1d1..000000000 --- a/vendor/github.com/DATA-DOG/godog/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -The three clause BSD license (http://en.wikipedia.org/wiki/BSD_licenses) - -Copyright (c) 2015-2018, DATA-DOG team -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. - -* The name DataDog.lt may not 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 MICHAEL BOSTOCK 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/DATA-DOG/godog/Makefile b/vendor/github.com/DATA-DOG/godog/Makefile deleted file mode 100644 index 9ceeaeea9..000000000 --- a/vendor/github.com/DATA-DOG/godog/Makefile +++ /dev/null @@ -1,32 +0,0 @@ -.PHONY: test gherkin bump cover - -VERS := $(shell grep 'const Version' -m 1 godog.go | awk -F\" '{print $$2}') - -test: - @echo "running all tests" - @go install ./... - @go fmt ./... - @golint github.com/DATA-DOG/godog - @golint github.com/DATA-DOG/godog/cmd/godog - go vet ./... - go test -race - godog -f progress -c 4 - -gherkin: - @if [ -z "$(VERS)" ]; then echo "Provide gherkin version like: 'VERS=commit-hash'"; exit 1; fi - @rm -rf gherkin - @mkdir gherkin - @curl -s -L https://github.com/cucumber/gherkin-go/tarball/$(VERS) | tar -C gherkin -zx --strip-components 1 - @rm -rf gherkin/{.travis.yml,.gitignore,*_test.go,gherkin-generate*,*.razor,*.jq,Makefile,CONTRIBUTING.md} - -bump: - @if [ -z "$(VERSION)" ]; then echo "Provide version like: 'VERSION=$(VERS) make bump'"; exit 1; fi - @echo "bumping version from: $(VERS) to $(VERSION)" - @sed -i.bak 's/$(VERS)/$(VERSION)/g' godog.go - @sed -i.bak 's/$(VERS)/$(VERSION)/g' examples/api/version.feature - @find . -name '*.bak' | xargs rm - -cover: - go test -race -coverprofile=coverage.txt - go tool cover -html=coverage.txt - rm coverage.txt diff --git a/vendor/github.com/DATA-DOG/godog/README.md b/vendor/github.com/DATA-DOG/godog/README.md deleted file mode 100644 index 1fefb7ca0..000000000 --- a/vendor/github.com/DATA-DOG/godog/README.md +++ /dev/null @@ -1,341 +0,0 @@ -[![Build Status](https://travis-ci.org/DATA-DOG/godog.svg?branch=master)](https://travis-ci.org/DATA-DOG/godog) -[![GoDoc](https://godoc.org/github.com/DATA-DOG/godog?status.svg)](https://godoc.org/github.com/DATA-DOG/godog) -[![codecov.io](https://codecov.io/github/DATA-DOG/godog/branch/master/graph/badge.svg)](https://codecov.io/github/DATA-DOG/godog) - -# Godog - -

Godog logo

- -**The API is likely to change a few times before we reach 1.0.0** - -Please read all the README, you may find it very useful. And do not forget -to peek into the -[CHANGELOG](https://github.com/DATA-DOG/godog/blob/master/CHANGELOG.md) -from time to time. - -Package godog is the official Cucumber BDD framework for Golang, it merges -specification and test documentation into one cohesive whole. The author -is a core member of [cucumber team](https://github.com/cucumber). - -The project is inspired by [behat][behat] and [cucumber][cucumber] and is -based on cucumber [gherkin3 parser][gherkin]. - -**Godog** does not intervene with the standard **go test** command -behavior. You can leverage both frameworks to functionally test your -application while maintaining all test related source code in **_test.go** -files. - -**Godog** acts similar compared to **go test** command, by using go -compiler and linker tool in order to produce test executable. Godog -contexts need to be exported the same way as **Test** functions for go -tests. Note, that if you use **godog** command tool, it will use `go` -executable to determine compiler and linker. - -**Godog** ships gherkin parser dependency as a subpackage. This will -ensure that it is always compatible with the installed version of godog. -So in general there are no vendor dependencies needed for installation. - -The following about section was taken from -[cucumber](https://cucumber.io/) homepage. - -## About - -#### A single source of truth - -Cucumber merges specification and test documentation into one cohesive whole. - -#### Living documentation - -Because they're automatically tested by Cucumber, your specifications are -always bang up-to-date. - -#### Focus on the customer - -Business and IT don't always understand each other. Cucumber's executable -specifications encourage closer collaboration, helping teams keep the -business goal in mind at all times. - -#### Less rework - -When automated testing is this much fun, teams can easily protect -themselves from costly regressions. - -## Install - - go get github.com/DATA-DOG/godog/cmd/godog - -## Example - -The following example can be [found -here](/examples/godogs). - -### Step 1 - -Given we create a new go package **$GOPATH/src/godogs**. From now on, this -is our work directory `cd $GOPATH/src/godogs`. - -Imagine we have a **godog cart** to serve godogs for lunch. First of all, -we describe our feature in plain text - `vim -$GOPATH/src/godogs/features/godogs.feature`: - -``` gherkin -# file: $GOPATH/src/godogs/features/godogs.feature -Feature: eat godogs - In order to be happy - As a hungry gopher - I need to be able to eat godogs - - Scenario: Eat 5 out of 12 - Given there are 12 godogs - When I eat 5 - Then there should be 7 remaining -``` - -**NOTE:** same as **go test** godog respects package level isolation. All -your step definitions should be in your tested package root directory. In -this case - `$GOPATH/src/godogs` - -### Step 2 - -If godog is installed in your GOPATH. We can run `godog` inside the -**$GOPATH/src/godogs** directory. You should see that the steps are -undefined: - -![Undefined step snippets](/screenshots/undefined.png?raw=true) - -If we wish to vendor godog dependency, we can do it as usual, using tools -you prefer: - - git clone https://github.com/DATA-DOG/godog.git $GOPATH/src/godogs/vendor/github.com/DATA-DOG/godog - -It gives you undefined step snippets to implement in your test context. -You may copy these snippets into your `godogs_test.go` file. - -Our directory structure should now look like: - -![Directory layout](/screenshots/dir-tree.png?raw=true) - -If you copy the snippets into our test file and run godog again. We should -see the step definition is now pending: - -![Pending step definition](/screenshots/pending.png?raw=true) - -You may change **ErrPending** to **nil** and the scenario will -pass successfully. - -Since we need a working implementation, we may start by implementing only what is necessary. - -### Step 3 - -We only need a number of **godogs** for now. Lets keep it simple. - -``` go -/* file: $GOPATH/src/godogs/godogs.go */ -package main - -// Godogs available to eat -var Godogs int - -func main() { /* usual main func */ } -``` - -### Step 4 - -Now lets implement our step definitions, which we can copy from generated -console output snippets in order to test our feature requirements: - -``` go -/* file: $GOPATH/src/godogs/godogs_test.go */ -package main - -import ( - "fmt" - - "github.com/DATA-DOG/godog" -) - -func thereAreGodogs(available int) error { - Godogs = available - return nil -} - -func iEat(num int) error { - if Godogs < num { - return fmt.Errorf("you cannot eat %d godogs, there are %d available", num, Godogs) - } - Godogs -= num - return nil -} - -func thereShouldBeRemaining(remaining int) error { - if Godogs != remaining { - return fmt.Errorf("expected %d godogs to be remaining, but there is %d", remaining, Godogs) - } - return nil -} - -func FeatureContext(s *godog.Suite) { - s.Step(`^there are (\d+) godogs$`, thereAreGodogs) - s.Step(`^I eat (\d+)$`, iEat) - s.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining) - - s.BeforeScenario(func(interface{}) { - Godogs = 0 // clean the state before every scenario - }) -} -``` - -Now when you run the `godog` again, you should see: - -![Passed suite](/screenshots/passed.png?raw=true) - -We have hooked to **BeforeScenario** event in order to reset application -state before each scenario. You may hook into more events, like -**AfterStep** to print all state in case of an error. Or -**BeforeSuite** to prepare a database. - -By now, you should have figured out, how to use **godog**. Another advice -is to make steps orthogonal, small and simple to read for an user. Whether -the user is a dumb website user or an API developer, who may understand -a little more technical context - it should target that user. - -When steps are orthogonal and small, you can combine them just like you do -with Unix tools. Look how to simplify or remove ones, which can be -composed. - -### References and Tutorials - -- [cucumber-html-reporter](https://github.com/gkushang/cucumber-html-reporter) - may be used in order to generate **html** reports together with - **cucumber** output formatter. See the [following docker - image](https://github.com/myie/cucumber-html-reporter) for usage - details. -- [how to use godog by semaphoreci](https://semaphoreci.com/community/tutorials/how-to-use-godog-for-behavior-driven-development-in-go) -- see [examples](https://github.com/DATA-DOG/godog/tree/master/examples) -- see extension [AssistDog](https://github.com/hellomd/assistdog), which - may have useful **gherkin.DataTable** transformations or comparison - methods for assertions. - -### Documentation - -See [godoc][godoc] for general API details. -See **.travis.yml** for supported **go** versions. -See `godog -h` for general command options. - -See implementation examples: - -- [rest API server](/examples/api) -- [rest API with Database](/examples/db) -- [godogs](/examples/godogs) - -## FAQ - -### Running Godog with go test - -You may integrate running **godog** in your **go test** command. You can -run it using go [TestMain](https://golang.org/pkg/testing/#hdr-Main) func -available since **go 1.4**. In this case it is not necessary to have -**godog** command installed. See the following example: - -``` go -func TestMain(m *testing.M) { - status := godog.RunWithOptions("godog", func(s *godog.Suite) { - FeatureContext(s) - }, godog.Options{ - Format: "progress", - Paths: []string{"features"}, - Randomize: time.Now().UTC().UnixNano(), // randomize scenario execution order - }) - - if st := m.Run(); st > status { - status = st - } - os.Exit(status) -} -``` - -You can even go one step further and reuse **go test** flags, like -**verbose** mode in order to switch godog **format**. See the following -example: - -``` go -func TestMain(m *testing.M) { - format := "progress" - for _, arg := range os.Args[1:] { - if arg == "-test.v=true" { // go test transforms -v option - format = "pretty" - break - } - } - status := godog.RunWithOptions("godog", func(s *godog.Suite) { - godog.SuiteContext(s) - }, godog.Options{ - Format: format, - Paths: []string{"features"}, - }) - - if st := m.Run(); st > status { - status = st - } - os.Exit(status) -} -``` - -Now when running `go test -v` it will use **pretty** format. - -### Configure common options for godog CLI - -There are no global options or configuration files. Alias your common or -project based commands: `alias godog-wip="godog --format=progress ---tags=@wip"` - -### Testing browser interactions - -**godog** does not come with builtin packages to connect to the browser. -You may want to look at [selenium](http://www.seleniumhq.org/) and -probably [phantomjs](http://phantomjs.org/). See also the following -components: - -1. [browsersteps](https://github.com/llonchj/browsersteps) - provides - basic context steps to start selenium and navigate browser content. -2. You may wish to have [goquery](https://github.com/PuerkitoBio/goquery) - in order to work with HTML responses like with JQuery. - -### Concurrency - -In order to support concurrency well, you should reset the state and -isolate each scenario. They should not share any state. It is suggested to -run the suite concurrently in order to make sure there is no state -corruption or race conditions in the application. - -It is also useful to randomize the order of scenario execution, which you -can now do with **--random** command option. - -**NOTE:** if suite runs with concurrency option, it concurrently runs -every feature, not scenario per different features. This gives -a flexibility to isolate state per feature. For example using -**BeforeFeature** hook, it is possible to spin up costly service and shut -it down only in **AfterFeature** hook and share the service between all -scenarios in that feature. It is not advisable though, because you are -risking having a state dependency. - -## Contributions - -Feel free to open a pull request. Note, if you wish to contribute an extension to public (exported methods or types) - -please open an issue before to discuss whether these changes can be accepted. All backward incompatible changes are -and will be treated cautiously. - -## License - -**Godog** is licensed under the [three clause BSD license][license] - -**Gherkin** is licensed under the [MIT][gherkin-license] and developed as -a part of the [cucumber project][cucumber] - -[godoc]: http://godoc.org/github.com/DATA-DOG/godog "Documentation on godoc" -[golang]: https://golang.org/ "GO programming language" -[behat]: http://docs.behat.org/ "Behavior driven development framework for PHP" -[cucumber]: https://cucumber.io/ "Behavior driven development framework" -[gherkin]: https://github.com/cucumber/gherkin-go "Gherkin3 parser for GO" -[gherkin-license]: https://en.wikipedia.org/wiki/MIT_License "The MIT license" -[license]: http://en.wikipedia.org/wiki/BSD_licenses "The three clause BSD license" diff --git a/vendor/github.com/DATA-DOG/godog/ast.go b/vendor/github.com/DATA-DOG/godog/ast.go deleted file mode 100644 index fe275e039..000000000 --- a/vendor/github.com/DATA-DOG/godog/ast.go +++ /dev/null @@ -1,31 +0,0 @@ -package godog - -import "go/ast" - -func astContexts(f *ast.File) []string { - var contexts []string - for _, d := range f.Decls { - switch fun := d.(type) { - case *ast.FuncDecl: - for _, param := range fun.Type.Params.List { - switch expr := param.Type.(type) { - case *ast.StarExpr: - switch x := expr.X.(type) { - case *ast.Ident: - if x.Name == "Suite" { - contexts = append(contexts, fun.Name.Name) - } - case *ast.SelectorExpr: - switch t := x.X.(type) { - case *ast.Ident: - if t.Name == "godog" && x.Sel.Name == "Suite" { - contexts = append(contexts, fun.Name.Name) - } - } - } - } - } - } - } - return contexts -} diff --git a/vendor/github.com/DATA-DOG/godog/builder.go b/vendor/github.com/DATA-DOG/godog/builder.go deleted file mode 100644 index d27d25f56..000000000 --- a/vendor/github.com/DATA-DOG/godog/builder.go +++ /dev/null @@ -1,337 +0,0 @@ -// +build !go1.10 - -package godog - -import ( - "bytes" - "fmt" - "go/build" - "go/parser" - "go/token" - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "strings" - "text/template" - "time" - "unicode" -) - -var tooldir = findToolDir() -var compiler = filepath.Join(tooldir, "compile") -var linker = filepath.Join(tooldir, "link") -var gopaths = filepath.SplitList(build.Default.GOPATH) -var goarch = build.Default.GOARCH -var goos = build.Default.GOOS - -var godogImportPath = "github.com/DATA-DOG/godog" -var runnerTemplate = template.Must(template.New("testmain").Parse(`package main - -import ( - "github.com/DATA-DOG/godog" - {{if .Contexts}}_test "{{.ImportPath}}"{{end}} - "os" -) - -func main() { - status := godog.Run("{{ .Name }}", func (suite *godog.Suite) { - os.Setenv("GODOG_TESTED_PACKAGE", "{{.ImportPath}}") - {{range .Contexts}} - _test.{{ . }}(suite) - {{end}} - }) - os.Exit(status) -}`)) - -// Build creates a test package like go test command at given target path. -// If there are no go files in tested directory, then -// it simply builds a godog executable to scan features. -// -// If there are go test files, it first builds a test -// package with standard go test command. -// -// Finally it generates godog suite executable which -// registers exported godog contexts from the test files -// of tested package. -// -// Returns the path to generated executable -func Build(bin string) error { - abs, err := filepath.Abs(".") - if err != nil { - return err - } - - // we allow package to be nil, if godog is run only when - // there is a feature file in empty directory - pkg := importPackage(abs) - src, anyContexts, err := buildTestMain(pkg) - if err != nil { - return err - } - - workdir := fmt.Sprintf(filepath.Join("%s", "godog-%d"), os.TempDir(), time.Now().UnixNano()) - testdir := workdir - - // if none of test files exist, or there are no contexts found - // we will skip test package compilation, since it is useless - if anyContexts { - // first of all compile test package dependencies - // that will save was many compilations for dependencies - // go does it better - out, err := exec.Command("go", "test", "-i").CombinedOutput() - if err != nil { - return fmt.Errorf("failed to compile package: %s, reason: %v, output: %s", pkg.Name, err, string(out)) - } - - // let go do the dirty work and compile test - // package with it's dependencies. Older go - // versions does not accept existing file output - // so we create a temporary executable which will - // removed. - temp := fmt.Sprintf(filepath.Join("%s", "temp-%d.test"), os.TempDir(), time.Now().UnixNano()) - - // builds and compile the tested package. - // generated test executable will be removed - // since we do not need it for godog suite. - // we also print back the temp WORK directory - // go has built. We will reuse it for our suite workdir. - out, err = exec.Command("go", "test", "-c", "-work", "-o", temp).CombinedOutput() - if err != nil { - return fmt.Errorf("failed to compile tested package: %s, reason: %v, output: %s", pkg.Name, err, string(out)) - } - defer os.Remove(temp) - - // extract go-build temporary directory as our workdir - workdir = strings.TrimSpace(string(out)) - if !strings.HasPrefix(workdir, "WORK=") { - return fmt.Errorf("expected WORK dir path, but got: %s", workdir) - } - workdir = strings.Replace(workdir, "WORK=", "", 1) - testdir = filepath.Join(workdir, pkg.ImportPath, "_test") - } else { - // still need to create temporary workdir - if err = os.MkdirAll(testdir, 0755); err != nil { - return err - } - } - defer os.RemoveAll(workdir) - - // replace _testmain.go file with our own - testmain := filepath.Join(testdir, "_testmain.go") - err = ioutil.WriteFile(testmain, src, 0644) - if err != nil { - return err - } - - // godog library may not be imported in tested package - // but we need it for our testmain package. - // So we look it up in available source paths - // including vendor directory, supported since 1.5. - try := maybeVendorPaths(abs) - for _, d := range build.Default.SrcDirs() { - try = append(try, filepath.Join(d, godogImportPath)) - } - godogPkg, err := locatePackage(try) - if err != nil { - return err - } - - // make sure godog package archive is installed, gherkin - // will be installed as dependency of godog - cmd := exec.Command("go", "install", godogPkg.ImportPath) - cmd.Env = os.Environ() - out, err := cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("failed to install godog package: %s, reason: %v", string(out), err) - } - - // collect all possible package dirs, will be - // used for includes and linker - pkgDirs := []string{workdir, testdir} - for _, gopath := range gopaths { - pkgDirs = append(pkgDirs, filepath.Join(gopath, "pkg", goos+"_"+goarch)) - } - pkgDirs = uniqStringList(pkgDirs) - - // compile godog testmain package archive - // we do not depend on CGO so a lot of checks are not necessary - testMainPkgOut := filepath.Join(testdir, "main.a") - args := []string{ - "-o", testMainPkgOut, - // "-trimpath", workdir, - "-p", "main", - "-complete", - } - // if godog library is in vendor directory - // link it with import map - if i := strings.LastIndex(godogPkg.ImportPath, "vendor/"); i != -1 { - args = append(args, "-importmap", godogImportPath+"="+godogPkg.ImportPath) - } - for _, inc := range pkgDirs { - args = append(args, "-I", inc) - } - args = append(args, "-pack", testmain) - cmd = exec.Command(compiler, args...) - cmd.Env = os.Environ() - out, err = cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("failed to compile testmain package: %v - output: %s", err, string(out)) - } - - // link test suite executable - args = []string{ - "-o", bin, - "-buildmode=exe", - } - for _, link := range pkgDirs { - args = append(args, "-L", link) - } - args = append(args, testMainPkgOut) - cmd = exec.Command(linker, args...) - cmd.Env = os.Environ() - - out, err = cmd.CombinedOutput() - if err != nil { - msg := `failed to link test executable: - reason: %s - command: %s` - return fmt.Errorf(msg, string(out), linker+" '"+strings.Join(args, "' '")+"'") - } - - return nil -} - -func locatePackage(try []string) (*build.Package, error) { - for _, p := range try { - abs, err := filepath.Abs(p) - if err != nil { - continue - } - pkg, err := build.ImportDir(abs, 0) - if err != nil { - continue - } - return pkg, nil - } - return nil, fmt.Errorf("failed to find godog package in any of:\n%s", strings.Join(try, "\n")) -} - -func importPackage(dir string) *build.Package { - pkg, _ := build.ImportDir(dir, 0) - - // normalize import path for local import packages - // taken from go source code - // see: https://github.com/golang/go/blob/go1.7rc5/src/cmd/go/pkg.go#L279 - if pkg != nil && pkg.ImportPath == "." { - pkg.ImportPath = path.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir))) - } - - return pkg -} - -// from go src -func makeImportValid(r rune) rune { - // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport. - const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" - if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { - return '_' - } - return r -} - -func uniqStringList(strs []string) (unique []string) { - uniq := make(map[string]void, len(strs)) - for _, s := range strs { - if _, ok := uniq[s]; !ok { - uniq[s] = void{} - unique = append(unique, s) - } - } - return -} - -// buildTestMain if given package is valid -// it scans test files for contexts -// and produces a testmain source code. -func buildTestMain(pkg *build.Package) ([]byte, bool, error) { - var contexts []string - var importPath string - name := "main" - if nil != pkg { - ctxs, err := processPackageTestFiles( - pkg.TestGoFiles, - pkg.XTestGoFiles, - ) - if err != nil { - return nil, false, err - } - contexts = ctxs - importPath = pkg.ImportPath - name = pkg.Name - } - - data := struct { - Name string - Contexts []string - ImportPath string - }{name, contexts, importPath} - - var buf bytes.Buffer - if err := runnerTemplate.Execute(&buf, data); err != nil { - return nil, len(contexts) > 0, err - } - return buf.Bytes(), len(contexts) > 0, nil -} - -// maybeVendorPaths determines possible vendor paths -// which goes levels down from given directory -// until it reaches GOPATH source dir -func maybeVendorPaths(dir string) (paths []string) { - for _, gopath := range gopaths { - gopath = filepath.Join(gopath, "src") - for strings.HasPrefix(dir, gopath) && dir != gopath { - paths = append(paths, filepath.Join(dir, "vendor", godogImportPath)) - dir = filepath.Dir(dir) - } - } - return -} - -// processPackageTestFiles runs through ast of each test -// file pack and looks for godog suite contexts to register -// on run -func processPackageTestFiles(packs ...[]string) ([]string, error) { - var ctxs []string - fset := token.NewFileSet() - for _, pack := range packs { - for _, testFile := range pack { - node, err := parser.ParseFile(fset, testFile, nil, 0) - if err != nil { - return ctxs, err - } - - ctxs = append(ctxs, astContexts(node)...) - } - } - var failed []string - for _, ctx := range ctxs { - runes := []rune(ctx) - if unicode.IsLower(runes[0]) { - expected := append([]rune{unicode.ToUpper(runes[0])}, runes[1:]...) - failed = append(failed, fmt.Sprintf("%s - should be: %s", ctx, string(expected))) - } - } - if len(failed) > 0 { - return ctxs, fmt.Errorf("godog contexts must be exported:\n\t%s", strings.Join(failed, "\n\t")) - } - return ctxs, nil -} - -func findToolDir() string { - if out, err := exec.Command("go", "env", "GOTOOLDIR").Output(); err != nil { - return filepath.Clean(strings.TrimSpace(string(out))) - } - return filepath.Clean(build.ToolDir) -} diff --git a/vendor/github.com/DATA-DOG/godog/builder_go110.go b/vendor/github.com/DATA-DOG/godog/builder_go110.go deleted file mode 100644 index 19aa297f9..000000000 --- a/vendor/github.com/DATA-DOG/godog/builder_go110.go +++ /dev/null @@ -1,409 +0,0 @@ -// +build go1.10 - -package godog - -import ( - "bytes" - "fmt" - "go/build" - "go/parser" - "go/token" - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "strings" - "text/template" - "time" - "unicode" -) - -var tooldir = findToolDir() -var compiler = filepath.Join(tooldir, "compile") -var linker = filepath.Join(tooldir, "link") -var gopaths = filepath.SplitList(build.Default.GOPATH) -var goarch = build.Default.GOARCH -var goroot = build.Default.GOROOT -var goos = build.Default.GOOS - -var godogImportPath = "github.com/DATA-DOG/godog" -var runnerTemplate = template.Must(template.New("testmain").Parse(`package main - -import ( - "github.com/DATA-DOG/godog" - {{if .Contexts}}_test "{{.ImportPath}}"{{end}} - "os" -) - -func main() { - status := godog.Run("{{ .Name }}", func (suite *godog.Suite) { - os.Setenv("GODOG_TESTED_PACKAGE", "{{.ImportPath}}") - {{range .Contexts}} - _test.{{ . }}(suite) - {{end}} - }) - os.Exit(status) -}`)) - -// Build creates a test package like go test command at given target path. -// If there are no go files in tested directory, then -// it simply builds a godog executable to scan features. -// -// If there are go test files, it first builds a test -// package with standard go test command. -// -// Finally it generates godog suite executable which -// registers exported godog contexts from the test files -// of tested package. -// -// Returns the path to generated executable -func Build(bin string) error { - abs, err := filepath.Abs(".") - if err != nil { - return err - } - - // we allow package to be nil, if godog is run only when - // there is a feature file in empty directory - pkg := importPackage(abs) - src, anyContexts, err := buildTestMain(pkg) - if err != nil { - return err - } - - workdir := fmt.Sprintf(filepath.Join("%s", "godog-%d"), os.TempDir(), time.Now().UnixNano()) - testdir := workdir - - // if none of test files exist, or there are no contexts found - // we will skip test package compilation, since it is useless - if anyContexts { - // first of all compile test package dependencies - // that will save us many compilations for dependencies - // go does it better - out, err := exec.Command("go", "test", "-i").CombinedOutput() - if err != nil { - return fmt.Errorf("failed to compile package: %s, reason: %v, output: %s", pkg.Name, err, string(out)) - } - - // builds and compile the tested package. - // generated test executable will be removed - // since we do not need it for godog suite. - // we also print back the temp WORK directory - // go has built. We will reuse it for our suite workdir. - out, err = exec.Command("go", "test", "-c", "-work", "-o", "/dev/null").CombinedOutput() - if err != nil { - return fmt.Errorf("failed to compile tested package: %s, reason: %v, output: %s", pkg.Name, err, string(out)) - } - - // extract go-build temporary directory as our workdir - workdir = strings.TrimSpace(string(out)) - if !strings.HasPrefix(workdir, "WORK=") { - return fmt.Errorf("expected WORK dir path, but got: %s", workdir) - } - workdir = strings.Replace(workdir, "WORK=", "", 1) - testdir = filepath.Join(workdir, "b001") - } else { - // still need to create temporary workdir - if err = os.MkdirAll(testdir, 0755); err != nil { - return err - } - } - defer os.RemoveAll(workdir) - - // replace _testmain.go file with our own - testmain := filepath.Join(testdir, "_testmain.go") - err = ioutil.WriteFile(testmain, src, 0644) - if err != nil { - return err - } - - // godog library may not be imported in tested package - // but we need it for our testmain package. - // So we look it up in available source paths - // including vendor directory, supported since 1.5. - godogPkg, err := locatePackage(godogImportPath) - if err != nil { - return err - } - - // make sure godog package archive is installed, gherkin - // will be installed as dependency of godog - cmd := exec.Command("go", "install", "-i", godogPkg.ImportPath) - cmd.Env = os.Environ() - out, err := cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("failed to install godog package: %s, reason: %v", string(out), err) - } - - // compile godog testmain package archive - // we do not depend on CGO so a lot of checks are not necessary - testMainPkgOut := filepath.Join(testdir, "main.a") - args := []string{ - "-o", testMainPkgOut, - "-p", "main", - "-complete", - } - - cfg := filepath.Join(testdir, "importcfg.link") - args = append(args, "-importcfg", cfg) - if _, err := os.Stat(cfg); err != nil { - // there were no go sources in the directory - // so we need to build all dependency tree ourselves - in, err := os.Create(cfg) - if err != nil { - return err - } - fmt.Fprintln(in, "# import config") - - deps := make(map[string]string) - if err := dependencies(godogPkg, deps, false); err != nil { - in.Close() - return err - } - - for pkgName, pkgObj := range deps { - if i := strings.LastIndex(pkgName, "vendor/"); i != -1 { - name := pkgName[i+7:] - fmt.Fprintf(in, "importmap %s=%s\n", name, pkgName) - } - fmt.Fprintf(in, "packagefile %s=%s\n", pkgName, pkgObj) - } - in.Close() - } else { - // need to make sure that vendor dependencies are mapped - in, err := os.OpenFile(cfg, os.O_APPEND|os.O_WRONLY, 0600) - if err != nil { - return err - } - deps := make(map[string]string) - if err := dependencies(pkg, deps, true); err != nil { - in.Close() - return err - } - if err := dependencies(godogPkg, deps, false); err != nil { - in.Close() - return err - } - for pkgName := range deps { - if i := strings.LastIndex(pkgName, "vendor/"); i != -1 { - name := pkgName[i+7:] - fmt.Fprintf(in, "importmap %s=%s\n", name, pkgName) - } - } - in.Close() - } - - args = append(args, "-pack", testmain) - cmd = exec.Command(compiler, args...) - cmd.Env = os.Environ() - out, err = cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("failed to compile testmain package: %v - output: %s", err, string(out)) - } - - // link test suite executable - args = []string{ - "-o", bin, - "-importcfg", cfg, - "-buildmode=exe", - } - args = append(args, testMainPkgOut) - cmd = exec.Command(linker, args...) - cmd.Env = os.Environ() - - // in case if build is without contexts, need to remove import maps - data, err := ioutil.ReadFile(cfg) - if err != nil { - return err - } - - lines := strings.Split(string(data), "\n") - var fixed []string - for _, line := range lines { - if strings.Index(line, "importmap") == 0 { - continue - } - fixed = append(fixed, line) - } - if err := ioutil.WriteFile(cfg, []byte(strings.Join(fixed, "\n")), 0600); err != nil { - return err - } - - out, err = cmd.CombinedOutput() - if err != nil { - msg := `failed to link test executable: - reason: %s - command: %s` - return fmt.Errorf(msg, string(out), linker+" '"+strings.Join(args, "' '")+"'") - } - - return nil -} - -func locatePackage(name string) (*build.Package, error) { - // search vendor paths first since that takes priority - dir, err := filepath.Abs(".") - if err != nil { - return nil, err - } - - for _, gopath := range gopaths { - gopath = filepath.Join(gopath, "src") - for strings.HasPrefix(dir, gopath) && dir != gopath { - pkg, err := build.ImportDir(filepath.Join(dir, "vendor", name), 0) - if err != nil { - dir = filepath.Dir(dir) - continue - } - return pkg, nil - } - } - - // search source paths otherwise - for _, p := range build.Default.SrcDirs() { - abs, err := filepath.Abs(filepath.Join(p, name)) - if err != nil { - continue - } - pkg, err := build.ImportDir(abs, 0) - if err != nil { - continue - } - return pkg, nil - } - - return nil, fmt.Errorf("failed to find %s package in any of:\n%s", name, strings.Join(build.Default.SrcDirs(), "\n")) -} - -func importPackage(dir string) *build.Package { - pkg, _ := build.ImportDir(dir, 0) - - // normalize import path for local import packages - // taken from go source code - // see: https://github.com/golang/go/blob/go1.7rc5/src/cmd/go/pkg.go#L279 - if pkg != nil && pkg.ImportPath == "." { - pkg.ImportPath = path.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir))) - } - - return pkg -} - -// from go src -func makeImportValid(r rune) rune { - // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport. - const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" - if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { - return '_' - } - return r -} - -func uniqStringList(strs []string) (unique []string) { - uniq := make(map[string]void, len(strs)) - for _, s := range strs { - if _, ok := uniq[s]; !ok { - uniq[s] = void{} - unique = append(unique, s) - } - } - return -} - -// buildTestMain if given package is valid -// it scans test files for contexts -// and produces a testmain source code. -func buildTestMain(pkg *build.Package) ([]byte, bool, error) { - var contexts []string - var importPath string - name := "main" - if nil != pkg { - ctxs, err := processPackageTestFiles( - pkg.TestGoFiles, - pkg.XTestGoFiles, - ) - if err != nil { - return nil, false, err - } - contexts = ctxs - importPath = pkg.ImportPath - name = pkg.Name - } - - data := struct { - Name string - Contexts []string - ImportPath string - }{name, contexts, importPath} - - var buf bytes.Buffer - if err := runnerTemplate.Execute(&buf, data); err != nil { - return nil, len(contexts) > 0, err - } - return buf.Bytes(), len(contexts) > 0, nil -} - -// processPackageTestFiles runs through ast of each test -// file pack and looks for godog suite contexts to register -// on run -func processPackageTestFiles(packs ...[]string) ([]string, error) { - var ctxs []string - fset := token.NewFileSet() - for _, pack := range packs { - for _, testFile := range pack { - node, err := parser.ParseFile(fset, testFile, nil, 0) - if err != nil { - return ctxs, err - } - - ctxs = append(ctxs, astContexts(node)...) - } - } - var failed []string - for _, ctx := range ctxs { - runes := []rune(ctx) - if unicode.IsLower(runes[0]) { - expected := append([]rune{unicode.ToUpper(runes[0])}, runes[1:]...) - failed = append(failed, fmt.Sprintf("%s - should be: %s", ctx, string(expected))) - } - } - if len(failed) > 0 { - return ctxs, fmt.Errorf("godog contexts must be exported:\n\t%s", strings.Join(failed, "\n\t")) - } - return ctxs, nil -} - -func findToolDir() string { - if out, err := exec.Command("go", "env", "GOTOOLDIR").Output(); err != nil { - return filepath.Clean(strings.TrimSpace(string(out))) - } - return filepath.Clean(build.ToolDir) -} - -func dependencies(pkg *build.Package, visited map[string]string, vendor bool) error { - visited[pkg.ImportPath] = pkg.PkgObj - imports := pkg.Imports - if vendor { - imports = append(imports, pkg.TestImports...) - } - for _, name := range imports { - if i := strings.LastIndex(name, "vendor/"); vendor && i == -1 { - continue // only interested in vendor packages - } - - if _, ok := visited[name]; ok { - continue - } - - next, err := locatePackage(name) - if err != nil { - return err - } - - visited[name] = pkg.PkgObj - if err := dependencies(next, visited, vendor); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/DATA-DOG/godog/colors/ansi_others.go b/vendor/github.com/DATA-DOG/godog/colors/ansi_others.go deleted file mode 100644 index 4ce4e7796..000000000 --- a/vendor/github.com/DATA-DOG/godog/colors/ansi_others.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2014 shiena Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -// +build !windows - -package colors - -import "io" - -type ansiColorWriter struct { - w io.Writer - mode outputMode -} - -func (cw *ansiColorWriter) Write(p []byte) (int, error) { - return cw.w.Write(p) -} diff --git a/vendor/github.com/DATA-DOG/godog/colors/ansi_windows.go b/vendor/github.com/DATA-DOG/godog/colors/ansi_windows.go deleted file mode 100644 index 66401f957..000000000 --- a/vendor/github.com/DATA-DOG/godog/colors/ansi_windows.go +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright 2014 shiena Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -// +build windows - -package colors - -import ( - "bytes" - "io" - "strings" - "syscall" - "unsafe" -) - -type csiState int - -const ( - outsideCsiCode csiState = iota - firstCsiCode - secondCsiCode -) - -type parseResult int - -const ( - noConsole parseResult = iota - changedColor - unknown -) - -type ansiColorWriter struct { - w io.Writer - mode outputMode - state csiState - paramStartBuf bytes.Buffer - paramBuf bytes.Buffer -} - -const ( - firstCsiChar byte = '\x1b' - secondeCsiChar byte = '[' - separatorChar byte = ';' - sgrCode byte = 'm' -) - -const ( - foregroundBlue = uint16(0x0001) - foregroundGreen = uint16(0x0002) - foregroundRed = uint16(0x0004) - foregroundIntensity = uint16(0x0008) - backgroundBlue = uint16(0x0010) - backgroundGreen = uint16(0x0020) - backgroundRed = uint16(0x0040) - backgroundIntensity = uint16(0x0080) - underscore = uint16(0x8000) - - foregroundMask = foregroundBlue | foregroundGreen | foregroundRed | foregroundIntensity - backgroundMask = backgroundBlue | backgroundGreen | backgroundRed | backgroundIntensity -) - -const ( - ansiReset = "0" - ansiIntensityOn = "1" - ansiIntensityOff = "21" - ansiUnderlineOn = "4" - ansiUnderlineOff = "24" - ansiBlinkOn = "5" - ansiBlinkOff = "25" - - ansiForegroundBlack = "30" - ansiForegroundRed = "31" - ansiForegroundGreen = "32" - ansiForegroundYellow = "33" - ansiForegroundBlue = "34" - ansiForegroundMagenta = "35" - ansiForegroundCyan = "36" - ansiForegroundWhite = "37" - ansiForegroundDefault = "39" - - ansiBackgroundBlack = "40" - ansiBackgroundRed = "41" - ansiBackgroundGreen = "42" - ansiBackgroundYellow = "43" - ansiBackgroundBlue = "44" - ansiBackgroundMagenta = "45" - ansiBackgroundCyan = "46" - ansiBackgroundWhite = "47" - ansiBackgroundDefault = "49" - - ansiLightForegroundGray = "90" - ansiLightForegroundRed = "91" - ansiLightForegroundGreen = "92" - ansiLightForegroundYellow = "93" - ansiLightForegroundBlue = "94" - ansiLightForegroundMagenta = "95" - ansiLightForegroundCyan = "96" - ansiLightForegroundWhite = "97" - - ansiLightBackgroundGray = "100" - ansiLightBackgroundRed = "101" - ansiLightBackgroundGreen = "102" - ansiLightBackgroundYellow = "103" - ansiLightBackgroundBlue = "104" - ansiLightBackgroundMagenta = "105" - ansiLightBackgroundCyan = "106" - ansiLightBackgroundWhite = "107" -) - -type drawType int - -const ( - foreground drawType = iota - background -) - -type winColor struct { - code uint16 - drawType drawType -} - -var colorMap = map[string]winColor{ - ansiForegroundBlack: {0, foreground}, - ansiForegroundRed: {foregroundRed, foreground}, - ansiForegroundGreen: {foregroundGreen, foreground}, - ansiForegroundYellow: {foregroundRed | foregroundGreen, foreground}, - ansiForegroundBlue: {foregroundBlue, foreground}, - ansiForegroundMagenta: {foregroundRed | foregroundBlue, foreground}, - ansiForegroundCyan: {foregroundGreen | foregroundBlue, foreground}, - ansiForegroundWhite: {foregroundRed | foregroundGreen | foregroundBlue, foreground}, - ansiForegroundDefault: {foregroundRed | foregroundGreen | foregroundBlue, foreground}, - - ansiBackgroundBlack: {0, background}, - ansiBackgroundRed: {backgroundRed, background}, - ansiBackgroundGreen: {backgroundGreen, background}, - ansiBackgroundYellow: {backgroundRed | backgroundGreen, background}, - ansiBackgroundBlue: {backgroundBlue, background}, - ansiBackgroundMagenta: {backgroundRed | backgroundBlue, background}, - ansiBackgroundCyan: {backgroundGreen | backgroundBlue, background}, - ansiBackgroundWhite: {backgroundRed | backgroundGreen | backgroundBlue, background}, - ansiBackgroundDefault: {0, background}, - - ansiLightForegroundGray: {foregroundIntensity, foreground}, - ansiLightForegroundRed: {foregroundIntensity | foregroundRed, foreground}, - ansiLightForegroundGreen: {foregroundIntensity | foregroundGreen, foreground}, - ansiLightForegroundYellow: {foregroundIntensity | foregroundRed | foregroundGreen, foreground}, - ansiLightForegroundBlue: {foregroundIntensity | foregroundBlue, foreground}, - ansiLightForegroundMagenta: {foregroundIntensity | foregroundRed | foregroundBlue, foreground}, - ansiLightForegroundCyan: {foregroundIntensity | foregroundGreen | foregroundBlue, foreground}, - ansiLightForegroundWhite: {foregroundIntensity | foregroundRed | foregroundGreen | foregroundBlue, foreground}, - - ansiLightBackgroundGray: {backgroundIntensity, background}, - ansiLightBackgroundRed: {backgroundIntensity | backgroundRed, background}, - ansiLightBackgroundGreen: {backgroundIntensity | backgroundGreen, background}, - ansiLightBackgroundYellow: {backgroundIntensity | backgroundRed | backgroundGreen, background}, - ansiLightBackgroundBlue: {backgroundIntensity | backgroundBlue, background}, - ansiLightBackgroundMagenta: {backgroundIntensity | backgroundRed | backgroundBlue, background}, - ansiLightBackgroundCyan: {backgroundIntensity | backgroundGreen | backgroundBlue, background}, - ansiLightBackgroundWhite: {backgroundIntensity | backgroundRed | backgroundGreen | backgroundBlue, background}, -} - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - defaultAttr *textAttributes -) - -func init() { - screenInfo := getConsoleScreenBufferInfo(uintptr(syscall.Stdout)) - if screenInfo != nil { - colorMap[ansiForegroundDefault] = winColor{ - screenInfo.WAttributes & (foregroundRed | foregroundGreen | foregroundBlue), - foreground, - } - colorMap[ansiBackgroundDefault] = winColor{ - screenInfo.WAttributes & (backgroundRed | backgroundGreen | backgroundBlue), - background, - } - defaultAttr = convertTextAttr(screenInfo.WAttributes) - } -} - -type coord struct { - X, Y int16 -} - -type smallRect struct { - Left, Top, Right, Bottom int16 -} - -type consoleScreenBufferInfo struct { - DwSize coord - DwCursorPosition coord - WAttributes uint16 - SrWindow smallRect - DwMaximumWindowSize coord -} - -func getConsoleScreenBufferInfo(hConsoleOutput uintptr) *consoleScreenBufferInfo { - var csbi consoleScreenBufferInfo - ret, _, _ := procGetConsoleScreenBufferInfo.Call( - hConsoleOutput, - uintptr(unsafe.Pointer(&csbi))) - if ret == 0 { - return nil - } - return &csbi -} - -func setConsoleTextAttribute(hConsoleOutput uintptr, wAttributes uint16) bool { - ret, _, _ := procSetConsoleTextAttribute.Call( - hConsoleOutput, - uintptr(wAttributes)) - return ret != 0 -} - -type textAttributes struct { - foregroundColor uint16 - backgroundColor uint16 - foregroundIntensity uint16 - backgroundIntensity uint16 - underscore uint16 - otherAttributes uint16 -} - -func convertTextAttr(winAttr uint16) *textAttributes { - fgColor := winAttr & (foregroundRed | foregroundGreen | foregroundBlue) - bgColor := winAttr & (backgroundRed | backgroundGreen | backgroundBlue) - fgIntensity := winAttr & foregroundIntensity - bgIntensity := winAttr & backgroundIntensity - underline := winAttr & underscore - otherAttributes := winAttr &^ (foregroundMask | backgroundMask | underscore) - return &textAttributes{fgColor, bgColor, fgIntensity, bgIntensity, underline, otherAttributes} -} - -func convertWinAttr(textAttr *textAttributes) uint16 { - var winAttr uint16 - winAttr |= textAttr.foregroundColor - winAttr |= textAttr.backgroundColor - winAttr |= textAttr.foregroundIntensity - winAttr |= textAttr.backgroundIntensity - winAttr |= textAttr.underscore - winAttr |= textAttr.otherAttributes - return winAttr -} - -func changeColor(param []byte) parseResult { - screenInfo := getConsoleScreenBufferInfo(uintptr(syscall.Stdout)) - if screenInfo == nil { - return noConsole - } - - winAttr := convertTextAttr(screenInfo.WAttributes) - strParam := string(param) - if len(strParam) <= 0 { - strParam = "0" - } - csiParam := strings.Split(strParam, string(separatorChar)) - for _, p := range csiParam { - c, ok := colorMap[p] - switch { - case !ok: - switch p { - case ansiReset: - winAttr.foregroundColor = defaultAttr.foregroundColor - winAttr.backgroundColor = defaultAttr.backgroundColor - winAttr.foregroundIntensity = defaultAttr.foregroundIntensity - winAttr.backgroundIntensity = defaultAttr.backgroundIntensity - winAttr.underscore = 0 - winAttr.otherAttributes = 0 - case ansiIntensityOn: - winAttr.foregroundIntensity = foregroundIntensity - case ansiIntensityOff: - winAttr.foregroundIntensity = 0 - case ansiUnderlineOn: - winAttr.underscore = underscore - case ansiUnderlineOff: - winAttr.underscore = 0 - case ansiBlinkOn: - winAttr.backgroundIntensity = backgroundIntensity - case ansiBlinkOff: - winAttr.backgroundIntensity = 0 - default: - // unknown code - } - case c.drawType == foreground: - winAttr.foregroundColor = c.code - case c.drawType == background: - winAttr.backgroundColor = c.code - } - } - winTextAttribute := convertWinAttr(winAttr) - setConsoleTextAttribute(uintptr(syscall.Stdout), winTextAttribute) - - return changedColor -} - -func parseEscapeSequence(command byte, param []byte) parseResult { - if defaultAttr == nil { - return noConsole - } - - switch command { - case sgrCode: - return changeColor(param) - default: - return unknown - } -} - -func (cw *ansiColorWriter) flushBuffer() (int, error) { - return cw.flushTo(cw.w) -} - -func (cw *ansiColorWriter) resetBuffer() (int, error) { - return cw.flushTo(nil) -} - -func (cw *ansiColorWriter) flushTo(w io.Writer) (int, error) { - var n1, n2 int - var err error - - startBytes := cw.paramStartBuf.Bytes() - cw.paramStartBuf.Reset() - if w != nil { - n1, err = cw.w.Write(startBytes) - if err != nil { - return n1, err - } - } else { - n1 = len(startBytes) - } - paramBytes := cw.paramBuf.Bytes() - cw.paramBuf.Reset() - if w != nil { - n2, err = cw.w.Write(paramBytes) - if err != nil { - return n1 + n2, err - } - } else { - n2 = len(paramBytes) - } - return n1 + n2, nil -} - -func isParameterChar(b byte) bool { - return ('0' <= b && b <= '9') || b == separatorChar -} - -func (cw *ansiColorWriter) Write(p []byte) (int, error) { - r, nw, first, last := 0, 0, 0, 0 - if cw.mode != discardNonColorEscSeq { - cw.state = outsideCsiCode - cw.resetBuffer() - } - - var err error - for i, ch := range p { - switch cw.state { - case outsideCsiCode: - if ch == firstCsiChar { - cw.paramStartBuf.WriteByte(ch) - cw.state = firstCsiCode - } - case firstCsiCode: - switch ch { - case firstCsiChar: - cw.paramStartBuf.WriteByte(ch) - break - case secondeCsiChar: - cw.paramStartBuf.WriteByte(ch) - cw.state = secondCsiCode - last = i - 1 - default: - cw.resetBuffer() - cw.state = outsideCsiCode - } - case secondCsiCode: - if isParameterChar(ch) { - cw.paramBuf.WriteByte(ch) - } else { - nw, err = cw.w.Write(p[first:last]) - r += nw - if err != nil { - return r, err - } - first = i + 1 - result := parseEscapeSequence(ch, cw.paramBuf.Bytes()) - if result == noConsole || (cw.mode == outputNonColorEscSeq && result == unknown) { - cw.paramBuf.WriteByte(ch) - nw, err := cw.flushBuffer() - if err != nil { - return r, err - } - r += nw - } else { - n, _ := cw.resetBuffer() - // Add one more to the size of the buffer for the last ch - r += n + 1 - } - - cw.state = outsideCsiCode - } - default: - cw.state = outsideCsiCode - } - } - - if cw.mode != discardNonColorEscSeq || cw.state == outsideCsiCode { - nw, err = cw.w.Write(p[first:len(p)]) - r += nw - } - - return r, err -} diff --git a/vendor/github.com/DATA-DOG/godog/colors/colors.go b/vendor/github.com/DATA-DOG/godog/colors/colors.go deleted file mode 100644 index df00cecff..000000000 --- a/vendor/github.com/DATA-DOG/godog/colors/colors.go +++ /dev/null @@ -1,59 +0,0 @@ -package colors - -import ( - "fmt" - "strings" -) - -const ansiEscape = "\x1b" - -// a color code type -type color int - -// some ansi colors -const ( - black color = iota + 30 - red - green - yellow - blue - magenta - cyan - white -) - -func colorize(s interface{}, c color) string { - return fmt.Sprintf("%s[%dm%v%s[0m", ansiEscape, c, s, ansiEscape) -} - -type ColorFunc func(interface{}) string - -func Bold(fn ColorFunc) ColorFunc { - return ColorFunc(func(input interface{}) string { - return strings.Replace(fn(input), ansiEscape+"[", ansiEscape+"[1;", 1) - }) -} - -func Green(s interface{}) string { - return colorize(s, green) -} - -func Red(s interface{}) string { - return colorize(s, red) -} - -func Cyan(s interface{}) string { - return colorize(s, cyan) -} - -func Black(s interface{}) string { - return colorize(s, black) -} - -func Yellow(s interface{}) string { - return colorize(s, yellow) -} - -func White(s interface{}) string { - return colorize(s, white) -} diff --git a/vendor/github.com/DATA-DOG/godog/colors/no_colors.go b/vendor/github.com/DATA-DOG/godog/colors/no_colors.go deleted file mode 100644 index 3381d1176..000000000 --- a/vendor/github.com/DATA-DOG/godog/colors/no_colors.go +++ /dev/null @@ -1,57 +0,0 @@ -package colors - -import ( - "bytes" - "fmt" - "io" -) - -type noColors struct { - out io.Writer - lastbuf bytes.Buffer -} - -func Uncolored(w io.Writer) io.Writer { - return &noColors{out: w} -} - -func (w *noColors) Write(data []byte) (n int, err error) { - er := bytes.NewBuffer(data) -loop: - for { - c1, _, err := er.ReadRune() - if err != nil { - break loop - } - if c1 != 0x1b { - fmt.Fprint(w.out, string(c1)) - continue - } - c2, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - break loop - } - if c2 != 0x5b { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - continue - } - - var buf bytes.Buffer - for { - c, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - w.lastbuf.Write(buf.Bytes()) - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - break - } - buf.Write([]byte(string(c))) - } - } - return len(data) - w.lastbuf.Len(), nil -} diff --git a/vendor/github.com/DATA-DOG/godog/colors/writer.go b/vendor/github.com/DATA-DOG/godog/colors/writer.go deleted file mode 100644 index 0d3365970..000000000 --- a/vendor/github.com/DATA-DOG/godog/colors/writer.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2014 shiena Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package colors - -import "io" - -type outputMode int - -// DiscardNonColorEscSeq supports the divided color escape sequence. -// But non-color escape sequence is not output. -// Please use the OutputNonColorEscSeq If you want to output a non-color -// escape sequences such as ncurses. However, it does not support the divided -// color escape sequence. -const ( - _ outputMode = iota - discardNonColorEscSeq - outputNonColorEscSeq -) - -// Colored creates and initializes a new ansiColorWriter -// using io.Writer w as its initial contents. -// In the console of Windows, which change the foreground and background -// colors of the text by the escape sequence. -// In the console of other systems, which writes to w all text. -func Colored(w io.Writer) io.Writer { - return createModeAnsiColorWriter(w, discardNonColorEscSeq) -} - -// NewModeAnsiColorWriter create and initializes a new ansiColorWriter -// by specifying the outputMode. -func createModeAnsiColorWriter(w io.Writer, mode outputMode) io.Writer { - if _, ok := w.(*ansiColorWriter); !ok { - return &ansiColorWriter{ - w: w, - mode: mode, - } - } - return w -} diff --git a/vendor/github.com/DATA-DOG/godog/flags.go b/vendor/github.com/DATA-DOG/godog/flags.go deleted file mode 100644 index 71bea294a..000000000 --- a/vendor/github.com/DATA-DOG/godog/flags.go +++ /dev/null @@ -1,192 +0,0 @@ -package godog - -import ( - "flag" - "fmt" - "io" - "math/rand" - "strconv" - "strings" - "time" - - "github.com/DATA-DOG/godog/colors" -) - -var descFeaturesArgument = "Optional feature(s) to run. Can be:\n" + - s(4) + "- dir " + colors.Yellow("(features/)") + "\n" + - s(4) + "- feature " + colors.Yellow("(*.feature)") + "\n" + - s(4) + "- scenario at specific line " + colors.Yellow("(*.feature:10)") + "\n" + - "If no feature paths are listed, suite tries " + colors.Yellow("features") + " path by default.\n" - -var descConcurrencyOption = "Run the test suite with concurrency level:\n" + - s(4) + "- " + colors.Yellow(`= 1`) + ": supports all types of formats.\n" + - s(4) + "- " + colors.Yellow(`>= 2`) + ": only supports " + colors.Yellow("progress") + ". Note, that\n" + - s(4) + "your context needs to support parallel execution." - -var descTagsOption = "Filter scenarios by tags. Expression can be:\n" + - s(4) + "- " + colors.Yellow(`"@wip"`) + ": run all scenarios with wip tag\n" + - s(4) + "- " + colors.Yellow(`"~@wip"`) + ": exclude all scenarios with wip tag\n" + - s(4) + "- " + colors.Yellow(`"@wip && ~@new"`) + ": run wip scenarios, but exclude new\n" + - s(4) + "- " + colors.Yellow(`"@wip,@undone"`) + ": run wip or undone scenarios" - -var descRandomOption = "Randomly shuffle the scenario execution order.\n" + - "Specify SEED to reproduce the shuffling from a previous run.\n" + - s(4) + `e.g. ` + colors.Yellow(`--random`) + " or " + colors.Yellow(`--random=5738`) - -// FlagSet allows to manage flags by external suite runner -func FlagSet(opt *Options) *flag.FlagSet { - descFormatOption := "How to format tests output. Built-in formats:\n" - // @TODO: sort by name - for name, desc := range AvailableFormatters() { - descFormatOption += s(4) + "- " + colors.Yellow(name) + ": " + desc + "\n" - } - descFormatOption = strings.TrimSpace(descFormatOption) - - set := flag.NewFlagSet("godog", flag.ExitOnError) - set.StringVar(&opt.Format, "format", "pretty", descFormatOption) - set.StringVar(&opt.Format, "f", "pretty", descFormatOption) - set.StringVar(&opt.Tags, "tags", "", descTagsOption) - set.StringVar(&opt.Tags, "t", "", descTagsOption) - set.IntVar(&opt.Concurrency, "concurrency", 1, descConcurrencyOption) - set.IntVar(&opt.Concurrency, "c", 1, descConcurrencyOption) - set.BoolVar(&opt.ShowStepDefinitions, "definitions", false, "Print all available step definitions.") - set.BoolVar(&opt.ShowStepDefinitions, "d", false, "Print all available step definitions.") - set.BoolVar(&opt.StopOnFailure, "stop-on-failure", false, "Stop processing on first failed scenario.") - set.BoolVar(&opt.Strict, "strict", false, "Fail suite when there are pending or undefined steps.") - set.BoolVar(&opt.NoColors, "no-colors", false, "Disable ansi colors.") - set.Var(&randomSeed{&opt.Randomize}, "random", descRandomOption) - set.Usage = usage(set, opt.Output) - return set -} - -type flagged struct { - short, long, descr, dflt string -} - -func (f *flagged) name() string { - var name string - switch { - case len(f.short) > 0 && len(f.long) > 0: - name = fmt.Sprintf("-%s, --%s", f.short, f.long) - case len(f.long) > 0: - name = fmt.Sprintf("--%s", f.long) - case len(f.short) > 0: - name = fmt.Sprintf("-%s", f.short) - } - - if f.long == "random" { - // `random` is special in that we will later assign it randomly - // if the user specifies `--random` without specifying one, - // so mask the "default" value here to avoid UI confusion about - // what the value will end up being. - name += "[=SEED]" - } else if f.dflt != "true" && f.dflt != "false" { - name += "=" + f.dflt - } - return name -} - -func usage(set *flag.FlagSet, w io.Writer) func() { - return func() { - var list []*flagged - var longest int - set.VisitAll(func(f *flag.Flag) { - var fl *flagged - for _, flg := range list { - if flg.descr == f.Usage { - fl = flg - break - } - } - if nil == fl { - fl = &flagged{ - dflt: f.DefValue, - descr: f.Usage, - } - list = append(list, fl) - } - if len(f.Name) > 2 { - fl.long = f.Name - } else { - fl.short = f.Name - } - }) - - for _, f := range list { - if len(f.name()) > longest { - longest = len(f.name()) - } - } - - // prints an option or argument with a description, or only description - opt := func(name, desc string) string { - var ret []string - lines := strings.Split(desc, "\n") - ret = append(ret, s(2)+colors.Green(name)+s(longest+2-len(name))+lines[0]) - if len(lines) > 1 { - for _, ln := range lines[1:] { - ret = append(ret, s(2)+s(longest+2)+ln) - } - } - return strings.Join(ret, "\n") - } - - // --- GENERAL --- - fmt.Fprintln(w, colors.Yellow("Usage:")) - fmt.Fprintf(w, s(2)+"godog [options] []\n\n") - // description - fmt.Fprintln(w, "Builds a test package and runs given feature files.") - fmt.Fprintf(w, "Command should be run from the directory of tested package and contain buildable go source.\n\n") - - // --- ARGUMENTS --- - fmt.Fprintln(w, colors.Yellow("Arguments:")) - // --> features - fmt.Fprintln(w, opt("features", descFeaturesArgument)) - - // --- OPTIONS --- - fmt.Fprintln(w, colors.Yellow("Options:")) - for _, f := range list { - fmt.Fprintln(w, opt(f.name(), f.descr)) - } - fmt.Fprintln(w, "") - } -} - -// randomSeed implements `flag.Value`, see https://golang.org/pkg/flag/#Value -type randomSeed struct { - ref *int64 -} - -// Choose randomly assigns a convenient pseudo-random seed value. -// The resulting seed will be between `1-99999` for later ease of specification. -func (rs *randomSeed) choose() { - r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) - *rs.ref = r.Int63n(99998) + 1 -} - -func (rs *randomSeed) Set(s string) error { - if s == "true" { - rs.choose() - return nil - } - - if s == "false" { - *rs.ref = 0 - return nil - } - - i, err := strconv.ParseInt(s, 10, 64) - *rs.ref = i - return err -} - -func (rs randomSeed) String() string { - return strconv.FormatInt(*rs.ref, 10) -} - -// If a Value has an IsBoolFlag() bool method returning true, the command-line -// parser makes -name equivalent to -name=true rather than using the next -// command-line argument. -func (rs *randomSeed) IsBoolFlag() bool { - return *rs.ref == 0 -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt.go b/vendor/github.com/DATA-DOG/godog/fmt.go deleted file mode 100644 index 5251bb2bc..000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt.go +++ /dev/null @@ -1,513 +0,0 @@ -package godog - -import ( - "bytes" - "fmt" - "io" - "os" - "reflect" - "regexp" - "strconv" - "strings" - "text/template" - "time" - "unicode" - - "github.com/DATA-DOG/godog/colors" - "github.com/DATA-DOG/godog/gherkin" -) - -// some snippet formatting regexps -var snippetExprCleanup = regexp.MustCompile("([\\/\\[\\]\\(\\)\\\\^\\$\\.\\|\\?\\*\\+\\'])") -var snippetExprQuoted = regexp.MustCompile("(\\W|^)\"(?:[^\"]*)\"(\\W|$)") -var snippetMethodName = regexp.MustCompile("[^a-zA-Z\\_\\ ]") -var snippetNumbers = regexp.MustCompile("(\\d+)") - -var snippetHelperFuncs = template.FuncMap{ - "backticked": func(s string) string { - return "`" + s + "`" - }, -} - -var undefinedSnippetsTpl = template.Must(template.New("snippets").Funcs(snippetHelperFuncs).Parse(` -{{ range . }}func {{ .Method }}({{ .Args }}) error { - return godog.ErrPending -} - -{{end}}func FeatureContext(s *godog.Suite) { {{ range . }} - s.Step({{ backticked .Expr }}, {{ .Method }}){{end}} -} -`)) - -type undefinedSnippet struct { - Method string - Expr string - argument interface{} // gherkin step argument -} - -type registeredFormatter struct { - name string - fmt FormatterFunc - description string -} - -var formatters []*registeredFormatter - -func findFmt(format string) FormatterFunc { - for _, el := range formatters { - if el.name == format { - return el.fmt - } - } - return nil -} - -// Format registers a feature suite output -// formatter by given name, description and -// FormatterFunc constructor function, to initialize -// formatter with the output recorder. -func Format(name, description string, f FormatterFunc) { - formatters = append(formatters, ®isteredFormatter{ - name: name, - fmt: f, - description: description, - }) -} - -// AvailableFormatters gives a map of all -// formatters registered with their name as key -// and description as value -func AvailableFormatters() map[string]string { - fmts := make(map[string]string, len(formatters)) - for _, f := range formatters { - fmts[f.name] = f.description - } - return fmts -} - -// Formatter is an interface for feature runner -// output summary presentation. -// -// New formatters may be created to represent -// suite results in different ways. These new -// formatters needs to be registered with a -// godog.Format function call -type Formatter interface { - Feature(*gherkin.Feature, string, []byte) - Node(interface{}) - Defined(*gherkin.Step, *StepDef) - Failed(*gherkin.Step, *StepDef, error) - Passed(*gherkin.Step, *StepDef) - Skipped(*gherkin.Step, *StepDef) - Undefined(*gherkin.Step, *StepDef) - Pending(*gherkin.Step, *StepDef) - Summary() -} - -// FormatterFunc builds a formatter with given -// suite name and io.Writer to record output -type FormatterFunc func(string, io.Writer) Formatter - -type stepType int - -const ( - passed stepType = iota - failed - skipped - undefined - pending -) - -func (st stepType) clr() colors.ColorFunc { - switch st { - case passed: - return green - case failed: - return red - case skipped: - return cyan - default: - return yellow - } -} - -func (st stepType) String() string { - switch st { - case passed: - return "passed" - case failed: - return "failed" - case skipped: - return "skipped" - case undefined: - return "undefined" - case pending: - return "pending" - default: - return "unknown" - } -} - -type stepResult struct { - typ stepType - feature *feature - owner interface{} - step *gherkin.Step - def *StepDef - err error -} - -func (f stepResult) line() string { - return fmt.Sprintf("%s:%d", f.feature.Path, f.step.Location.Line) -} - -func (f stepResult) scenarioDesc() string { - if sc, ok := f.owner.(*gherkin.Scenario); ok { - return fmt.Sprintf("%s: %s", sc.Keyword, sc.Name) - } - - if row, ok := f.owner.(*gherkin.TableRow); ok { - for _, def := range f.feature.Feature.ScenarioDefinitions { - out, ok := def.(*gherkin.ScenarioOutline) - if !ok { - continue - } - - for _, ex := range out.Examples { - for _, rw := range ex.TableBody { - if rw.Location.Line == row.Location.Line { - return fmt.Sprintf("%s: %s", out.Keyword, out.Name) - } - } - } - } - } - return f.line() // was not expecting different owner -} - -func (f stepResult) scenarioLine() string { - if sc, ok := f.owner.(*gherkin.Scenario); ok { - return fmt.Sprintf("%s:%d", f.feature.Path, sc.Location.Line) - } - - if row, ok := f.owner.(*gherkin.TableRow); ok { - for _, def := range f.feature.Feature.ScenarioDefinitions { - out, ok := def.(*gherkin.ScenarioOutline) - if !ok { - continue - } - - for _, ex := range out.Examples { - for _, rw := range ex.TableBody { - if rw.Location.Line == row.Location.Line { - return fmt.Sprintf("%s:%d", f.feature.Path, out.Location.Line) - } - } - } - } - } - return f.line() // was not expecting different owner -} - -type basefmt struct { - out io.Writer - owner interface{} - indent int - - started time.Time - features []*feature - failed []*stepResult - passed []*stepResult - skipped []*stepResult - undefined []*stepResult - pending []*stepResult -} - -func (f *basefmt) Node(n interface{}) { - switch t := n.(type) { - case *gherkin.TableRow: - f.owner = t - case *gherkin.Scenario: - f.owner = t - } -} - -func (f *basefmt) Defined(*gherkin.Step, *StepDef) { - -} - -func (f *basefmt) Feature(ft *gherkin.Feature, p string, c []byte) { - f.features = append(f.features, &feature{Path: p, Feature: ft}) -} - -func (f *basefmt) Passed(step *gherkin.Step, match *StepDef) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - def: match, - typ: passed, - } - f.passed = append(f.passed, s) -} - -func (f *basefmt) Skipped(step *gherkin.Step, match *StepDef) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - def: match, - typ: skipped, - } - f.skipped = append(f.skipped, s) -} - -func (f *basefmt) Undefined(step *gherkin.Step, match *StepDef) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - def: match, - typ: undefined, - } - f.undefined = append(f.undefined, s) -} - -func (f *basefmt) Failed(step *gherkin.Step, match *StepDef, err error) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - def: match, - err: err, - typ: failed, - } - f.failed = append(f.failed, s) -} - -func (f *basefmt) Pending(step *gherkin.Step, match *StepDef) { - s := &stepResult{ - owner: f.owner, - feature: f.features[len(f.features)-1], - step: step, - def: match, - typ: pending, - } - f.pending = append(f.pending, s) -} - -func (f *basefmt) Summary() { - var total, passed, undefined int - for _, ft := range f.features { - for _, def := range ft.ScenarioDefinitions { - switch t := def.(type) { - case *gherkin.Scenario: - total++ - case *gherkin.ScenarioOutline: - for _, ex := range t.Examples { - if examples, hasExamples := examples(ex); hasExamples { - total += len(examples.TableBody) - } - } - } - } - } - passed = total - var owner interface{} - for _, undef := range f.undefined { - if owner != undef.owner { - undefined++ - owner = undef.owner - } - } - - var steps, parts, scenarios []string - nsteps := len(f.passed) + len(f.failed) + len(f.skipped) + len(f.undefined) + len(f.pending) - if len(f.passed) > 0 { - steps = append(steps, green(fmt.Sprintf("%d passed", len(f.passed)))) - } - if len(f.failed) > 0 { - passed -= len(f.failed) - parts = append(parts, red(fmt.Sprintf("%d failed", len(f.failed)))) - steps = append(steps, parts[len(parts)-1]) - } - if len(f.pending) > 0 { - passed -= len(f.pending) - parts = append(parts, yellow(fmt.Sprintf("%d pending", len(f.pending)))) - steps = append(steps, yellow(fmt.Sprintf("%d pending", len(f.pending)))) - } - if len(f.undefined) > 0 { - passed -= undefined - parts = append(parts, yellow(fmt.Sprintf("%d undefined", undefined))) - steps = append(steps, yellow(fmt.Sprintf("%d undefined", len(f.undefined)))) - } - if len(f.skipped) > 0 { - steps = append(steps, cyan(fmt.Sprintf("%d skipped", len(f.skipped)))) - } - if passed > 0 { - scenarios = append(scenarios, green(fmt.Sprintf("%d passed", passed))) - } - scenarios = append(scenarios, parts...) - elapsed := timeNowFunc().Sub(f.started) - - fmt.Fprintln(f.out, "") - if total == 0 { - fmt.Fprintln(f.out, "No scenarios") - } else { - fmt.Fprintln(f.out, fmt.Sprintf("%d scenarios (%s)", total, strings.Join(scenarios, ", "))) - } - - if nsteps == 0 { - fmt.Fprintln(f.out, "No steps") - } else { - fmt.Fprintln(f.out, fmt.Sprintf("%d steps (%s)", nsteps, strings.Join(steps, ", "))) - } - fmt.Fprintln(f.out, elapsed) - - // prints used randomization seed - seed, err := strconv.ParseInt(os.Getenv("GODOG_SEED"), 10, 64) - if err == nil && seed != 0 { - fmt.Fprintln(f.out, "") - fmt.Fprintln(f.out, "Randomized with seed:", colors.Yellow(seed)) - } - - if text := f.snippets(); text != "" { - fmt.Fprintln(f.out, yellow("\nYou can implement step definitions for undefined steps with these snippets:")) - fmt.Fprintln(f.out, yellow(text)) - } -} - -func (s *undefinedSnippet) Args() (ret string) { - var args []string - var pos, idx int - var breakLoop bool - for !breakLoop { - part := s.Expr[pos:] - ipos := strings.Index(part, "(\\d+)") - spos := strings.Index(part, "\"([^\"]*)\"") - switch { - case spos == -1 && ipos == -1: - breakLoop = true - case spos == -1: - idx++ - pos += ipos + len("(\\d+)") - args = append(args, reflect.Int.String()) - case ipos == -1: - idx++ - pos += spos + len("\"([^\"]*)\"") - args = append(args, reflect.String.String()) - case ipos < spos: - idx++ - pos += ipos + len("(\\d+)") - args = append(args, reflect.Int.String()) - case spos < ipos: - idx++ - pos += spos + len("\"([^\"]*)\"") - args = append(args, reflect.String.String()) - } - } - if s.argument != nil { - idx++ - switch s.argument.(type) { - case *gherkin.DocString: - args = append(args, "*gherkin.DocString") - case *gherkin.DataTable: - args = append(args, "*gherkin.DataTable") - } - } - - var last string - for i, arg := range args { - if last == "" || last == arg { - ret += fmt.Sprintf("arg%d, ", i+1) - } else { - ret = strings.TrimRight(ret, ", ") + fmt.Sprintf(" %s, arg%d, ", last, i+1) - } - last = arg - } - return strings.TrimSpace(strings.TrimRight(ret, ", ") + " " + last) -} - -func (f *basefmt) snippets() string { - if len(f.undefined) == 0 { - return "" - } - - var index int - var snips []*undefinedSnippet - // build snippets - for _, u := range f.undefined { - steps := []string{u.step.Text} - arg := u.step.Argument - if u.def != nil { - steps = u.def.undefined - arg = nil - } - for _, step := range steps { - expr := snippetExprCleanup.ReplaceAllString(step, "\\$1") - expr = snippetNumbers.ReplaceAllString(expr, "(\\d+)") - expr = snippetExprQuoted.ReplaceAllString(expr, "$1\"([^\"]*)\"$2") - expr = "^" + strings.TrimSpace(expr) + "$" - - name := snippetNumbers.ReplaceAllString(step, " ") - name = snippetExprQuoted.ReplaceAllString(name, " ") - name = strings.TrimSpace(snippetMethodName.ReplaceAllString(name, "")) - var words []string - for i, w := range strings.Split(name, " ") { - switch { - case i != 0: - w = strings.Title(w) - case len(w) > 0: - w = string(unicode.ToLower(rune(w[0]))) + w[1:] - } - words = append(words, w) - } - name = strings.Join(words, "") - if len(name) == 0 { - index++ - name = fmt.Sprintf("stepDefinition%d", index) - } - - var found bool - for _, snip := range snips { - if snip.Expr == expr { - found = true - break - } - } - if !found { - snips = append(snips, &undefinedSnippet{Method: name, Expr: expr, argument: arg}) - } - } - } - - var buf bytes.Buffer - if err := undefinedSnippetsTpl.Execute(&buf, snips); err != nil { - panic(err) - } - // there may be trailing spaces - return strings.Replace(buf.String(), " \n", "\n", -1) -} - -func (f *basefmt) isLastStep(s *gherkin.Step) bool { - ft := f.features[len(f.features)-1] - - for _, def := range ft.ScenarioDefinitions { - if outline, ok := def.(*gherkin.ScenarioOutline); ok { - for n, step := range outline.Steps { - if step.Location.Line == s.Location.Line { - return n == len(outline.Steps)-1 - } - } - } - - if scenario, ok := def.(*gherkin.Scenario); ok { - for n, step := range scenario.Steps { - if step.Location.Line == s.Location.Line { - return n == len(scenario.Steps)-1 - } - } - } - } - return false -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt_cucumber.go b/vendor/github.com/DATA-DOG/godog/fmt_cucumber.go deleted file mode 100644 index 19897efe0..000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt_cucumber.go +++ /dev/null @@ -1,332 +0,0 @@ -package godog - -/* - The specification for the formatting originated from https://www.relishapp.com/cucumber/cucumber/docs/formatters/json-output-formatter. - I found that documentation was misleading or out dated. To validate formatting I create a ruby cucumber test harness and ran the - same feature files through godog and the ruby cucumber. - - The docstrings in the cucumber.feature represent the cucumber output for those same feature definitions. - - I did note that comments in ruby could be at just about any level in particular Feature, Scenario and Step. In godog I - could only find comments under the Feature data structure. -*/ - -import ( - "encoding/json" - "fmt" - "io" - "strconv" - "strings" - "time" - - "github.com/DATA-DOG/godog/gherkin" -) - -func init() { - Format("cucumber", "Produces cucumber JSON format output.", cucumberFunc) -} - -func cucumberFunc(suite string, out io.Writer) Formatter { - formatter := &cukefmt{ - basefmt: basefmt{ - started: timeNowFunc(), - indent: 2, - out: out, - }, - } - - return formatter -} - -// Replace spaces with - This function is used to create the "id" fields of the cucumber output. -func makeID(name string) string { - return strings.Replace(strings.ToLower(name), " ", "-", -1) -} - -// The sequence of type structs are used to marshall the json object. -type cukeComment struct { - Value string `json:"value"` - Line int `json:"line"` -} - -type cukeDocstring struct { - Value string `json:"value"` - ContentType string `json:"content_type"` - Line int `json:"line"` -} - -type cukeTag struct { - Name string `json:"name"` - Line int `json:"line"` -} - -type cukeResult struct { - Status string `json:"status"` - Error string `json:"error_message,omitempty"` - Duration *int `json:"duration,omitempty"` -} - -type cukeMatch struct { - Location string `json:"location"` -} - -type cukeStep struct { - Keyword string `json:"keyword"` - Name string `json:"name"` - Line int `json:"line"` - Docstring *cukeDocstring `json:"doc_string,omitempty"` - Match cukeMatch `json:"match"` - Result cukeResult `json:"result"` -} - -type cukeElement struct { - ID string `json:"id"` - Keyword string `json:"keyword"` - Name string `json:"name"` - Description string `json:"description"` - Line int `json:"line"` - Type string `json:"type"` - Tags []cukeTag `json:"tags,omitempty"` - Steps []cukeStep `json:"steps,omitempty"` -} - -type cukeFeatureJSON struct { - URI string `json:"uri"` - ID string `json:"id"` - Keyword string `json:"keyword"` - Name string `json:"name"` - Description string `json:"description"` - Line int `json:"line"` - Comments []cukeComment `json:"comments,omitempty"` - Tags []cukeTag `json:"tags,omitempty"` - Elements []cukeElement `json:"elements,omitempty"` -} - -type cukefmt struct { - basefmt - - // currently running feature path, to be part of id. - // this is sadly not passed by gherkin nodes. - // it restricts this formatter to run only in synchronous single - // threaded execution. Unless running a copy of formatter for each feature - path string - stat stepType // last step status, before skipped - outlineSteps int // number of current outline scenario steps - ID string // current test id. - results []cukeFeatureJSON // structure that represent cuke results - curStep *cukeStep // track the current step - curElement *cukeElement // track the current element - curFeature *cukeFeatureJSON // track the current feature - curOutline cukeElement // Each example show up as an outline element but the outline is parsed only once - // so I need to keep track of the current outline - curRow int // current row of the example table as it is being processed. - curExampleTags []cukeTag // temporary storage for tags associate with the current example table. - startTime time.Time // used to time duration of the step execution - curExampleName string // Due to the fact that examples are parsed once and then iterated over for each result then we need to keep track - // of the example name inorder to build id fields. -} - -func (f *cukefmt) Node(n interface{}) { - f.basefmt.Node(n) - - switch t := n.(type) { - - // When the example definition is seen we just need track the id and - // append the name associated with the example as part of the id. - case *gherkin.Examples: - - f.curExampleName = makeID(t.Name) - f.curRow = 2 // there can be more than one example set per outline so reset row count. - // cucumber counts the header row as an example when creating the id. - - // store any example level tags in a temp location. - f.curExampleTags = make([]cukeTag, len(t.Tags)) - for idx, element := range t.Tags { - f.curExampleTags[idx].Line = element.Location.Line - f.curExampleTags[idx].Name = element.Name - } - - // The outline node creates a placeholder and the actual element is added as each TableRow is processed. - case *gherkin.ScenarioOutline: - - f.curOutline = cukeElement{} - f.curOutline.Name = t.Name - f.curOutline.Line = t.Location.Line - f.curOutline.Description = t.Description - f.curOutline.Keyword = t.Keyword - f.curOutline.ID = f.curFeature.ID + ";" + makeID(t.Name) - f.curOutline.Type = "scenario" - f.curOutline.Tags = make([]cukeTag, len(t.Tags)+len(f.curFeature.Tags)) - - // apply feature level tags - if len(f.curOutline.Tags) > 0 { - copy(f.curOutline.Tags, f.curFeature.Tags) - - // apply outline level tags. - for idx, element := range t.Tags { - f.curOutline.Tags[idx+len(f.curFeature.Tags)].Line = element.Location.Line - f.curOutline.Tags[idx+len(f.curFeature.Tags)].Name = element.Name - } - } - - // This scenario adds the element to the output immediately. - case *gherkin.Scenario: - f.curFeature.Elements = append(f.curFeature.Elements, cukeElement{}) - f.curElement = &f.curFeature.Elements[len(f.curFeature.Elements)-1] - - f.curElement.Name = t.Name - f.curElement.Line = t.Location.Line - f.curElement.Description = t.Description - f.curElement.Keyword = t.Keyword - f.curElement.ID = f.curFeature.ID + ";" + makeID(t.Name) - f.curElement.Type = "scenario" - f.curElement.Tags = make([]cukeTag, len(t.Tags)+len(f.curFeature.Tags)) - - if len(f.curElement.Tags) > 0 { - // apply feature level tags - copy(f.curElement.Tags, f.curFeature.Tags) - - // apply scenario level tags. - for idx, element := range t.Tags { - f.curElement.Tags[idx+len(f.curFeature.Tags)].Line = element.Location.Line - f.curElement.Tags[idx+len(f.curFeature.Tags)].Name = element.Name - } - } - - // This is an outline scenario and the element is added to the output as - // the TableRows are encountered. - case *gherkin.TableRow: - tmpElem := f.curOutline - tmpElem.Line = t.Location.Line - tmpElem.ID = tmpElem.ID + ";" + f.curExampleName + ";" + strconv.Itoa(f.curRow) - f.curRow++ - f.curFeature.Elements = append(f.curFeature.Elements, tmpElem) - f.curElement = &f.curFeature.Elements[len(f.curFeature.Elements)-1] - - // copy in example level tags. - f.curElement.Tags = append(f.curElement.Tags, f.curExampleTags...) - - } - -} - -func (f *cukefmt) Feature(ft *gherkin.Feature, p string, c []byte) { - - f.basefmt.Feature(ft, p, c) - f.path = p - f.ID = makeID(ft.Name) - f.results = append(f.results, cukeFeatureJSON{}) - - f.curFeature = &f.results[len(f.results)-1] - f.curFeature.URI = p - f.curFeature.Name = ft.Name - f.curFeature.Keyword = ft.Keyword - f.curFeature.Line = ft.Location.Line - f.curFeature.Description = ft.Description - f.curFeature.ID = f.ID - f.curFeature.Tags = make([]cukeTag, len(ft.Tags)) - - for idx, element := range ft.Tags { - f.curFeature.Tags[idx].Line = element.Location.Line - f.curFeature.Tags[idx].Name = element.Name - } - - f.curFeature.Comments = make([]cukeComment, len(ft.Comments)) - for idx, comment := range ft.Comments { - f.curFeature.Comments[idx].Value = strings.TrimSpace(comment.Text) - f.curFeature.Comments[idx].Line = comment.Location.Line - } - -} - -func (f *cukefmt) Summary() { - dat, err := json.MarshalIndent(f.results, "", " ") - if err != nil { - panic(err) - } - fmt.Fprintf(f.out, "%s\n", string(dat)) -} - -func (f *cukefmt) step(res *stepResult) { - - // determine if test case has finished - switch t := f.owner.(type) { - case *gherkin.TableRow: - d := int(timeNowFunc().Sub(f.startTime).Nanoseconds()) - f.curStep.Result.Duration = &d - f.curStep.Line = t.Location.Line - f.curStep.Result.Status = res.typ.String() - if res.err != nil { - f.curStep.Result.Error = res.err.Error() - } - case *gherkin.Scenario: - d := int(timeNowFunc().Sub(f.startTime).Nanoseconds()) - f.curStep.Result.Duration = &d - f.curStep.Result.Status = res.typ.String() - if res.err != nil { - f.curStep.Result.Error = res.err.Error() - } - } -} - -func (f *cukefmt) Defined(step *gherkin.Step, def *StepDef) { - - f.startTime = timeNowFunc() // start timing the step - f.curElement.Steps = append(f.curElement.Steps, cukeStep{}) - f.curStep = &f.curElement.Steps[len(f.curElement.Steps)-1] - - f.curStep.Name = step.Text - f.curStep.Line = step.Location.Line - f.curStep.Keyword = step.Keyword - - if _, ok := step.Argument.(*gherkin.DocString); ok { - f.curStep.Docstring = &cukeDocstring{} - f.curStep.Docstring.ContentType = strings.TrimSpace(step.Argument.(*gherkin.DocString).ContentType) - f.curStep.Docstring.Line = step.Argument.(*gherkin.DocString).Location.Line - f.curStep.Docstring.Value = step.Argument.(*gherkin.DocString).Content - } - - if def != nil { - f.curStep.Match.Location = strings.Split(def.definitionID(), " ")[0] - } -} - -func (f *cukefmt) Passed(step *gherkin.Step, match *StepDef) { - f.basefmt.Passed(step, match) - f.stat = passed - f.step(f.passed[len(f.passed)-1]) -} - -func (f *cukefmt) Skipped(step *gherkin.Step, match *StepDef) { - f.basefmt.Skipped(step, match) - f.step(f.skipped[len(f.skipped)-1]) - - // no duration reported for skipped. - f.curStep.Result.Duration = nil -} - -func (f *cukefmt) Undefined(step *gherkin.Step, match *StepDef) { - f.basefmt.Undefined(step, match) - f.stat = undefined - f.step(f.undefined[len(f.undefined)-1]) - - // the location for undefined is the feature file location not the step file. - f.curStep.Match.Location = fmt.Sprintf("%s:%d", f.path, step.Location.Line) - f.curStep.Result.Duration = nil -} - -func (f *cukefmt) Failed(step *gherkin.Step, match *StepDef, err error) { - f.basefmt.Failed(step, match, err) - f.stat = failed - f.step(f.failed[len(f.failed)-1]) -} - -func (f *cukefmt) Pending(step *gherkin.Step, match *StepDef) { - f.stat = pending - f.basefmt.Pending(step, match) - f.step(f.pending[len(f.pending)-1]) - - // the location for pending is the feature file location not the step file. - f.curStep.Match.Location = fmt.Sprintf("%s:%d", f.path, step.Location.Line) - f.curStep.Result.Duration = nil -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt_events.go b/vendor/github.com/DATA-DOG/godog/fmt_events.go deleted file mode 100644 index 17e92ff4d..000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt_events.go +++ /dev/null @@ -1,269 +0,0 @@ -package godog - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/DATA-DOG/godog/gherkin" -) - -const nanoSec = 1000000 -const spec = "0.1.0" - -func init() { - Format("events", fmt.Sprintf("Produces JSON event stream, based on spec: %s.", spec), eventsFunc) -} - -func eventsFunc(suite string, out io.Writer) Formatter { - formatter := &events{ - basefmt: basefmt{ - started: timeNowFunc(), - indent: 2, - out: out, - }, - } - - formatter.event(&struct { - Event string `json:"event"` - Version string `json:"version"` - Timestamp int64 `json:"timestamp"` - Suite string `json:"suite"` - }{ - "TestRunStarted", - spec, - timeNowFunc().UnixNano() / nanoSec, - suite, - }) - - return formatter -} - -type events struct { - basefmt - - // currently running feature path, to be part of id. - // this is sadly not passed by gherkin nodes. - // it restricts this formatter to run only in synchronous single - // threaded execution. Unless running a copy of formatter for each feature - path string - stat stepType // last step status, before skipped - outlineSteps int // number of current outline scenario steps -} - -func (f *events) event(ev interface{}) { - data, err := json.Marshal(ev) - if err != nil { - panic(fmt.Sprintf("failed to marshal stream event: %+v - %v", ev, err)) - } - fmt.Fprintln(f.out, string(data)) -} - -func (f *events) Node(n interface{}) { - f.basefmt.Node(n) - - var id string - var undefined bool - switch t := n.(type) { - case *gherkin.Scenario: - id = fmt.Sprintf("%s:%d", f.path, t.Location.Line) - undefined = len(t.Steps) == 0 - case *gherkin.TableRow: - id = fmt.Sprintf("%s:%d", f.path, t.Location.Line) - undefined = f.outlineSteps == 0 - case *gherkin.ScenarioOutline: - f.outlineSteps = len(t.Steps) - } - - if len(id) == 0 { - return - } - - f.event(&struct { - Event string `json:"event"` - Location string `json:"location"` - Timestamp int64 `json:"timestamp"` - }{ - "TestCaseStarted", - id, - timeNowFunc().UnixNano() / nanoSec, - }) - - if undefined { - // @TODO: is status undefined or passed? when there are no steps - // for this scenario - f.event(&struct { - Event string `json:"event"` - Location string `json:"location"` - Timestamp int64 `json:"timestamp"` - Status string `json:"status"` - }{ - "TestCaseFinished", - id, - timeNowFunc().UnixNano() / nanoSec, - "undefined", - }) - } -} - -func (f *events) Feature(ft *gherkin.Feature, p string, c []byte) { - f.basefmt.Feature(ft, p, c) - f.path = p - f.event(&struct { - Event string `json:"event"` - Location string `json:"location"` - Source string `json:"source"` - }{ - "TestSource", - fmt.Sprintf("%s:%d", p, ft.Location.Line), - string(c), - }) -} - -func (f *events) Summary() { - // @TODO: determine status - status := passed - if len(f.failed) > 0 { - status = failed - } else if len(f.passed) == 0 { - if len(f.undefined) > len(f.pending) { - status = undefined - } else { - status = pending - } - } - - snips := f.snippets() - if len(snips) > 0 { - snips = "You can implement step definitions for undefined steps with these snippets:\n" + snips - } - - f.event(&struct { - Event string `json:"event"` - Status string `json:"status"` - Timestamp int64 `json:"timestamp"` - Snippets string `json:"snippets"` - Memory string `json:"memory"` - }{ - "TestRunFinished", - status.String(), - timeNowFunc().UnixNano() / nanoSec, - snips, - "", // @TODO not sure that could be correctly implemented - }) -} - -func (f *events) step(res *stepResult) { - var errMsg string - if res.err != nil { - errMsg = res.err.Error() - } - f.event(&struct { - Event string `json:"event"` - Location string `json:"location"` - Timestamp int64 `json:"timestamp"` - Status string `json:"status"` - Summary string `json:"summary,omitempty"` - }{ - "TestStepFinished", - fmt.Sprintf("%s:%d", f.path, res.step.Location.Line), - timeNowFunc().UnixNano() / nanoSec, - res.typ.String(), - errMsg, - }) - - // determine if test case has finished - var finished bool - var line int - switch t := f.owner.(type) { - case *gherkin.TableRow: - line = t.Location.Line - finished = f.isLastStep(res.step) - case *gherkin.Scenario: - line = t.Location.Line - finished = f.isLastStep(res.step) - } - - if finished { - f.event(&struct { - Event string `json:"event"` - Location string `json:"location"` - Timestamp int64 `json:"timestamp"` - Status string `json:"status"` - }{ - "TestCaseFinished", - fmt.Sprintf("%s:%d", f.path, line), - timeNowFunc().UnixNano() / nanoSec, - f.stat.String(), - }) - } -} - -func (f *events) Defined(step *gherkin.Step, def *StepDef) { - if def != nil { - m := def.Expr.FindStringSubmatchIndex(step.Text)[2:] - var args [][2]int - for i := 0; i < len(m)/2; i++ { - pair := m[i : i*2+2] - var idxs [2]int - idxs[0] = pair[0] - idxs[1] = pair[1] - args = append(args, idxs) - } - - if len(args) == 0 { - args = make([][2]int, 0) - } - - f.event(&struct { - Event string `json:"event"` - Location string `json:"location"` - DefID string `json:"definition_id"` - Args [][2]int `json:"arguments"` - }{ - "StepDefinitionFound", - fmt.Sprintf("%s:%d", f.path, step.Location.Line), - def.definitionID(), - args, - }) - } - - f.event(&struct { - Event string `json:"event"` - Location string `json:"location"` - Timestamp int64 `json:"timestamp"` - }{ - "TestStepStarted", - fmt.Sprintf("%s:%d", f.path, step.Location.Line), - timeNowFunc().UnixNano() / nanoSec, - }) -} - -func (f *events) Passed(step *gherkin.Step, match *StepDef) { - f.basefmt.Passed(step, match) - f.stat = passed - f.step(f.passed[len(f.passed)-1]) -} - -func (f *events) Skipped(step *gherkin.Step, match *StepDef) { - f.basefmt.Skipped(step, match) - f.step(f.skipped[len(f.skipped)-1]) -} - -func (f *events) Undefined(step *gherkin.Step, match *StepDef) { - f.basefmt.Undefined(step, match) - f.stat = undefined - f.step(f.undefined[len(f.undefined)-1]) -} - -func (f *events) Failed(step *gherkin.Step, match *StepDef, err error) { - f.basefmt.Failed(step, match, err) - f.stat = failed - f.step(f.failed[len(f.failed)-1]) -} - -func (f *events) Pending(step *gherkin.Step, match *StepDef) { - f.stat = pending - f.basefmt.Pending(step, match) - f.step(f.pending[len(f.pending)-1]) -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt_junit.go b/vendor/github.com/DATA-DOG/godog/fmt_junit.go deleted file mode 100644 index 8762cbebb..000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt_junit.go +++ /dev/null @@ -1,208 +0,0 @@ -package godog - -import ( - "encoding/xml" - "fmt" - "io" - "os" - "time" - - "github.com/DATA-DOG/godog/gherkin" -) - -func init() { - Format("junit", "Prints junit compatible xml to stdout", junitFunc) -} - -func junitFunc(suite string, out io.Writer) Formatter { - return &junitFormatter{ - suite: &junitPackageSuite{ - Name: suite, - TestSuites: make([]*junitTestSuite, 0), - }, - out: out, - started: timeNowFunc(), - } -} - -type junitFormatter struct { - suite *junitPackageSuite - out io.Writer - - // timing - started time.Time - caseStarted time.Time - featStarted time.Time - - outline *gherkin.ScenarioOutline - outlineExample int -} - -func (j *junitFormatter) Feature(feature *gherkin.Feature, path string, c []byte) { - testSuite := &junitTestSuite{ - TestCases: make([]*junitTestCase, 0), - Name: feature.Name, - } - - if len(j.suite.TestSuites) > 0 { - j.current().Time = timeNowFunc().Sub(j.featStarted).String() - } - j.featStarted = timeNowFunc() - j.suite.TestSuites = append(j.suite.TestSuites, testSuite) -} - -func (j *junitFormatter) Defined(*gherkin.Step, *StepDef) { - -} - -func (j *junitFormatter) Node(node interface{}) { - suite := j.current() - tcase := &junitTestCase{} - - switch t := node.(type) { - case *gherkin.ScenarioOutline: - j.outline = t - j.outlineExample = 0 - return - case *gherkin.Scenario: - tcase.Name = t.Name - suite.Tests++ - j.suite.Tests++ - case *gherkin.TableRow: - j.outlineExample++ - tcase.Name = fmt.Sprintf("%s #%d", j.outline.Name, j.outlineExample) - suite.Tests++ - j.suite.Tests++ - default: - return - } - j.caseStarted = timeNowFunc() - suite.TestCases = append(suite.TestCases, tcase) -} - -func (j *junitFormatter) Failed(step *gherkin.Step, match *StepDef, err error) { - suite := j.current() - suite.Failures++ - j.suite.Failures++ - - tcase := suite.current() - tcase.Time = timeNowFunc().Sub(j.caseStarted).String() - tcase.Status = "failed" - tcase.Failure = &junitFailure{ - Message: fmt.Sprintf("%s %s: %s", step.Type, step.Text, err.Error()), - } -} - -func (j *junitFormatter) Passed(step *gherkin.Step, match *StepDef) { - suite := j.current() - - tcase := suite.current() - tcase.Time = timeNowFunc().Sub(j.caseStarted).String() - tcase.Status = "passed" -} - -func (j *junitFormatter) Skipped(step *gherkin.Step, match *StepDef) { - suite := j.current() - - tcase := suite.current() - tcase.Time = timeNowFunc().Sub(j.caseStarted).String() - tcase.Error = append(tcase.Error, &junitError{ - Type: "skipped", - Message: fmt.Sprintf("%s %s", step.Type, step.Text), - }) -} - -func (j *junitFormatter) Undefined(step *gherkin.Step, match *StepDef) { - suite := j.current() - tcase := suite.current() - if tcase.Status != "undefined" { - // do not count two undefined steps as another error - suite.Errors++ - j.suite.Errors++ - } - - tcase.Time = timeNowFunc().Sub(j.caseStarted).String() - tcase.Status = "undefined" - tcase.Error = append(tcase.Error, &junitError{ - Type: "undefined", - Message: fmt.Sprintf("%s %s", step.Type, step.Text), - }) -} - -func (j *junitFormatter) Pending(step *gherkin.Step, match *StepDef) { - suite := j.current() - suite.Errors++ - j.suite.Errors++ - - tcase := suite.current() - tcase.Time = timeNowFunc().Sub(j.caseStarted).String() - tcase.Status = "pending" - tcase.Error = append(tcase.Error, &junitError{ - Type: "pending", - Message: fmt.Sprintf("%s %s: TODO: write pending definition", step.Type, step.Text), - }) -} - -func (j *junitFormatter) Summary() { - if j.current() != nil { - j.current().Time = timeNowFunc().Sub(j.featStarted).String() - } - j.suite.Time = timeNowFunc().Sub(j.started).String() - io.WriteString(j.out, xml.Header) - - enc := xml.NewEncoder(j.out) - enc.Indent("", s(2)) - if err := enc.Encode(j.suite); err != nil { - fmt.Fprintln(os.Stderr, "failed to write junit xml:", err) - } -} - -type junitFailure struct { - Message string `xml:"message,attr"` - Type string `xml:"type,attr,omitempty"` -} - -type junitError struct { - XMLName xml.Name `xml:"error,omitempty"` - Message string `xml:"message,attr"` - Type string `xml:"type,attr"` -} - -type junitTestCase struct { - XMLName xml.Name `xml:"testcase"` - Name string `xml:"name,attr"` - Status string `xml:"status,attr"` - Time string `xml:"time,attr"` - Failure *junitFailure `xml:"failure,omitempty"` - Error []*junitError -} - -type junitTestSuite struct { - XMLName xml.Name `xml:"testsuite"` - Name string `xml:"name,attr"` - Tests int `xml:"tests,attr"` - Skipped int `xml:"skipped,attr"` - Failures int `xml:"failures,attr"` - Errors int `xml:"errors,attr"` - Time string `xml:"time,attr"` - TestCases []*junitTestCase -} - -func (ts *junitTestSuite) current() *junitTestCase { - return ts.TestCases[len(ts.TestCases)-1] -} - -type junitPackageSuite struct { - XMLName xml.Name `xml:"testsuites"` - Name string `xml:"name,attr"` - Tests int `xml:"tests,attr"` - Skipped int `xml:"skipped,attr"` - Failures int `xml:"failures,attr"` - Errors int `xml:"errors,attr"` - Time string `xml:"time,attr"` - TestSuites []*junitTestSuite -} - -func (j *junitFormatter) current() *junitTestSuite { - return j.suite.TestSuites[len(j.suite.TestSuites)-1] -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt_pretty.go b/vendor/github.com/DATA-DOG/godog/fmt_pretty.go deleted file mode 100644 index d304769e0..000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt_pretty.go +++ /dev/null @@ -1,456 +0,0 @@ -package godog - -import ( - "fmt" - "io" - "math" - "regexp" - "strings" - "unicode/utf8" - - "github.com/DATA-DOG/godog/colors" - "github.com/DATA-DOG/godog/gherkin" -) - -func init() { - Format("pretty", "Prints every feature with runtime statuses.", prettyFunc) -} - -func prettyFunc(suite string, out io.Writer) Formatter { - return &pretty{ - basefmt: basefmt{ - started: timeNowFunc(), - indent: 2, - out: out, - }, - } -} - -var outlinePlaceholderRegexp = regexp.MustCompile("<[^>]+>") - -// a built in default pretty formatter -type pretty struct { - basefmt - - // currently processed - feature *gherkin.Feature - scenario *gherkin.Scenario - outline *gherkin.ScenarioOutline - - // state - bgSteps int - totalBgSteps int - steps int - commentPos int - - // whether scenario or scenario outline keyword was printed - scenarioKeyword bool - - // outline - outlineSteps []*stepResult - outlineNumExample int - outlineNumExamples int -} - -func (f *pretty) Feature(ft *gherkin.Feature, p string, c []byte) { - if len(f.features) != 0 { - // not a first feature, add a newline - fmt.Fprintln(f.out, "") - } - f.features = append(f.features, &feature{Path: p, Feature: ft}) - fmt.Fprintln(f.out, whiteb(ft.Keyword+": ")+ft.Name) - if strings.TrimSpace(ft.Description) != "" { - for _, line := range strings.Split(ft.Description, "\n") { - fmt.Fprintln(f.out, s(f.indent)+strings.TrimSpace(line)) - } - } - - f.feature = ft - f.scenario = nil - f.outline = nil - f.bgSteps = 0 - f.totalBgSteps = 0 - if ft.Background != nil { - f.bgSteps = len(ft.Background.Steps) - f.totalBgSteps = len(ft.Background.Steps) - } -} - -// Node takes a gherkin node for formatting -func (f *pretty) Node(node interface{}) { - f.basefmt.Node(node) - - switch t := node.(type) { - case *gherkin.Examples: - f.outlineNumExamples = len(t.TableBody) - f.outlineNumExample++ - case *gherkin.Scenario: - f.scenario = t - f.outline = nil - f.steps = len(t.Steps) + f.totalBgSteps - f.scenarioKeyword = false - if isEmptyScenario(t) { - f.printUndefinedScenario(t) - } - case *gherkin.ScenarioOutline: - f.outline = t - f.scenario = nil - f.outlineNumExample = -1 - f.scenarioKeyword = false - case *gherkin.TableRow: - f.steps = len(f.outline.Steps) + f.totalBgSteps - f.outlineSteps = []*stepResult{} - } -} - -func (f *pretty) printUndefinedScenario(sc *gherkin.Scenario) { - if f.bgSteps > 0 { - f.commentPos = f.longestStep(f.feature.Background.Steps, f.length(f.feature.Background)) - fmt.Fprintln(f.out, "\n"+s(f.indent)+whiteb(f.feature.Background.Keyword+": "+f.feature.Background.Name)) - - for _, step := range f.feature.Background.Steps { - f.bgSteps-- - f.printStep(step, nil, colors.Cyan) - } - } - text := s(f.indent) + whiteb(f.scenario.Keyword+": ") + sc.Name - text += s(f.commentPos-f.length(f.scenario)+1) + f.line(sc.Location) - fmt.Fprintln(f.out, "\n"+text) -} - -// Summary sumarize the feature formatter output -func (f *pretty) Summary() { - if len(f.failed) > 0 { - fmt.Fprintln(f.out, "\n--- "+red("Failed steps:")+"\n") - for _, fail := range f.failed { - fmt.Fprintln(f.out, s(2)+red(fail.scenarioDesc())+black(" # "+fail.scenarioLine())) - fmt.Fprintln(f.out, s(4)+red(strings.TrimSpace(fail.step.Keyword)+" "+fail.step.Text)+black(" # "+fail.line())) - fmt.Fprintln(f.out, s(6)+red("Error: ")+redb(fmt.Sprintf("%+v", fail.err))+"\n") - } - } - f.basefmt.Summary() -} - -func (f *pretty) printOutlineExample(outline *gherkin.ScenarioOutline) { - var msg string - var clr colors.ColorFunc - - ex := outline.Examples[f.outlineNumExample] - example, hasExamples := examples(ex) - if !hasExamples { - // do not print empty examples - return - } - - firstExample := f.outlineNumExamples == len(example.TableBody) - printSteps := firstExample && f.outlineNumExample == 0 - - for i, res := range f.outlineSteps { - // determine example row status - switch { - case res.typ == failed: - msg = res.err.Error() - clr = res.typ.clr() - case res.typ == undefined || res.typ == pending: - clr = res.typ.clr() - case res.typ == skipped && clr == nil: - clr = cyan - } - if printSteps && i >= f.totalBgSteps { - // in first example, we need to print steps - var text string - ostep := outline.Steps[i-f.totalBgSteps] - if res.def != nil { - if m := outlinePlaceholderRegexp.FindAllStringIndex(ostep.Text, -1); len(m) > 0 { - var pos int - for i := 0; i < len(m); i++ { - pair := m[i] - text += cyan(ostep.Text[pos:pair[0]]) - text += cyanb(ostep.Text[pair[0]:pair[1]]) - pos = pair[1] - } - text += cyan(ostep.Text[pos:len(ostep.Text)]) - } else { - text = cyan(ostep.Text) - } - text += s(f.commentPos-f.length(ostep)+1) + black(fmt.Sprintf("# %s", res.def.definitionID())) - } else { - text = cyan(ostep.Text) - } - // print the step outline - fmt.Fprintln(f.out, s(f.indent*2)+cyan(strings.TrimSpace(ostep.Keyword))+" "+text) - - // print step argument - // @TODO: need to make example header cells bold - switch t := ostep.Argument.(type) { - case *gherkin.DataTable: - f.printTable(t, cyan) - case *gherkin.DocString: - var ct string - if len(t.ContentType) > 0 { - ct = " " + cyan(t.ContentType) - } - fmt.Fprintln(f.out, s(f.indent*3)+cyan(t.Delimitter)+ct) - for _, ln := range strings.Split(t.Content, "\n") { - fmt.Fprintln(f.out, s(f.indent*3)+cyan(ln)) - } - fmt.Fprintln(f.out, s(f.indent*3)+cyan(t.Delimitter)) - } - } - } - - if clr == nil { - clr = green - } - cells := make([]string, len(example.TableHeader.Cells)) - max := longest(example, clr, cyan) - // an example table header - if firstExample { - fmt.Fprintln(f.out, "") - fmt.Fprintln(f.out, s(f.indent*2)+whiteb(example.Keyword+": ")+example.Name) - - for i, cell := range example.TableHeader.Cells { - val := cyan(cell.Value) - ln := utf8.RuneCountInString(val) - cells[i] = val + s(max[i]-ln) - } - fmt.Fprintln(f.out, s(f.indent*3)+"| "+strings.Join(cells, " | ")+" |") - } - - // an example table row - row := example.TableBody[len(example.TableBody)-f.outlineNumExamples] - for i, cell := range row.Cells { - val := clr(cell.Value) - ln := utf8.RuneCountInString(val) - cells[i] = val + s(max[i]-ln) - } - fmt.Fprintln(f.out, s(f.indent*3)+"| "+strings.Join(cells, " | ")+" |") - - // if there is an error - if msg != "" { - fmt.Fprintln(f.out, s(f.indent*4)+redb(msg)) - } -} - -func (f *pretty) printStep(step *gherkin.Step, def *StepDef, c colors.ColorFunc) { - text := s(f.indent*2) + c(strings.TrimSpace(step.Keyword)) + " " - switch { - case def != nil: - if m := def.Expr.FindStringSubmatchIndex(step.Text)[2:]; len(m) > 0 { - var pos, i int - for pos, i = 0, 0; i < len(m); i++ { - if m[i] == -1 { - continue // no index for this match - } - if math.Mod(float64(i), 2) == 0 { - text += c(step.Text[pos:m[i]]) - } else { - text += colors.Bold(c)(step.Text[pos:m[i]]) - } - pos = m[i] - } - text += c(step.Text[pos:len(step.Text)]) - } else { - text += c(step.Text) - } - text += s(f.commentPos-f.length(step)+1) + black(fmt.Sprintf("# %s", def.definitionID())) - default: - text += c(step.Text) - } - - fmt.Fprintln(f.out, text) - switch t := step.Argument.(type) { - case *gherkin.DataTable: - f.printTable(t, c) - case *gherkin.DocString: - var ct string - if len(t.ContentType) > 0 { - ct = " " + c(t.ContentType) - } - fmt.Fprintln(f.out, s(f.indent*3)+c(t.Delimitter)+ct) - for _, ln := range strings.Split(t.Content, "\n") { - fmt.Fprintln(f.out, s(f.indent*3)+c(ln)) - } - fmt.Fprintln(f.out, s(f.indent*3)+c(t.Delimitter)) - } -} - -func (f *pretty) printStepKind(res *stepResult) { - f.steps-- - if f.outline != nil { - f.outlineSteps = append(f.outlineSteps, res) - } - var bgStep bool - - // if has not printed background yet - switch { - // first background step - case f.bgSteps > 0 && f.bgSteps == len(f.feature.Background.Steps): - f.commentPos = f.longestStep(f.feature.Background.Steps, f.length(f.feature.Background)) - fmt.Fprintln(f.out, "\n"+s(f.indent)+whiteb(f.feature.Background.Keyword+": "+f.feature.Background.Name)) - f.bgSteps-- - bgStep = true - // subsequent background steps - case f.bgSteps > 0: - f.bgSteps-- - bgStep = true - // first step of scenario, print header and calculate comment position - case f.scenario != nil: - // print scenario keyword and value if first example - if !f.scenarioKeyword { - f.commentPos = f.longestStep(f.scenario.Steps, f.length(f.scenario)) - if f.feature.Background != nil { - if bgLen := f.longestStep(f.feature.Background.Steps, f.length(f.feature.Background)); bgLen > f.commentPos { - f.commentPos = bgLen - } - } - text := s(f.indent) + whiteb(f.scenario.Keyword+": ") + f.scenario.Name - text += s(f.commentPos-f.length(f.scenario)+1) + f.line(f.scenario.Location) - fmt.Fprintln(f.out, "\n"+text) - f.scenarioKeyword = true - } - // first step of outline scenario, print header and calculate comment position - case f.outline != nil: - // print scenario keyword and value if first example - if !f.scenarioKeyword { - f.commentPos = f.longestStep(f.outline.Steps, f.length(f.outline)) - if f.feature.Background != nil { - if bgLen := f.longestStep(f.feature.Background.Steps, f.length(f.feature.Background)); bgLen > f.commentPos { - f.commentPos = bgLen - } - } - text := s(f.indent) + whiteb(f.outline.Keyword+": ") + f.outline.Name - text += s(f.commentPos-f.length(f.outline)+1) + f.line(f.outline.Location) - fmt.Fprintln(f.out, "\n"+text) - f.scenarioKeyword = true - } - if len(f.outlineSteps) == len(f.outline.Steps)+f.totalBgSteps { - // an outline example steps has went through - f.printOutlineExample(f.outline) - f.outlineNumExamples-- - } - return - } - - if !f.isBackgroundStep(res.step) || bgStep { - f.printStep(res.step, res.def, res.typ.clr()) - } - if res.err != nil { - fmt.Fprintln(f.out, s(f.indent*2)+redb(fmt.Sprintf("%+v", res.err))) - } - if res.typ == pending { - fmt.Fprintln(f.out, s(f.indent*3)+yellow("TODO: write pending definition")) - } -} - -func (f *pretty) isBackgroundStep(step *gherkin.Step) bool { - if f.feature.Background == nil { - return false - } - - for _, bstep := range f.feature.Background.Steps { - if bstep.Location.Line == step.Location.Line { - return true - } - } - return false -} - -// print table with aligned table cells -func (f *pretty) printTable(t *gherkin.DataTable, c colors.ColorFunc) { - var l = longest(t, c) - var cols = make([]string, len(t.Rows[0].Cells)) - for _, row := range t.Rows { - for i, cell := range row.Cells { - val := c(cell.Value) - ln := utf8.RuneCountInString(val) - cols[i] = val + s(l[i]-ln) - } - fmt.Fprintln(f.out, s(f.indent*3)+"| "+strings.Join(cols, " | ")+" |") - } -} - -func (f *pretty) Passed(step *gherkin.Step, match *StepDef) { - f.basefmt.Passed(step, match) - f.printStepKind(f.passed[len(f.passed)-1]) -} - -func (f *pretty) Skipped(step *gherkin.Step, match *StepDef) { - f.basefmt.Skipped(step, match) - f.printStepKind(f.skipped[len(f.skipped)-1]) -} - -func (f *pretty) Undefined(step *gherkin.Step, match *StepDef) { - f.basefmt.Undefined(step, match) - f.printStepKind(f.undefined[len(f.undefined)-1]) -} - -func (f *pretty) Failed(step *gherkin.Step, match *StepDef, err error) { - f.basefmt.Failed(step, match, err) - f.printStepKind(f.failed[len(f.failed)-1]) -} - -func (f *pretty) Pending(step *gherkin.Step, match *StepDef) { - f.basefmt.Pending(step, match) - f.printStepKind(f.pending[len(f.pending)-1]) -} - -// longest gives a list of longest columns of all rows in Table -func longest(tbl interface{}, clrs ...colors.ColorFunc) []int { - var rows []*gherkin.TableRow - switch t := tbl.(type) { - case *gherkin.Examples: - rows = append(rows, t.TableHeader) - rows = append(rows, t.TableBody...) - case *gherkin.DataTable: - rows = append(rows, t.Rows...) - } - - longest := make([]int, len(rows[0].Cells)) - for _, row := range rows { - for i, cell := range row.Cells { - for _, c := range clrs { - ln := utf8.RuneCountInString(c(cell.Value)) - if longest[i] < ln { - longest[i] = ln - } - } - - ln := utf8.RuneCountInString(cell.Value) - if longest[i] < ln { - longest[i] = ln - } - } - } - return longest -} - -func (f *pretty) longestStep(steps []*gherkin.Step, base int) int { - ret := base - for _, step := range steps { - length := f.length(step) - if length > ret { - ret = length - } - } - return ret -} - -// a line number representation in feature file -func (f *pretty) line(loc *gherkin.Location) string { - return black(fmt.Sprintf("# %s:%d", f.features[len(f.features)-1].Path, loc.Line)) -} - -func (f *pretty) length(node interface{}) int { - switch t := node.(type) { - case *gherkin.Background: - return f.indent + utf8.RuneCountInString(strings.TrimSpace(t.Keyword)+": "+t.Name) - case *gherkin.Step: - return f.indent*2 + utf8.RuneCountInString(strings.TrimSpace(t.Keyword)+" "+t.Text) - case *gherkin.Scenario: - return f.indent + utf8.RuneCountInString(strings.TrimSpace(t.Keyword)+": "+t.Name) - case *gherkin.ScenarioOutline: - return f.indent + utf8.RuneCountInString(strings.TrimSpace(t.Keyword)+": "+t.Name) - } - panic(fmt.Sprintf("unexpected node %T to determine length", node)) -} diff --git a/vendor/github.com/DATA-DOG/godog/fmt_progress.go b/vendor/github.com/DATA-DOG/godog/fmt_progress.go deleted file mode 100644 index a63e4748e..000000000 --- a/vendor/github.com/DATA-DOG/godog/fmt_progress.go +++ /dev/null @@ -1,121 +0,0 @@ -package godog - -import ( - "fmt" - "io" - "math" - "strings" - "sync" - - "github.com/DATA-DOG/godog/gherkin" -) - -func init() { - Format("progress", "Prints a character per step.", progressFunc) -} - -func progressFunc(suite string, out io.Writer) Formatter { - return &progress{ - basefmt: basefmt{ - started: timeNowFunc(), - indent: 2, - out: out, - }, - stepsPerRow: 70, - } -} - -type progress struct { - basefmt - sync.Mutex - stepsPerRow int - steps int -} - -func (f *progress) Node(n interface{}) { - f.Lock() - defer f.Unlock() - f.basefmt.Node(n) -} - -func (f *progress) Feature(ft *gherkin.Feature, p string, c []byte) { - f.Lock() - defer f.Unlock() - f.basefmt.Feature(ft, p, c) -} - -func (f *progress) Summary() { - left := math.Mod(float64(f.steps), float64(f.stepsPerRow)) - if left != 0 { - if int(f.steps) > f.stepsPerRow { - fmt.Fprintf(f.out, s(f.stepsPerRow-int(left))+fmt.Sprintf(" %d\n", f.steps)) - } else { - fmt.Fprintf(f.out, " %d\n", f.steps) - } - } - fmt.Fprintln(f.out, "") - - if len(f.failed) > 0 { - fmt.Fprintln(f.out, "\n--- "+red("Failed steps:")+"\n") - for _, fail := range f.failed { - fmt.Fprintln(f.out, s(2)+red(fail.scenarioDesc())+black(" # "+fail.scenarioLine())) - fmt.Fprintln(f.out, s(4)+red(strings.TrimSpace(fail.step.Keyword)+" "+fail.step.Text)+black(" # "+fail.line())) - fmt.Fprintln(f.out, s(6)+red("Error: ")+redb(fmt.Sprintf("%+v", fail.err))+"\n") - } - } - f.basefmt.Summary() -} - -func (f *progress) step(res *stepResult) { - switch res.typ { - case passed: - fmt.Fprint(f.out, green(".")) - case skipped: - fmt.Fprint(f.out, cyan("-")) - case failed: - fmt.Fprint(f.out, red("F")) - case undefined: - fmt.Fprint(f.out, yellow("U")) - case pending: - fmt.Fprint(f.out, yellow("P")) - } - f.steps++ - if math.Mod(float64(f.steps), float64(f.stepsPerRow)) == 0 { - fmt.Fprintf(f.out, " %d\n", f.steps) - } -} - -func (f *progress) Passed(step *gherkin.Step, match *StepDef) { - f.Lock() - defer f.Unlock() - f.basefmt.Passed(step, match) - f.step(f.passed[len(f.passed)-1]) -} - -func (f *progress) Skipped(step *gherkin.Step, match *StepDef) { - f.Lock() - defer f.Unlock() - f.basefmt.Skipped(step, match) - f.step(f.skipped[len(f.skipped)-1]) -} - -func (f *progress) Undefined(step *gherkin.Step, match *StepDef) { - f.Lock() - defer f.Unlock() - f.basefmt.Undefined(step, match) - f.step(f.undefined[len(f.undefined)-1]) -} - -func (f *progress) Failed(step *gherkin.Step, match *StepDef, err error) { - f.Lock() - defer f.Unlock() - f.basefmt.Failed(step, match, err) - f.step(f.failed[len(f.failed)-1]) -} - -func (f *progress) Pending(step *gherkin.Step, match *StepDef) { - f.Lock() - defer f.Unlock() - f.basefmt.Pending(step, match) - f.step(f.pending[len(f.pending)-1]) -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin.go b/vendor/github.com/DATA-DOG/godog/gherkin.go deleted file mode 100644 index 6a4e8040e..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin.go +++ /dev/null @@ -1,36 +0,0 @@ -package godog - -import "github.com/DATA-DOG/godog/gherkin" - -// examples is a helper func to cast gherkin.Examples -// or gherkin.BaseExamples if its empty -// @TODO: this should go away with gherkin update -func examples(ex interface{}) (*gherkin.Examples, bool) { - t, ok := ex.(*gherkin.Examples) - return t, ok -} - -// means there are no scenarios or they do not have steps -func isEmptyFeature(ft *gherkin.Feature) bool { - for _, def := range ft.ScenarioDefinitions { - if !isEmptyScenario(def) { - return false - } - } - return true -} - -// means scenario dooes not have steps -func isEmptyScenario(def interface{}) bool { - switch t := def.(type) { - case *gherkin.Scenario: - if len(t.Steps) > 0 { - return false - } - case *gherkin.ScenarioOutline: - if len(t.Steps) > 0 { - return false - } - } - return true -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin/LICENSE b/vendor/github.com/DATA-DOG/godog/gherkin/LICENSE deleted file mode 100644 index ea6854907..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014-2016 Cucumber Ltd, Gaspar Nagy - -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/DATA-DOG/godog/gherkin/README.md b/vendor/github.com/DATA-DOG/godog/gherkin/README.md deleted file mode 100644 index 6b90df006..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/README.md +++ /dev/null @@ -1,3 +0,0 @@ -[![Build Status](https://secure.travis-ci.org/cucumber/gherkin-go.svg)](http://travis-ci.org/cucumber/gherkin-go) - -Gherkin parser/compiler for Go. Please see [Gherkin](https://github.com/cucumber/gherkin) for details. diff --git a/vendor/github.com/DATA-DOG/godog/gherkin/ast.go b/vendor/github.com/DATA-DOG/godog/gherkin/ast.go deleted file mode 100644 index d0909e639..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/ast.go +++ /dev/null @@ -1,97 +0,0 @@ -package gherkin - -type Location struct { - Line int `json:"line"` - Column int `json:"column"` -} - -type Node struct { - Location *Location `json:"location,omitempty"` - Type string `json:"type"` -} - -type Feature struct { - Node - Tags []*Tag `json:"tags"` - Language string `json:"language,omitempty"` - Keyword string `json:"keyword"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - Background *Background `json:"background,omitempty"` - ScenarioDefinitions []interface{} `json:"scenarioDefinitions"` - Comments []*Comment `json:"comments"` -} - -type Comment struct { - Node - Location *Location `json:"location,omitempty"` - Text string `json:"text"` -} - -type Tag struct { - Node - Location *Location `json:"location,omitempty"` - Name string `json:"name"` -} - -type Background struct { - ScenarioDefinition -} - -type Scenario struct { - ScenarioDefinition - Tags []*Tag `json:"tags"` -} - -type ScenarioOutline struct { - ScenarioDefinition - Tags []*Tag `json:"tags"` - Examples []*Examples `json:"examples,omitempty"` -} - -type Examples struct { - Node - Tags []*Tag `json:"tags"` - Keyword string `json:"keyword"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - TableHeader *TableRow `json:"tableHeader"` - TableBody []*TableRow `json:"tableBody"` -} - -type TableRow struct { - Node - Cells []*TableCell `json:"cells"` -} - -type TableCell struct { - Node - Value string `json:"value"` -} - -type ScenarioDefinition struct { - Node - Keyword string `json:"keyword"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - Steps []*Step `json:"steps"` -} - -type Step struct { - Node - Keyword string `json:"keyword"` - Text string `json:"text"` - Argument interface{} `json:"argument,omitempty"` -} - -type DocString struct { - Node - ContentType string `json:"contentType,omitempty"` - Content string `json:"content"` - Delimitter string `json:"-"` -} - -type DataTable struct { - Node - Rows []*TableRow `json:"rows"` -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin/astbuilder.go b/vendor/github.com/DATA-DOG/godog/gherkin/astbuilder.go deleted file mode 100644 index e92ea362a..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/astbuilder.go +++ /dev/null @@ -1,378 +0,0 @@ -package gherkin - -import ( - "strings" -) - -type AstBuilder interface { - Builder - GetFeature() *Feature -} - -type astBuilder struct { - stack []*astNode - comments []*Comment -} - -func (t *astBuilder) Reset() { - t.comments = []*Comment{} - t.stack = []*astNode{} - t.push(newAstNode(RuleType_None)) -} - -func (t *astBuilder) GetFeature() *Feature { - res := t.currentNode().getSingle(RuleType_Feature) - if val, ok := res.(*Feature); ok { - return val - } - return nil -} - -type astNode struct { - ruleType RuleType - subNodes map[RuleType][]interface{} -} - -func (a *astNode) add(rt RuleType, obj interface{}) { - a.subNodes[rt] = append(a.subNodes[rt], obj) -} - -func (a *astNode) getSingle(rt RuleType) interface{} { - if val, ok := a.subNodes[rt]; ok { - for i := range val { - return val[i] - } - } - return nil -} - -func (a *astNode) getItems(rt RuleType) []interface{} { - var res []interface{} - if val, ok := a.subNodes[rt]; ok { - for i := range val { - res = append(res, val[i]) - } - } - return res -} - -func (a *astNode) getToken(tt TokenType) *Token { - if val, ok := a.getSingle(tt.RuleType()).(*Token); ok { - return val - } - return nil -} - -func (a *astNode) getTokens(tt TokenType) []*Token { - var items = a.getItems(tt.RuleType()) - var tokens []*Token - for i := range items { - if val, ok := items[i].(*Token); ok { - tokens = append(tokens, val) - } - } - return tokens -} - -func (t *astBuilder) currentNode() *astNode { - if len(t.stack) > 0 { - return t.stack[len(t.stack)-1] - } - return nil -} - -func newAstNode(rt RuleType) *astNode { - return &astNode{ - ruleType: rt, - subNodes: make(map[RuleType][]interface{}), - } -} - -func NewAstBuilder() AstBuilder { - builder := new(astBuilder) - builder.comments = []*Comment{} - builder.push(newAstNode(RuleType_None)) - return builder -} - -func (t *astBuilder) push(n *astNode) { - t.stack = append(t.stack, n) -} - -func (t *astBuilder) pop() *astNode { - x := t.stack[len(t.stack)-1] - t.stack = t.stack[:len(t.stack)-1] - return x -} - -func (t *astBuilder) Build(tok *Token) (bool, error) { - if tok.Type == TokenType_Comment { - comment := new(Comment) - comment.Type = "Comment" - comment.Location = astLocation(tok) - comment.Text = tok.Text - t.comments = append(t.comments, comment) - } else { - t.currentNode().add(tok.Type.RuleType(), tok) - } - return true, nil -} -func (t *astBuilder) StartRule(r RuleType) (bool, error) { - t.push(newAstNode(r)) - return true, nil -} -func (t *astBuilder) EndRule(r RuleType) (bool, error) { - node := t.pop() - transformedNode, err := t.transformNode(node) - t.currentNode().add(node.ruleType, transformedNode) - return true, err -} - -func (t *astBuilder) transformNode(node *astNode) (interface{}, error) { - switch node.ruleType { - - case RuleType_Step: - stepLine := node.getToken(TokenType_StepLine) - step := new(Step) - step.Type = "Step" - step.Location = astLocation(stepLine) - step.Keyword = stepLine.Keyword - step.Text = stepLine.Text - step.Argument = node.getSingle(RuleType_DataTable) - if step.Argument == nil { - step.Argument = node.getSingle(RuleType_DocString) - } - return step, nil - - case RuleType_DocString: - separatorToken := node.getToken(TokenType_DocStringSeparator) - contentType := separatorToken.Text - lineTokens := node.getTokens(TokenType_Other) - var text string - for i := range lineTokens { - if i > 0 { - text += "\n" - } - text += lineTokens[i].Text - } - ds := new(DocString) - ds.Type = "DocString" - ds.Location = astLocation(separatorToken) - ds.ContentType = contentType - ds.Content = text - ds.Delimitter = DOCSTRING_SEPARATOR // TODO: remember separator - return ds, nil - - case RuleType_DataTable: - rows, err := astTableRows(node) - dt := new(DataTable) - dt.Type = "DataTable" - dt.Location = rows[0].Location - dt.Rows = rows - return dt, err - - case RuleType_Background: - backgroundLine := node.getToken(TokenType_BackgroundLine) - description, _ := node.getSingle(RuleType_Description).(string) - bg := new(Background) - bg.Type = "Background" - bg.Location = astLocation(backgroundLine) - bg.Keyword = backgroundLine.Keyword - bg.Name = backgroundLine.Text - bg.Description = description - bg.Steps = astSteps(node) - return bg, nil - - case RuleType_Scenario_Definition: - tags := astTags(node) - scenarioNode, _ := node.getSingle(RuleType_Scenario).(*astNode) - if scenarioNode != nil { - scenarioLine := scenarioNode.getToken(TokenType_ScenarioLine) - description, _ := scenarioNode.getSingle(RuleType_Description).(string) - sc := new(Scenario) - sc.Type = "Scenario" - sc.Tags = tags - sc.Location = astLocation(scenarioLine) - sc.Keyword = scenarioLine.Keyword - sc.Name = scenarioLine.Text - sc.Description = description - sc.Steps = astSteps(scenarioNode) - return sc, nil - } else { - scenarioOutlineNode, ok := node.getSingle(RuleType_ScenarioOutline).(*astNode) - if !ok { - panic("Internal grammar error") - } - scenarioOutlineLine := scenarioOutlineNode.getToken(TokenType_ScenarioOutlineLine) - description, _ := scenarioOutlineNode.getSingle(RuleType_Description).(string) - sc := new(ScenarioOutline) - sc.Type = "ScenarioOutline" - sc.Tags = tags - sc.Location = astLocation(scenarioOutlineLine) - sc.Keyword = scenarioOutlineLine.Keyword - sc.Name = scenarioOutlineLine.Text - sc.Description = description - sc.Steps = astSteps(scenarioOutlineNode) - sc.Examples = astExamples(scenarioOutlineNode) - return sc, nil - } - - case RuleType_Examples_Definition: - tags := astTags(node) - examplesNode, _ := node.getSingle(RuleType_Examples).(*astNode) - examplesLine := examplesNode.getToken(TokenType_ExamplesLine) - description, _ := examplesNode.getSingle(RuleType_Description).(string) - allRows, err := astTableRows(examplesNode) - ex := new(Examples) - ex.Type = "Examples" - ex.Tags = tags - ex.Location = astLocation(examplesLine) - ex.Keyword = examplesLine.Keyword - ex.Name = examplesLine.Text - ex.Description = description - ex.TableHeader = allRows[0] - ex.TableBody = allRows[1:] - return ex, err - - case RuleType_Description: - lineTokens := node.getTokens(TokenType_Other) - // Trim trailing empty lines - end := len(lineTokens) - for end > 0 && strings.TrimSpace(lineTokens[end-1].Text) == "" { - end-- - } - var desc []string - for i := range lineTokens[0:end] { - desc = append(desc, lineTokens[i].Text) - } - return strings.Join(desc, "\n"), nil - - case RuleType_Feature: - header, ok := node.getSingle(RuleType_Feature_Header).(*astNode) - if !ok { - return nil, nil - } - tags := astTags(header) - featureLine := header.getToken(TokenType_FeatureLine) - if featureLine == nil { - return nil, nil - } - background, _ := node.getSingle(RuleType_Background).(*Background) - scenarioDefinitions := node.getItems(RuleType_Scenario_Definition) - if scenarioDefinitions == nil { - scenarioDefinitions = []interface{}{} - } - description, _ := header.getSingle(RuleType_Description).(string) - - feat := new(Feature) - feat.Type = "Feature" - feat.Tags = tags - feat.Location = astLocation(featureLine) - feat.Language = featureLine.GherkinDialect - feat.Keyword = featureLine.Keyword - feat.Name = featureLine.Text - feat.Description = description - feat.Background = background - feat.ScenarioDefinitions = scenarioDefinitions - feat.Comments = t.comments - return feat, nil - } - return node, nil -} - -func astLocation(t *Token) *Location { - return &Location{ - Line: t.Location.Line, - Column: t.Location.Column, - } -} - -func astTableRows(t *astNode) (rows []*TableRow, err error) { - rows = []*TableRow{} - tokens := t.getTokens(TokenType_TableRow) - for i := range tokens { - row := new(TableRow) - row.Type = "TableRow" - row.Location = astLocation(tokens[i]) - row.Cells = astTableCells(tokens[i]) - rows = append(rows, row) - } - err = ensureCellCount(rows) - return -} - -func ensureCellCount(rows []*TableRow) error { - if len(rows) <= 1 { - return nil - } - cellCount := len(rows[0].Cells) - for i := range rows { - if cellCount != len(rows[i].Cells) { - return &parseError{"inconsistent cell count within the table", &Location{ - Line: rows[i].Location.Line, - Column: rows[i].Location.Column, - }} - } - } - return nil -} - -func astTableCells(t *Token) (cells []*TableCell) { - cells = []*TableCell{} - for i := range t.Items { - item := t.Items[i] - cell := new(TableCell) - cell.Type = "TableCell" - cell.Location = &Location{ - Line: t.Location.Line, - Column: item.Column, - } - cell.Value = item.Text - cells = append(cells, cell) - } - return -} - -func astSteps(t *astNode) (steps []*Step) { - steps = []*Step{} - tokens := t.getItems(RuleType_Step) - for i := range tokens { - step, _ := tokens[i].(*Step) - steps = append(steps, step) - } - return -} - -func astExamples(t *astNode) (examples []*Examples) { - examples = []*Examples{} - tokens := t.getItems(RuleType_Examples_Definition) - for i := range tokens { - example, _ := tokens[i].(*Examples) - examples = append(examples, example) - } - return -} - -func astTags(node *astNode) (tags []*Tag) { - tags = []*Tag{} - tagsNode, ok := node.getSingle(RuleType_Tags).(*astNode) - if !ok { - return - } - tokens := tagsNode.getTokens(TokenType_TagLine) - for i := range tokens { - token := tokens[i] - for k := range token.Items { - item := token.Items[k] - tag := new(Tag) - tag.Type = "Tag" - tag.Location = &Location{ - Line: token.Location.Line, - Column: item.Column, - } - tag.Name = item.Text - tags = append(tags, tag) - } - } - return -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin/dialect.go b/vendor/github.com/DATA-DOG/godog/gherkin/dialect.go deleted file mode 100644 index e8af1e455..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/dialect.go +++ /dev/null @@ -1,47 +0,0 @@ -package gherkin - -type GherkinDialect struct { - Language string - Name string - Native string - Keywords map[string][]string -} - -func (g *GherkinDialect) FeatureKeywords() []string { - return g.Keywords["feature"] -} - -func (g *GherkinDialect) ScenarioKeywords() []string { - return g.Keywords["scenario"] -} - -func (g *GherkinDialect) StepKeywords() []string { - result := g.Keywords["given"] - result = append(result, g.Keywords["when"]...) - result = append(result, g.Keywords["then"]...) - result = append(result, g.Keywords["and"]...) - result = append(result, g.Keywords["but"]...) - return result -} - -func (g *GherkinDialect) BackgroundKeywords() []string { - return g.Keywords["background"] -} - -func (g *GherkinDialect) ScenarioOutlineKeywords() []string { - return g.Keywords["scenarioOutline"] -} - -func (g *GherkinDialect) ExamplesKeywords() []string { - return g.Keywords["examples"] -} - -type GherkinDialectProvider interface { - GetDialect(language string) *GherkinDialect -} - -type gherkinDialectMap map[string]*GherkinDialect - -func (g gherkinDialectMap) GetDialect(language string) *GherkinDialect { - return g[language] -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin/dialects_builtin.go b/vendor/github.com/DATA-DOG/godog/gherkin/dialects_builtin.go deleted file mode 100644 index 1d74625c6..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/dialects_builtin.go +++ /dev/null @@ -1,2988 +0,0 @@ -package gherkin - -// Builtin dialects for af (Afrikaans), am (Armenian), ar (Arabic), bg (Bulgarian), bm (Malay), bs (Bosnian), ca (Catalan), cs (Czech), cy-GB (Welsh), da (Danish), de (German), el (Greek), em (Emoji), en (English), en-Scouse (Scouse), en-au (Australian), en-lol (LOLCAT), en-old (Old English), en-pirate (Pirate), eo (Esperanto), es (Spanish), et (Estonian), fa (Persian), fi (Finnish), fr (French), ga (Irish), gj (Gujarati), gl (Galician), he (Hebrew), hi (Hindi), hr (Croatian), ht (Creole), hu (Hungarian), id (Indonesian), is (Icelandic), it (Italian), ja (Japanese), jv (Javanese), kn (Kannada), ko (Korean), lt (Lithuanian), lu (Luxemburgish), lv (Latvian), mn (Mongolian), nl (Dutch), no (Norwegian), pa (Panjabi), pl (Polish), pt (Portuguese), ro (Romanian), ru (Russian), sk (Slovak), sl (Slovenian), sr-Cyrl (Serbian), sr-Latn (Serbian (Latin)), sv (Swedish), ta (Tamil), th (Thai), tl (Telugu), tlh (Klingon), tr (Turkish), tt (Tatar), uk (Ukrainian), ur (Urdu), uz (Uzbek), vi (Vietnamese), zh-CN (Chinese simplified), zh-TW (Chinese traditional) -func GherkinDialectsBuildin() GherkinDialectProvider { - return buildinDialects -} - -const ( - feature = "feature" - background = "background" - scenario = "scenario" - scenarioOutline = "scenarioOutline" - examples = "examples" - given = "given" - when = "when" - then = "then" - and = "and" - but = "but" -) - -var buildinDialects = gherkinDialectMap{ - "af": &GherkinDialect{ - "af", "Afrikaans", "Afrikaans", map[string][]string{ - and: []string{ - "* ", - "En ", - }, - background: []string{ - "Agtergrond", - }, - but: []string{ - "* ", - "Maar ", - }, - examples: []string{ - "Voorbeelde", - }, - feature: []string{ - "Funksie", - "Besigheid Behoefte", - "Vermoë", - }, - given: []string{ - "* ", - "Gegewe ", - }, - scenario: []string{ - "Situasie", - }, - scenarioOutline: []string{ - "Situasie Uiteensetting", - }, - then: []string{ - "* ", - "Dan ", - }, - when: []string{ - "* ", - "Wanneer ", - }, - }, - }, - "am": &GherkinDialect{ - "am", "Armenian", "հայերեն", map[string][]string{ - and: []string{ - "* ", - "Եվ ", - }, - background: []string{ - "Կոնտեքստ", - }, - but: []string{ - "* ", - "Բայց ", - }, - examples: []string{ - "Օրինակներ", - }, - feature: []string{ - "Ֆունկցիոնալություն", - "Հատկություն", - }, - given: []string{ - "* ", - "Դիցուք ", - }, - scenario: []string{ - "Սցենար", - }, - scenarioOutline: []string{ - "Սցենարի կառուցվացքը", - }, - then: []string{ - "* ", - "Ապա ", - }, - when: []string{ - "* ", - "Եթե ", - "Երբ ", - }, - }, - }, - "ar": &GherkinDialect{ - "ar", "Arabic", "العربية", map[string][]string{ - and: []string{ - "* ", - "و ", - }, - background: []string{ - "الخلفية", - }, - but: []string{ - "* ", - "لكن ", - }, - examples: []string{ - "امثلة", - }, - feature: []string{ - "خاصية", - }, - given: []string{ - "* ", - "بفرض ", - }, - scenario: []string{ - "سيناريو", - }, - scenarioOutline: []string{ - "سيناريو مخطط", - }, - then: []string{ - "* ", - "اذاً ", - "ثم ", - }, - when: []string{ - "* ", - "متى ", - "عندما ", - }, - }, - }, - "bg": &GherkinDialect{ - "bg", "Bulgarian", "български", map[string][]string{ - and: []string{ - "* ", - "И ", - }, - background: []string{ - "Предистория", - }, - but: []string{ - "* ", - "Но ", - }, - examples: []string{ - "Примери", - }, - feature: []string{ - "Функционалност", - }, - given: []string{ - "* ", - "Дадено ", - }, - scenario: []string{ - "Сценарий", - }, - scenarioOutline: []string{ - "Рамка на сценарий", - }, - then: []string{ - "* ", - "То ", - }, - when: []string{ - "* ", - "Когато ", - }, - }, - }, - "bm": &GherkinDialect{ - "bm", "Malay", "Bahasa Melayu", map[string][]string{ - and: []string{ - "* ", - "Dan ", - }, - background: []string{ - "Latar Belakang", - }, - but: []string{ - "* ", - "Tetapi ", - "Tapi ", - }, - examples: []string{ - "Contoh", - }, - feature: []string{ - "Fungsi", - }, - given: []string{ - "* ", - "Diberi ", - "Bagi ", - }, - scenario: []string{ - "Senario", - "Situasi", - "Keadaan", - }, - scenarioOutline: []string{ - "Kerangka Senario", - "Kerangka Situasi", - "Kerangka Keadaan", - "Garis Panduan Senario", - }, - then: []string{ - "* ", - "Maka ", - "Kemudian ", - }, - when: []string{ - "* ", - "Apabila ", - }, - }, - }, - "bs": &GherkinDialect{ - "bs", "Bosnian", "Bosanski", map[string][]string{ - and: []string{ - "* ", - "I ", - "A ", - }, - background: []string{ - "Pozadina", - }, - but: []string{ - "* ", - "Ali ", - }, - examples: []string{ - "Primjeri", - }, - feature: []string{ - "Karakteristika", - }, - given: []string{ - "* ", - "Dato ", - }, - scenario: []string{ - "Scenariju", - "Scenario", - }, - scenarioOutline: []string{ - "Scenariju-obris", - "Scenario-outline", - }, - then: []string{ - "* ", - "Zatim ", - }, - when: []string{ - "* ", - "Kada ", - }, - }, - }, - "ca": &GherkinDialect{ - "ca", "Catalan", "català", map[string][]string{ - and: []string{ - "* ", - "I ", - }, - background: []string{ - "Rerefons", - "Antecedents", - }, - but: []string{ - "* ", - "Però ", - }, - examples: []string{ - "Exemples", - }, - feature: []string{ - "Característica", - "Funcionalitat", - }, - given: []string{ - "* ", - "Donat ", - "Donada ", - "Atès ", - "Atesa ", - }, - scenario: []string{ - "Escenari", - }, - scenarioOutline: []string{ - "Esquema de l'escenari", - }, - then: []string{ - "* ", - "Aleshores ", - "Cal ", - }, - when: []string{ - "* ", - "Quan ", - }, - }, - }, - "cs": &GherkinDialect{ - "cs", "Czech", "Česky", map[string][]string{ - and: []string{ - "* ", - "A také ", - "A ", - }, - background: []string{ - "Pozadí", - "Kontext", - }, - but: []string{ - "* ", - "Ale ", - }, - examples: []string{ - "Příklady", - }, - feature: []string{ - "Požadavek", - }, - given: []string{ - "* ", - "Pokud ", - "Za předpokladu ", - }, - scenario: []string{ - "Scénář", - }, - scenarioOutline: []string{ - "Náčrt Scénáře", - "Osnova scénáře", - }, - then: []string{ - "* ", - "Pak ", - }, - when: []string{ - "* ", - "Když ", - }, - }, - }, - "cy-GB": &GherkinDialect{ - "cy-GB", "Welsh", "Cymraeg", map[string][]string{ - and: []string{ - "* ", - "A ", - }, - background: []string{ - "Cefndir", - }, - but: []string{ - "* ", - "Ond ", - }, - examples: []string{ - "Enghreifftiau", - }, - feature: []string{ - "Arwedd", - }, - given: []string{ - "* ", - "Anrhegedig a ", - }, - scenario: []string{ - "Scenario", - }, - scenarioOutline: []string{ - "Scenario Amlinellol", - }, - then: []string{ - "* ", - "Yna ", - }, - when: []string{ - "* ", - "Pryd ", - }, - }, - }, - "da": &GherkinDialect{ - "da", "Danish", "dansk", map[string][]string{ - and: []string{ - "* ", - "Og ", - }, - background: []string{ - "Baggrund", - }, - but: []string{ - "* ", - "Men ", - }, - examples: []string{ - "Eksempler", - }, - feature: []string{ - "Egenskab", - }, - given: []string{ - "* ", - "Givet ", - }, - scenario: []string{ - "Scenarie", - }, - scenarioOutline: []string{ - "Abstrakt Scenario", - }, - then: []string{ - "* ", - "Så ", - }, - when: []string{ - "* ", - "Når ", - }, - }, - }, - "de": &GherkinDialect{ - "de", "German", "Deutsch", map[string][]string{ - and: []string{ - "* ", - "Und ", - }, - background: []string{ - "Grundlage", - }, - but: []string{ - "* ", - "Aber ", - }, - examples: []string{ - "Beispiele", - }, - feature: []string{ - "Funktionalität", - }, - given: []string{ - "* ", - "Angenommen ", - "Gegeben sei ", - "Gegeben seien ", - }, - scenario: []string{ - "Szenario", - }, - scenarioOutline: []string{ - "Szenariogrundriss", - }, - then: []string{ - "* ", - "Dann ", - }, - when: []string{ - "* ", - "Wenn ", - }, - }, - }, - "el": &GherkinDialect{ - "el", "Greek", "Ελληνικά", map[string][]string{ - and: []string{ - "* ", - "Και ", - }, - background: []string{ - "Υπόβαθρο", - }, - but: []string{ - "* ", - "Αλλά ", - }, - examples: []string{ - "Παραδείγματα", - "Σενάρια", - }, - feature: []string{ - "Δυνατότητα", - "Λειτουργία", - }, - given: []string{ - "* ", - "Δεδομένου ", - }, - scenario: []string{ - "Σενάριο", - }, - scenarioOutline: []string{ - "Περιγραφή Σεναρίου", - }, - then: []string{ - "* ", - "Τότε ", - }, - when: []string{ - "* ", - "Όταν ", - }, - }, - }, - "em": &GherkinDialect{ - "em", "Emoji", "😀", map[string][]string{ - and: []string{ - "* ", - "😂", - }, - background: []string{ - "💤", - }, - but: []string{ - "* ", - "😔", - }, - examples: []string{ - "📓", - }, - feature: []string{ - "📚", - }, - given: []string{ - "* ", - "😐", - }, - scenario: []string{ - "📕", - }, - scenarioOutline: []string{ - "📖", - }, - then: []string{ - "* ", - "🙏", - }, - when: []string{ - "* ", - "🎬", - }, - }, - }, - "en": &GherkinDialect{ - "en", "English", "English", map[string][]string{ - and: []string{ - "* ", - "And ", - }, - background: []string{ - "Background", - }, - but: []string{ - "* ", - "But ", - }, - examples: []string{ - "Examples", - "Scenarios", - }, - feature: []string{ - "Feature", - "Business Need", - "Ability", - }, - given: []string{ - "* ", - "Given ", - }, - scenario: []string{ - "Scenario", - }, - scenarioOutline: []string{ - "Scenario Outline", - "Scenario Template", - }, - then: []string{ - "* ", - "Then ", - }, - when: []string{ - "* ", - "When ", - }, - }, - }, - "en-Scouse": &GherkinDialect{ - "en-Scouse", "Scouse", "Scouse", map[string][]string{ - and: []string{ - "* ", - "An ", - }, - background: []string{ - "Dis is what went down", - }, - but: []string{ - "* ", - "Buh ", - }, - examples: []string{ - "Examples", - }, - feature: []string{ - "Feature", - }, - given: []string{ - "* ", - "Givun ", - "Youse know when youse got ", - }, - scenario: []string{ - "The thing of it is", - }, - scenarioOutline: []string{ - "Wharrimean is", - }, - then: []string{ - "* ", - "Dun ", - "Den youse gotta ", - }, - when: []string{ - "* ", - "Wun ", - "Youse know like when ", - }, - }, - }, - "en-au": &GherkinDialect{ - "en-au", "Australian", "Australian", map[string][]string{ - and: []string{ - "* ", - "Too right ", - }, - background: []string{ - "First off", - }, - but: []string{ - "* ", - "Yeah nah ", - }, - examples: []string{ - "You'll wanna", - }, - feature: []string{ - "Pretty much", - }, - given: []string{ - "* ", - "Y'know ", - }, - scenario: []string{ - "Awww, look mate", - }, - scenarioOutline: []string{ - "Reckon it's like", - }, - then: []string{ - "* ", - "But at the end of the day I reckon ", - }, - when: []string{ - "* ", - "It's just unbelievable ", - }, - }, - }, - "en-lol": &GherkinDialect{ - "en-lol", "LOLCAT", "LOLCAT", map[string][]string{ - and: []string{ - "* ", - "AN ", - }, - background: []string{ - "B4", - }, - but: []string{ - "* ", - "BUT ", - }, - examples: []string{ - "EXAMPLZ", - }, - feature: []string{ - "OH HAI", - }, - given: []string{ - "* ", - "I CAN HAZ ", - }, - scenario: []string{ - "MISHUN", - }, - scenarioOutline: []string{ - "MISHUN SRSLY", - }, - then: []string{ - "* ", - "DEN ", - }, - when: []string{ - "* ", - "WEN ", - }, - }, - }, - "en-old": &GherkinDialect{ - "en-old", "Old English", "Englisc", map[string][]string{ - and: []string{ - "* ", - "Ond ", - "7 ", - }, - background: []string{ - "Aer", - "Ær", - }, - but: []string{ - "* ", - "Ac ", - }, - examples: []string{ - "Se the", - "Se þe", - "Se ðe", - }, - feature: []string{ - "Hwaet", - "Hwæt", - }, - given: []string{ - "* ", - "Thurh ", - "Þurh ", - "Ðurh ", - }, - scenario: []string{ - "Swa", - }, - scenarioOutline: []string{ - "Swa hwaer swa", - "Swa hwær swa", - }, - then: []string{ - "* ", - "Tha ", - "Þa ", - "Ða ", - "Tha the ", - "Þa þe ", - "Ða ðe ", - }, - when: []string{ - "* ", - "Tha ", - "Þa ", - "Ða ", - }, - }, - }, - "en-pirate": &GherkinDialect{ - "en-pirate", "Pirate", "Pirate", map[string][]string{ - and: []string{ - "* ", - "Aye ", - }, - background: []string{ - "Yo-ho-ho", - }, - but: []string{ - "* ", - "Avast! ", - }, - examples: []string{ - "Dead men tell no tales", - }, - feature: []string{ - "Ahoy matey!", - }, - given: []string{ - "* ", - "Gangway! ", - }, - scenario: []string{ - "Heave to", - }, - scenarioOutline: []string{ - "Shiver me timbers", - }, - then: []string{ - "* ", - "Let go and haul ", - }, - when: []string{ - "* ", - "Blimey! ", - }, - }, - }, - "eo": &GherkinDialect{ - "eo", "Esperanto", "Esperanto", map[string][]string{ - and: []string{ - "* ", - "Kaj ", - }, - background: []string{ - "Fono", - }, - but: []string{ - "* ", - "Sed ", - }, - examples: []string{ - "Ekzemploj", - }, - feature: []string{ - "Trajto", - }, - given: []string{ - "* ", - "Donitaĵo ", - "Komence ", - }, - scenario: []string{ - "Scenaro", - "Kazo", - }, - scenarioOutline: []string{ - "Konturo de la scenaro", - "Skizo", - "Kazo-skizo", - }, - then: []string{ - "* ", - "Do ", - }, - when: []string{ - "* ", - "Se ", - }, - }, - }, - "es": &GherkinDialect{ - "es", "Spanish", "español", map[string][]string{ - and: []string{ - "* ", - "Y ", - "E ", - }, - background: []string{ - "Antecedentes", - }, - but: []string{ - "* ", - "Pero ", - }, - examples: []string{ - "Ejemplos", - }, - feature: []string{ - "Característica", - }, - given: []string{ - "* ", - "Dado ", - "Dada ", - "Dados ", - "Dadas ", - }, - scenario: []string{ - "Escenario", - }, - scenarioOutline: []string{ - "Esquema del escenario", - }, - then: []string{ - "* ", - "Entonces ", - }, - when: []string{ - "* ", - "Cuando ", - }, - }, - }, - "et": &GherkinDialect{ - "et", "Estonian", "eesti keel", map[string][]string{ - and: []string{ - "* ", - "Ja ", - }, - background: []string{ - "Taust", - }, - but: []string{ - "* ", - "Kuid ", - }, - examples: []string{ - "Juhtumid", - }, - feature: []string{ - "Omadus", - }, - given: []string{ - "* ", - "Eeldades ", - }, - scenario: []string{ - "Stsenaarium", - }, - scenarioOutline: []string{ - "Raamstsenaarium", - }, - then: []string{ - "* ", - "Siis ", - }, - when: []string{ - "* ", - "Kui ", - }, - }, - }, - "fa": &GherkinDialect{ - "fa", "Persian", "فارسی", map[string][]string{ - and: []string{ - "* ", - "و ", - }, - background: []string{ - "زمینه", - }, - but: []string{ - "* ", - "اما ", - }, - examples: []string{ - "نمونه ها", - }, - feature: []string{ - "وِیژگی", - }, - given: []string{ - "* ", - "با فرض ", - }, - scenario: []string{ - "سناریو", - }, - scenarioOutline: []string{ - "الگوی سناریو", - }, - then: []string{ - "* ", - "آنگاه ", - }, - when: []string{ - "* ", - "هنگامی ", - }, - }, - }, - "fi": &GherkinDialect{ - "fi", "Finnish", "suomi", map[string][]string{ - and: []string{ - "* ", - "Ja ", - }, - background: []string{ - "Tausta", - }, - but: []string{ - "* ", - "Mutta ", - }, - examples: []string{ - "Tapaukset", - }, - feature: []string{ - "Ominaisuus", - }, - given: []string{ - "* ", - "Oletetaan ", - }, - scenario: []string{ - "Tapaus", - }, - scenarioOutline: []string{ - "Tapausaihio", - }, - then: []string{ - "* ", - "Niin ", - }, - when: []string{ - "* ", - "Kun ", - }, - }, - }, - "fr": &GherkinDialect{ - "fr", "French", "français", map[string][]string{ - and: []string{ - "* ", - "Et que ", - "Et qu'", - "Et ", - }, - background: []string{ - "Contexte", - }, - but: []string{ - "* ", - "Mais que ", - "Mais qu'", - "Mais ", - }, - examples: []string{ - "Exemples", - }, - feature: []string{ - "Fonctionnalité", - }, - given: []string{ - "* ", - "Soit ", - "Etant donné que ", - "Etant donné qu'", - "Etant donné ", - "Etant donnée ", - "Etant donnés ", - "Etant données ", - "Étant donné que ", - "Étant donné qu'", - "Étant donné ", - "Étant donnée ", - "Étant donnés ", - "Étant données ", - }, - scenario: []string{ - "Scénario", - }, - scenarioOutline: []string{ - "Plan du scénario", - "Plan du Scénario", - }, - then: []string{ - "* ", - "Alors ", - }, - when: []string{ - "* ", - "Quand ", - "Lorsque ", - "Lorsqu'", - }, - }, - }, - "ga": &GherkinDialect{ - "ga", "Irish", "Gaeilge", map[string][]string{ - and: []string{ - "* ", - "Agus", - }, - background: []string{ - "Cúlra", - }, - but: []string{ - "* ", - "Ach", - }, - examples: []string{ - "Samplaí", - }, - feature: []string{ - "Gné", - }, - given: []string{ - "* ", - "Cuir i gcás go", - "Cuir i gcás nach", - "Cuir i gcás gur", - "Cuir i gcás nár", - }, - scenario: []string{ - "Cás", - }, - scenarioOutline: []string{ - "Cás Achomair", - }, - then: []string{ - "* ", - "Ansin", - }, - when: []string{ - "* ", - "Nuair a", - "Nuair nach", - "Nuair ba", - "Nuair nár", - }, - }, - }, - "gj": &GherkinDialect{ - "gj", "Gujarati", "ગુજરાતી", map[string][]string{ - and: []string{ - "* ", - "અને ", - }, - background: []string{ - "બેકગ્રાઉન્ડ", - }, - but: []string{ - "* ", - "પણ ", - }, - examples: []string{ - "ઉદાહરણો", - }, - feature: []string{ - "લક્ષણ", - "વ્યાપાર જરૂર", - "ક્ષમતા", - }, - given: []string{ - "* ", - "આપેલ છે ", - }, - scenario: []string{ - "સ્થિતિ", - }, - scenarioOutline: []string{ - "પરિદ્દશ્ય રૂપરેખા", - "પરિદ્દશ્ય ઢાંચો", - }, - then: []string{ - "* ", - "પછી ", - }, - when: []string{ - "* ", - "ક્યારે ", - }, - }, - }, - "gl": &GherkinDialect{ - "gl", "Galician", "galego", map[string][]string{ - and: []string{ - "* ", - "E ", - }, - background: []string{ - "Contexto", - }, - but: []string{ - "* ", - "Mais ", - "Pero ", - }, - examples: []string{ - "Exemplos", - }, - feature: []string{ - "Característica", - }, - given: []string{ - "* ", - "Dado ", - "Dada ", - "Dados ", - "Dadas ", - }, - scenario: []string{ - "Escenario", - }, - scenarioOutline: []string{ - "Esbozo do escenario", - }, - then: []string{ - "* ", - "Entón ", - "Logo ", - }, - when: []string{ - "* ", - "Cando ", - }, - }, - }, - "he": &GherkinDialect{ - "he", "Hebrew", "עברית", map[string][]string{ - and: []string{ - "* ", - "וגם ", - }, - background: []string{ - "רקע", - }, - but: []string{ - "* ", - "אבל ", - }, - examples: []string{ - "דוגמאות", - }, - feature: []string{ - "תכונה", - }, - given: []string{ - "* ", - "בהינתן ", - }, - scenario: []string{ - "תרחיש", - }, - scenarioOutline: []string{ - "תבנית תרחיש", - }, - then: []string{ - "* ", - "אז ", - "אזי ", - }, - when: []string{ - "* ", - "כאשר ", - }, - }, - }, - "hi": &GherkinDialect{ - "hi", "Hindi", "हिंदी", map[string][]string{ - and: []string{ - "* ", - "और ", - "तथा ", - }, - background: []string{ - "पृष्ठभूमि", - }, - but: []string{ - "* ", - "पर ", - "परन्तु ", - "किन्तु ", - }, - examples: []string{ - "उदाहरण", - }, - feature: []string{ - "रूप लेख", - }, - given: []string{ - "* ", - "अगर ", - "यदि ", - "चूंकि ", - }, - scenario: []string{ - "परिदृश्य", - }, - scenarioOutline: []string{ - "परिदृश्य रूपरेखा", - }, - then: []string{ - "* ", - "तब ", - "तदा ", - }, - when: []string{ - "* ", - "जब ", - "कदा ", - }, - }, - }, - "hr": &GherkinDialect{ - "hr", "Croatian", "hrvatski", map[string][]string{ - and: []string{ - "* ", - "I ", - }, - background: []string{ - "Pozadina", - }, - but: []string{ - "* ", - "Ali ", - }, - examples: []string{ - "Primjeri", - "Scenariji", - }, - feature: []string{ - "Osobina", - "Mogućnost", - "Mogucnost", - }, - given: []string{ - "* ", - "Zadan ", - "Zadani ", - "Zadano ", - }, - scenario: []string{ - "Scenarij", - }, - scenarioOutline: []string{ - "Skica", - "Koncept", - }, - then: []string{ - "* ", - "Onda ", - }, - when: []string{ - "* ", - "Kada ", - "Kad ", - }, - }, - }, - "ht": &GherkinDialect{ - "ht", "Creole", "kreyòl", map[string][]string{ - and: []string{ - "* ", - "Ak ", - "Epi ", - "E ", - }, - background: []string{ - "Kontèks", - "Istorik", - }, - but: []string{ - "* ", - "Men ", - }, - examples: []string{ - "Egzanp", - }, - feature: []string{ - "Karakteristik", - "Mak", - "Fonksyonalite", - }, - given: []string{ - "* ", - "Sipoze ", - "Sipoze ke ", - "Sipoze Ke ", - }, - scenario: []string{ - "Senaryo", - }, - scenarioOutline: []string{ - "Plan senaryo", - "Plan Senaryo", - "Senaryo deskripsyon", - "Senaryo Deskripsyon", - "Dyagram senaryo", - "Dyagram Senaryo", - }, - then: []string{ - "* ", - "Lè sa a ", - "Le sa a ", - }, - when: []string{ - "* ", - "Lè ", - "Le ", - }, - }, - }, - "hu": &GherkinDialect{ - "hu", "Hungarian", "magyar", map[string][]string{ - and: []string{ - "* ", - "És ", - }, - background: []string{ - "Háttér", - }, - but: []string{ - "* ", - "De ", - }, - examples: []string{ - "Példák", - }, - feature: []string{ - "Jellemző", - }, - given: []string{ - "* ", - "Amennyiben ", - "Adott ", - }, - scenario: []string{ - "Forgatókönyv", - }, - scenarioOutline: []string{ - "Forgatókönyv vázlat", - }, - then: []string{ - "* ", - "Akkor ", - }, - when: []string{ - "* ", - "Majd ", - "Ha ", - "Amikor ", - }, - }, - }, - "id": &GherkinDialect{ - "id", "Indonesian", "Bahasa Indonesia", map[string][]string{ - and: []string{ - "* ", - "Dan ", - }, - background: []string{ - "Dasar", - }, - but: []string{ - "* ", - "Tapi ", - }, - examples: []string{ - "Contoh", - }, - feature: []string{ - "Fitur", - }, - given: []string{ - "* ", - "Dengan ", - }, - scenario: []string{ - "Skenario", - }, - scenarioOutline: []string{ - "Skenario konsep", - }, - then: []string{ - "* ", - "Maka ", - }, - when: []string{ - "* ", - "Ketika ", - }, - }, - }, - "is": &GherkinDialect{ - "is", "Icelandic", "Íslenska", map[string][]string{ - and: []string{ - "* ", - "Og ", - }, - background: []string{ - "Bakgrunnur", - }, - but: []string{ - "* ", - "En ", - }, - examples: []string{ - "Dæmi", - "Atburðarásir", - }, - feature: []string{ - "Eiginleiki", - }, - given: []string{ - "* ", - "Ef ", - }, - scenario: []string{ - "Atburðarás", - }, - scenarioOutline: []string{ - "Lýsing Atburðarásar", - "Lýsing Dæma", - }, - then: []string{ - "* ", - "Þá ", - }, - when: []string{ - "* ", - "Þegar ", - }, - }, - }, - "it": &GherkinDialect{ - "it", "Italian", "italiano", map[string][]string{ - and: []string{ - "* ", - "E ", - }, - background: []string{ - "Contesto", - }, - but: []string{ - "* ", - "Ma ", - }, - examples: []string{ - "Esempi", - }, - feature: []string{ - "Funzionalità", - }, - given: []string{ - "* ", - "Dato ", - "Data ", - "Dati ", - "Date ", - }, - scenario: []string{ - "Scenario", - }, - scenarioOutline: []string{ - "Schema dello scenario", - }, - then: []string{ - "* ", - "Allora ", - }, - when: []string{ - "* ", - "Quando ", - }, - }, - }, - "ja": &GherkinDialect{ - "ja", "Japanese", "日本語", map[string][]string{ - and: []string{ - "* ", - "かつ", - }, - background: []string{ - "背景", - }, - but: []string{ - "* ", - "しかし", - "但し", - "ただし", - }, - examples: []string{ - "例", - "サンプル", - }, - feature: []string{ - "フィーチャ", - "機能", - }, - given: []string{ - "* ", - "前提", - }, - scenario: []string{ - "シナリオ", - }, - scenarioOutline: []string{ - "シナリオアウトライン", - "シナリオテンプレート", - "テンプレ", - "シナリオテンプレ", - }, - then: []string{ - "* ", - "ならば", - }, - when: []string{ - "* ", - "もし", - }, - }, - }, - "jv": &GherkinDialect{ - "jv", "Javanese", "Basa Jawa", map[string][]string{ - and: []string{ - "* ", - "Lan ", - }, - background: []string{ - "Dasar", - }, - but: []string{ - "* ", - "Tapi ", - "Nanging ", - "Ananging ", - }, - examples: []string{ - "Conto", - "Contone", - }, - feature: []string{ - "Fitur", - }, - given: []string{ - "* ", - "Nalika ", - "Nalikaning ", - }, - scenario: []string{ - "Skenario", - }, - scenarioOutline: []string{ - "Konsep skenario", - }, - then: []string{ - "* ", - "Njuk ", - "Banjur ", - }, - when: []string{ - "* ", - "Manawa ", - "Menawa ", - }, - }, - }, - "kn": &GherkinDialect{ - "kn", "Kannada", "ಕನ್ನಡ", map[string][]string{ - and: []string{ - "* ", - "ಮತ್ತು ", - }, - background: []string{ - "ಹಿನ್ನೆಲೆ", - }, - but: []string{ - "* ", - "ಆದರೆ ", - }, - examples: []string{ - "ಉದಾಹರಣೆಗಳು", - }, - feature: []string{ - "ಹೆಚ್ಚಳ", - }, - given: []string{ - "* ", - "ನೀಡಿದ ", - }, - scenario: []string{ - "ಕಥಾಸಾರಾಂಶ", - }, - scenarioOutline: []string{ - "ವಿವರಣೆ", - }, - then: []string{ - "* ", - "ನಂತರ ", - }, - when: []string{ - "* ", - "ಸ್ಥಿತಿಯನ್ನು ", - }, - }, - }, - "ko": &GherkinDialect{ - "ko", "Korean", "한국어", map[string][]string{ - and: []string{ - "* ", - "그리고", - }, - background: []string{ - "배경", - }, - but: []string{ - "* ", - "하지만", - "단", - }, - examples: []string{ - "예", - }, - feature: []string{ - "기능", - }, - given: []string{ - "* ", - "조건", - "먼저", - }, - scenario: []string{ - "시나리오", - }, - scenarioOutline: []string{ - "시나리오 개요", - }, - then: []string{ - "* ", - "그러면", - }, - when: []string{ - "* ", - "만일", - "만약", - }, - }, - }, - "lt": &GherkinDialect{ - "lt", "Lithuanian", "lietuvių kalba", map[string][]string{ - and: []string{ - "* ", - "Ir ", - }, - background: []string{ - "Kontekstas", - }, - but: []string{ - "* ", - "Bet ", - }, - examples: []string{ - "Pavyzdžiai", - "Scenarijai", - "Variantai", - }, - feature: []string{ - "Savybė", - }, - given: []string{ - "* ", - "Duota ", - }, - scenario: []string{ - "Scenarijus", - }, - scenarioOutline: []string{ - "Scenarijaus šablonas", - }, - then: []string{ - "* ", - "Tada ", - }, - when: []string{ - "* ", - "Kai ", - }, - }, - }, - "lu": &GherkinDialect{ - "lu", "Luxemburgish", "Lëtzebuergesch", map[string][]string{ - and: []string{ - "* ", - "an ", - "a ", - }, - background: []string{ - "Hannergrond", - }, - but: []string{ - "* ", - "awer ", - "mä ", - }, - examples: []string{ - "Beispiller", - }, - feature: []string{ - "Funktionalitéit", - }, - given: []string{ - "* ", - "ugeholl ", - }, - scenario: []string{ - "Szenario", - }, - scenarioOutline: []string{ - "Plang vum Szenario", - }, - then: []string{ - "* ", - "dann ", - }, - when: []string{ - "* ", - "wann ", - }, - }, - }, - "lv": &GherkinDialect{ - "lv", "Latvian", "latviešu", map[string][]string{ - and: []string{ - "* ", - "Un ", - }, - background: []string{ - "Konteksts", - "Situācija", - }, - but: []string{ - "* ", - "Bet ", - }, - examples: []string{ - "Piemēri", - "Paraugs", - }, - feature: []string{ - "Funkcionalitāte", - "Fīča", - }, - given: []string{ - "* ", - "Kad ", - }, - scenario: []string{ - "Scenārijs", - }, - scenarioOutline: []string{ - "Scenārijs pēc parauga", - }, - then: []string{ - "* ", - "Tad ", - }, - when: []string{ - "* ", - "Ja ", - }, - }, - }, - "mn": &GherkinDialect{ - "mn", "Mongolian", "монгол", map[string][]string{ - and: []string{ - "* ", - "Мөн ", - "Тэгээд ", - }, - background: []string{ - "Агуулга", - }, - but: []string{ - "* ", - "Гэхдээ ", - "Харин ", - }, - examples: []string{ - "Тухайлбал", - }, - feature: []string{ - "Функц", - "Функционал", - }, - given: []string{ - "* ", - "Өгөгдсөн нь ", - "Анх ", - }, - scenario: []string{ - "Сценар", - }, - scenarioOutline: []string{ - "Сценарын төлөвлөгөө", - }, - then: []string{ - "* ", - "Тэгэхэд ", - "Үүний дараа ", - }, - when: []string{ - "* ", - "Хэрэв ", - }, - }, - }, - "nl": &GherkinDialect{ - "nl", "Dutch", "Nederlands", map[string][]string{ - and: []string{ - "* ", - "En ", - }, - background: []string{ - "Achtergrond", - }, - but: []string{ - "* ", - "Maar ", - }, - examples: []string{ - "Voorbeelden", - }, - feature: []string{ - "Functionaliteit", - }, - given: []string{ - "* ", - "Gegeven ", - "Stel ", - }, - scenario: []string{ - "Scenario", - }, - scenarioOutline: []string{ - "Abstract Scenario", - }, - then: []string{ - "* ", - "Dan ", - }, - when: []string{ - "* ", - "Als ", - }, - }, - }, - "no": &GherkinDialect{ - "no", "Norwegian", "norsk", map[string][]string{ - and: []string{ - "* ", - "Og ", - }, - background: []string{ - "Bakgrunn", - }, - but: []string{ - "* ", - "Men ", - }, - examples: []string{ - "Eksempler", - }, - feature: []string{ - "Egenskap", - }, - given: []string{ - "* ", - "Gitt ", - }, - scenario: []string{ - "Scenario", - }, - scenarioOutline: []string{ - "Scenariomal", - "Abstrakt Scenario", - }, - then: []string{ - "* ", - "Så ", - }, - when: []string{ - "* ", - "Når ", - }, - }, - }, - "pa": &GherkinDialect{ - "pa", "Panjabi", "ਪੰਜਾਬੀ", map[string][]string{ - and: []string{ - "* ", - "ਅਤੇ ", - }, - background: []string{ - "ਪਿਛੋਕੜ", - }, - but: []string{ - "* ", - "ਪਰ ", - }, - examples: []string{ - "ਉਦਾਹਰਨਾਂ", - }, - feature: []string{ - "ਖਾਸੀਅਤ", - "ਮੁਹਾਂਦਰਾ", - "ਨਕਸ਼ ਨੁਹਾਰ", - }, - given: []string{ - "* ", - "ਜੇਕਰ ", - "ਜਿਵੇਂ ਕਿ ", - }, - scenario: []string{ - "ਪਟਕਥਾ", - }, - scenarioOutline: []string{ - "ਪਟਕਥਾ ਢਾਂਚਾ", - "ਪਟਕਥਾ ਰੂਪ ਰੇਖਾ", - }, - then: []string{ - "* ", - "ਤਦ ", - }, - when: []string{ - "* ", - "ਜਦੋਂ ", - }, - }, - }, - "pl": &GherkinDialect{ - "pl", "Polish", "polski", map[string][]string{ - and: []string{ - "* ", - "Oraz ", - "I ", - }, - background: []string{ - "Założenia", - }, - but: []string{ - "* ", - "Ale ", - }, - examples: []string{ - "Przykłady", - }, - feature: []string{ - "Właściwość", - "Funkcja", - "Aspekt", - "Potrzeba biznesowa", - }, - given: []string{ - "* ", - "Zakładając ", - "Mając ", - "Zakładając, że ", - }, - scenario: []string{ - "Scenariusz", - }, - scenarioOutline: []string{ - "Szablon scenariusza", - }, - then: []string{ - "* ", - "Wtedy ", - }, - when: []string{ - "* ", - "Jeżeli ", - "Jeśli ", - "Gdy ", - "Kiedy ", - }, - }, - }, - "pt": &GherkinDialect{ - "pt", "Portuguese", "português", map[string][]string{ - and: []string{ - "* ", - "E ", - }, - background: []string{ - "Contexto", - "Cenário de Fundo", - "Cenario de Fundo", - "Fundo", - }, - but: []string{ - "* ", - "Mas ", - }, - examples: []string{ - "Exemplos", - "Cenários", - "Cenarios", - }, - feature: []string{ - "Funcionalidade", - "Característica", - "Caracteristica", - }, - given: []string{ - "* ", - "Dado ", - "Dada ", - "Dados ", - "Dadas ", - }, - scenario: []string{ - "Cenário", - "Cenario", - }, - scenarioOutline: []string{ - "Esquema do Cenário", - "Esquema do Cenario", - "Delineação do Cenário", - "Delineacao do Cenario", - }, - then: []string{ - "* ", - "Então ", - "Entao ", - }, - when: []string{ - "* ", - "Quando ", - }, - }, - }, - "ro": &GherkinDialect{ - "ro", "Romanian", "română", map[string][]string{ - and: []string{ - "* ", - "Si ", - "Și ", - "Şi ", - }, - background: []string{ - "Context", - }, - but: []string{ - "* ", - "Dar ", - }, - examples: []string{ - "Exemple", - }, - feature: []string{ - "Functionalitate", - "Funcționalitate", - "Funcţionalitate", - }, - given: []string{ - "* ", - "Date fiind ", - "Dat fiind ", - "Dati fiind ", - "Dați fiind ", - "Daţi fiind ", - }, - scenario: []string{ - "Scenariu", - }, - scenarioOutline: []string{ - "Structura scenariu", - "Structură scenariu", - }, - then: []string{ - "* ", - "Atunci ", - }, - when: []string{ - "* ", - "Cand ", - "Când ", - }, - }, - }, - "ru": &GherkinDialect{ - "ru", "Russian", "русский", map[string][]string{ - and: []string{ - "* ", - "И ", - "К тому же ", - "Также ", - }, - background: []string{ - "Предыстория", - "Контекст", - }, - but: []string{ - "* ", - "Но ", - "А ", - }, - examples: []string{ - "Примеры", - }, - feature: []string{ - "Функция", - "Функционал", - "Свойство", - }, - given: []string{ - "* ", - "Допустим ", - "Дано ", - "Пусть ", - }, - scenario: []string{ - "Сценарий", - }, - scenarioOutline: []string{ - "Структура сценария", - }, - then: []string{ - "* ", - "То ", - "Тогда ", - }, - when: []string{ - "* ", - "Если ", - "Когда ", - }, - }, - }, - "sk": &GherkinDialect{ - "sk", "Slovak", "Slovensky", map[string][]string{ - and: []string{ - "* ", - "A ", - "A tiež ", - "A taktiež ", - "A zároveň ", - }, - background: []string{ - "Pozadie", - }, - but: []string{ - "* ", - "Ale ", - }, - examples: []string{ - "Príklady", - }, - feature: []string{ - "Požiadavka", - "Funkcia", - "Vlastnosť", - }, - given: []string{ - "* ", - "Pokiaľ ", - "Za predpokladu ", - }, - scenario: []string{ - "Scenár", - }, - scenarioOutline: []string{ - "Náčrt Scenáru", - "Náčrt Scenára", - "Osnova Scenára", - }, - then: []string{ - "* ", - "Tak ", - "Potom ", - }, - when: []string{ - "* ", - "Keď ", - "Ak ", - }, - }, - }, - "sl": &GherkinDialect{ - "sl", "Slovenian", "Slovenski", map[string][]string{ - and: []string{ - "In ", - "Ter ", - }, - background: []string{ - "Kontekst", - "Osnova", - "Ozadje", - }, - but: []string{ - "Toda ", - "Ampak ", - "Vendar ", - }, - examples: []string{ - "Primeri", - "Scenariji", - }, - feature: []string{ - "Funkcionalnost", - "Funkcija", - "Možnosti", - "Moznosti", - "Lastnost", - "Značilnost", - }, - given: []string{ - "Dano ", - "Podano ", - "Zaradi ", - "Privzeto ", - }, - scenario: []string{ - "Scenarij", - "Primer", - }, - scenarioOutline: []string{ - "Struktura scenarija", - "Skica", - "Koncept", - "Oris scenarija", - "Osnutek", - }, - then: []string{ - "Nato ", - "Potem ", - "Takrat ", - }, - when: []string{ - "Ko ", - "Ce ", - "Če ", - "Kadar ", - }, - }, - }, - "sr-Cyrl": &GherkinDialect{ - "sr-Cyrl", "Serbian", "Српски", map[string][]string{ - and: []string{ - "* ", - "И ", - }, - background: []string{ - "Контекст", - "Основа", - "Позадина", - }, - but: []string{ - "* ", - "Али ", - }, - examples: []string{ - "Примери", - "Сценарији", - }, - feature: []string{ - "Функционалност", - "Могућност", - "Особина", - }, - given: []string{ - "* ", - "За дато ", - "За дате ", - "За дати ", - }, - scenario: []string{ - "Сценарио", - "Пример", - }, - scenarioOutline: []string{ - "Структура сценарија", - "Скица", - "Концепт", - }, - then: []string{ - "* ", - "Онда ", - }, - when: []string{ - "* ", - "Када ", - "Кад ", - }, - }, - }, - "sr-Latn": &GherkinDialect{ - "sr-Latn", "Serbian (Latin)", "Srpski (Latinica)", map[string][]string{ - and: []string{ - "* ", - "I ", - }, - background: []string{ - "Kontekst", - "Osnova", - "Pozadina", - }, - but: []string{ - "* ", - "Ali ", - }, - examples: []string{ - "Primeri", - "Scenariji", - }, - feature: []string{ - "Funkcionalnost", - "Mogućnost", - "Mogucnost", - "Osobina", - }, - given: []string{ - "* ", - "Za dato ", - "Za date ", - "Za dati ", - }, - scenario: []string{ - "Scenario", - "Primer", - }, - scenarioOutline: []string{ - "Struktura scenarija", - "Skica", - "Koncept", - }, - then: []string{ - "* ", - "Onda ", - }, - when: []string{ - "* ", - "Kada ", - "Kad ", - }, - }, - }, - "sv": &GherkinDialect{ - "sv", "Swedish", "Svenska", map[string][]string{ - and: []string{ - "* ", - "Och ", - }, - background: []string{ - "Bakgrund", - }, - but: []string{ - "* ", - "Men ", - }, - examples: []string{ - "Exempel", - }, - feature: []string{ - "Egenskap", - }, - given: []string{ - "* ", - "Givet ", - }, - scenario: []string{ - "Scenario", - }, - scenarioOutline: []string{ - "Abstrakt Scenario", - "Scenariomall", - }, - then: []string{ - "* ", - "Så ", - }, - when: []string{ - "* ", - "När ", - }, - }, - }, - "ta": &GherkinDialect{ - "ta", "Tamil", "தமிழ்", map[string][]string{ - and: []string{ - "* ", - "மேலும் ", - "மற்றும் ", - }, - background: []string{ - "பின்னணி", - }, - but: []string{ - "* ", - "ஆனால் ", - }, - examples: []string{ - "எடுத்துக்காட்டுகள்", - "காட்சிகள்", - " நிலைமைகளில்", - }, - feature: []string{ - "அம்சம்", - "வணிக தேவை", - "திறன்", - }, - given: []string{ - "* ", - "கொடுக்கப்பட்ட ", - }, - scenario: []string{ - "காட்சி", - }, - scenarioOutline: []string{ - "காட்சி சுருக்கம்", - "காட்சி வார்ப்புரு", - }, - then: []string{ - "* ", - "அப்பொழுது ", - }, - when: []string{ - "* ", - "எப்போது ", - }, - }, - }, - "th": &GherkinDialect{ - "th", "Thai", "ไทย", map[string][]string{ - and: []string{ - "* ", - "และ ", - }, - background: []string{ - "แนวคิด", - }, - but: []string{ - "* ", - "แต่ ", - }, - examples: []string{ - "ชุดของตัวอย่าง", - "ชุดของเหตุการณ์", - }, - feature: []string{ - "โครงหลัก", - "ความต้องการทางธุรกิจ", - "ความสามารถ", - }, - given: []string{ - "* ", - "กำหนดให้ ", - }, - scenario: []string{ - "เหตุการณ์", - }, - scenarioOutline: []string{ - "สรุปเหตุการณ์", - "โครงสร้างของเหตุการณ์", - }, - then: []string{ - "* ", - "ดังนั้น ", - }, - when: []string{ - "* ", - "เมื่อ ", - }, - }, - }, - "tl": &GherkinDialect{ - "tl", "Telugu", "తెలుగు", map[string][]string{ - and: []string{ - "* ", - "మరియు ", - }, - background: []string{ - "నేపథ్యం", - }, - but: []string{ - "* ", - "కాని ", - }, - examples: []string{ - "ఉదాహరణలు", - }, - feature: []string{ - "గుణము", - }, - given: []string{ - "* ", - "చెప్పబడినది ", - }, - scenario: []string{ - "సన్నివేశం", - }, - scenarioOutline: []string{ - "కథనం", - }, - then: []string{ - "* ", - "అప్పుడు ", - }, - when: []string{ - "* ", - "ఈ పరిస్థితిలో ", - }, - }, - }, - "tlh": &GherkinDialect{ - "tlh", "Klingon", "tlhIngan", map[string][]string{ - and: []string{ - "* ", - "'ej ", - "latlh ", - }, - background: []string{ - "mo'", - }, - but: []string{ - "* ", - "'ach ", - "'a ", - }, - examples: []string{ - "ghantoH", - "lutmey", - }, - feature: []string{ - "Qap", - "Qu'meH 'ut", - "perbogh", - "poQbogh malja'", - "laH", - }, - given: []string{ - "* ", - "ghu' noblu' ", - "DaH ghu' bejlu' ", - }, - scenario: []string{ - "lut", - }, - scenarioOutline: []string{ - "lut chovnatlh", - }, - then: []string{ - "* ", - "vaj ", - }, - when: []string{ - "* ", - "qaSDI' ", - }, - }, - }, - "tr": &GherkinDialect{ - "tr", "Turkish", "Türkçe", map[string][]string{ - and: []string{ - "* ", - "Ve ", - }, - background: []string{ - "Geçmiş", - }, - but: []string{ - "* ", - "Fakat ", - "Ama ", - }, - examples: []string{ - "Örnekler", - }, - feature: []string{ - "Özellik", - }, - given: []string{ - "* ", - "Diyelim ki ", - }, - scenario: []string{ - "Senaryo", - }, - scenarioOutline: []string{ - "Senaryo taslağı", - }, - then: []string{ - "* ", - "O zaman ", - }, - when: []string{ - "* ", - "Eğer ki ", - }, - }, - }, - "tt": &GherkinDialect{ - "tt", "Tatar", "Татарча", map[string][]string{ - and: []string{ - "* ", - "Һәм ", - "Вә ", - }, - background: []string{ - "Кереш", - }, - but: []string{ - "* ", - "Ләкин ", - "Әмма ", - }, - examples: []string{ - "Үрнәкләр", - "Мисаллар", - }, - feature: []string{ - "Мөмкинлек", - "Үзенчәлеклелек", - }, - given: []string{ - "* ", - "Әйтик ", - }, - scenario: []string{ - "Сценарий", - }, - scenarioOutline: []string{ - "Сценарийның төзелеше", - }, - then: []string{ - "* ", - "Нәтиҗәдә ", - }, - when: []string{ - "* ", - "Әгәр ", - }, - }, - }, - "uk": &GherkinDialect{ - "uk", "Ukrainian", "Українська", map[string][]string{ - and: []string{ - "* ", - "І ", - "А також ", - "Та ", - }, - background: []string{ - "Передумова", - }, - but: []string{ - "* ", - "Але ", - }, - examples: []string{ - "Приклади", - }, - feature: []string{ - "Функціонал", - }, - given: []string{ - "* ", - "Припустимо ", - "Припустимо, що ", - "Нехай ", - "Дано ", - }, - scenario: []string{ - "Сценарій", - }, - scenarioOutline: []string{ - "Структура сценарію", - }, - then: []string{ - "* ", - "То ", - "Тоді ", - }, - when: []string{ - "* ", - "Якщо ", - "Коли ", - }, - }, - }, - "ur": &GherkinDialect{ - "ur", "Urdu", "اردو", map[string][]string{ - and: []string{ - "* ", - "اور ", - }, - background: []string{ - "پس منظر", - }, - but: []string{ - "* ", - "لیکن ", - }, - examples: []string{ - "مثالیں", - }, - feature: []string{ - "صلاحیت", - "کاروبار کی ضرورت", - "خصوصیت", - }, - given: []string{ - "* ", - "اگر ", - "بالفرض ", - "فرض کیا ", - }, - scenario: []string{ - "منظرنامہ", - }, - scenarioOutline: []string{ - "منظر نامے کا خاکہ", - }, - then: []string{ - "* ", - "پھر ", - "تب ", - }, - when: []string{ - "* ", - "جب ", - }, - }, - }, - "uz": &GherkinDialect{ - "uz", "Uzbek", "Узбекча", map[string][]string{ - and: []string{ - "* ", - "Ва ", - }, - background: []string{ - "Тарих", - }, - but: []string{ - "* ", - "Лекин ", - "Бирок ", - "Аммо ", - }, - examples: []string{ - "Мисоллар", - }, - feature: []string{ - "Функционал", - }, - given: []string{ - "* ", - "Агар ", - }, - scenario: []string{ - "Сценарий", - }, - scenarioOutline: []string{ - "Сценарий структураси", - }, - then: []string{ - "* ", - "Унда ", - }, - when: []string{ - "* ", - "Агар ", - }, - }, - }, - "vi": &GherkinDialect{ - "vi", "Vietnamese", "Tiếng Việt", map[string][]string{ - and: []string{ - "* ", - "Và ", - }, - background: []string{ - "Bối cảnh", - }, - but: []string{ - "* ", - "Nhưng ", - }, - examples: []string{ - "Dữ liệu", - }, - feature: []string{ - "Tính năng", - }, - given: []string{ - "* ", - "Biết ", - "Cho ", - }, - scenario: []string{ - "Tình huống", - "Kịch bản", - }, - scenarioOutline: []string{ - "Khung tình huống", - "Khung kịch bản", - }, - then: []string{ - "* ", - "Thì ", - }, - when: []string{ - "* ", - "Khi ", - }, - }, - }, - "zh-CN": &GherkinDialect{ - "zh-CN", "Chinese simplified", "简体中文", map[string][]string{ - and: []string{ - "* ", - "而且", - "并且", - "同时", - }, - background: []string{ - "背景", - }, - but: []string{ - "* ", - "但是", - }, - examples: []string{ - "例子", - }, - feature: []string{ - "功能", - }, - given: []string{ - "* ", - "假如", - "假设", - "假定", - }, - scenario: []string{ - "场景", - "剧本", - }, - scenarioOutline: []string{ - "场景大纲", - "剧本大纲", - }, - then: []string{ - "* ", - "那么", - }, - when: []string{ - "* ", - "当", - }, - }, - }, - "zh-TW": &GherkinDialect{ - "zh-TW", "Chinese traditional", "繁體中文", map[string][]string{ - and: []string{ - "* ", - "而且", - "並且", - "同時", - }, - background: []string{ - "背景", - }, - but: []string{ - "* ", - "但是", - }, - examples: []string{ - "例子", - }, - feature: []string{ - "功能", - }, - given: []string{ - "* ", - "假如", - "假設", - "假定", - }, - scenario: []string{ - "場景", - "劇本", - }, - scenarioOutline: []string{ - "場景大綱", - "劇本大綱", - }, - then: []string{ - "* ", - "那麼", - }, - when: []string{ - "* ", - "當", - }, - }, - }, -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin/gherkin.go b/vendor/github.com/DATA-DOG/godog/gherkin/gherkin.go deleted file mode 100644 index 0dc469cc4..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/gherkin.go +++ /dev/null @@ -1,137 +0,0 @@ -package gherkin - -import ( - "bufio" - "fmt" - "io" - "strings" -) - -type Parser interface { - StopAtFirstError(b bool) - Parse(s Scanner, m Matcher) (err error) -} - -/* -The scanner reads a gherkin doc (typically read from a .feature file) and creates a token for -each line. The tokens are passed to the parser, which outputs an AST (Abstract Syntax Tree). - -If the scanner sees a # language header, it will reconfigure itself dynamically to look for -Gherkin keywords for the associated language. The keywords are defined in gherkin-languages.json. -*/ -type Scanner interface { - Scan() (line *Line, atEof bool, err error) -} - -type Builder interface { - Build(*Token) (bool, error) - StartRule(RuleType) (bool, error) - EndRule(RuleType) (bool, error) - Reset() -} - -type Token struct { - Type TokenType - Keyword string - Text string - Items []*LineSpan - GherkinDialect string - Indent string - Location *Location -} - -func (t *Token) IsEOF() bool { - return t.Type == TokenType_EOF -} -func (t *Token) String() string { - return fmt.Sprintf("%s: %s/%s", t.Type.Name(), t.Keyword, t.Text) -} - -type LineSpan struct { - Column int - Text string -} - -func (l *LineSpan) String() string { - return fmt.Sprintf("%d:%s", l.Column, l.Text) -} - -type parser struct { - builder Builder - stopAtFirstError bool -} - -func NewParser(b Builder) Parser { - return &parser{ - builder: b, - } -} - -func (p *parser) StopAtFirstError(b bool) { - p.stopAtFirstError = b -} - -func NewScanner(r io.Reader) Scanner { - return &scanner{ - s: bufio.NewScanner(r), - line: 0, - } -} - -type scanner struct { - s *bufio.Scanner - line int -} - -func (t *scanner) Scan() (line *Line, atEof bool, err error) { - scanning := t.s.Scan() - if !scanning { - err = t.s.Err() - if err == nil { - atEof = true - } - } - if err == nil { - t.line += 1 - str := t.s.Text() - line = &Line{str, t.line, strings.TrimLeft(str, " \t"), atEof} - } - return -} - -type Line struct { - LineText string - LineNumber int - TrimmedLineText string - AtEof bool -} - -func (g *Line) Indent() int { - return len(g.LineText) - len(g.TrimmedLineText) -} - -func (g *Line) IsEmpty() bool { - return len(g.TrimmedLineText) == 0 -} - -func (g *Line) IsEof() bool { - return g.AtEof -} - -func (g *Line) StartsWith(prefix string) bool { - return strings.HasPrefix(g.TrimmedLineText, prefix) -} - -func ParseFeature(in io.Reader) (feature *Feature, err error) { - - builder := NewAstBuilder() - parser := NewParser(builder) - parser.StopAtFirstError(false) - matcher := NewMatcher(GherkinDialectsBuildin()) - - scanner := NewScanner(in) - - err = parser.Parse(scanner, matcher) - - return builder.GetFeature(), err -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin/matcher.go b/vendor/github.com/DATA-DOG/godog/gherkin/matcher.go deleted file mode 100644 index d8c7efc8b..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/matcher.go +++ /dev/null @@ -1,270 +0,0 @@ -package gherkin - -import ( - "regexp" - "strings" - "unicode/utf8" -) - -const ( - DEFAULT_DIALECT = "en" - COMMENT_PREFIX = "#" - TAG_PREFIX = "@" - TITLE_KEYWORD_SEPARATOR = ":" - TABLE_CELL_SEPARATOR = '|' - ESCAPE_CHAR = '\\' - ESCAPED_NEWLINE = 'n' - DOCSTRING_SEPARATOR = "\"\"\"" - DOCSTRING_ALTERNATIVE_SEPARATOR = "```" -) - -type matcher struct { - gdp GherkinDialectProvider - default_lang string - lang string - dialect *GherkinDialect - activeDocStringSeparator string - indentToRemove int - languagePattern *regexp.Regexp -} - -func NewMatcher(gdp GherkinDialectProvider) Matcher { - return &matcher{ - gdp: gdp, - default_lang: DEFAULT_DIALECT, - lang: DEFAULT_DIALECT, - dialect: gdp.GetDialect(DEFAULT_DIALECT), - languagePattern: regexp.MustCompile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$"), - } -} - -func NewLanguageMatcher(gdp GherkinDialectProvider, language string) Matcher { - return &matcher{ - gdp: gdp, - default_lang: language, - lang: language, - dialect: gdp.GetDialect(language), - languagePattern: regexp.MustCompile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$"), - } -} - -func (m *matcher) Reset() { - m.indentToRemove = 0 - m.activeDocStringSeparator = "" - if m.lang != "en" { - m.dialect = m.gdp.GetDialect(m.default_lang) - m.lang = "en" - } -} - -func (m *matcher) newTokenAtLocation(line, index int) (token *Token) { - column := index + 1 - token = new(Token) - token.GherkinDialect = m.lang - token.Location = &Location{line, column} - return -} - -func (m *matcher) MatchEOF(line *Line) (ok bool, token *Token, err error) { - if line.IsEof() { - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = TokenType_EOF - } - return -} - -func (m *matcher) MatchEmpty(line *Line) (ok bool, token *Token, err error) { - if line.IsEmpty() { - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = TokenType_Empty - } - return -} - -func (m *matcher) MatchComment(line *Line) (ok bool, token *Token, err error) { - if line.StartsWith(COMMENT_PREFIX) { - token, ok = m.newTokenAtLocation(line.LineNumber, 0), true - token.Type = TokenType_Comment - token.Text = line.LineText - } - return -} - -func (m *matcher) MatchTagLine(line *Line) (ok bool, token *Token, err error) { - if line.StartsWith(TAG_PREFIX) { - var tags []*LineSpan - var column = line.Indent() - splits := strings.Split(line.TrimmedLineText, TAG_PREFIX) - for i := range splits { - txt := strings.Trim(splits[i], " ") - if txt != "" { - tags = append(tags, &LineSpan{column, TAG_PREFIX + txt}) - } - column = column + len(splits[i]) + 1 - } - - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = TokenType_TagLine - token.Items = tags - } - return -} - -func (m *matcher) matchTitleLine(line *Line, tokenType TokenType, keywords []string) (ok bool, token *Token, err error) { - for i := range keywords { - keyword := keywords[i] - if line.StartsWith(keyword + TITLE_KEYWORD_SEPARATOR) { - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = tokenType - token.Keyword = keyword - token.Text = strings.Trim(line.TrimmedLineText[len(keyword)+1:], " ") - return - } - } - return -} - -func (m *matcher) MatchFeatureLine(line *Line) (ok bool, token *Token, err error) { - return m.matchTitleLine(line, TokenType_FeatureLine, m.dialect.FeatureKeywords()) -} -func (m *matcher) MatchBackgroundLine(line *Line) (ok bool, token *Token, err error) { - return m.matchTitleLine(line, TokenType_BackgroundLine, m.dialect.BackgroundKeywords()) -} -func (m *matcher) MatchScenarioLine(line *Line) (ok bool, token *Token, err error) { - return m.matchTitleLine(line, TokenType_ScenarioLine, m.dialect.ScenarioKeywords()) -} -func (m *matcher) MatchScenarioOutlineLine(line *Line) (ok bool, token *Token, err error) { - return m.matchTitleLine(line, TokenType_ScenarioOutlineLine, m.dialect.ScenarioOutlineKeywords()) -} -func (m *matcher) MatchExamplesLine(line *Line) (ok bool, token *Token, err error) { - return m.matchTitleLine(line, TokenType_ExamplesLine, m.dialect.ExamplesKeywords()) -} -func (m *matcher) MatchStepLine(line *Line) (ok bool, token *Token, err error) { - keywords := m.dialect.StepKeywords() - for i := range keywords { - keyword := keywords[i] - if line.StartsWith(keyword) { - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = TokenType_StepLine - token.Keyword = keyword - token.Text = strings.Trim(line.TrimmedLineText[len(keyword):], " ") - return - } - } - return -} - -func (m *matcher) MatchDocStringSeparator(line *Line) (ok bool, token *Token, err error) { - if m.activeDocStringSeparator != "" { - if line.StartsWith(m.activeDocStringSeparator) { - // close - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = TokenType_DocStringSeparator - - m.indentToRemove = 0 - m.activeDocStringSeparator = "" - } - return - } - if line.StartsWith(DOCSTRING_SEPARATOR) { - m.activeDocStringSeparator = DOCSTRING_SEPARATOR - } else if line.StartsWith(DOCSTRING_ALTERNATIVE_SEPARATOR) { - m.activeDocStringSeparator = DOCSTRING_ALTERNATIVE_SEPARATOR - } - if m.activeDocStringSeparator != "" { - // open - contentType := line.TrimmedLineText[len(m.activeDocStringSeparator):] - m.indentToRemove = line.Indent() - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = TokenType_DocStringSeparator - token.Text = contentType - } - return -} - -func (m *matcher) MatchTableRow(line *Line) (ok bool, token *Token, err error) { - var firstChar, firstPos = utf8.DecodeRuneInString(line.TrimmedLineText) - if firstChar == TABLE_CELL_SEPARATOR { - var cells []*LineSpan - var cell []rune - var startCol = line.Indent() + 2 // column where the current cell started - // start after the first separator, it's not included in the cell - for i, w, col := firstPos, 0, startCol; i < len(line.TrimmedLineText); i += w { - var char rune - char, w = utf8.DecodeRuneInString(line.TrimmedLineText[i:]) - if char == TABLE_CELL_SEPARATOR { - // append current cell - txt := string(cell) - txtTrimmed := strings.TrimLeft(txt, " ") - ind := len(txt) - len(txtTrimmed) - cells = append(cells, &LineSpan{startCol + ind, strings.TrimRight(txtTrimmed, " ")}) - // start building next - cell = make([]rune, 0) - startCol = col + 1 - } else if char == ESCAPE_CHAR { - // skip this character but count the column - i += w - col++ - char, w = utf8.DecodeRuneInString(line.TrimmedLineText[i:]) - if char == ESCAPED_NEWLINE { - cell = append(cell, '\n') - } else { - if char != TABLE_CELL_SEPARATOR && char != ESCAPE_CHAR { - cell = append(cell, ESCAPE_CHAR) - } - cell = append(cell, char) - } - } else { - cell = append(cell, char) - } - col++ - } - - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = TokenType_TableRow - token.Items = cells - } - return -} - -func (m *matcher) MatchLanguage(line *Line) (ok bool, token *Token, err error) { - matches := m.languagePattern.FindStringSubmatch(line.TrimmedLineText) - if len(matches) > 0 { - lang := matches[1] - token, ok = m.newTokenAtLocation(line.LineNumber, line.Indent()), true - token.Type = TokenType_Language - token.Text = lang - - dialect := m.gdp.GetDialect(lang) - if dialect == nil { - err = &parseError{"Language not supported: " + lang, token.Location} - } else { - m.lang = lang - m.dialect = dialect - } - } - return -} - -func (m *matcher) MatchOther(line *Line) (ok bool, token *Token, err error) { - token, ok = m.newTokenAtLocation(line.LineNumber, 0), true - token.Type = TokenType_Other - - element := line.LineText - txt := strings.TrimLeft(element, " ") - - if len(element)-len(txt) > m.indentToRemove { - token.Text = m.unescapeDocString(element[m.indentToRemove:]) - } else { - token.Text = m.unescapeDocString(txt) - } - return -} - -func (m *matcher) unescapeDocString(text string) string { - if m.activeDocStringSeparator != "" { - return strings.Replace(text, "\\\"\\\"\\\"", "\"\"\"", -1) - } else { - return text - } -} diff --git a/vendor/github.com/DATA-DOG/godog/gherkin/parser.go b/vendor/github.com/DATA-DOG/godog/gherkin/parser.go deleted file mode 100644 index 0e2620053..000000000 --- a/vendor/github.com/DATA-DOG/godog/gherkin/parser.go +++ /dev/null @@ -1,2270 +0,0 @@ -// -// This file is generated. Do not edit! Edit gherkin-golang.razor instead. - -// -package gherkin - -import ( - "fmt" - "strings" -) - -type TokenType int - -const ( - TokenType_None TokenType = iota - TokenType_EOF - TokenType_Empty - TokenType_Comment - TokenType_TagLine - TokenType_FeatureLine - TokenType_BackgroundLine - TokenType_ScenarioLine - TokenType_ScenarioOutlineLine - TokenType_ExamplesLine - TokenType_StepLine - TokenType_DocStringSeparator - TokenType_TableRow - TokenType_Language - TokenType_Other -) - -func tokenTypeForRule(rt RuleType) TokenType { - return TokenType_None -} - -func (t TokenType) Name() string { - switch t { - case TokenType_EOF: - return "EOF" - case TokenType_Empty: - return "Empty" - case TokenType_Comment: - return "Comment" - case TokenType_TagLine: - return "TagLine" - case TokenType_FeatureLine: - return "FeatureLine" - case TokenType_BackgroundLine: - return "BackgroundLine" - case TokenType_ScenarioLine: - return "ScenarioLine" - case TokenType_ScenarioOutlineLine: - return "ScenarioOutlineLine" - case TokenType_ExamplesLine: - return "ExamplesLine" - case TokenType_StepLine: - return "StepLine" - case TokenType_DocStringSeparator: - return "DocStringSeparator" - case TokenType_TableRow: - return "TableRow" - case TokenType_Language: - return "Language" - case TokenType_Other: - return "Other" - } - return "" -} - -func (t TokenType) RuleType() RuleType { - switch t { - case TokenType_EOF: - return RuleType__EOF - case TokenType_Empty: - return RuleType__Empty - case TokenType_Comment: - return RuleType__Comment - case TokenType_TagLine: - return RuleType__TagLine - case TokenType_FeatureLine: - return RuleType__FeatureLine - case TokenType_BackgroundLine: - return RuleType__BackgroundLine - case TokenType_ScenarioLine: - return RuleType__ScenarioLine - case TokenType_ScenarioOutlineLine: - return RuleType__ScenarioOutlineLine - case TokenType_ExamplesLine: - return RuleType__ExamplesLine - case TokenType_StepLine: - return RuleType__StepLine - case TokenType_DocStringSeparator: - return RuleType__DocStringSeparator - case TokenType_TableRow: - return RuleType__TableRow - case TokenType_Language: - return RuleType__Language - case TokenType_Other: - return RuleType__Other - } - return RuleType_None -} - -type RuleType int - -const ( - RuleType_None RuleType = iota - - RuleType__EOF - RuleType__Empty - RuleType__Comment - RuleType__TagLine - RuleType__FeatureLine - RuleType__BackgroundLine - RuleType__ScenarioLine - RuleType__ScenarioOutlineLine - RuleType__ExamplesLine - RuleType__StepLine - RuleType__DocStringSeparator - RuleType__TableRow - RuleType__Language - RuleType__Other - RuleType_Feature - RuleType_Feature_Header - RuleType_Background - RuleType_Scenario_Definition - RuleType_Scenario - RuleType_ScenarioOutline - RuleType_Examples_Definition - RuleType_Examples - RuleType_Scenario_Step - RuleType_ScenarioOutline_Step - RuleType_Step - RuleType_Step_Arg - RuleType_DataTable - RuleType_DocString - RuleType_Tags - RuleType_Feature_Description - RuleType_Background_Description - RuleType_Scenario_Description - RuleType_ScenarioOutline_Description - RuleType_Examples_Description - RuleType_Description_Helper - RuleType_Description -) - -func (t RuleType) IsEOF() bool { - return t == RuleType__EOF -} -func (t RuleType) Name() string { - switch t { - case RuleType__EOF: - return "#EOF" - case RuleType__Empty: - return "#Empty" - case RuleType__Comment: - return "#Comment" - case RuleType__TagLine: - return "#TagLine" - case RuleType__FeatureLine: - return "#FeatureLine" - case RuleType__BackgroundLine: - return "#BackgroundLine" - case RuleType__ScenarioLine: - return "#ScenarioLine" - case RuleType__ScenarioOutlineLine: - return "#ScenarioOutlineLine" - case RuleType__ExamplesLine: - return "#ExamplesLine" - case RuleType__StepLine: - return "#StepLine" - case RuleType__DocStringSeparator: - return "#DocStringSeparator" - case RuleType__TableRow: - return "#TableRow" - case RuleType__Language: - return "#Language" - case RuleType__Other: - return "#Other" - case RuleType_Feature: - return "Feature" - case RuleType_Feature_Header: - return "Feature_Header" - case RuleType_Background: - return "Background" - case RuleType_Scenario_Definition: - return "Scenario_Definition" - case RuleType_Scenario: - return "Scenario" - case RuleType_ScenarioOutline: - return "ScenarioOutline" - case RuleType_Examples_Definition: - return "Examples_Definition" - case RuleType_Examples: - return "Examples" - case RuleType_Scenario_Step: - return "Scenario_Step" - case RuleType_ScenarioOutline_Step: - return "ScenarioOutline_Step" - case RuleType_Step: - return "Step" - case RuleType_Step_Arg: - return "Step_Arg" - case RuleType_DataTable: - return "DataTable" - case RuleType_DocString: - return "DocString" - case RuleType_Tags: - return "Tags" - case RuleType_Feature_Description: - return "Feature_Description" - case RuleType_Background_Description: - return "Background_Description" - case RuleType_Scenario_Description: - return "Scenario_Description" - case RuleType_ScenarioOutline_Description: - return "ScenarioOutline_Description" - case RuleType_Examples_Description: - return "Examples_Description" - case RuleType_Description_Helper: - return "Description_Helper" - case RuleType_Description: - return "Description" - } - return "" -} - -type parseError struct { - msg string - loc *Location -} - -func (a *parseError) Error() string { - return fmt.Sprintf("(%d:%d): %s", a.loc.Line, a.loc.Column, a.msg) -} - -type parseErrors []error - -func (pe parseErrors) Error() string { - var ret = []string{"Parser errors:"} - for i := range pe { - ret = append(ret, pe[i].Error()) - } - return strings.Join(ret, "\n") -} - -func (p *parser) Parse(s Scanner, m Matcher) (err error) { - p.builder.Reset() - m.Reset() - ctxt := &parseContext{p, s, p.builder, m, nil, nil} - var state int - ctxt.startRule(RuleType_Feature) - for { - gl, eof, err := ctxt.scan() - if err != nil { - ctxt.addError(err) - if p.stopAtFirstError { - break - } - } - state, err = ctxt.match(state, gl) - if err != nil { - ctxt.addError(err) - if p.stopAtFirstError { - break - } - } - if eof { - // done! \o/ - break - } - } - ctxt.endRule(RuleType_Feature) - if len(ctxt.errors) > 0 { - return ctxt.errors - } - return -} - -type parseContext struct { - p *parser - s Scanner - b Builder - m Matcher - queue []*scanResult - errors parseErrors -} - -func (ctxt *parseContext) addError(e error) { - ctxt.errors = append(ctxt.errors, e) - // if (p.errors.length > 10) - // throw Errors.CompositeParserException.create(p.errors); -} - -type scanResult struct { - line *Line - atEof bool - err error -} - -func (ctxt *parseContext) scan() (*Line, bool, error) { - l := len(ctxt.queue) - if l > 0 { - x := ctxt.queue[0] - ctxt.queue = ctxt.queue[1:] - return x.line, x.atEof, x.err - } - return ctxt.s.Scan() -} - -func (ctxt *parseContext) startRule(r RuleType) (bool, error) { - ok, err := ctxt.b.StartRule(r) - if err != nil { - ctxt.addError(err) - } - return ok, err -} - -func (ctxt *parseContext) endRule(r RuleType) (bool, error) { - ok, err := ctxt.b.EndRule(r) - if err != nil { - ctxt.addError(err) - } - return ok, err -} - -func (ctxt *parseContext) build(t *Token) (bool, error) { - ok, err := ctxt.b.Build(t) - if err != nil { - ctxt.addError(err) - } - return ok, err -} - -func (ctxt *parseContext) match(state int, line *Line) (newState int, err error) { - switch state { - case 0: - return ctxt.matchAt_0(line) - case 1: - return ctxt.matchAt_1(line) - case 2: - return ctxt.matchAt_2(line) - case 3: - return ctxt.matchAt_3(line) - case 4: - return ctxt.matchAt_4(line) - case 5: - return ctxt.matchAt_5(line) - case 6: - return ctxt.matchAt_6(line) - case 7: - return ctxt.matchAt_7(line) - case 8: - return ctxt.matchAt_8(line) - case 9: - return ctxt.matchAt_9(line) - case 10: - return ctxt.matchAt_10(line) - case 11: - return ctxt.matchAt_11(line) - case 12: - return ctxt.matchAt_12(line) - case 13: - return ctxt.matchAt_13(line) - case 14: - return ctxt.matchAt_14(line) - case 15: - return ctxt.matchAt_15(line) - case 16: - return ctxt.matchAt_16(line) - case 17: - return ctxt.matchAt_17(line) - case 18: - return ctxt.matchAt_18(line) - case 19: - return ctxt.matchAt_19(line) - case 20: - return ctxt.matchAt_20(line) - case 21: - return ctxt.matchAt_21(line) - case 22: - return ctxt.matchAt_22(line) - case 23: - return ctxt.matchAt_23(line) - case 24: - return ctxt.matchAt_24(line) - case 25: - return ctxt.matchAt_25(line) - case 26: - return ctxt.matchAt_26(line) - case 27: - return ctxt.matchAt_27(line) - case 29: - return ctxt.matchAt_29(line) - case 30: - return ctxt.matchAt_30(line) - case 31: - return ctxt.matchAt_31(line) - case 32: - return ctxt.matchAt_32(line) - case 33: - return ctxt.matchAt_33(line) - case 34: - return ctxt.matchAt_34(line) - default: - return state, fmt.Errorf("Unknown state: %+v", state) - } -} - -// Start -func (ctxt *parseContext) matchAt_0(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_Language(line); ok { - ctxt.startRule(RuleType_Feature_Header) - ctxt.build(token) - return 1, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.startRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 2, err - } - if ok, token, err := ctxt.match_FeatureLine(line); ok { - ctxt.startRule(RuleType_Feature_Header) - ctxt.build(token) - return 3, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 0, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 0, err - } - - // var stateComment = "State: 0 - Start" - var expectedTokens = []string{"#Language", "#TagLine", "#FeatureLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 0, err -} - -// Feature:0>Feature_Header:0>#Language:0 -func (ctxt *parseContext) matchAt_1(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 2, err - } - if ok, token, err := ctxt.match_FeatureLine(line); ok { - ctxt.build(token) - return 3, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 1, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 1, err - } - - // var stateComment = "State: 1 - Feature:0>Feature_Header:0>#Language:0" - var expectedTokens = []string{"#TagLine", "#FeatureLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 1, err -} - -// Feature:0>Feature_Header:1>Tags:0>#TagLine:0 -func (ctxt *parseContext) matchAt_2(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.build(token) - return 2, err - } - if ok, token, err := ctxt.match_FeatureLine(line); ok { - ctxt.endRule(RuleType_Tags) - ctxt.build(token) - return 3, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 2, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 2, err - } - - // var stateComment = "State: 2 - Feature:0>Feature_Header:1>Tags:0>#TagLine:0" - var expectedTokens = []string{"#TagLine", "#FeatureLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 2, err -} - -// Feature:0>Feature_Header:2>#FeatureLine:0 -func (ctxt *parseContext) matchAt_3(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 3, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 5, err - } - if ok, token, err := ctxt.match_BackgroundLine(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Background) - ctxt.build(token) - return 6, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.startRule(RuleType_Description) - ctxt.build(token) - return 4, err - } - - // var stateComment = "State: 3 - Feature:0>Feature_Header:2>#FeatureLine:0" - var expectedTokens = []string{"#EOF", "#Empty", "#Comment", "#BackgroundLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 3, err -} - -// Feature:0>Feature_Header:3>Feature_Description:0>Description_Helper:1>Description:0>#Other:0 -func (ctxt *parseContext) matchAt_4(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Feature_Header) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.build(token) - return 5, err - } - if ok, token, err := ctxt.match_BackgroundLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Background) - ctxt.build(token) - return 6, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.build(token) - return 4, err - } - - // var stateComment = "State: 4 - Feature:0>Feature_Header:3>Feature_Description:0>Description_Helper:1>Description:0>#Other:0" - var expectedTokens = []string{"#EOF", "#Comment", "#BackgroundLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 4, err -} - -// Feature:0>Feature_Header:3>Feature_Description:0>Description_Helper:2>#Comment:0 -func (ctxt *parseContext) matchAt_5(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 5, err - } - if ok, token, err := ctxt.match_BackgroundLine(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Background) - ctxt.build(token) - return 6, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Feature_Header) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 5, err - } - - // var stateComment = "State: 5 - Feature:0>Feature_Header:3>Feature_Description:0>Description_Helper:2>#Comment:0" - var expectedTokens = []string{"#EOF", "#Comment", "#BackgroundLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 5, err -} - -// Feature:1>Background:0>#BackgroundLine:0 -func (ctxt *parseContext) matchAt_6(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Background) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 6, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 8, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 9, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.startRule(RuleType_Description) - ctxt.build(token) - return 7, err - } - - // var stateComment = "State: 6 - Feature:1>Background:0>#BackgroundLine:0" - var expectedTokens = []string{"#EOF", "#Empty", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 6, err -} - -// Feature:1>Background:1>Background_Description:0>Description_Helper:1>Description:0>#Other:0 -func (ctxt *parseContext) matchAt_7(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Background) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.build(token) - return 8, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 9, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.build(token) - return 7, err - } - - // var stateComment = "State: 7 - Feature:1>Background:1>Background_Description:0>Description_Helper:1>Description:0>#Other:0" - var expectedTokens = []string{"#EOF", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 7, err -} - -// Feature:1>Background:1>Background_Description:0>Description_Helper:2>#Comment:0 -func (ctxt *parseContext) matchAt_8(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Background) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 8, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 9, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 8, err - } - - // var stateComment = "State: 8 - Feature:1>Background:1>Background_Description:0>Description_Helper:2>#Comment:0" - var expectedTokens = []string{"#EOF", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 8, err -} - -// Feature:1>Background:2>Scenario_Step:0>Step:0>#StepLine:0 -func (ctxt *parseContext) matchAt_9(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.startRule(RuleType_DataTable) - ctxt.build(token) - return 10, err - } - if ok, token, err := ctxt.match_DocStringSeparator(line); ok { - ctxt.startRule(RuleType_DocString) - ctxt.build(token) - return 33, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 9, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 9, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 9, err - } - - // var stateComment = "State: 9 - Feature:1>Background:2>Scenario_Step:0>Step:0>#StepLine:0" - var expectedTokens = []string{"#EOF", "#TableRow", "#DocStringSeparator", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 9, err -} - -// Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0 -func (ctxt *parseContext) matchAt_10(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.build(token) - return 10, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 9, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 10, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 10, err - } - - // var stateComment = "State: 10 - Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0" - var expectedTokens = []string{"#EOF", "#TableRow", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 10, err -} - -// Feature:2>Scenario_Definition:0>Tags:0>#TagLine:0 -func (ctxt *parseContext) matchAt_11(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Tags) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Tags) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 11, err - } - - // var stateComment = "State: 11 - Feature:2>Scenario_Definition:0>Tags:0>#TagLine:0" - var expectedTokens = []string{"#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 11, err -} - -// Feature:2>Scenario_Definition:1>__alt0:0>Scenario:0>#ScenarioLine:0 -func (ctxt *parseContext) matchAt_12(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 14, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 15, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.startRule(RuleType_Description) - ctxt.build(token) - return 13, err - } - - // var stateComment = "State: 12 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:0>#ScenarioLine:0" - var expectedTokens = []string{"#EOF", "#Empty", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 12, err -} - -// Feature:2>Scenario_Definition:1>__alt0:0>Scenario:1>Scenario_Description:0>Description_Helper:1>Description:0>#Other:0 -func (ctxt *parseContext) matchAt_13(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.build(token) - return 14, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 15, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.build(token) - return 13, err - } - - // var stateComment = "State: 13 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:1>Scenario_Description:0>Description_Helper:1>Description:0>#Other:0" - var expectedTokens = []string{"#EOF", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 13, err -} - -// Feature:2>Scenario_Definition:1>__alt0:0>Scenario:1>Scenario_Description:0>Description_Helper:2>#Comment:0 -func (ctxt *parseContext) matchAt_14(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 14, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 15, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 14, err - } - - // var stateComment = "State: 14 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:1>Scenario_Description:0>Description_Helper:2>#Comment:0" - var expectedTokens = []string{"#EOF", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 14, err -} - -// Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:0>#StepLine:0 -func (ctxt *parseContext) matchAt_15(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.startRule(RuleType_DataTable) - ctxt.build(token) - return 16, err - } - if ok, token, err := ctxt.match_DocStringSeparator(line); ok { - ctxt.startRule(RuleType_DocString) - ctxt.build(token) - return 31, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 15, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 15, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 15, err - } - - // var stateComment = "State: 15 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:0>#StepLine:0" - var expectedTokens = []string{"#EOF", "#TableRow", "#DocStringSeparator", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 15, err -} - -// Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0 -func (ctxt *parseContext) matchAt_16(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.build(token) - return 16, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 15, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 16, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 16, err - } - - // var stateComment = "State: 16 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0" - var expectedTokens = []string{"#EOF", "#TableRow", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 16, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:0>#ScenarioOutlineLine:0 -func (ctxt *parseContext) matchAt_17(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 19, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 20, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 22, err - } - if ok, token, err := ctxt.match_ExamplesLine(line); ok { - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples) - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.startRule(RuleType_Description) - ctxt.build(token) - return 18, err - } - - // var stateComment = "State: 17 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:0>#ScenarioOutlineLine:0" - var expectedTokens = []string{"#Empty", "#Comment", "#StepLine", "#TagLine", "#ExamplesLine", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 17, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:1>ScenarioOutline_Description:0>Description_Helper:1>Description:0>#Other:0 -func (ctxt *parseContext) matchAt_18(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.build(token) - return 19, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 20, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 22, err - } - if ok, token, err := ctxt.match_ExamplesLine(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples) - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.build(token) - return 18, err - } - - // var stateComment = "State: 18 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:1>ScenarioOutline_Description:0>Description_Helper:1>Description:0>#Other:0" - var expectedTokens = []string{"#Comment", "#StepLine", "#TagLine", "#ExamplesLine", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 18, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:1>ScenarioOutline_Description:0>Description_Helper:2>#Comment:0 -func (ctxt *parseContext) matchAt_19(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 19, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 20, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 22, err - } - if ok, token, err := ctxt.match_ExamplesLine(line); ok { - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples) - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 19, err - } - - // var stateComment = "State: 19 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:1>ScenarioOutline_Description:0>Description_Helper:2>#Comment:0" - var expectedTokens = []string{"#Comment", "#StepLine", "#TagLine", "#ExamplesLine", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 19, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:0>#StepLine:0 -func (ctxt *parseContext) matchAt_20(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.startRule(RuleType_DataTable) - ctxt.build(token) - return 21, err - } - if ok, token, err := ctxt.match_DocStringSeparator(line); ok { - ctxt.startRule(RuleType_DocString) - ctxt.build(token) - return 29, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 20, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 22, err - } - if ok, token, err := ctxt.match_ExamplesLine(line); ok { - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples) - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 20, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 20, err - } - - // var stateComment = "State: 20 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:0>#StepLine:0" - var expectedTokens = []string{"#TableRow", "#DocStringSeparator", "#StepLine", "#TagLine", "#ExamplesLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 20, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0 -func (ctxt *parseContext) matchAt_21(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.build(token) - return 21, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 20, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 22, err - } - if ok, token, err := ctxt.match_ExamplesLine(line); ok { - ctxt.endRule(RuleType_DataTable) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples) - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 21, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 21, err - } - - // var stateComment = "State: 21 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0" - var expectedTokens = []string{"#TableRow", "#StepLine", "#TagLine", "#ExamplesLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 21, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:0>Tags:0>#TagLine:0 -func (ctxt *parseContext) matchAt_22(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.build(token) - return 22, err - } - if ok, token, err := ctxt.match_ExamplesLine(line); ok { - ctxt.endRule(RuleType_Tags) - ctxt.startRule(RuleType_Examples) - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 22, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 22, err - } - - // var stateComment = "State: 22 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:0>Tags:0>#TagLine:0" - var expectedTokens = []string{"#TagLine", "#ExamplesLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 22, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:0>#ExamplesLine:0 -func (ctxt *parseContext) matchAt_23(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 25, err - } - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.build(token) - return 26, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.startRule(RuleType_Description) - ctxt.build(token) - return 24, err - } - - // var stateComment = "State: 23 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:0>#ExamplesLine:0" - var expectedTokens = []string{"#Empty", "#Comment", "#TableRow", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 23, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:1>Examples_Description:0>Description_Helper:1>Description:0>#Other:0 -func (ctxt *parseContext) matchAt_24(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.build(token) - return 25, err - } - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.endRule(RuleType_Description) - ctxt.build(token) - return 26, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.build(token) - return 24, err - } - - // var stateComment = "State: 24 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:1>Examples_Description:0>Description_Helper:1>Description:0>#Other:0" - var expectedTokens = []string{"#Comment", "#TableRow", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 24, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:1>Examples_Description:0>Description_Helper:2>#Comment:0 -func (ctxt *parseContext) matchAt_25(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 25, err - } - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.build(token) - return 26, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 25, err - } - - // var stateComment = "State: 25 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:1>Examples_Description:0>Description_Helper:2>#Comment:0" - var expectedTokens = []string{"#Comment", "#TableRow", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 25, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:2>#TableRow:0 -func (ctxt *parseContext) matchAt_26(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.build(token) - return 27, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 26, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 26, err - } - - // var stateComment = "State: 26 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:2>#TableRow:0" - var expectedTokens = []string{"#TableRow", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 26, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:3>#TableRow:0 -func (ctxt *parseContext) matchAt_27(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_Examples) - ctxt.endRule(RuleType_Examples_Definition) - ctxt.endRule(RuleType_ScenarioOutline) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_TableRow(line); ok { - ctxt.build(token) - return 27, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - if ctxt.lookahead_0(line) { - ctxt.endRule(RuleType_Examples) - ctxt.endRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 22, err - } - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_Examples) - ctxt.endRule(RuleType_Examples_Definition) - ctxt.endRule(RuleType_ScenarioOutline) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ExamplesLine(line); ok { - ctxt.endRule(RuleType_Examples) - ctxt.endRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples) - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_Examples) - ctxt.endRule(RuleType_Examples_Definition) - ctxt.endRule(RuleType_ScenarioOutline) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_Examples) - ctxt.endRule(RuleType_Examples_Definition) - ctxt.endRule(RuleType_ScenarioOutline) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 27, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 27, err - } - - // var stateComment = "State: 27 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:3>#TableRow:0" - var expectedTokens = []string{"#EOF", "#TableRow", "#TagLine", "#ExamplesLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 27, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0 -func (ctxt *parseContext) matchAt_29(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_DocStringSeparator(line); ok { - ctxt.build(token) - return 30, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.build(token) - return 29, err - } - - // var stateComment = "State: 29 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0" - var expectedTokens = []string{"#DocStringSeparator", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 29, err -} - -// Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0 -func (ctxt *parseContext) matchAt_30(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 20, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 22, err - } - if ok, token, err := ctxt.match_ExamplesLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Examples_Definition) - ctxt.startRule(RuleType_Examples) - ctxt.build(token) - return 23, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 30, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 30, err - } - - // var stateComment = "State: 30 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0" - var expectedTokens = []string{"#StepLine", "#TagLine", "#ExamplesLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 30, err -} - -// Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0 -func (ctxt *parseContext) matchAt_31(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_DocStringSeparator(line); ok { - ctxt.build(token) - return 32, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.build(token) - return 31, err - } - - // var stateComment = "State: 31 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0" - var expectedTokens = []string{"#DocStringSeparator", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 31, err -} - -// Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0 -func (ctxt *parseContext) matchAt_32(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 15, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Scenario) - ctxt.endRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 32, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 32, err - } - - // var stateComment = "State: 32 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0" - var expectedTokens = []string{"#EOF", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 32, err -} - -// Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0 -func (ctxt *parseContext) matchAt_33(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_DocStringSeparator(line); ok { - ctxt.build(token) - return 34, err - } - if ok, token, err := ctxt.match_Other(line); ok { - ctxt.build(token) - return 33, err - } - - // var stateComment = "State: 33 - Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0" - var expectedTokens = []string{"#DocStringSeparator", "#Other"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 33, err -} - -// Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0 -func (ctxt *parseContext) matchAt_34(line *Line) (newState int, err error) { - if ok, token, err := ctxt.match_EOF(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.build(token) - return 28, err - } - if ok, token, err := ctxt.match_StepLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.startRule(RuleType_Step) - ctxt.build(token) - return 9, err - } - if ok, token, err := ctxt.match_TagLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Tags) - ctxt.build(token) - return 11, err - } - if ok, token, err := ctxt.match_ScenarioLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_Scenario) - ctxt.build(token) - return 12, err - } - if ok, token, err := ctxt.match_ScenarioOutlineLine(line); ok { - ctxt.endRule(RuleType_DocString) - ctxt.endRule(RuleType_Step) - ctxt.endRule(RuleType_Background) - ctxt.startRule(RuleType_Scenario_Definition) - ctxt.startRule(RuleType_ScenarioOutline) - ctxt.build(token) - return 17, err - } - if ok, token, err := ctxt.match_Comment(line); ok { - ctxt.build(token) - return 34, err - } - if ok, token, err := ctxt.match_Empty(line); ok { - ctxt.build(token) - return 34, err - } - - // var stateComment = "State: 34 - Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0" - var expectedTokens = []string{"#EOF", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"} - if line.IsEof() { - err = fmt.Errorf("(%d:0): unexpected end of file, expected: %s", line.LineNumber, strings.Join(expectedTokens, ", ")) - } else { - err = fmt.Errorf("(%d:%d): expected: %s, got '%s'", line.LineNumber, line.Indent()+1, strings.Join(expectedTokens, ", "), line.LineText) - } - // if (ctxt.p.stopAtFirstError) throw error; - //ctxt.addError(err) - return 34, err -} - -type Matcher interface { - MatchEOF(line *Line) (bool, *Token, error) - MatchEmpty(line *Line) (bool, *Token, error) - MatchComment(line *Line) (bool, *Token, error) - MatchTagLine(line *Line) (bool, *Token, error) - MatchFeatureLine(line *Line) (bool, *Token, error) - MatchBackgroundLine(line *Line) (bool, *Token, error) - MatchScenarioLine(line *Line) (bool, *Token, error) - MatchScenarioOutlineLine(line *Line) (bool, *Token, error) - MatchExamplesLine(line *Line) (bool, *Token, error) - MatchStepLine(line *Line) (bool, *Token, error) - MatchDocStringSeparator(line *Line) (bool, *Token, error) - MatchTableRow(line *Line) (bool, *Token, error) - MatchLanguage(line *Line) (bool, *Token, error) - MatchOther(line *Line) (bool, *Token, error) - Reset() -} - -func (ctxt *parseContext) isMatch_EOF(line *Line) bool { - ok, _, _ := ctxt.match_EOF(line) - return ok -} -func (ctxt *parseContext) match_EOF(line *Line) (bool, *Token, error) { - return ctxt.m.MatchEOF(line) -} - -func (ctxt *parseContext) isMatch_Empty(line *Line) bool { - ok, _, _ := ctxt.match_Empty(line) - return ok -} -func (ctxt *parseContext) match_Empty(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchEmpty(line) -} - -func (ctxt *parseContext) isMatch_Comment(line *Line) bool { - ok, _, _ := ctxt.match_Comment(line) - return ok -} -func (ctxt *parseContext) match_Comment(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchComment(line) -} - -func (ctxt *parseContext) isMatch_TagLine(line *Line) bool { - ok, _, _ := ctxt.match_TagLine(line) - return ok -} -func (ctxt *parseContext) match_TagLine(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchTagLine(line) -} - -func (ctxt *parseContext) isMatch_FeatureLine(line *Line) bool { - ok, _, _ := ctxt.match_FeatureLine(line) - return ok -} -func (ctxt *parseContext) match_FeatureLine(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchFeatureLine(line) -} - -func (ctxt *parseContext) isMatch_BackgroundLine(line *Line) bool { - ok, _, _ := ctxt.match_BackgroundLine(line) - return ok -} -func (ctxt *parseContext) match_BackgroundLine(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchBackgroundLine(line) -} - -func (ctxt *parseContext) isMatch_ScenarioLine(line *Line) bool { - ok, _, _ := ctxt.match_ScenarioLine(line) - return ok -} -func (ctxt *parseContext) match_ScenarioLine(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchScenarioLine(line) -} - -func (ctxt *parseContext) isMatch_ScenarioOutlineLine(line *Line) bool { - ok, _, _ := ctxt.match_ScenarioOutlineLine(line) - return ok -} -func (ctxt *parseContext) match_ScenarioOutlineLine(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchScenarioOutlineLine(line) -} - -func (ctxt *parseContext) isMatch_ExamplesLine(line *Line) bool { - ok, _, _ := ctxt.match_ExamplesLine(line) - return ok -} -func (ctxt *parseContext) match_ExamplesLine(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchExamplesLine(line) -} - -func (ctxt *parseContext) isMatch_StepLine(line *Line) bool { - ok, _, _ := ctxt.match_StepLine(line) - return ok -} -func (ctxt *parseContext) match_StepLine(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchStepLine(line) -} - -func (ctxt *parseContext) isMatch_DocStringSeparator(line *Line) bool { - ok, _, _ := ctxt.match_DocStringSeparator(line) - return ok -} -func (ctxt *parseContext) match_DocStringSeparator(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchDocStringSeparator(line) -} - -func (ctxt *parseContext) isMatch_TableRow(line *Line) bool { - ok, _, _ := ctxt.match_TableRow(line) - return ok -} -func (ctxt *parseContext) match_TableRow(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchTableRow(line) -} - -func (ctxt *parseContext) isMatch_Language(line *Line) bool { - ok, _, _ := ctxt.match_Language(line) - return ok -} -func (ctxt *parseContext) match_Language(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchLanguage(line) -} - -func (ctxt *parseContext) isMatch_Other(line *Line) bool { - ok, _, _ := ctxt.match_Other(line) - return ok -} -func (ctxt *parseContext) match_Other(line *Line) (bool, *Token, error) { - if line.IsEof() { - return false, nil, nil - } - return ctxt.m.MatchOther(line) -} - -func (ctxt *parseContext) lookahead_0(initialLine *Line) bool { - var queue []*scanResult - var match bool - - for { - line, atEof, err := ctxt.scan() - queue = append(queue, &scanResult{line, atEof, err}) - - if false || ctxt.isMatch_ExamplesLine(line) { - match = true - break - } - if !(false || ctxt.isMatch_Empty(line) || ctxt.isMatch_Comment(line) || ctxt.isMatch_TagLine(line)) { - break - } - if atEof { - break - } - } - - ctxt.queue = append(ctxt.queue, queue...) - - return match -} diff --git a/vendor/github.com/DATA-DOG/godog/godog.go b/vendor/github.com/DATA-DOG/godog/godog.go deleted file mode 100644 index 163982c09..000000000 --- a/vendor/github.com/DATA-DOG/godog/godog.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Package godog is the official Cucumber BDD framework for Golang, it merges specification -and test documentation into one cohesive whole. - -Godog does not intervene with the standard "go test" command and it's behavior. -You can leverage both frameworks to functionally test your application while -maintaining all test related source code in *_test.go files. - -Godog acts similar compared to go test command. It uses go -compiler and linker tool in order to produce test executable. Godog -contexts needs to be exported same as Test functions for go test. - -For example, imagine you’re about to create the famous UNIX ls command. -Before you begin, you describe how the feature should work, see the example below.. - -Example: - Feature: ls - In order to see the directory structure - As a UNIX user - I need to be able to list the current directory's contents - - Scenario: - Given I am in a directory "test" - And I have a file named "foo" - And I have a file named "bar" - When I run ls - Then I should get output: - """ - bar - foo - """ - -Now, wouldn’t it be cool if something could read this sentence and use it to actually -run a test against the ls command? Hey, that’s exactly what this package does! -As you’ll see, Godog is easy to learn, quick to use, and will put the fun back into tests. - -Godog was inspired by Behat and Cucumber the above description is taken from it's documentation. -*/ -package godog - -// Version of package - based on Semantic Versioning 2.0.0 http://semver.org/ -const Version = "v0.7.6" diff --git a/vendor/github.com/DATA-DOG/godog/logo.png b/vendor/github.com/DATA-DOG/godog/logo.png deleted file mode 100644 index 079509f568830a212271177aadc7603f0c29992d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 48144 zcmZr%Wl$S!w8q`t3GS{%i#wF!P~6?!iWi6ARve1ETXFY7aCdi?oA1ute|Iv;?(9q^ zo4h&aJoZL@QDdqP5FW)pxf!n?^SNx^TzBOwZM1ps5?As_${a*|@|UMpugo_^}) zi^DxFij#^y=yJ03atJJUl;4Yxm^E?gLOS}!PIWccnrgbznvCJq)hqw}q}NZt^Qp-% zqD#t9%x&9$H-(CV>SJZBzP;V0qjnwVIuz+SO!ocl3W%aF_(l2uyzD%pB$cf@i*gaP zk2*UGPe_}R_t%N2$hT87{-sxD3jKo+Kse%pjAK5HKC;fC1@xooHA;cf6_f*V@hI8O zxVu*@th_-CkVi$o_N+ujDZGhxDtkQieDQMnuAZkV>0HuhbMA;U*mw)u`%(bVPNhg+ z{|cS=x%CN=J_g%cuL;}{Y0yQ!Xj%2mnJ=3sI^8}kDm5g;wZKu$wq_@~g}@k078her zA*XeZ8LVs>vn}CsOs)2$x5>wE9$Dm?2i~4eot63-6QfWV z97}1_o{Pv%po@uiY4hT#2`uO7E-$;dRRiuEFV_7;Op7fFtU>eggQQj!PoTMTN;i_t zU)(mk>}4D~A@SpQ)$7)8O8llhXu|N~X>pLJ_ju;b%k5G$b(kwdu7jgm@L7T}$jn_u zl2m4@$=_*<^c3-UvKB5#7hA0Ny2$^7j6|8Q0FYNm1pq(<(^HO8Y8GM^E`+W->}Jsv z3*GE=RIWD?%hhidm&c+*3=G^2p6Zj}df=48FfazsLq`|WZC@>xY>Knl=GeoL`crcKdMu4I8QL+WUsO5eEe*q+89>Di`h`eQIRpdTy7mj{5+Iz#;e7US< z)r41x7IBIm+W%VE7e^_7w~5pqfS?aArbt|39k*K3V-mXm&=Vt_YVP*|D4+)*(DCNM zK*ET9#enT369ocXHflxGH5XPvj>}7nM)ca{*6!|+k*3$Ld{SX#QvcjOSun^qr+3_{ z(^r_+1Fm0c42vr(p>(iR=>6U;s|hu6cXoCNoEOf|*0esOme{7%U~`Xm7;{?ABhUowxvT8D!u^;5rMXj?Qf(i$@7BP)4B#Hwe0h6liJjf+dUo-r4!7YHSlf3 zK5@S_wf(||6=9J?AAdYnx`PhKMI9lS!vI4PdnWJHq=~*{IOrKzTVNDfx8>?f)!jl5 zOg1`9^4`4ZO-p>-^!E0SA>xUOBNgNfc=K{2O|4#;fW^Kr-MEvPulWQ~Gq za!31c?%$s<@G|ub$!`UaY}8W;gcb4=A_OwK@X4r-1-y7NOjrKVkjpEAs`@(vw>MRf z!`iqy;awjCLv-yy46c-@dQH7e0ArN2tSSPWyT&{e#S9B?R!RjcS)X@^Phu(#`jHur zBk^P4>vaq zKty^!TOx#qHacYFj2*O5X)8hC+;hl^Kl|N3yG7?1TH zzvJ6NMY0h}f3Sxn{)D9A?g1BAN)XLcrf=*p(K;(}yhKZ`!<%=^s2NSDldL-Xbpe7@ zYGLN?*QR}fxun?FWNI7@F;%w&sS^@qO~;i{y~}Cy@dy7z-*GHssrT7FDw8JNYcC<0 z_jNPwtGjhLGHO3wPj-skh?;mV>X8ynTyIc zA?Ob29H!v`%jRj%fy^PDZ+;Kw>%=+t;I8SIby~mHtgVW+fmp3t*GzEh&!LldWlRxbFDb*4p~wzx+}7YV|v z-^b08_A6tEoi-71Zf&=JX29XZ_$4(oP~%r+Dh@L4PBr>ILNxw$tkFlkG-NmdsX6bmf4g01hfbeAGtA<~7CmWe zRmJb@>Qh7VDJF7_>0& zJ#)($N70rb`>RL*$BHg`A!epu$JuV!>%v(H% zkGmr5n5?FyroDhGS+?iMwO?*`A0HjN8$*WUI^XqH9g>U;u=s0o9JJX31<}x!=MSj8 zq(#v8nUs>4;QQfEhUh_DUhQ04AFj3W44m$MzCch#@3-PK=FqEMwl}k|phSYwYjNm5 zyv;9{-xIN*DulZ~7(<4i?Pf=BS&e4H5C>8Rr1w^z3LFVE6EI0PV79RRjT44q&YZU)*u?E&Ed~F;96oxMF%V-vE8CyFb@pO5EyS3~ES!SBZDzMrLe;1)?8&88C|@vH|DBZdo?^3B_ESeX>U^mIxkP>f<&`^W+iwrz`+le0UwXnXUZA)yFu*f>?^bRu~m97Vh zS2RuXFY`7{oPJMEFAwJmEe`AKS(E9L7AB^qkbla`C`iz-k;0Zby}8hZ?=W5;&Z#)2 zls`9U)?9aSi>Q|vYO03;a-tlw?)owqp(XlultAjda)I*lyi);pREOp>;Q?au3G>|p zeHm^qlg=Ci{S}w_R^%h~HDJ_)#w{hjCp(w5HWW7;RUMS7O%xu{HI`YA zmgT-QTNYZFPCdTI`KnA|1%=BmF-;S@2Y<`QFRvfp=_Audi9mgd`~Gq7o194%_0drR{4UUbTJKfPZIvY%w=;!8CQ@K9O#BCkDCt2X)! zFTC(_MSm{X6x)KTW5|Rv#X{g_3#6h8f$GYkFE2hND!Ef?D#C;L5)rb$TAat9qT6il zzLhiCCZgVOxPs!bx&e9Rj1h&tycLn!zRVquq&xeBhMcEa``o-fkiQy+XPWdOJ=gqb z!dU86)x#`H0;a0X$DfYE@en9wxx28ed@2Qq5Ez4(LoE`t8}&^?YSQEJ{DyD#H}k1} zR-3Yq$bbJnXWN{f-gCLpFs!y#f~wa{mZP{=ZNP#M{F9|AnygqU`KSl6a%nroDBG~}#ze0b+GggyepRp8FKAOE4Aga4Je8>!F3*=UlAh}`4Fx=QBSu(*;E z>U@dP?kHVuQF(dPxD5Jsb&sJ!-bUENuKHqbQ1$7bC~3u*$ccmHRzJv+&Kt;akVAg^ zMp$956gy6dOoX_Pr|ocdak2Vkh0!S$DaQz7CN1U1QR2zb&+xoR7#66Gax?JG{4KxF4A2 z%HVG&GI4+h1Lcb`xTl(_`6zz)0IQSR^}v>m8Veq!1Qi*cA{ohP-l9UDSJV*YOAK`V!9F&GV@9jg9kd6>2{ zJ(-LmnOa&hS70w?HYysm93>y0r>23yhX3v1v>`IPao_!qz{zg{Zh~xMshb=Dk2N4l z%!l*z$-%*Gr-gsOoz850@;A}sZ|SuK2_%k(>(h8QTep{6xA4cCJ)$bY_c$zi%|cbX zRvVpPNCiF2j^~Q)mKt*$@v3MU7=Dw{NVN)gtIeGS1Gr)D|DIoOUq5}FXP2e4j=atW zx0pk;v&d01lgXiTzqaPgeP5w}Jh}`MwHT(em@_khd7D(Wu?X$I=n1SX(1DbKqhn(f zOf?BPuZ&i1d^>Ie$V9}%3es^TZT91-EbyR89SL0@1w1w#EOQ0$ilCx|`-$hD4-CY} zql7K`FH_RhZ56|R#1HTjN0n2JbEY(*3cbzws)KlEnryW!CNrg!m8YzU`!Cizbeio5 zi;If~hKA;93`J9!b;PAKP!+TssD-}-0h_B3o}dBQ?T|D`n`wD-+`>TPQi<%zvA@4b z+b&j+*_S5$*nJ5%?L~OJ{_1#4+x$(_JX>>kZnr1U3o9ctFM7~ohEhYtJJ4Sb7rz>v(|J^g zJQXrLCZy%WRm?`yBgw)=(hz%GgY?Lux5DrZjCKYhKkwh&^({{qt2!Syd^S(AwHTX03Z)?C$W^Q?#vx3Di>En)8ut+ME_BE>{&cMY0s7&~;@EvHo%{tnxW^?ls2GZAO}jZT)?R;Bcho$swj#F~jp%^M zANM&d2$6yDQS=@!W#N9wj@Q8dUZYa;G|)dVcY64bYN6NX`(ylGxdL#Y?eKT>q=o5F z458w0p^T>|uWr3MB(1_U%n)Bpq=;Fb_eM;EWJ$9SNqc+fYiC~8FOCq_k%%OfwZBiuwcK%adYb9{neSD zgxR1oz0PzPn3gvDkC0qdRcAQGbgHJo;G`QM+bHdU@!~0~nK!{L{EqM>5Z#<8UUK?OS;M z$_g9}3L2V7CI=q^rFnWr#vSk~P|?yJG{%^oE!F)4fyi$goYZt}*$K=*)%uFr{E6Y= za2AvLKbNhHmhuevPjY_k9P{j=>meE#LKHI3c1ci3z`M~^GIl=R6LqhstB6T+=~~<* z%{7Qi)|n)}*vJ-z(heDpUf^2~z)BP;*5g5>v(qSj)+!=k#-e)%FYpZQ82S*+E^WUlu@ZyCQ^ zhxPWHRE~*U(cIG9fS1r=#dP){AP}qj`G6P*1bXd6(mjFeB%{NK@VSk!k!5W7@IKcg zS6KY1XYl6H`irW!2#W zdPUj&$q{g|Xst)Z6yGh#t06Kplc!R4}e|iy!sp4$Trb`EYR*0QgU2m zS#Uy9b2xvH1+ADXl4HNxO!{~m6N4fhPZkS6sMKi)f4)6T%E}twPcu~3 z_ZQ9$5XsW?*1>6>pddiW@xcC|V``({xqp#UjxqnYW$;gs*!%Pp)lL|vz)=j!+2c4u zC_Y^>^Q#X~+J2cA%34@Xu6DLTOAAFB+g6@$?&#s0zQ#Hg0aC73yGK>NQ~+}R>^y-R zpHC-*DJyCJ!DLq9nLx-@hj&-WsQ?hiv!{gTV>k7b73k1)LCI)K6d;bHu`n_sTjIW1 zQMgcS=> z00b0b-k1wvpL(Z#T9fZdSwD^qhikDi>(5Byq|Z1syS;896*Z~YrkKnp6wFC%tTNHs zf3Zq>Z0-+bMzUo|NQB@^l7?)m+=gmbw_DLiTXanX#~XrmHjh7Ms_dn?M? z8!KITA^eylg_%=92M7g_I|^`O#eFsYskjG5I)zBlMbD z+jE8?ixs@lc&R@RAPARcOEY9oMmG%nbsPR5rh#j7YQyR(kmLH>|72O__V$Jo0$fu4 zzL#C(=K9G;oBeiVus>&)D$!fv4c#0JZ@ARNK=H(#STK-|fUn+4)ER@P_a7!77s8Kg z5pvyNcno?XNpNAJS<<+aBBu*oW08_j)koll6Tdi@L)Q#hm4d z1xwM@J-a$0IV~}Led6*83M%7qO}Q;!p`P9YaHPQ4X5TX2(aH+I#ugvksVL%o3u!ZE zi!rcy;SA=m)gk4fa?`T=n~wf{^EFe{1aqyIea&mU+_Ov>!aF_HQKQu(aiXZYrh<%m8(@+ z{iykE0SA|fx(SsUQQ1oedye0dZTp)<;KF$dF=j;5%yBMB0Yvd<$0p8exTf??=|_ zX}%l0n63S$4>*);Sq?X9xQ7;!(pNz0*fTGokT2yOFk+W%xHI!f#@Tk_t_3$$F3qRO zOdi|00>*X^3m)-VchV%Wf}!oA!09-lz)flt+8o51>H*T`EsmZY?#uxcu9A0dCVGf}V2zd_L0kT$lqg_UoHbnU~pxS0o76hb9=Qkf*C zyreA|+s^)qs(%-b_JNr1PHoxDx{XIMxB=qgP_%`LmFsw;yn_9CrvL>kG#RSHhtn}p zy14ws-Glm4P=nE|zz=r^3=}|URtYeG(iPba6$iFM$zrFK<7Zs8H9tvQ1+U{WXPfzW zs!K935My2#<4*$t>dr{;nxZ1yv$}V{z#fU8hb5MYJ+n@IXl7<6*Y_vZG-OE9j=`80 zCVPkH=`$}U{`DULA76w7yh-jabbtH4DwOzlVxX8Ljec;U%VSgN>d*8pk7$@q7wfn{ zK?L;V8Ufg+thh_08J1DpTDs17aqQYX;GR3+I#8~G4SFYiPJ@H9B8`3MAFQ#-Wy2QyBazP^n6WsfG zrVvSakIKp_(85+veKpCqiSdSBbFW|m<~&yA;WcFnCxoIpFhQ9Dbmw|JmSEe%YF#Kr z@UkaFYtsPDC22^65LyhVx<(-#%b&H_mT~mQDpTIu`&r{K+f}(C3>m*3tnkqbeu93n z$_+wjS5-~Vxoe$lb+6azPJY%&$G3)3;uQu3tgmv}uW)-@ta%S1_B1!+g{ThM@&3Lh zdS^G&>03Ucp`uAlBkN4;OI=p%JPp|J3#1`aK~QG&DyPVb(Z-FH1H~RV4Q%YY6gz?e zY+Jv~{rM{2*vuzQ0X`0j_1wvQ8dAZ?bN}m>6ZeOfd8(x9SD@rji~xKOXq+lu#0UJD zb#<5_%%&}ac{V+{54#2QTTZ;dtdy~Tbae9#Y6{g|&%6$;wn(_Rs7}F$H@0Qj|Ca?Q zAwQNVr8tJdH{g#UTNfa?zSd{edQ~ly#)SlvU;eR~P2$<}ho#+sX7^Jy9GuRCqVfyl zDpxM+q+C~BMSG2TdWRf^jsic6PQj2CFj|el^plW)hDRs+PncPoXf&*vn>eQG_*Iyn z=;e#zD13_!_j@6=jLXtx-e1kBL&7K_?zlmwxs?pDBq1?<q zdj~wGV~vm64Q-i?q0DnhlLU(4EWv z+c+{w%Ow24Pwe65rbHvs8$P^iJbTl0bYzuj!9jpRSf$tUVe)Xc97L})4N;)t?TuvU zcRiT6N$$OuH~>bZ4GIb%<;wEP?&Z__wPPzM14Df^VM-FTLuk_A_C<3~fY$|Ci|?I5 z&*jZ|(AHE1PxyghQsuFflLLD zXA45LaWEdQIm zKu*htv^VoL>V{crk=l~RyY8=m8F5t{uAi!$Gi9d4zrFT&KfG^we(?Dqq#5#u-bUON zSWdH|oPm;9^;dVQ9rG5qW2~IS{w^OGZ+;-PH?a*^d|o~RWgc`->C1sI#pj6T4;U^?TSrudX^#j)pov1V-SLBHfrCQ7>z_XsuJV8dNBsP*;|G{-8ML>&#A zr6Vm(J!?_yFGi*>zcN#!g&0T}i0J=%Z#;d`rLMl1e+rcn2bcWyCz*bfitVFn#h@hU z0hU?2?l+soGz}G1$W)HtCu3jt=f|t}X;ljWM=c#V_Yzrd^O@C9UWRVKPC_fll0jkV zZqfhXPx9xF@$`p(=j*Z7z;eB{Uc$3KA&aUcj4lrM;d_QFLU_MbJFTXsCa-JTkIVLT zhfF@lxcTFl`Ueo@i&WZ=fkhTQ@3Y82Vsif@L+tT~%MN)p4LNuUDxM5MIu)apXwRga zOaupVfkdAj1grx3AZp4#NbOkC2uv6#GeUGpwjVAGa2ok;yUI|#5NMu11N2w1$Q?!P z4fzSsl5#S{<(!f60$PGH$o<6?6;brt-JS>Q=iT%zxBJ3k$VJJ1UYp9yQ3}R#`Qe`j zqN-vbz({Db;IZ~Nu_Jmg@!YdAmRDpnIEfgt34gWlAz98i#_X#gl9Rh8p|3GIACe7D znm)8$EK@7Z!NtYZE2RERiR^YC*Cg}X6MOZ&?DPkvvSiUQMcE`uX0Vb*d%xuCwVur7 z6KJ5SXO6)||McP4qnsO5OQsCOACUbft@;YW36&2?SJ1n5x$WhUO+3jSoMk^8V zEcfKrv{}1{pO9-ZDcz98v!>(z1p!X=%!yZJ`*ki^ih(_7~0>+JYqim0Zv0Ljenf@ zOdZdq-jy6cl*XQQL+Dt`p`3zpZpMfVavwy%ZHShOD+#P`<)*%d_8S`nJeyy%pR$6% zB%zB3{_pl%A5OKTfcp~E9-d`La9)bT0t^u^rFC^Vk<)7ENYK8uTMH{_ofo+}LuTk8 za*t1#9R|rSR&7Eh;?1O{r>Em8m%0uc1Bp?*tuk*zsZ|s^p?U&MllM#I@8ptbuMe^u zIh}VxvnR87yAM1%Od(i1jOf{VULYR65=g$+c15v9VV<+RDc&bu#tP54nNUZ%zIYf< zzMP+ls!v8Kt$ryjLVb8znlFKc6$2Fg(N=_;B3>gN1>DS5)_B>TxQTrF;boT0mMCR? zKH;v7r7#ilIgqgRym30jX9aaBc)dsVgrMa+J$a^)xVD>B+Yt4BOK<3C-c^zCxxL@v z;r8)YUr^`p?e%oCU(H#2^O`95D`UtEsIG;CrZqDcHq_JcPRmTn3uCx^G)8g7knq1#)A ztvD%vBvV4YeF)O+lPr=g|gNG$TU zhDyv=Ee+gZ2{t0GIYq4@L<#B{8p@1{8FJFA&>)1Hx<*Bfj?k+jeE=<9tP-Qu%sz+g z7Fqm|lN(Ls9_Z}sltCjcZ`IK1pPTG=AzY?OS);}j78i>V% z7$?k(TZz|>+8MQQ+LCD3;(U0YHq)trX3X>5XOwdg?DG%NG!>w)jDJu0u~Yt6X3tb}82?;X2#cLk>_{gHDxPk*@dEi13t>#U&Ljce4W6BP7KVLlB(Bl#9nzT(C7A?)TIC7VjUj_}ixW@`Eyerzj51i(G+Lje)R&f`X`KaPQr4&Be$- zH)49scj}Q6n@S-JGXo_gXqn$K(?Ibn*ephroN`S^T|zUeiso~R37(b)&rb?FJZxH> zq3wqP=z8h|0?U3I-lUX7aR+5MhnBS9H;Zh+Jb2P5J@8*8ewtjU&1F`=s$AYKJN7GJ zASj9mO=Gd%XcDhG`;`T*A?2+T46RBlD^YY(ojTT^-aiT_sa4JT_5)4ciY0zEtzLQg zSxPb-ayj3WWrmNMQL?gz3z7$hv{+0*!^lUia=b4LdmlDTdp*tKXE8%278O~r{aYX% zVJA=wY=65M-_vtw3j-@qxj#CptK+VBhi{iH8%Su?#(R6Ws^`GI6x5e5U!3pn?`wR! zHjwF1&t-(4lwI;IU7qLa^MaK4r5Z+MM zsKS#B>kz*Ny@Yq1&a&nD(P-ui%JP5!s$N&=L`dCCa%Lss(};pyF5cm|vGxKMtsaVg>QD|uhv((NqMjqq`LgHM;*YG3=~GY(Eh`RG83TgFT>3|j zqWCz}%3f)H1kN}0%tP8b+fQZQ6nN_eA!IQ%Wnp&E-WGDXeAdpQ-KKwnz2IZL-#+6M zD+5KT`FNq}L%}a_O8}3=jV@o;^Cr;F!?V}He%XY6E3h#JM*wF(-%6m|iBx1gMeHUv{2lz^HT zCaqQ|@``TEF3W#HbhO??dcN9p(2{JWrKIQpM!lt3Y&?3Ke|Iy6(E z#im(fFbTe;#C@-PTTmwc_&9kC*1NXVay<=NL`YQBSnt$Jrc8|hodnqmEgB{!DW({n zc3Tymr3<{Y+cZ=URKZWyKNwiD(L7saRedzevWmZ?zDdET3O5<`04Nclq;;rSm{N3H z)3)4r>I)i^yDjf2c!b|uONnBo;n0aBZ`XbtuzjQ+llzTM)w{HN+RE5`hazjaOrEoa zrTE??jRRwHuF0(F8ak61P!v`14+nXM2Q_**v=?wYS?}&A^r*M!xZ1y{4}T2@Rb*b0 zkc=V2Pav+*_!%3^QVLnmJpb*o$lqCE1((}$ezEHxPb)pc@yNe2H3kNT=Ve=MW<1>% zhe>cWhJlUEaB=IUw38m%128w@RD^@T-J>v$+APYbIg(J zX=ZfkTP%%`ElC7XSyu<=Q5;d$(gRaCX!AIk$x*29+!iL_Tpu=G^ZVYluI*jk>ZzC0*-2QmByys>M;iSxL z>wTRx#mr3W^4hA$>T6hq%d&aLsA4z(c}j=Utg{$1xclRYmI^*KkGx>8drQJ~*7QbTk~PDu*n)FM_%I6;c%$J$9sAJ=z0jVHNxpGBPVT2lHEQ4QBha7ydqs z$f-3l3vS<&cIAG>QViM9kZAI28}t|KpXzjbFiF5Y445UT_RFg`kaO(8^hE_Po0&P~ zPEC9^Czm-+=c$zf)fi!Ova=_^YAP6tWoc-1vB?x(4CDW^6=`u@>lAFC>1aX~rvAxT z_zUu(wTheR=;x%Fgp9;j*!5qmj4~Su`G|lhn0V#iwB1ADL$Q-)k6D{r_e$ zVMqrZ%=f$l%`XaY38W%mk=q>Z6;yvJ=c((WsF^ zK4R2l((;2B!QaL8i=$bN-J@6A{gJW4ZS^kLbjn6!$)2YxEuQ8zhHP&XOpDnwZkJ2> zri;BdH*_5>vW@G)wCH{SE2vNFk~OYA*OPqXf65(=cEe-Aq&~j2i27hEXS~&Ucd5~O zUbR#ulN+%HG%k4A**^ZsS>Gl0>vx{x(Hc(Wn zL@}c;3YW>L?MG`@0Gj5%fKe;^GDbDWkdx4mnj|6!sq2W;Y4^ErN z3knK?13zwa`ExF4G&DSwW8roKeln<0?&nY7-I~X}ydXP}rm(r&lEUY+XA;N>3U6V^ zS#4l-EX+x|VTwH&k5xEP+r%Nz3)E>sJJW_~bTExhPRo2xQM&?B>5ITn6zF4{Dr(#F z9LiB@hXuBJRjB)9 z4H&CMN_b%$5#{Z_yV&5Z7c<;9nZ*r0{k#unHCskXEP}iaC2s4wKZcJZ16t*RSI;dL z$~A;u&l;#{X>S%fYnIy{0iZb2pw08>vj)LzzD*nw-7aT%bkR@NkH3$IU%}#GNo8dW zco#(B#e9P)1;{`kxqJnVT9v;#kUEOeSc*bWIP6~UvEDL}##_faxsmPf>4S8LtBkY$ zUvh*5Ai?xck(`VUD_n){_qgET#YS6DTxKSb$lH~~Z{LeA8@`vqBJX$DWIjg}npL{d z<(av^A{nx=P%hLyeo>3&AAd}6O&9q+jUKk3*;`I$u(M-BK?!^x2<1iW>{2(r`inJ? zP%}!7pOxGeUu)Owuj@;YuDY}A{lmDbIkV!(`N z(W)K18(cC@lk0d4=R|T@OdJ)IZ&Ma>kl{eL(*u4X1>;cz=rAl>C?dt&^r5)j#J=L+ zCH=ZY#F!yiYe-*L5b4F&#H8i`8q<-GO-(;vx=@d^79}QTOhwG+(umR_OMzxE6XUqT z!GSkU<31Q##q_T~evtf^t}QQjS+#HBa9H!&c(tRb>3XMGUOtu)C{2%%UbJ8Ce-MU` zYu5w^KEXFW!BKc`U3MKR!ARGVB?G`vr?*LrWtQ{u6H~-AJxkPyRD4%0kIp7*I=@7XveP}Zxm(S{yPB3 z1`|56;hC1?5tiZiFy+cUJxW_tfzVgiqb(%`i(wr`jR3Xj|47PZIW=I#?E*dprsYoO zsC18(*!#-HL`!M#?ChRTWWUZkRD#*M8F&zd_HXC$uh+*LMJo1&!~+vyk3wYsa@E|bw% z?-2wXCNN+I6#k8V4FyKmoH38PYhwh>bulWI@G0gh*gyq|uQ~;`xP! z+v{B^=u6jV;f#tOr=$rK5QUX|kfpxWeWw^A)E$wE@_;;t$8kfby8VQaEa1tQDC_MB zY}`U8q@)aTfq!!LqN}5Ea!De_BLVQ1r@2_c_~T3R=sh64NkgUz%~a^{q2*w^{hv%} z4{0O{4VrfB1IuharGBuTIlDSMU#xHIrcXgq-8N^!&`!Uj%OmJgIo-n0&QHdK0ZvbD zP}hjgh_VfS9j8_(itPGBkrzZ}<{6Tbdd!h1;8+mMijYW6_^#eoooL4~!#e-B{Zd|a zpoIUg9G{s@dud*N*!vIf4Zw%Uv3v|1B5V$OpQ_j|BleM1$DT>BniLOn;BmeZHjM4O z`Ege&>b&j_;&2=#>Ncnkf8r%@Xr!htp0828X9Vp9$i&5W6t{+q!Y;!Umu@v4c>Il zsWBA*9Oi(m87b)-5Va)%1_;#-sh@=5miTGbAGMJzk(OgeB`5lKC01`1Rh+u(A-N|! zbdvgJWbc$e@JL4qFZ@?*Vc~|TgGzQ*mhZogCGdPs+S|i1$o?QKps)8hEptb(HcSBT z2@xv$nq7T75q$+!M`|I>+Moiy#^Qw^rnQP zk@~m+SXg2!YPzGE^d4$G9BJTu*W}`RZFpzf{B6zTUUa;V+LeD)hTUZPfI}VGwFOr* zd$ymsUAHLlg#xc1mlJk|RX&&NK$c~o?wao?_X>5MMmHUqhZ>cv(z6=XQKL3g~v!YBT>h zDC6hg$WUx_cXI`?AnWk^_VtR&z(C$*Wy@T4y6S z`tHpk0Qa4Kc!H|Dd?EO>pX!*f;a!~YY_;oPymNW z_~5180h8zpHgWSA<=FmSdxZrjw~(LQ%-38wRb1E_(6H8JTgJbl*4lmE^x4IS6Rm=R z3#T6e5|@xZ%S+e!f7NYtfx&S~s_Zzzdz{2S5gGL+o>Cx=UbeTEtuM!CV41^>Eb^1? z6*m5sDtyBUbLiarD858Sr0cmBJQg%>vh|-e;k;x6tZ&I{G%^X z&KYYTJ4ZoB2kRu>P!TCcC#{J~RjIpB3l==4EqdUb^#0p5x#JG9)<5sAfRE?geKX6V zEvKb87Y^3(YtY*6y=rpq;A6KRD8Gj&{8h8YbN@YwE`p@(&!2jQM|Po`z!mhyL_>ag z6toA?N?5i+!!i`JE9<$A9 z)sCa6FxT&|FRuzaq>RqAfk(_35rwN9)so+{4H6i|e^WmxQwx>K0&^^WTqr-ZG*X2z zBufisysh_gzJ5)xwTRm%Hta;MSe~e*B-G)I8m#H;a}0ddGchsQc*K&Dk{TEuzTL4M ze;xx}&<=!cTjDv;oH^iL@o#KTZWFQ;{Rm< zHoBDc9sR^KOzFr)M(_>bUe5W}MXVZh*PU6JW<5@gH?<&WxmJl+BV(iCh1aM8hKLx= z|C~sNGlyNnI-gbQO2iw!vfX}!3PWNFq+h{3KY%WG+nFo@?jhmpsBYZn?|&7N)6$Ys zQ+E3A1CDoNh!T}lJ^}3>c9gO~e{qd1?H80&Ybq$f zrrqY-0pAbb^QMT#S#aiYv|OXY>t?hkAtPt{u=~;W_s1jW1R6YE1>vrX!#m7c=?v4# z=D#uWfEV-n`J{fM$EDD#H&sUtDW3dIiT>;%KC5(4(q!lD$t za~@3MY75o=;2Q((ffMo|1SN>Oc&Qq-oTQRNVc-Yy;-)Ml4&K(J;3p5dOyt#*&)eIN z*gCV`>oke{KYyg<w=u_F^?flLYxxcw$kUTvh-aZ}pG{$A5MXjDAvLzAv z5XjF;D}-(5d}ae59&GMma-y1aX7DU@fx(DC+2TCild^VE7O{7BG1nH+1@@s=sGe^D=W6% zth=#+3mBA_t|$dDVDt-UPFTXQnjkGCL|&06vvuf_$acpS^h+wIZ*33z(Myn1`sevi zDZ*We6cbZ0wg#H}eiDpGU{?Rh%U0aSm zUHa$qln<5}_EpAUhoXwg*WdN^-e)n2%v0;{9i2Sfb2UEpIH9A$Ue;6sIXTj1;;G}b z1JH!dXyT}C4c_Sbe!l=fv9k4o=f7zLK=eD9`_M)7{1+GQ^hX{a;qGJzzVLVCx-NSP z3Ri<4rFU})IKh{MJ8ajp+o-&B=32f|i6A*R)G_hrR_U}N{qpz!U}q>sMK|g`v;96i{)5T0 zJx^#tLPMW>i9Wi3FNdoC(rbOs<4xz*z_rhD12lqjIF|*z3-!-0vI@-Hdmu3dD8cuI z_0*ngOqzF^txpv>xt6-3L%s5a>y*F88=3|=;82v}!kDyDvqrOeBAK!?8vHifLK|J{B;)x8BQ=b*EpFpKo@+02M}m;ev>oQr*lzmiNa*X4j|h!vmQB?8ct! zWeXX^+l4Ir5%8{Bd9Unv8R7YoN1GcGXs;4N`CBGj?Pn_Y@0ABtgefo)8AmiS<`=i? z%f%ECvA*GYYgweCL+7r;-3`U{vBQfd!m7~k?z#3y;FIz7=1u}Tu7@6Ad(5|nq*Sv4X`JVR@2eUqX$2k_SmM7N+ zb8`F=b1Q|Lq@HTO8K|k7`B_sv`gx-w`|kUpe05&`W1+q2mNoHx*k6dv_4P>>`Usyh z=-)_-3%)Tb99D@DXMmI`4B58)rC9GJ(bs#^_dQjFF%r~}U%$GO@|{Pr)@?LZ{q0lZ zLinBoMT2HGq8DzaM& z#3QtE&{8m*R~MEv$9CJ`&f&GwL=ot#caAmRt@_fo0jFE3oB}n4YA1m$kE>6={2NFNV`5rj@HCknXxrv)!l7Z18patd1J6NPK21^%*JNB%ip!ZPVhsbM9CbdVpx~q zVSdWIOPNBtreAcgiaS%*O@!d1;9e`a+;!OKOpC!U$`$<&QvYF?_XYMMWxOvejKs>?jaYp@2^nds z>(XTV&N2IQ^^YdK#>RS6+NIwi@13&?DmJ>fgf?l5?bPh-Wcl!)=bIwCd}C{VyUHaw zZO3mPCdx8t7%w3qxDPMXbTqkUc4RpnhlJ@F8G=`pSoE5|0NU!~_3|)T$99`a@EP{! z&!2CdiW@>Ax)>?eMv5lA@WDP_t4|Bqw&pvjN^5=0YmE9&dMnq=#wB>7 zqZMPBnrKHTQ&&*F+{gQ34%*z;vyDa~ew3|5E{3l22SXLehG+SpGtKuQPWH-|)pCaXzc?>b zfogqy-6DP9J*O##$>)XAd!uU~O z;^K)+zOz1J$`1N2>ig>&d36@Xq_C(UG50;Rh=3__tU4JHeL_y~f;e-7&TnhS>B6qs z2xUL2M5Jjb7K}vjsMws|I;H*+8!9oALYIwC%>2e@{x!K)4->i^fcMu0$qEnnp25wy z<(i$rh1R9Zn+yHr(uJDxSmY$x51SwFh{;u}J(5-F-2o2b7^akL&E=^EpZhs?56H|; z0|@k3qp#_yKz;*^%>FZzLE5C9PYdlhEin$uEP_7ge_{S(c&6hE%qVXcY7u{t<6z9z z)jKy9!_58Oet~jQihm`3aYWBl zbqWiaQyRN11_N}9R);P8r&a@45HZS}`_E_4$NK@EBb(~ey69&tOlaW6hOi^6%8;D& z)}i7X2P3h(5+=%eO~aX8yy21n}}=Qqx)c6 z{V3K_DvcXOUgN^Y?!>0ZF2&U@%*y%?9oqIn^)o zjSTR4PafH5`P26P^@*w}^%4>t(_HJi-P6lS;XSz3TA3h@F3wk*+u`Guz( zA=$=atE*o@21E_X4jR?nj2e8VO-wLWw%v?8LSF913Mx4D68hfNx7uqm9KGyc)U#nP zAX>VXoQ|b`kGaoioZVQCth5Hv;JzOUezyMY?CflAZOv$F;{y<2M(5c5>i<+#AjMBi zNNB03D)X8f-J~}+QifqMW28u5meG?HTqt+g zD=N(F(>!=YjSSWs_eygb=l|yhT*rS8#CBfONbLRn#8yx8C!aAIR8k92nOWWlUPsH1 ztWB4D`YH*1l24Y!_f*z-`t!zAE9Aw^oZjk4&35L-hGY&eAij94F>F{~YZY~aR_yS0!ATc9<`QnJ-BFH00 zIvkatC2i4Z?g9)$)e`HY0aFd`BGfHW_qtpwFjiv*_KR|(uBxn$`ggF1n>x+rGmrdC zq?5;no7j}iZvHcmNq7td#8;dn{4QQ*v8d7TapQq03jNO-e7_gy(C1FO&CySvOCVR6 z^m7~}aGRQ%`c-)fK)EX`D^DXoIwh1f_!gNmWqv4rn#K8PQdZ<|-99NHL=O_a>2jx@ z^zS-QJ>1<1=xJ)YhiO0XZaz=+8?|6#VJR7O>d?{BGTK<5raJdNK@1dV_h!hEVnWhj zVt}Q`^%d@!hzJhG60-yeNrjKw43xMRSDq5LG82h&DZGD!Q&sM#7>rBH?$H@tP}SKC z5@liWR3j`c{rF*{#6eRGJ?m|R7V+5sH|XL+7$lE39=AGL$J8;BKp}g4e!dTQ{ClUH zPf!fwh!f^xxUiD%qW z3otOBphlGnQi@mU#l-CHXlG!*e;#5OgYIOCYD(-BEcv1@_$TtVT3oz#Z#~+kv_jO1 zXLcl#1tVCMRuP>Y^}r$1KU(tt1cS*;~sDXF#E)TQ=y-rysrjcdZmHHjuuLy zbYYcW*m2^()kO%y-5sJKXEThIzb1*Pw1dO-OG86LCGaMWh=^cp`m)aAB|od88p*@c zdO)Ab9Wb1hN384qqU}DB9x-n-b>0|Brc;t zIzuFs`PD^9icS{BDk*sn9PX6XYN^GEh`$|Nj_8NC%p$)^9W=P`4XbLC!?xT&EaTpv z9}0&tr-y8%%`e#@qUqa;LS^CEyYIjW(KHupx|6EMh|DljF;%s@u=r=hCK?(^!3 z8A$E^z>fF^!&A?!@C{Up4CfqW9Ne!~QyFrQ!!v~tL6h4Ix zD$>(_IqEhbT@!|wm}V>@&q@cK#d3K`t_ajY)Rvu33nR*G{^9(9N=-)%!tpq=o+T#==|(K}r)D$LwhSg2gO8BCxU= z>eKV9fl6mm0T6*;WhllUL9pl>D}W5i+m+?EF$^fTOmexBl9CyGgp;I^^QdlvXU_Ra z%=J!7Nxxb9vRSw0S-vOQYpOl{Y8ZDi3QY?l-a0KRnN^ff;1rovhzyX10TUKn)Dz6v z=r&sTu~6&tC@_GzpOBtl@6j^iwT4zUA4LKrbFrAGjkS&@46+(O51K#QdQa&%YdajF zE6&#o3MdjXQAC-G^DKEHNGJ9ix~E)7GhJsAcHLcuJu&+IlZ3mv4j;9EaQ^@xyqtVY zOm_X@!S)6rUKTq)TmamHqX5Dnc@)Nsf9 zEH)JZdIgJKT^Ym|=W<_F| z!lUe`W;VvFa-NYpJx|Q^eZ3Iz%iL;xCVh8QYnd_d*8_cN8#u0ZcHD%z&PvQQ$0^qc zFTWR>XasffpBdRmgSm_|oUPR1tGZ+5#wFxd_9G%A$I{c$>C^+Q108_16Q7zY_2b8) z2Z0~A%zz>e_Tt>!o3WzXWTv36E!?A=LjYrpg)uzjW=p#;(vqZdW_*ye^5kq5bcp=+ zJ|=IP^FBcV)qtUeZ<6ZI3QUP&*Z~`3J8P=O^+!EUwV!0)8AC!lJ+aXTV#(d(UlxhT zLr7}07@A1W%Gdt=X7aw|xtHgc5cAx2xb&zjAS6q~+VV8(hN z!jFUXD8hJIYsts&hx#e3?4Z{duTDi-FCrDVps5}+7Zh{?)x_*<-$~$ai3|8kO8os> zTwZ=W*rWw$C4tC!8C8Au@d;!bFx5=cIfL6z7c1tOKtW?R!G!V=_$7cWU@bg|Z4@b~YIJ$Lo84FCn{GGYUbG-GMJ zDO5SW$$o9MK@NqGriGLQb?=WhgV^*SbcY(ogI zRc#%eMrUVdC2egPbMr%wM$W;tV^q#o(9sLnlv$@Fbe{1y7HGZrykzA>X<@fVfi~=hO&-Oj4mZiG`0~`bGp~`lKw>_@Uf-1kG z1lh=vQW+m7_{Ggv;!(gUwQ0BkUbor(k=Xx12MNi^u4|jIK!X+6hI`;r5Qe~O*5LBu zM)Yz)wkn()34}1i&{?<%4lgZHo%FtrK@)t@tgA(5>$cs1vg=JZ19)09NJVZl&)dbi?;!hIcgqbE!K(2RpH(uHfux)xg2 zrHlml@;Ky*9d#pIf)a!2~eCD+P)k3~7Gq=JbI_wsF5RTLH}IPg)WFbLo+UeH5B zLtAd0uLQCD4>$m+M)b6rmq!8wb2N;M2bX@Y_#jDgWWF17dJtQS>&4ehl@OJYcvOYT zR%2Rqoko0Ag@p%GOUq-JUw}KLk0S(Kz4DVE4uQkj!{VOc zAd2^>4JPkbUfdCyvrB!RW)?}21kNGJ!hYWCL~NtUKN~XxML&0uAa0A|%o)`DQcwZq zkbKm(U94c&QT+4Ubz$M#P52>mhI|UbQlM~jJY?FMkF!)R#IUl!KX^A`<3UkVKoO6yYJCHLKv*n2uxW>3GQrJ2!A|m6WI-T-o zW@l$V0I~|?l#~=n@V2L&$ivQ9q^roB&$UkD{u^sPeS?D|ZecAW=P;uKeh0qD(Ggj? z6&$WQgzf8432hmQF##t+D>ujjOxOCBVFr332=6>E0Yq!DpjDk&R+ZslnZtdqAGJRp z1+>#wQ`wp^)b10$w31LHjzoIg#eSOh^o8&3?`KV2l9G`%znqi-tr~}P2G4LmbR8f8 zUG%f9Cd$jUGeY?B>brciWs9(g4SUTrW47P9o@Xoc(+akrf8Hs*PK|&r1i3gf4!vWu z?zEnso~%SPo>``%%k^a|xB-w^R`psk-Fvp7@9ZQdiSOpe36tp(xa~1=brtM5kfWLZ z=snL%xJ_AB{CH?ggN22)#>dC! z{{n#0gIRTM6Td#9nSA`~@j2s@QrSUczAVb(~f~F`6kZ$2Sza zhJksRylgh?`O-^FNfXhfMD@Ggiv~wIDDDN9I}_r`TP}+$I4B4LxM+&YzY7@KU`b$@ z8nNn~=~;YDl%}9yi3uh8qu5PBLQ$v{XRy>rH0R`O;+D&7QE6KQ+N|9D?%X zgLhk$a@%8lIkOjdv{24cP(WE%526AW?LBIV8Qi5|Lom_M)m>`BS1#=*h9T4Rl$rQ73$bZI;;Be0NrND=+UB&@6nKd_kw%4zxT+Fy^4Pk0Zp;`3qN zx{0Ub8ErJ+{oEhqG5UL=SUluX+0&;f$d;;`le0U(3X%X)o}HvmOnx@`{^8*P0E}jV zDh8vnI=`8#2|4XngjI~mT@-FK^fLC)npeIRcAV9QL>f=Xv~MO35!}OD#;M$17QQqjC4p^b z;Cz2}iRs5IrJ&E#>2)Ixgj&78!AardQKRfPppjg*_owmQDatc4~hmBDo{Ga2qWs-ccA(2{lcvqn$Z0h zAin01h2C?s8aaP2%|By9$U4Xti0hv63vIiadgIVjuKBY)j}U;Z+1v>Gn@)nFy3-gl zD^Q>dBb&oKbHN%D4#ptPZv9=k!+ud70x?kXeI1WI|JXWsk)isrAsA)8&e<}3mDEWk3L1?3ki;n+c=JwoQuH5--R{n+OyzNnW zf4(B$JnhEL0@u*LmcYBY+H4dHh^&gvDp!Zekk_zn9hE0q%|}P&%tvGRZ7P=~?EK=y zBS9puFKL{9cxkW>ZOz{N>4f=&c0Ye+wE=eiPEb&g%lrF#V3!tEmHQ@_W?TlM5J;h0 z2UVeUlK)%5Y6Y1Raw0xhThyhnZTi{1J6>z{^YkyT(C&MSlgjF?ula}*z@y@S)A&&#J0M`obC`{ej`lvc zHZYlXS-fsE&o=(-fI2xn^?17;)B*|)>pKwnak8%`4n5nB(4o0nnvGC{iENkN*FDcIMu zc7Q~2ybl51ed~G&@l_be@9P@t6J37K-yy#=gDw!puprm5P2Y~b4k%EYjlTdFT;yC@ zTHj8=#;U5x>m`%e3Qynwcz65tNOB|$Rs0xwWz{@sub+*V32i?W-yk;~0=fm-q0n?& zNz`Qz>hQCG*&pU{8DDI59O4~Z?eab@B`qcnPsQH(y-PX`@#__uQKaF(S;;?_`#P(i zkoeXoVXopzsVNTA^^I^OSFc~`_4I~oG0Qxj_fsq_mnTy$I^ylt+~_J{cr_Bk=lZw@ zVn$3(o|JVv?eS&@es5Llz*?+$wA%%tJiUQYCSzXj;FnpfY)X4b!#+0;Q%3~Mxd1b8 zYWyEPwZAbDkXqtZ(lONueyFO>&d;vvf!PCN1K+KJ^*WI#D5n2s0if>6s@hvRTUs7E zG>d+hjfzIG?if}PhE}+X$A@h(pK3e9In5|Llkr*Ji%^3j%DbQgZ!qO!!kaBQxj`ei zY3cCU8aXkXGZABDjLJ@1PWf>LoAMRu`xt(VL-U0AbbDogJsAIC8{_$dpJ&$RedV-k z4(qyvZ!=UlIL@Cb9F>+(Ew)?tFH_D0mP7EygBAc;+wt0Ei259ai-BP zsUz3Vw>s?a?f%p3o>BlmV%7Dc6NyIiC+6}#)21zRQ*C#F&LVi1qh}x{?Qu~4r7IJ@ z4%!zoM`r45Pma~+&8Pw%sTUnTNuYT=nK#&oE{Qo@i<2~UnR|`Z#f^r}jZB3()&Dag zWEo5%BB}Ay@I4t5VZWal^~_DXd-GUxs)6NMcsn`GisekEu<$hL@VtIM8U#TO|Q{0B|0=0&tqOTS$P+E#I$6h;=;C@`eF~?PZdyRi! zQWp$27?dwGmFsPTs*qJ2 z*#Y|P*LB|9QRcSfyEw*es`RZi01|D$o9Q&!>MwVYU0h*thRNX+U-Wrm~oSS!!7_VvS;=6X?{FC{#e#*M_-?6 zzMQaDMm_uoe%>1+3Dh~AY2eE)swpilb$_lgBPWXU>nf5`P#St$l9cA(Oti>gz^4CQ zefRw=kM-Uo8}=X-$guIYd&53LST3}ao#&!M>b6Ep;P8KA#g+TL&cB0nIpD|7jm8hO5qgPH5Sq%dM&~j!Gu=`cbQTa%5;KD) z`Mq8JKUNalJTC0~fZ7$7CElZsypsO&7QbnjG3_fDejG*{6cSQse=(A<1E~QsWJGuF zbE`Th({XqNdcb}GU!Nnoicd)a<1uHnC^+sbpmdtgq$$_d>A#8QXnGB$W*Q!}s@Js_ zINh3JwoIe3S)LxM@_iC7mr@hoHpZgqwrosD&g|;k(Cu${0sWOvRd97Zn@;rM*FV_! z7nb}NtJKQ%O8`)mWja}XNEUt#y9xybo#As~^dF@QoYGw%esvg)!@ayfADvwsyC0+# z4RSTQM2*NhN8ETrL&St75F(6)$8GLZ7ym=BAgAaf;=4c<*$*g*!9tZ>k zdUIz>fkFUG*GD2YJrqwNyRwRmAVp(oWyQnx=tgQ_WwYXCk6LJa6*PW<65HOA(cw!r zMt++;%W$@%tsbTXW$%R;1mhB%rC&Gny>XIySfOXGF485#ikOy?FMOICm+5E;jHf>c z0cuDwe78ojVT&7pU~c#%L^G3E8{#MC|G9|XKjr@>#0eK#FNHi_W zbE?i(9(-7X%q$?0l8yly(Ip=4AcjUK zVDLG2?iizB4)wtM`UmaD+lJ>j&JVL(bSx~E6s2vUDlHZvYqr-3nL-?nYC^K*N6JYtDDub zlJX643D6BB3zr@$TuMH*$QCk$v`m!w{0koNd@;M2votlQ{MH@|16ftLsHk9smNP(gE^x`LyK{Q`4yomr@#Vwx!;3cuK_D|G1lMc_~axV2OGQ5&febsuq5Cu z>DR{c@^EA4`7L{*&#}eQFfhCF0ZZ^Li9ArOv0VMefJ5ij5)O1#@*-zcJ_ZK#`1u`l#e5 z8bfb_Mc&+KDda{?-Ad?7?vyo>WAW}tg2av*OeD^kGPh)hBvGa0Xqz&5&Iv@h(a~$t z<*38h2D~d|hDH>MEaqU6>Gj5I=hgd~GJ%#Eqxw`PvQs`ah#D4U=SSok<8{i?MvkkJ zj4H8jMLbF{=px9hz9-xv9K#{^I#Y<@dHB=%RaA||#YfQ;vdQivBO?}ez-YOZx9(PRM|WR>%Jn_4L!uuJ4Q+htDOpL#wp(Os_ba-Mnfn|zX$n%WMI||$ zsBN#PsQBC74xApu03J}#JJ+D`hzIyTv?$%we?KD1j<#D{wFm1l&BA`5g< zK{-~k zK~=T+BVFqb(bN6>e12}>9PzgysL-%+nR(C5>BAePQ&31j1Mi%my}Y8h(5`Dx9^O1J zz0ZLw0pbh^y6$gsor@QE^s6=t!qsydx}&4x#u@N4`T`x@9tUaW0^Yfc^Yad;6-2w} zZtI0UcYnB?+wLCHz3jdb$%+(2Bw3{nbi?4YkjT)8!l^mM9SB1o57&@9C_2Q?%Sm_r zqHg`|o+2YEiXJ~~$(_kLbuS8*s@mFs_fk=5@m@{0Tbo(=HNIn}U!+JAwy7)2L^YP2#Eh(xiQu{N0Efrrb&lmsg-XEJqpF8o_&*>5t1Tv#)I*2 zoMh-R$qxQfV)UEGL+g0$wV4+e58>+ObkyBRogxdmB~_qfuczd1tCYAhgsc?|`=8BrmK5FwNTQD|K$XH0zzfnk$Cb$=3y%6~M+4eJ+?&vhshCDg_FI zCepj=;r~u=@^;;voVT^q20R>aq9yJ~Nh=5`_lZl2cx-^{!GwhRL{SeFtCvKNuhMl}EexLpm z!)$~7`vVz!%HQvMHMyiBP;D${h9(rmPgcB0@3FJ$ux^G6M7#?yI|aHjWXpyK_>*B; zaoKnO1>6{E%N8uk0vPtKd5rl>Qq8}AE;XjRSPSas#-IL-wJPZ0(cx|6vZ|AX#iap* zyJVaK=_wnU{gok4(_=mT-W1VcdRsA9p7q6V{?qxx@=fBf{crcK(F&# znqWpp%U??X9;|gg<^jMF>Y-tyk)VV}#d-o*Y!VcGrd@OSgL^KGnT6?KTbzfzf`XW( zr6xBlhL#D8lo@8li+Z?uR`Ugi}P$GM$h@`$|nW+|kvv zub^BYMhhhZjSmO^cdy3iTpOV-GHeM)p_PjvGZeE2gH!~C*>BqW>RGFvLxo1syekuXdeKiCW*|&BRZ5K$dYFq#5Qpeq}x1uWbj=49{h;MDSr)O!b^m>Q`vBs^5=kAY-^=B?h{%*_Y=>)`IZE}KI~N@)=`l|)kxMr0ks9L$2_r4U8VSfOL7 zDCE2l;yD9bd4ez0A|1_ii; zEDkoo7V7d_lh!!YsLh`h{52w~=fy`Y4SzeskfWU47g`Uc2dIg}_?}Yv)uqh^|5@DL zfacxadrTq=BvLiZymX6;Z-(bDZ~@)9QZhgd9Dva5mw#=qEsY3X)Emui@l;{GDSc=_ z1|aLFCF)2tJUJ?)-)^uddET|sFd^QeHg;@7<1v!cqIkzDEQfJl5fF>!<%AOwCn_~s zpj=egW<`wPJyxh>j+CYmbWxEgqi9UK=bf%S!2hc!8|S!x3I#}FETF8(jNLcP7zb(^ zI5pfq)PYnPyjFRdT_4DecmKp5{Pq%DoHR8$E{!fSgZ;wi6S)(Sc;p0nkDtG1rTW>7W7jcd}96T<4u2_b8movdBaUCx% zf1xl>>Zm zNPD(_UU&Cm4D<~$;*r-Q7n`Hn_tM72;-A-L%1EAu&W-zqA1M9Bydcydw-l~%)00EIAJUo7 z;;`P0b82B)w4hhP*aia>`CPmCK~iofG>gl|nq#i-oiTAi5+O61s+54q810)Q&tzKc z)@NgW9N|K*Qx7YytjTQmVfSA#tgFu*Sz%cjL8G~pK)aL0;icbO;!Lbu6pi%1G+6Y) z(6R%h$0}KZ9b*EUm3bL`VN^&Lba-}yzb}_${GE?DIP+MoU0nnd|0E?aHRY;JUN$>-_eNpNs z!O>;Y@gFBuo1Q;``60ZkN%kYKO3uLYDU^z8o3hv))M1pl?SuwmQA`)cvgrIM&6gGY zlG2})BxLYj1?b1f_F;vG&Ks)4Ql>$HX|sbYKPTj}y|!JfPVuxl@}MrKm}jYy^7TNq z-%X5F>tDmRB^?U8V+N-RjPYNcq(VrOoQt z+Wc?8ugEMZJMWekXD%!<*62E+{-3KyYL?yK%I4T>r=q}B^b?~kDK0KuKT<=Vd0=6V z6VSw$I5svm2yD%I^&e*-;+ZO%OdIVup!}*2(5g*>*VoI_AXN648#d&>8$n4+YS9co zeP?D9mG-;SmQ#en&!E$9cqsGYexKzQ)&(}w;tkOa^?{V*(qp*C?^4Bbk9Z*ao9R;p z;s=slAL{?9F3yR_-y^B)m`F)Q_1duNL7iF#>KSsD{rd+b)a^0x$FMgG`C!u`Si`W_ zQg@;hZ5p#l`(gr!O97R|pTAF?=tS6pCCt4d#x>&}CjAEQ*AK1{N2A(7`uC zb=ixgcLbYQ;Co0JmK+r$M;e9fk6D&2korDj2=uxfp^kUZKr?;ONf~}fpDE{c4#nwG zvz^e#WVxwwduztoP54qUYPK1UzCEr+aH*-AB+=yit{@BvkU-ryAtE9Y4Pkj`Xp}jd z;(lSNsVpMWTUc-Qd}NLg?-nAB&HP6z5=ayWN4A5}^1#VjfRBA(KY*-7AJTKD{C$ju zRrPkl+W8Kd$1}BU?Hkm(ZMIHZ!sW+KRk1MQ zymNEc!9RNHUSdHuU?nF8)Vsj`b>mAKT4!v#%WAhNPw@aU3%s;AX(4PK4F*%q>Uk5X zZmZ&v;dgvwwN^5WcSU)*V|dNP&g;7oBt9^LIifu4H$#Z16UL9(u)pu|fMF0F!68W9$n`sYpkJC%!I>Q&SuPp;Q z)}>D~li9|8vWNTLugB%NL34eYBa)b3sxLn4+%}9{)#qP7&zvSI*xW!Dcj?lUW;0Sn zZYUzk+9+xm@5WVc7^wYl)WyURGMMp5Gx1XiaUz~srmShhcN<>q=b7z(ewn;9ad8kR zsu!Nwe2Rb9cpooXH`^CHAGI$_kJ#aNI96nnXIM-x-nHn0dv{IQIl-sD6g+E4UT;y;xf@q0B6v~vpyZ9?INrxPwGO6$lPPjILS4%u}TV# z{aM~_^3y*LV|Son2j{}DcL6Rc$P~@nfhcPl1xjQV1*?FZ%6|Cw;r8RR=F5dd=}AU0 zO$F#>&*AC4W*`+A+BtZ2pO~K`oGZnypw3T9*J*`2Pm%|gLV<*V1-3@kg{E|g7?XkE zobTi8l$t_HPDXouW22$aFZc2a%=2PN1kYNgmmlnhpQZY#$KizB4TTp%($aX(CFKEz z3~d4$KfRW!X|RfnF4=60kTo51SuDjk>dEG9V#2V%~khrP?(tJ?*P zo~RaDBgOaovBYT?;pqlPS{)wh6|K>;VMx=zR3`m%=E&EX4TD_r8SKf6DYm&4b&}qm zAb-AkrEoW{xj4Z~wM-NkQ^yAS{TJC3Aq zor)Vq<*piCk+L23X)KEkA=rObwTcQS{cOZAsmrplo54xRiK&&#sKJiFS$ou_i<2Rt z&&ou=_F;&gV|PnP5yUDQtwR(?p5)>?$;TZ`kw!@c0+zDUo(5sK05SAvwD zcohbQh`5bnA%0((QN&6fF%!IzR^QqSG}Nu~-vv?%{_HC$WHN(`%@!ysiC5E_pM?hfIx_B!&)`CoxE8P0X<4qYyF5JEg)Veea=^ z92I{BjXF~nM@}|BzIN@4#jq*mB=pD7hO_0FMaqUQSXEW`Bdu`izpnRh33( zrn2AUP?d~~%rwB>iiDhtjDTQ2TIDC{XRs(GZ<1kRE&llYBXe&s6ry)2RPCSqSo9>y z+(JFN^WXS{BM~iPcGRB`z=9S2kish*sOM$<^iwNX8f@I>XIE45eaSCvB3ft!(aUV` zX>3k-Rc*}yS@ZX5^No&c1vLdvCWeBBPmC0>;n#dud)C}pwu~)DB7E84k68a%rr!H> z2Hm?3gB5zMH+|jRjacHO_j;GSavv#n7vmIFH#@RST8p~3%YGMUFr6QbuW|T5`K1(=26-$?b!qZS$!CJ9~Y9@@Ll}g^bo7 z=x=SE_kV5}^nJB@nMMt;IIXs}R!Ttu2l|Bcl?pdBR1(_4$_C1CJ-xnrE{XkfRcA#( zu!6W-JuV|`g=0?WOr8~%pf{m_D&3|SE+Ol8jA)+>3o>km%=Tlya@;w{YuI%q019C0 zag@>Sdiy2528X~w56dX-pG@j^y^Ld)uQmiSWVqQsSUQD0dK!N_@%_W-zqp^DS089r z#^nH1&#^h|^nq&-g3QgGfKzgf`?YaE_ZOLxn)KwiAeHmHUZ|rl<~cq{E-v*^2*@_y z47gqPvgGfvy>|n2*)8*vKnBgQxIQITKiFaiQN#j#{y}7#7Lbz|=WUZ5E~GYFeCLAdW#UlE7 z=Nz{TOxdG^u8#X*Re*rqKbejrG|&(){}sT=%NMq_Wdd>ral($HnJvfo20pFEDkR_?l;ek!$V_x39^jesm(Uf6}bI}6RB<|crO8guN zB~(5}z$y}}eVm3WD_|&;d)onhiD-{A8fH4DY5|4f!Q>lLPsTp-!Uqz~;K5*`y|7GyHyEtwEqi>ICRH3gvj`8&N=670G!TU1x`M}7 zw1>uBG%Mb2!q@co<%~iI&?Fj8e6o|Bt&owPg0AoO{4qONUt$l%Qz+aX2mOH#UR$`5 z$#dr5(m%TNwpSCJd+sSjfYlqev1I*rPM1;*7&J`;c((-PR~XKtbLbmMwL2J5?!=)_t9=9k(26;mB=1)vL4N^1*nKgR;r&_ z`3aQmD5qC?$;eD&v@iNY9VG&EP2=Q~=CFN7HN`tB*s`shbB~{n&!2#diBBT1r@1U% zwVArcHde1*O-f2C4NcAb@y(;F}oleG$8;7xntk;qyOIW;kF^P%u zZyz3B+cFCB!xHG@CrzTayPMY5md4z?{H`@SS}&e4CefHYApsdO?Jg=|jcVmZ2|5W< z;P*3^EfP)Hc`i#Ov#sHe(tdUE@QMo&toDI1P>C z=S-oYv5hrFr8Kv8FtczRiHW{ro}d##AW^*d`bt_ly6NxlXZg~lwC-3>bx9dDP3`m# z^if(`${TOIK|@2sF4lc$Xoy>Hy@l%P#S;VaiJAWhSw10uzTcuEVDV#J%kH^295o_ua0Cr&TqH$VI$Sy^evcAl;jxLtht zd%tCSSq({EFH3(qld-9BC?m*yn^G8m^2L1N|84|AXqrh{nx9ioJslz7jW^y21p=H3 z{hJ2|6)7p{gu|VO7a6ywZ7(U}qKiHQz{udx--d<1;R|=Iqi4WEXaY^j-2fjg=28MB zAtBDkL|M+8Z)^mQmzWm9N6g!mj<8H-XC*R!iop{PJ&NUtLn*-_FRmgwZ%^Rq@8LNejc+Y#N+pZ%Of~xMj8{w`GJ0P-6Ab* z!u=y7nQy-I(i<%=zW8cgFeq&q_d55qZ=z393^dtWu2W`~^8A}PUOI5b3W*o{BMhbC1ljQ>c!T}N3anf^p(=f<&e z?HZ&r9&chY4nb6{R6FQrL(>qtfo@rxd(J5o@2umUbzAX7B*)D-cBi`9qqGIjFI+)q zPd{Hdr;s_h4p17>8llygMn&roufDOAxHxZU^5oo~R#z9@o|N?eo^Uvv4~9bJD=e$o zQflOV&wW_0XityL#P{^}*CeN;BrPjyIKCj=%iOW?NON@J%lj7#DMYLiB9MBk- zof_SYA_n*my$S6rIKwa)lj&oyy@|D@E%?$iNN^b_CEllR_JO7eG@;}5xR^3^92>Xn zWZ{a9_}(7M*NlY2bpZgwNJGl^1O2eSY)(tdq^GxQ(CKj8p6E}0`KIS;s2a4;bPZ$# zh!)bk$7^WPU|NR2>T9DXAoqxkMwy`)ct2F$t`vr;D9B8pFusSa>sAvoG=$TEl3~=r zUU!T}0a7vdxJf+v!0oubPX6)io4oSEB1FVI7FU_c!0!X?H%=)>Su^SCxI)(&LwZ?#}H5q(JBnyOBbS zR>bYS$-IWaT>l^&)^21ZDzLYgSC4`H!<#9YoRh}foCr%_eU+yEVMLtI7Vi`X)Akze zc*EAAn=v(?zu)l_x(9}M;`MiFYwJ4Zs^^q|NI1g4;2@BR<@12FNoMIxptNj&|Gf6r zsL$%ROl$C9pZka@AN%z!w~(2VHkg%}@%*;tk&$ceEg`6nPH?gIs)65=+(=Gx;fU0- zW^*m3GpdL>dW{piYyW6wS!8CksC?Ll3aDG*NRAL1)txR6_J z`X(jy%`DnjLL?A6wty}bVW}7ign=$xRs?hng^mmlGHGfqU4u5ZgTY{^wXNl#!=59C z^;ofdIRITY~)q6dNsMwmH!D#fK${CnXtG6F%S&YO;u z>ZoVqMN}`KvY~}n-(F2>d;&LJmWNvkgbr=Pic0M`9{cw~Ow+>Ua<(NUB|Y2M*VlJc zd31oW6DI@kxi4P(`;4sYckX?wj-}<@AWX!5bcTfxNK-NGpAL zP$j?_QJg+ConXs$o_Og^NJ~99kG|)xXa;_l;Lo@GfN?pQ{Pv|Klx^F2Y_zosTg5y8o0y!5qfXZg++&@?QRU1uG``$ur;wzi)Fbfq(^ zAcYjGoedjNrsVpf_#u)T`jNEm^EkhT<+60xNHBRM1`Kw79sn2U}t;N0;M zR=%?YOLrg-wbeCZaq)#`GH*s9D~iimzouxfn(m{~Ow+=M^H9^!0_YTEWuWPxOT~z3 z(jE4)t+aYH)v-e1P|w${`^rJf1sst_<+r~5O#ohf`Q>HlN&dTcH1!70{>56FLm(U) zN?QB9=1Fk5IW;}ZmQ|~%>Kp{85tUPmwY7dk*B;HubyO(Kym1*Mt5()+*@m^NnC2i3 zQehX=5FF<3fB6*=)8zJlzC>qx7ur!;&MbsLnI^=$Y47U8Wf*+=1UFjP1R)qOT~r0q z>Fnu6AaJ={^*8?Lh9?KQ`pknpLyySa{lNVXl9`zaz}aV?_`sOFoZG7g-QjOOP)6H` zLPV#u?$abBcpaQIUSsj{rIgimfWwW3jOFYfPpXMfI+!L?vr}+(?WAZ&2>}axdafG1 zdfQJ(ucEgi!vSVZ9>X`j{8{Q6TPfLIc~oDw84iQ0XnsB=FNMO4gk6&eBSP@*#uA2x zhV9=q^qoJs>8JIF^881v8*6K8W6GpSJo@Adk^1_&+cGmUZeOyklN+9@VbId;&9*^%IyZ@+ME~ym$q(s)Qwi~%ln36?ioMuO*x@5@o^6tiB0)Ze(NhVB~xIzeF z9TPwYh)BtmS6*(1WbQ<6X?<+!S7?q zsx5dO4(3ny;4~~WsR-!~9$r{Vab*h%MQU1V+b@50>!XMIH;!naS5;NKH0@7l(H)-{7e?&F5X?s!8pQA*&@bUrm^h^o!2=?sSKK`}8>?qg<} zERKu!a@OQ{%1U;ign`tIXqdj=?GKs*!vSZUaRQm?sg%^W9d&9nB6=V?90u#Rl#!q1 zKbx`upcWN2c?wdYs`h%BUdU3~3Zu;4=1N2er>afdXn;IL+)6-Lbr^h8# zedCczwl@qQR2V7uQ4gy{uSM#K7PX6SLAt_qo9o zkm%r_&zI95v_&H0y>T6zH*bCt;E#W}Ppxu0aG+JT6Yo7c`e{qOPMG;WT!K`7!%QNEaxCROmz);|(*=+jPKM z8k2VnCLztwiyQ2k7>C1w zH$MKB!NI|*#KeR{{yRqv&<6&4`T5U&3cxEbzPvU!JL@}r!e95RSL*1sBpL!KEY!Yw z)1$4eLQ3XOanMk)lbtQYpgW@@n>AvL{6}zEis)oqL7Lw~b9EIxQID<;(D#Crn2`X3 zeFF@kXl`gds?=khPJ`OUHdb#cLDw`co*oCmFr+2(>nAFy@9INC;P!ZS7*69=fV?qd zk6oa*wY2lQJAMzqv?e2})s^VTK}-B&R&+?WashTbJFn)iV@0Y8qTLO(3PkmXa!@lzipP3{W~DDXB6i z(LWN22Ao=(u8XCA`|G{tK>xsp`ddeBU13S_4oZr5DB#~&V{+X$Jz8~dNApnJjaQ5% z(V-)yhK9xdiZ*4JFexhuF%pV-^h0IhL^OsH8dAZA%09--JcoE) zM1>*^4%A>|DaFu;T`b~p96i2CXd3lxT@;m6;xycxH^mD|5i~7|tLv$(u8mI3vdT=; zs`*HV%F(>dF1*;DAlur|^jMNV@##M;YUbz9)?z6ct%TF|yT4@EB0s^yb!Ws=x^W%V z%^lz{V%R-okSqI!13}P|IDDC0aK>y5a|CckOX;i+1bQeOqPw%#_Dl)!A6i@fuv#5q zOCxM9t)`)=jck`{?RAH@|lboKNh5F@}db#?XaF`)0q-hBNHvd3fr(B0i} z{in{K|K&$lwsXy2i|H8&VVa?+%E>-9siq;NNs{5IZpa5)FwiB?jPdJC2HF*A1QKmQLPXw~dnuGsyEQETMy@v#hR<+KypR7MiB*C@n3m zhync|ti7de*RGj3zTm-e`MEd0TQS^o%hPq39w(Y+qNMqL-8lh57zm*-gp+GePo%4C z6Gc@u45Ha3v$45h`*+2o%c<$K^bZo3J_${ed;B~~Zhp`mn}VLcL8|K;5ePi-aYy`` zOQlFo^6~4t9|K^)$vMP1T<9oz0}&RlZNiii!_dRo+1Wo7LdYqTr^JAMuvSnofmN&5 z1Z!(+{+ykaanE1hZZ&`WL^<7-fiMgdd#c5%J)%$%9T4H-_u3!Qs9Y8ULR9bnp&@em9h^7gcZPB;?AX-k0~@vGzYxY@X^oOd^DC(-L+&KM6a zheT-_OLi(2Z|lYBbdi;nbz5U&<2Hb@on&#ps5{Q$WI`S$u8G)NUf znV>lt>1tR|UElNits(JHEJZX+irhq3wjPxupjcRaDaM_zEpW*Wm$CQb=Z8Und*qDU%I zJr1s$HpIP8EM~}I=kiJjJJgR^6t4oWGk_^Pz`-cP?s1@^p_D~^V;jM6gfPl3VLnoq zLMi-72|W7Tn}os23J&pbAO-}cEwg^Vmwz&39@-j5#7Tk!Vwd& zc<&A~1A;S7ngBz=U6Im(^BWQEd{gv=ZE%lGOFp6%VRc<+U?jlXD>k8&;``^1Cofe% zoRjC5RP(}ydNkdLBqk+2^u;fJvFc;~7>->lDJkL0U;QGFJoMPe)fZg++Zo4A|JKIZ z5qZ^Lwz6<*54i0TMcx;_kM3283|maiOk`SI2OBo6WA)Ash;_W}Hn)q4ifYnxbHN&w zkkFRp`ARl zrW?&AkfG=dtoQ6pp>%|%Ax)E1kCRg}g0xm{rfoP34res{KgL0?AZ)o%ZXZ|?cHd}N z2a0o1Qee4VEM03$ES-Du%p+F%SxU*^aDcx(@)E&NguA~y1&=Pl<>a3$Iw@@p0g9>9 zroMjNb+(N2Npnw%0sZ5&;vFTNbn1x+Ayj>B{aaZX8Rw2zu65TxR?UC5bP|d8V3`q= z48Q-RR-g&HUOT~Q@R^A^r7IV*W?K#Yx&&=MIsP#NbcNTgp#nX&x~tm5lkaa?ga&8` zCFvarvT^fvJ9JM^K8S9&!!(1@G%D+xDJiex#PR8Ty3pP;#dW>>?Uf>e5sQqBjFl^v z72ghU*Ijqf(AW?I`p0eSR6|k&g#xvMqLrJeXdjC5@W<$67-?a6;%Vs|+|>nmz_M2rJsdTK7Ln-D{_}u3 zGH*1bQp9=P{PmHS0l}@GEkM@{EY0BcExlCtnD~70^2sNk{DPuKW@qQ};~)R{~= zyuI`tw$%5cbemW@<|^sJ7E|&Q=xy%+r(>`Dd;i`%`a7DF)}}^=MuPYp1{vuoN1VEh zX`19^r}6YFOIf$2l=EliaD2WOp$p2|L;Uqk+iU0LRSGBiFrF9p9>gLpT$Jie8-z9G`m(|7p&{@Vd=y6L9>PU;YY z_WP}JXC--g`2eg~@ora6cFv92*_l7A?1;!O-Lr$=J+%{&kz(JmD~sra$9=_Yq!FfQm-}FHO3HV1!>Iqo!e({pEo&Ljod{iz5=8s=&mP0c z2@{hjbXBo#)kYeIB~tSsltKx)|AXR)HZ2qUHtNj@uVh5lyGzXzwFv|kH=j;u3+2-A^y9~ z5;343z*enVMPXqft5>fHG&eOqc*PZ$o|m1O@%r0E-PV`?R>bPsA@CePkU}YlSfqQL zO!D>f{EM%%tg;p1aoIE7l^*>lj-p^*NKhIIiQ#k-81Bb1Wi$sr2vZ6)Cp&8z0q~+Q zjv#(R(=|$V*7C|*tB^|Z)6Y!iqM7mFb#vPjn<%R5!0B`iXJ%&J@!Ef0EBOSD-IyK7 z%FD~i8-EYD!A4aq6x8)FsP>7&B6wN&WhQ`pKEg_Ykn~l@sJ~DE1rEoeO z{O6r@baeNTlbXQImt=x6sB8@K@6GmTsf>*D&1Gd}j{{_9=f;43ScLKojl8{R2@@xd zXUC46Z7!$ri}B;feQQ{`I=*?|4lcZXGixe(z-xT)Et(~9X%5aTh-aeKK+%@9Y_96U z(sYiR>o;YW53A8T^Pv#)CZsXa(+Rpd$jC*2DS3U-3Y?GhZycI3K`7qd+D>KL2sXI0-x__)e}id{0sW&8b(MC`*xb}KR9#*5;A4;e^CV?> z>fYMc&Dp=%z;B+ZV92sQunbm8g(f7)F2Naj0@1XIrQ2&TT}PKDoj`yvU?fa@fuE|< z8gO{_2;V>GV3PzRlGe^14Bfza1XRQcAuuBr>8XCce$(BI1VZGdCUf=ien2oBk*qCk zCt_J-W@a|z=_Kxl4NJ6@#Eh;#P;%91R6j3Og_2E2B5L7&g8W%T_6Ng zrc8PErI%i6IP0vlK9ScJYqk22wr<^e-d(wpF*$iu)>Q`+6a7mKhr?}Ik>hK7LgJMT zJq(&AnF$(c$)5Mrz1yRpl(55GO~Q;x$z-_$R5f%nU+0%a9wc~AH2?q`VM#hUP{J zCrzfdwz_rtv}r&0`;&j@^?I9I`bW6!g&HpXO9{6=UqO!Xu$`yN-(7UC0P7rz8}%L2e&%A8;+{c2m5wg8rc)!luR0;K*UU z4o;^|bwewE|JTa^#JRnE>)aet5;QObYir=SH8nUKPV(}`-1GQjkC%Vx+An=_XKf6s zAKl6;b^@?``Lcnww${JhamO9Av$C?D^Z9(TvNgc1uQV|2N9%cfNe!lEfxdU!s{ngk zl+zkLKnn#>dgE);BS9S2#`Wjp=cQ_?A^^wh+Hr0OO*;5RfAFrKv z{&~CpzhudhM~^%1xcNSxZ<|B6ug^Bu4s!l&MSSVOa=HUyFyubcQ-RO~Dr~nmo>?I2 zuPfq-B}Ei>41%tMain~7!X9cV44k^8rM}sYXg;VIP-tL=Ny!@vK>KizU^sHvHMA(D z5GVqs$q#S24@+7AYUY@Dt~oOYOpD5f5Z`}b0}&KyX{oRL;qG7m8L-kaGC$eFHU`cA zuC=zdHs<8yY%+9XNC+__9F90aP}Vd;S$i0dQ!+8jg{A|RJt1Z{VP}Wx1 zY^!KsV^uevxCGKN62Ls%%V(u6uqkvbWfIU6$VkupVDBsxXd2ypz5M+j&oXcP7%uqK z$yibzMj!`W*GNzH^Q~XpLseb#sDtO7-^>zXua0*ws~pXlq2dG!CHO^%B0*VNQ(ns(f@pN$!lck#rD6PCJNc7@k#n_9Wk!jmnE2;=i~F!Je)ITfF&!JaOcyj7!aCWS$Ej7^IEhS&BU-Q z%+Mf1AE@mfZR?AGJ23%(uHhizaQHCu=n8*g0=M7y3`W%=XPfx-tOq9~zv$5^#Ib9PZ8-jV`;_-`K z?tXd$!)_l_$7kAt4TlrnqXQJ}W6PG(ju>%xd?~n`j(tBsD3m4;nnF5U{O!Ic`P7^# zoPOFIOv^fK-dcJ}5)VGTkUu~2GKrdoLkN|#4b4)d`m2*k(>YV?p4OF)GVi*qM;}dRaZ)^EJz@-Z=rM#^CfAgASQ2b&HC6_$i-{0SEnbs+$8Sw~BqocE%r&qU9Gn7a-i3|lJSaOJz1oz%;oFZC) z6S9~#-p`5S3=+aUG&Z%+5dfv>c;dWv%KyJ)s|6rz2`C{PSXPLjCym5}glNQ~?Um09 zbo()ug(oSVdmelSkD+t%S;wO}9RK^o955UXes%X_Y%8rM-q6*csc`Cuo%LPZ|7JBq z;V@peH^>3CZx3TY*a|ZJ5ikC#3 z70Xsr-`L7Ur_aUXi~Cr{G07;YXBaxBX(6L2!KfbHzPNzVfxFph$=rVbGraQp3f!7T zKmtM&rjqmrOcV;A&lgHhOZ~}Bzxw$fZ~oa$0|33fJ^$M%BnG|zjdgZ*0&}5 z=m8%C`Y~*#X;NKX9U2@Q+&*pEw1Jshe35qKmN%xafiYPT|~E`*!%Dh0zv`eGcx$wgHMqnbmq<~ z#BhFu@Leg~E(iUC0lxFgzjE`PkMQiPOWClwl&-#hn%cYAvb~(7!~`UYdFjnn+Mu?R#ZqWpDKL_Q~AbTm}XP{^uZv z*xb*<%BD`8N@=Oh$ewxTnG;%CT5hSUtGh@_m1Idf>=i=r^=mFiS`ki8>*mA)n4IWD zcQ~Un5!7BATPY9@8?92e*j77CSo2~eW{{APg{7S2Cdc7**wbW@7D(|vpxf78?^RWg zrUFvDN7>arFjVy5uxHUp5IVRF7Og2G`^*JQ_a{bO&3?9_v70N1T+Tb|1fG2E zZJvGZZMuhs3Gbepi$dV>xQ8{tj!A`uzb-1;`qtsNw_-p)%xu!6NmNu+L~*LbxN+ky z2d?hu=(s!>3^^1EB_(+|nar9#nQ3`GW~UBQ=<8v6b^^M?Wdm=oTvpmr>CtN|r9pRJ znD!xyEnSjH<8p{|C9$*E@1ZT*#v_@%FD}1OiZM^yPMY5 zHde1$&APQ~0hlsrER{7an5G#;_wK?Suh$bg{`eDa?C$AWSh9UbEx`A__g((}_j_YN zkJ$&?wbx$Df&~k>^wLWK`1#L&p772)@0{My(D2i?wzkuxln5a(be)uBKc^o*gR^Ik zWpZkmxc=?T%}YRcdm-}PDKWN(m)NDXLReT*F=BzGGes%;%{SjnPEO8#$-0h?4sN~mR_?$5{^)n@D@%KL zhn>4;W@eTpBqaQ~tgP%|A%yb#y`-n-QC?nt*zKtp&<|s~?z-!EV)6f9Fel?#lU8EPRA9s)4CveIOlC&o}x{XLRnFon2~C z$E;8Yq)?zqMnaPIkucTmI$p1fZFM0Meeq=FBvIRLF)23=GzSyM`)Td*5N3$n1SgFx zLs&!I6xa3yRaK;&U%?O~O`Mvz=-tEji{RC#r|2+8xd5Ga5gc3**t)&yA zDzecn>UFWRvVm`1{~K0rC}mnsDqfG9o?w`hCXFF0E0e4=KLum5aQS`YW~XCWR`d#A z!w`Zy9(tad_5d%v_yXza=?7f@Kp;SVemKSC@!JDcX_W`q!2cinZal9H02R#sMCH#j($qZGO& z0cA3IY#zV8{RYP5X4AiQF;iVNIE5s^so^v#kgq?!?B={-(R7J-ov z1H)iAHClRy7zsis5=WfJ#0-Z?iFc5gAvO5 zmp^i(?VlLXk1#vmP+-kuY8<&{@X-nMPqmz$cJF0w3hhG~JcOh9q|Stsy?FI+}4 z5!$-i@C?^7)7M2|PCQPB3l*}EQlbli5@Mgj3sscR8zuJ8BnYQ{NGN+Y8cG9Q+IhUL z+v+hAl(I8*saa@@R`y8{0%a-i=q%gZ#yKbD(BC=2&PW!%{Mp21PavWU{7H$Vcy!R5 zAfr=Qr3Gl<^MK}HsCSSZ+e=unemlD1VAvm%oewJ!T)j zMZ@?#3A~A2U0t6Ihr?eD1cL=if|M49p)qyhSQcD%9`okS!yIg-t7IvTkq+ihPa-|l z3*pfzNHSVqznf3q3-D1=Z&#Db=yyh=gZI_u+bq3(h^Y6UAa0FiMJ=2@D-RbkS=o=s|J`r7*;PxPcAu1Z$&~24y zTH53wmR#wJ5 zdd&X&_Kk0RgNGh^XxG;#oN$8P*48#Q5D0v8XlUqr!C=UvX##0U3|(X5gnZ`An$EZX z?@}_e(|P#5hbdGwoLXQoA=eMmfg}u;h~~)pdx*T~71=(w%%M(-6`)Cqx(w1ph}@KD z_noj0C{t++SQeH;U=BH{8-}o+g!1Ju)IUICVjMlqb-3fb1S1;K8OLyU8)Fl7d=8WL zo*{Cxd>|!0ItaV-xbyW^S_3W?E?UkVcl?eUZ~O`RLCkW?%*>>{y`x@;q^p(cU4NwR zml)8G63frer@r1EBQ<&QDkG@H7-vCBW zJ5`%kFgKx^1OtT2jS&ihX8d^oADQ*ED44KVM(w|Fa#0Hpr}=_vfjhOt?g_mE@osX1W2yB>a#rl_~W=- zt`B^Pp-_nAao+fVX=>eBSt*&t#aj)Z?}Mka zhQndf($eJcu=8Ha>iR(p=rKDiZTj@-l$7kA-}jyGd?%@-q-0!wfB)BNYHGeQG&F3e zXqA^Hpm6*cuDJLd=3j6YC(ND2P){?R)y1rOXEiCIN=}^=N2=e4X1Hw3DFre*5jL9F zi(Rl(QO`YEGNT07fKOJS7?5?yG_M}$u%+m6o2qDcsxNQ#aO<4`NWEfif{Mz^?hr2c-SG( zP(q;#jpQUBSsAIEd)`^hEXd-5%P(SkaS1z%wvcG`Fg9Gt@e|{5dp%%jU?d+y!SYkyh1*H|8{Gv3Ju<*D&rr+5q4IcHY+C*MF*MnNBICtE;D<&YnJs%c=nI|MIVVdj9ET7vylx zm7l}waY-Eby%{lp^vp&YcVrU;NNeRFxc0<+gk~NQkq?ZFEpi4 zf!v(jb;lon{9igdJKtHhY}v@@?>e3C;YdV=M%#oBWK*Y31<28~a3N4}B!WB!^kdLY zJn_W6zAh;#+4S%~9=`bA`|h3J-#?h$)z$I!a3nI-ibQ-7(*|hoU_Vd1un>Sh{P97~ zJ$WvdU;ZhwPFR5HcJog44m$b=Nek9+%9KQ`KtF>f@vEZUn&Rn>jo@yfxg>(eeM=JG+=Dt|*TG z@13vx9%f+|MruI>SuKk;ba$g5g#;TPOd9%7L(}lEfQ_amB)k~Y_*4@$(Hh&Q8j^+w zqw%RVZSlbO1GpeKN)vOEboB>Cz>1b#X?KWarMOW7Q)^jwn8#ue`iGaMbVje`*-UBSlfN*)fbW zVvMiOmLbL%X*P}AE*E)o4a(7V@_0OCx7o?#a!_E~7Ao9ilI}6cqw8eoI?1w{39O&| zURBC`TgwSx#26@35hJ^(sz$o5_k}{Cqg7Q^)ipIWd4IqEYuCP7v#$*eqyo-chYo!} z&%^ZeG*wi*Mu7J_!)WjeZ4tb5IPG@S*ViK$3`(YHdLog??ocT7q0i^L<954$x7ln< zoO1$W#2CvMXZDdhF(wf>h%t%yYKMSjC&3{RW6RsCorRQfAdE39Gdo*$yFFnR6nq~H z2G5zM`EF@xsRjV8t*zN|Pd9Jgd}g0cpC$%q*Mq@IvMh@%%c6KZPD@KmYZ`honWO^; z4iKOWE6SE4p%sFcl8TCor}hyM9~>NXL?V&BMMXuQ<>lsn?eqD5k!0x)MNy^|MM+4K zM3O9#EK8)w3Ngkr&R~^6bDrHVNzxMMJf$egw9DhZ=W@A5{C@vcuh)Cw;K74$A3Jue zoQVDsY6b!U6cqgPI&zAV-=!$36_3YhY;25bYip^aql1#k>mNc!X&M@|i z7+vu4vHCr{X_^=x9|v2`aZLia4d8ZXXQ!g;y0fFBqt4^;a9Ng((b3U8nxm~aLRVFF90XO>)CsrSJsgk67j#`8uC1*dsIRY&H8(ep1HhFl zR{#K~PMrb(c)ec4VlfO24gIS=F~$c{sZ@G!a8RzQszPC5AS}%a_U(BmKR&5fR#p~< z!{L%>G`eZmu3e?&<>mQ@41AXp#h0Dx$e zxYN1&9l-S^;24l)+e1LQ%b4v3=f-<$oyqxDAwGd%y#7bAxBlW6$6e+#_|G^ zROkmnPgTs6WuFk7K(OA>v^Rwi1OkCTAP}r0{sh|tlGL}+QY!!e002ovPDHLkV1mUK B4E+EA diff --git a/vendor/github.com/DATA-DOG/godog/options.go b/vendor/github.com/DATA-DOG/godog/options.go deleted file mode 100644 index 064b414f1..000000000 --- a/vendor/github.com/DATA-DOG/godog/options.go +++ /dev/null @@ -1,59 +0,0 @@ -package godog - -import ( - "io" -) - -// Options are suite run options -// flags are mapped to these options. -// -// It can also be used together with godog.RunWithOptions -// to run test suite from go source directly -// -// See the flags for more details -type Options struct { - // Print step definitions found and exit - ShowStepDefinitions bool - - // Randomize, if not `0`, will be used to run scenarios in a random order. - // - // Randomizing scenario order is especially helpful for detecting - // situations where you have state leaking between scenarios, which can - // cause flickering or fragile tests. - // - // The default value of `0` means "do not randomize". - // - // The magic value of `-1` means "pick a random seed for me", and godog will - // assign a seed on it's own during the `RunWithOptions` phase, similar to if - // you specified `--random` on the command line. - // - // Any other value will be used as the random seed for shuffling. Re-using the - // same seed will allow you to reproduce the shuffle order of a previous run - // to isolate an error condition. - Randomize int64 - - // Stops on the first failure - StopOnFailure bool - - // Fail suite when there are pending or undefined steps - Strict bool - - // Forces ansi color stripping - NoColors bool - - // Various filters for scenarios parsed - // from feature files - Tags string - - // The formatter name - Format string - - // Concurrency rate, not all formatters accepts this - Concurrency int - - // All feature file paths - Paths []string - - // Where it should print formatter output - Output io.Writer -} diff --git a/vendor/github.com/DATA-DOG/godog/run.go b/vendor/github.com/DATA-DOG/godog/run.go deleted file mode 100644 index c1c488fa4..000000000 --- a/vendor/github.com/DATA-DOG/godog/run.go +++ /dev/null @@ -1,232 +0,0 @@ -package godog - -import ( - "fmt" - "io" - "os" - "path/filepath" - "runtime" - "strconv" - "strings" - - "github.com/DATA-DOG/godog/colors" -) - -const ( - exitSuccess int = iota - exitFailure - exitOptionError -) - -type initializer func(*Suite) - -type runner struct { - randomSeed int64 - stopOnFailure, strict bool - features []*feature - fmt Formatter - initializer initializer -} - -func (r *runner) concurrent(rate int) (failed bool) { - queue := make(chan int, rate) - for i, ft := range r.features { - queue <- i // reserve space in queue - go func(fail *bool, feat *feature) { - defer func() { - <-queue // free a space in queue - }() - if r.stopOnFailure && *fail { - return - } - suite := &Suite{ - fmt: r.fmt, - randomSeed: r.randomSeed, - stopOnFailure: r.stopOnFailure, - strict: r.strict, - features: []*feature{feat}, - } - r.initializer(suite) - suite.run() - if suite.failed { - *fail = true - } - }(&failed, ft) - } - // wait until last are processed - for i := 0; i < rate; i++ { - queue <- i - } - close(queue) - - // print summary - r.fmt.Summary() - return -} - -func (r *runner) run() bool { - suite := &Suite{ - fmt: r.fmt, - randomSeed: r.randomSeed, - stopOnFailure: r.stopOnFailure, - strict: r.strict, - features: r.features, - } - r.initializer(suite) - suite.run() - - r.fmt.Summary() - return suite.failed -} - -// RunWithOptions is same as Run function, except -// it uses Options provided in order to run the -// test suite without parsing flags -// -// This method is useful in case if you run -// godog in for example TestMain function together -// with go tests -// -// The exit codes may vary from: -// 0 - success -// 1 - failed -// 2 - command line usage error -// 128 - or higher, os signal related error exit codes -// -// If there are flag related errors they will -// be directed to os.Stderr -func RunWithOptions(suite string, contextInitializer func(suite *Suite), opt Options) int { - var output io.Writer = os.Stdout - if nil != opt.Output { - output = opt.Output - } - - if opt.NoColors { - output = colors.Uncolored(output) - } else { - output = colors.Colored(output) - } - - if opt.ShowStepDefinitions { - s := &Suite{} - contextInitializer(s) - s.printStepDefinitions(output) - return exitOptionError - } - - if len(opt.Paths) == 0 { - inf, err := os.Stat("features") - if err == nil && inf.IsDir() { - opt.Paths = []string{"features"} - } - } - - if opt.Concurrency > 1 && !supportsConcurrency(opt.Format) { - fmt.Fprintln(os.Stderr, fmt.Errorf("format \"%s\" does not support concurrent execution", opt.Format)) - return exitOptionError - } - formatter := findFmt(opt.Format) - if nil == formatter { - var names []string - for name := range AvailableFormatters() { - names = append(names, name) - } - fmt.Fprintln(os.Stderr, fmt.Errorf( - `unregistered formatter name: "%s", use one of: %s`, - opt.Format, - strings.Join(names, ", "), - )) - return exitOptionError - } - - features, err := parseFeatures(opt.Tags, opt.Paths) - if err != nil { - fmt.Fprintln(os.Stderr, err) - return exitOptionError - } - - r := runner{ - fmt: formatter(suite, output), - initializer: contextInitializer, - features: features, - randomSeed: opt.Randomize, - stopOnFailure: opt.StopOnFailure, - strict: opt.Strict, - } - - // store chosen seed in environment, so it could be seen in formatter summary report - os.Setenv("GODOG_SEED", strconv.FormatInt(r.randomSeed, 10)) - // determine tested package - _, filename, _, _ := runtime.Caller(1) - os.Setenv("GODOG_TESTED_PACKAGE", runsFromPackage(filename)) - - var failed bool - if opt.Concurrency > 1 { - failed = r.concurrent(opt.Concurrency) - } else { - failed = r.run() - } - if failed && opt.Format != "events" { - return exitFailure - } - return exitSuccess -} - -func runsFromPackage(fp string) string { - dir := filepath.Dir(fp) - for _, gp := range gopaths { - gp = filepath.Join(gp, "src") - if strings.Index(dir, gp) == 0 { - return strings.TrimLeft(strings.Replace(dir, gp, "", 1), string(filepath.Separator)) - } - } - return dir -} - -// Run creates and runs the feature suite. -// Reads all configuration options from flags. -// uses contextInitializer to register contexts -// -// the concurrency option allows runner to -// initialize a number of suites to be run -// separately. Only progress formatter -// is supported when concurrency level is -// higher than 1 -// -// contextInitializer must be able to register -// the step definitions and event handlers. -// -// The exit codes may vary from: -// 0 - success -// 1 - failed -// 2 - command line usage error -// 128 - or higher, os signal related error exit codes -// -// If there are flag related errors they will -// be directed to os.Stderr -func Run(suite string, contextInitializer func(suite *Suite)) int { - var opt Options - opt.Output = colors.Colored(os.Stdout) - flagSet := FlagSet(&opt) - if err := flagSet.Parse(os.Args[1:]); err != nil { - fmt.Fprintln(os.Stderr, err) - return exitOptionError - } - - opt.Paths = flagSet.Args() - - return RunWithOptions(suite, contextInitializer, opt) -} - -func supportsConcurrency(format string) bool { - switch format { - case "events": - case "junit": - case "pretty": - case "cucumber": - default: - return true // supports concurrency - } - - return false // does not support concurrency -} diff --git a/vendor/github.com/DATA-DOG/godog/stacktrace.go b/vendor/github.com/DATA-DOG/godog/stacktrace.go deleted file mode 100644 index ed594c941..000000000 --- a/vendor/github.com/DATA-DOG/godog/stacktrace.go +++ /dev/null @@ -1,141 +0,0 @@ -package godog - -import ( - "fmt" - "go/build" - "io" - "path" - "path/filepath" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type stackFrame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f stackFrame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f stackFrame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -func trimGoPath(file string) string { - for _, p := range filepath.SplitList(build.Default.GOPATH) { - file = strings.Replace(file, filepath.Join(p, "src")+string(filepath.Separator), "", 1) - } - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f stackFrame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d -func (f stackFrame) Format(s fmt.State, verb rune) { - funcname := func(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] - } - - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), trimGoPath(file)) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := stackFrame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func callStack() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// fundamental is an error that has a message and a stack, but no caller. -type traceError struct { - msg string - *stack -} - -func (f *traceError) Error() string { return f.msg } - -func (f *traceError) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} diff --git a/vendor/github.com/DATA-DOG/godog/stepdef.go b/vendor/github.com/DATA-DOG/godog/stepdef.go deleted file mode 100644 index 952c95498..000000000 --- a/vendor/github.com/DATA-DOG/godog/stepdef.go +++ /dev/null @@ -1,211 +0,0 @@ -package godog - -import ( - "fmt" - "os" - "path/filepath" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - - "github.com/DATA-DOG/godog/gherkin" -) - -var matchFuncDefRef = regexp.MustCompile(`\(([^\)]+)\)`) - -// Steps allows to nest steps -// instead of returning an error in step func -// it is possible to return combined steps: -// -// func multistep(name string) godog.Steps { -// return godog.Steps{ -// fmt.Sprintf(`an user named "%s"`, name), -// fmt.Sprintf(`user "%s" is authenticated`, name), -// } -// } -// -// These steps will be matched and executed in -// sequential order. The first one which fails -// will result in main step failure. -type Steps []string - -// StepDef is a registered step definition -// contains a StepHandler and regexp which -// is used to match a step. Args which -// were matched by last executed step -// -// This structure is passed to the formatter -// when step is matched and is either failed -// or successful -type StepDef struct { - args []interface{} - hv reflect.Value - Expr *regexp.Regexp - Handler interface{} - - // multistep related - nested bool - undefined []string -} - -func (sd *StepDef) definitionID() string { - ptr := sd.hv.Pointer() - f := runtime.FuncForPC(ptr) - file, line := f.FileLine(ptr) - dir := filepath.Dir(file) - - fn := strings.Replace(f.Name(), dir, "", -1) - var parts []string - for _, gr := range matchFuncDefRef.FindAllStringSubmatch(fn, -1) { - parts = append(parts, strings.Trim(gr[1], "_.")) - } - if len(parts) > 0 { - // case when suite is a structure with methods - fn = strings.Join(parts, ".") - } else { - // case when steps are just plain funcs - fn = strings.Trim(fn, "_.") - } - - if pkg := os.Getenv("GODOG_TESTED_PACKAGE"); len(pkg) > 0 { - fn = strings.Replace(fn, pkg, "", 1) - fn = strings.TrimLeft(fn, ".") - fn = strings.Replace(fn, "..", ".", -1) - } - - return fmt.Sprintf("%s:%d -> %s", filepath.Base(file), line, fn) -} - -// run a step with the matched arguments using -// reflect -func (sd *StepDef) run() interface{} { - typ := sd.hv.Type() - if len(sd.args) < typ.NumIn() { - return fmt.Errorf("func expects %d arguments, which is more than %d matched from step", typ.NumIn(), len(sd.args)) - } - var values []reflect.Value - for i := 0; i < typ.NumIn(); i++ { - param := typ.In(i) - switch param.Kind() { - case reflect.Int: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 0) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int(v))) - case reflect.Int64: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int64: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int64(v))) - case reflect.Int32: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 32) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int32: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int32(v))) - case reflect.Int16: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 16) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int16: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int16(v))) - case reflect.Int8: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseInt(s, 10, 8) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to int8: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(int8(v))) - case reflect.String: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - values = append(values, reflect.ValueOf(s)) - case reflect.Float64: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseFloat(s, 64) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to float64: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(v)) - case reflect.Float32: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - v, err := strconv.ParseFloat(s, 32) - if err != nil { - return fmt.Errorf(`cannot convert argument %d: "%s" to float32: %s`, i, s, err) - } - values = append(values, reflect.ValueOf(float32(v))) - case reflect.Ptr: - arg := sd.args[i] - switch param.Elem().String() { - case "gherkin.DocString": - v, ok := arg.(*gherkin.DocString) - if !ok { - return fmt.Errorf(`cannot convert argument %d: "%v" of type "%T" to *gherkin.DocString`, i, arg, arg) - } - values = append(values, reflect.ValueOf(v)) - case "gherkin.DataTable": - v, ok := arg.(*gherkin.DataTable) - if !ok { - return fmt.Errorf(`cannot convert argument %d: "%v" of type "%T" to *gherkin.DocString`, i, arg, arg) - } - values = append(values, reflect.ValueOf(v)) - default: - return fmt.Errorf("the argument %d type %T is not supported", i, arg) - } - case reflect.Slice: - switch param { - case typeOfBytes: - s, err := sd.shouldBeString(i) - if err != nil { - return err - } - values = append(values, reflect.ValueOf([]byte(s))) - default: - return fmt.Errorf("the slice argument %d type %s is not supported", i, param.Kind()) - } - default: - return fmt.Errorf("the argument %d type %s is not supported", i, param.Kind()) - } - } - return sd.hv.Call(values)[0].Interface() -} - -func (sd *StepDef) shouldBeString(idx int) (string, error) { - arg := sd.args[idx] - s, ok := arg.(string) - if !ok { - return "", fmt.Errorf(`cannot convert argument %d: "%v" of type "%T" to string`, idx, arg, arg) - } - return s, nil -} diff --git a/vendor/github.com/DATA-DOG/godog/suite.go b/vendor/github.com/DATA-DOG/godog/suite.go deleted file mode 100644 index a3c75debe..000000000 --- a/vendor/github.com/DATA-DOG/godog/suite.go +++ /dev/null @@ -1,804 +0,0 @@ -package godog - -import ( - "bytes" - "fmt" - "io" - "math/rand" - "os" - "path/filepath" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "unicode/utf8" - - "github.com/DATA-DOG/godog/gherkin" -) - -var errorInterface = reflect.TypeOf((*error)(nil)).Elem() -var typeOfBytes = reflect.TypeOf([]byte(nil)) - -type feature struct { - *gherkin.Feature - Content []byte `json:"-"` - Path string `json:"path"` - scenarios map[int]bool - order int -} - -// ErrUndefined is returned in case if step definition was not found -var ErrUndefined = fmt.Errorf("step is undefined") - -// ErrPending should be returned by step definition if -// step implementation is pending -var ErrPending = fmt.Errorf("step implementation is pending") - -// Suite allows various contexts -// to register steps and event handlers. -// -// When running a test suite, the instance of Suite -// is passed to all functions (contexts), which -// have it as a first and only argument. -// -// Note that all event hooks does not catch panic errors -// in order to have a trace information. Only step -// executions are catching panic error since it may -// be a context specific error. -type Suite struct { - steps []*StepDef - features []*feature - fmt Formatter - - failed bool - randomSeed int64 - stopOnFailure bool - strict bool - - // suite event handlers - beforeSuiteHandlers []func() - beforeFeatureHandlers []func(*gherkin.Feature) - beforeScenarioHandlers []func(interface{}) - beforeStepHandlers []func(*gherkin.Step) - afterStepHandlers []func(*gherkin.Step, error) - afterScenarioHandlers []func(interface{}, error) - afterFeatureHandlers []func(*gherkin.Feature) - afterSuiteHandlers []func() -} - -// Step allows to register a *StepDef in Godog -// feature suite, the definition will be applied -// to all steps matching the given Regexp expr. -// -// It will panic if expr is not a valid regular -// expression or stepFunc is not a valid step -// handler. -// -// Note that if there are two definitions which may match -// the same step, then only the first matched handler -// will be applied. -// -// If none of the *StepDef is matched, then -// ErrUndefined error will be returned when -// running steps. -func (s *Suite) Step(expr interface{}, stepFunc interface{}) { - var regex *regexp.Regexp - - switch t := expr.(type) { - case *regexp.Regexp: - regex = t - case string: - regex = regexp.MustCompile(t) - case []byte: - regex = regexp.MustCompile(string(t)) - default: - panic(fmt.Sprintf("expecting expr to be a *regexp.Regexp or a string, got type: %T", expr)) - } - - v := reflect.ValueOf(stepFunc) - typ := v.Type() - if typ.Kind() != reflect.Func { - panic(fmt.Sprintf("expected handler to be func, but got: %T", stepFunc)) - } - - if typ.NumOut() != 1 { - panic(fmt.Sprintf("expected handler to return only one value, but it has: %d", typ.NumOut())) - } - - def := &StepDef{ - Handler: stepFunc, - Expr: regex, - hv: v, - } - - typ = typ.Out(0) - switch typ.Kind() { - case reflect.Interface: - if !typ.Implements(errorInterface) { - panic(fmt.Sprintf("expected handler to return an error, but got: %s", typ.Kind())) - } - case reflect.Slice: - if typ.Elem().Kind() != reflect.String { - panic(fmt.Sprintf("expected handler to return []string for multistep, but got: []%s", typ.Kind())) - } - def.nested = true - default: - panic(fmt.Sprintf("expected handler to return an error or []string, but got: %s", typ.Kind())) - } - - s.steps = append(s.steps, def) -} - -// BeforeSuite registers a function or method -// to be run once before suite runner. -// -// Use it to prepare the test suite for a spin. -// Connect and prepare database for instance... -func (s *Suite) BeforeSuite(fn func()) { - s.beforeSuiteHandlers = append(s.beforeSuiteHandlers, fn) -} - -// BeforeFeature registers a function or method -// to be run once before every feature execution. -// -// If godog is run with concurrency option, it will -// run every feature per goroutine. So user may choose -// whether to isolate state within feature context or -// scenario. -// -// Best practice is not to have any state dependency on -// every scenario, but in some cases if VM for example -// needs to be started it may take very long for each -// scenario to restart it. -// -// Use it wisely and avoid sharing state between scenarios. -func (s *Suite) BeforeFeature(fn func(*gherkin.Feature)) { - s.beforeFeatureHandlers = append(s.beforeFeatureHandlers, fn) -} - -// BeforeScenario registers a function or method -// to be run before every scenario or scenario outline. -// -// The interface argument may be *gherkin.Scenario -// or *gherkin.ScenarioOutline -// -// It is a good practice to restore the default state -// before every scenario so it would be isolated from -// any kind of state. -func (s *Suite) BeforeScenario(fn func(interface{})) { - s.beforeScenarioHandlers = append(s.beforeScenarioHandlers, fn) -} - -// BeforeStep registers a function or method -// to be run before every scenario -func (s *Suite) BeforeStep(fn func(*gherkin.Step)) { - s.beforeStepHandlers = append(s.beforeStepHandlers, fn) -} - -// AfterStep registers an function or method -// to be run after every scenario -// -// It may be convenient to return a different kind of error -// in order to print more state details which may help -// in case of step failure -// -// In some cases, for example when running a headless -// browser, to take a screenshot after failure. -func (s *Suite) AfterStep(fn func(*gherkin.Step, error)) { - s.afterStepHandlers = append(s.afterStepHandlers, fn) -} - -// AfterScenario registers an function or method -// to be run after every scenario or scenario outline -// -// The interface argument may be *gherkin.Scenario -// or *gherkin.ScenarioOutline -func (s *Suite) AfterScenario(fn func(interface{}, error)) { - s.afterScenarioHandlers = append(s.afterScenarioHandlers, fn) -} - -// AfterFeature registers a function or method -// to be run once after feature executed all scenarios. -func (s *Suite) AfterFeature(fn func(*gherkin.Feature)) { - s.afterFeatureHandlers = append(s.afterFeatureHandlers, fn) -} - -// AfterSuite registers a function or method -// to be run once after suite runner -func (s *Suite) AfterSuite(fn func()) { - s.afterSuiteHandlers = append(s.afterSuiteHandlers, fn) -} - -func (s *Suite) run() { - // run before suite handlers - for _, f := range s.beforeSuiteHandlers { - f() - } - // run features - for _, f := range s.features { - s.runFeature(f) - if s.failed && s.stopOnFailure { - // stop on first failure - break - } - } - // run after suite handlers - for _, f := range s.afterSuiteHandlers { - f() - } -} - -func (s *Suite) matchStep(step *gherkin.Step) *StepDef { - def := s.matchStepText(step.Text) - if def != nil && step.Argument != nil { - def.args = append(def.args, step.Argument) - } - return def -} - -func (s *Suite) runStep(step *gherkin.Step, prevStepErr error) (err error) { - match := s.matchStep(step) - s.fmt.Defined(step, match) - - // user multistep definitions may panic - defer func() { - if e := recover(); e != nil { - err = &traceError{ - msg: fmt.Sprintf("%v", e), - stack: callStack(), - } - } - - if prevStepErr != nil { - return - } - - if err == ErrUndefined { - return - } - - switch err { - case nil: - s.fmt.Passed(step, match) - case ErrPending: - s.fmt.Pending(step, match) - default: - s.fmt.Failed(step, match, err) - } - - // run after step handlers - for _, f := range s.afterStepHandlers { - f(step, err) - } - }() - - if undef, err := s.maybeUndefined(step.Text, step.Argument); err != nil { - return err - } else if len(undef) > 0 { - if match != nil { - match = &StepDef{ - args: match.args, - hv: match.hv, - Expr: match.Expr, - Handler: match.Handler, - nested: match.nested, - undefined: undef, - } - } - s.fmt.Undefined(step, match) - return ErrUndefined - } - - if prevStepErr != nil { - s.fmt.Skipped(step, match) - return nil - } - - // run before step handlers - for _, f := range s.beforeStepHandlers { - f(step) - } - - err = s.maybeSubSteps(match.run()) - return -} - -func (s *Suite) maybeUndefined(text string, arg interface{}) ([]string, error) { - step := s.matchStepText(text) - if nil == step { - return []string{text}, nil - } - - var undefined []string - if !step.nested { - return undefined, nil - } - - if arg != nil { - step.args = append(step.args, arg) - } - - for _, next := range step.run().(Steps) { - lines := strings.Split(next, "\n") - // @TODO: we cannot currently parse table or content body from nested steps - if len(lines) > 1 { - return undefined, fmt.Errorf("nested steps cannot be multiline and have table or content body argument") - } - if len(lines[0]) > 0 && lines[0][len(lines[0])-1] == ':' { - return undefined, fmt.Errorf("nested steps cannot be multiline and have table or content body argument") - } - undef, err := s.maybeUndefined(next, nil) - if err != nil { - return undefined, err - } - undefined = append(undefined, undef...) - } - return undefined, nil -} - -func (s *Suite) maybeSubSteps(result interface{}) error { - if nil == result { - return nil - } - - if err, ok := result.(error); ok { - return err - } - - steps, ok := result.(Steps) - if !ok { - return fmt.Errorf("unexpected error, should have been []string: %T - %+v", result, result) - } - - for _, text := range steps { - if def := s.matchStepText(text); def == nil { - return ErrUndefined - } else if err := s.maybeSubSteps(def.run()); err != nil { - return fmt.Errorf("%s: %+v", text, err) - } - } - return nil -} - -func (s *Suite) matchStepText(text string) *StepDef { - for _, h := range s.steps { - if m := h.Expr.FindStringSubmatch(text); len(m) > 0 { - var args []interface{} - for _, m := range m[1:] { - args = append(args, m) - } - - // since we need to assign arguments - // better to copy the step definition - return &StepDef{ - args: args, - hv: h.hv, - Expr: h.Expr, - Handler: h.Handler, - nested: h.nested, - } - } - } - return nil -} - -func (s *Suite) runSteps(steps []*gherkin.Step) (err error) { - for _, step := range steps { - stepErr := s.runStep(step, err) - switch stepErr { - case ErrUndefined: - // do not overwrite failed error - if err == ErrUndefined || err == nil { - err = stepErr - } - case ErrPending: - err = stepErr - case nil: - default: - err = stepErr - } - } - return -} - -func (s *Suite) skipSteps(steps []*gherkin.Step) { - for _, step := range steps { - s.fmt.Skipped(step, s.matchStep(step)) - } -} - -func (s *Suite) runOutline(outline *gherkin.ScenarioOutline, b *gherkin.Background) (failErr error) { - s.fmt.Node(outline) - - for _, ex := range outline.Examples { - example, hasExamples := examples(ex) - if !hasExamples { - // @TODO: may need to print empty example node, but - // for backward compatibility, cannot cast to *gherkin.ExamplesBase - // at the moment - continue - } - - s.fmt.Node(example) - placeholders := example.TableHeader.Cells - groups := example.TableBody - - for _, group := range groups { - if !isEmptyScenario(outline) { - for _, f := range s.beforeScenarioHandlers { - f(outline) - } - } - var steps []*gherkin.Step - for _, outlineStep := range outline.Steps { - text := outlineStep.Text - for i, placeholder := range placeholders { - text = strings.Replace(text, "<"+placeholder.Value+">", group.Cells[i].Value, -1) - } - - // translate argument - arg := outlineStep.Argument - switch t := outlineStep.Argument.(type) { - case *gherkin.DataTable: - tbl := &gherkin.DataTable{ - Node: t.Node, - Rows: make([]*gherkin.TableRow, len(t.Rows)), - } - for i, row := range t.Rows { - cells := make([]*gherkin.TableCell, len(row.Cells)) - for j, cell := range row.Cells { - trans := cell.Value - for i, placeholder := range placeholders { - trans = strings.Replace(trans, "<"+placeholder.Value+">", group.Cells[i].Value, -1) - } - cells[j] = &gherkin.TableCell{ - Node: cell.Node, - Value: trans, - } - } - tbl.Rows[i] = &gherkin.TableRow{ - Node: row.Node, - Cells: cells, - } - } - arg = tbl - case *gherkin.DocString: - trans := t.Content - for i, placeholder := range placeholders { - trans = strings.Replace(trans, "<"+placeholder.Value+">", group.Cells[i].Value, -1) - } - arg = &gherkin.DocString{ - Node: t.Node, - Content: trans, - ContentType: t.ContentType, - Delimitter: t.Delimitter, - } - } - - // clone a step - step := &gherkin.Step{ - Node: outlineStep.Node, - Text: text, - Keyword: outlineStep.Keyword, - Argument: arg, - } - steps = append(steps, step) - } - - // run example table row - s.fmt.Node(group) - - if b != nil { - steps = append(b.Steps, steps...) - } - - err := s.runSteps(steps) - - if !isEmptyScenario(outline) { - for _, f := range s.afterScenarioHandlers { - f(outline, err) - } - } - - if s.shouldFail(err) { - failErr = err - if s.stopOnFailure { - return - } - } - } - } - return -} - -func (s *Suite) shouldFail(err error) bool { - if err == nil { - return false - } - - if err == ErrUndefined || err == ErrPending { - return s.strict - } - - return true -} - -func (s *Suite) runFeature(f *feature) { - if !isEmptyFeature(f.Feature) { - for _, fn := range s.beforeFeatureHandlers { - fn(f.Feature) - } - } - - s.fmt.Feature(f.Feature, f.Path, f.Content) - - // make a local copy of the feature scenario defenitions, - // then shuffle it if we are randomizing scenarios - scenarios := make([]interface{}, len(f.ScenarioDefinitions)) - if s.randomSeed != 0 { - r := rand.New(rand.NewSource(s.randomSeed)) - perm := r.Perm(len(f.ScenarioDefinitions)) - for i, v := range perm { - scenarios[v] = f.ScenarioDefinitions[i] - } - } else { - copy(scenarios, f.ScenarioDefinitions) - } - - defer func() { - if !isEmptyFeature(f.Feature) { - for _, fn := range s.afterFeatureHandlers { - fn(f.Feature) - } - } - }() - - for _, scenario := range scenarios { - var err error - if f.Background != nil { - s.fmt.Node(f.Background) - } - switch t := scenario.(type) { - case *gherkin.ScenarioOutline: - err = s.runOutline(t, f.Background) - case *gherkin.Scenario: - err = s.runScenario(t, f.Background) - } - if s.shouldFail(err) { - s.failed = true - if s.stopOnFailure { - return - } - } - } -} - -func (s *Suite) runScenario(scenario *gherkin.Scenario, b *gherkin.Background) (err error) { - if isEmptyScenario(scenario) { - s.fmt.Node(scenario) - return ErrUndefined - } - - // run before scenario handlers - for _, f := range s.beforeScenarioHandlers { - f(scenario) - } - - s.fmt.Node(scenario) - - // background - steps := scenario.Steps - if b != nil { - steps = append(b.Steps, steps...) - } - - // scenario - err = s.runSteps(steps) - - // run after scenario handlers - for _, f := range s.afterScenarioHandlers { - f(scenario, err) - } - - return -} - -func (s *Suite) printStepDefinitions(w io.Writer) { - var longest int - for _, def := range s.steps { - n := utf8.RuneCountInString(def.Expr.String()) - if longest < n { - longest = n - } - } - for _, def := range s.steps { - n := utf8.RuneCountInString(def.Expr.String()) - location := def.definitionID() - spaces := strings.Repeat(" ", longest-n) - fmt.Fprintln(w, yellow(def.Expr.String())+spaces, black("# "+location)) - } - if len(s.steps) == 0 { - fmt.Fprintln(w, "there were no contexts registered, could not find any step definition..") - } -} - -func parseFeatures(filter string, paths []string) ([]*feature, error) { - byPath := make(map[string]*feature) - var order int - for _, pat := range paths { - // check if line number is specified - parts := strings.Split(pat, ":") - path := parts[0] - line := -1 - var err error - if len(parts) > 1 { - line, err = strconv.Atoi(parts[1]) - if err != nil { - return nil, fmt.Errorf("line number should follow after colon path delimiter") - } - } - // parse features - err = filepath.Walk(path, func(p string, f os.FileInfo, err error) error { - if err == nil && !f.IsDir() && strings.HasSuffix(p, ".feature") { - reader, err := os.Open(p) - if err != nil { - return err - } - var buf bytes.Buffer - ft, err := gherkin.ParseFeature(io.TeeReader(reader, &buf)) - reader.Close() - if err != nil { - return fmt.Errorf("%s - %v", p, err) - } - - feat := byPath[p] - if feat == nil { - feat = &feature{ - Path: p, - Feature: ft, - Content: buf.Bytes(), - scenarios: make(map[int]bool), - order: order, - } - order++ - byPath[p] = feat - } - // filter scenario by line number - for _, def := range ft.ScenarioDefinitions { - var ln int - switch t := def.(type) { - case *gherkin.Scenario: - ln = t.Location.Line - case *gherkin.ScenarioOutline: - ln = t.Location.Line - } - if line == -1 || ln == line { - feat.scenarios[ln] = true - } - } - } - return err - }) - // check error - switch { - case os.IsNotExist(err): - return nil, fmt.Errorf(`feature path "%s" is not available`, path) - case os.IsPermission(err): - return nil, fmt.Errorf(`feature path "%s" is not accessible`, path) - case err != nil: - return nil, err - } - } - return filterFeatures(filter, byPath), nil -} - -type sortByOrderGiven []*feature - -func (s sortByOrderGiven) Len() int { return len(s) } -func (s sortByOrderGiven) Less(i, j int) bool { return s[i].order < s[j].order } -func (s sortByOrderGiven) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -func filterFeatures(tags string, collected map[string]*feature) (features []*feature) { - for _, ft := range collected { - var scenarios []interface{} - for _, def := range ft.ScenarioDefinitions { - var ln int - switch t := def.(type) { - case *gherkin.Scenario: - ln = t.Location.Line - case *gherkin.ScenarioOutline: - ln = t.Location.Line - } - if ft.scenarios[ln] { - scenarios = append(scenarios, def) - } - } - ft.ScenarioDefinitions = scenarios - applyTagFilter(tags, ft.Feature) - - features = append(features, ft) - } - - sort.Sort(sortByOrderGiven(features)) - - return features -} - -func applyTagFilter(tags string, ft *gherkin.Feature) { - if len(tags) == 0 { - return - } - - var scenarios []interface{} - for _, scenario := range ft.ScenarioDefinitions { - if matchesTags(tags, allTags(ft, scenario)) { - scenarios = append(scenarios, scenario) - } - } - ft.ScenarioDefinitions = scenarios -} - -func allTags(nodes ...interface{}) []string { - var tags, tmp []string - for _, node := range nodes { - var gr []*gherkin.Tag - switch t := node.(type) { - case *gherkin.Feature: - gr = t.Tags - case *gherkin.ScenarioOutline: - gr = t.Tags - case *gherkin.Scenario: - gr = t.Tags - case *gherkin.Examples: - gr = t.Tags - } - - for _, gtag := range gr { - tag := strings.TrimSpace(gtag.Name) - if tag[0] == '@' { - tag = tag[1:] - } - copy(tmp, tags) - var found bool - for _, tg := range tmp { - if tg == tag { - found = true - break - } - } - if !found { - tags = append(tags, tag) - } - } - } - return tags -} - -func hasTag(tags []string, tag string) bool { - for _, t := range tags { - if t == tag { - return true - } - } - return false -} - -// based on http://behat.readthedocs.org/en/v2.5/guides/6.cli.html#gherkin-filters -func matchesTags(filter string, tags []string) (ok bool) { - ok = true - for _, andTags := range strings.Split(filter, "&&") { - var okComma bool - for _, tag := range strings.Split(andTags, ",") { - tag = strings.Replace(strings.TrimSpace(tag), "@", "", -1) - if tag[0] == '~' { - tag = tag[1:] - okComma = !hasTag(tags, tag) || okComma - } else { - okComma = hasTag(tags, tag) || okComma - } - } - ok = (false != okComma && ok && okComma) || false - } - return -} diff --git a/vendor/github.com/DATA-DOG/godog/suite_context.go b/vendor/github.com/DATA-DOG/godog/suite_context.go deleted file mode 100644 index e8528ffe7..000000000 --- a/vendor/github.com/DATA-DOG/godog/suite_context.go +++ /dev/null @@ -1,489 +0,0 @@ -package godog - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "path/filepath" - "reflect" - "regexp" - "strconv" - "strings" - - "github.com/DATA-DOG/godog/gherkin" -) - -// SuiteContext provides steps for godog suite execution and -// can be used for meta-testing of godog features/steps themselves. -// -// Beware, steps or their definitions might change without backward -// compatibility guarantees. A typical user of the godog library should never -// need this, rather it is provided for those developing add-on libraries for godog. -// -// For an example of how to use, see godog's own `features/` and `suite_test.go`. -func SuiteContext(s *Suite, additionalContextInitializers ...func(suite *Suite)) { - c := &suiteContext{ - extraCIs: additionalContextInitializers, - } - - // apply any additional context intializers to modify the context that the - // meta-tests will be run in - for _, ci := range additionalContextInitializers { - ci(s) - } - - s.BeforeScenario(c.ResetBeforeEachScenario) - - s.Step(`^(?:a )?feature path "([^"]*)"$`, c.featurePath) - s.Step(`^I parse features$`, c.parseFeatures) - s.Step(`^I'm listening to suite events$`, c.iAmListeningToSuiteEvents) - s.Step(`^I run feature suite$`, c.iRunFeatureSuite) - s.Step(`^I run feature suite with formatter "([^"]*)"$`, c.iRunFeatureSuiteWithFormatter) - s.Step(`^(?:a )?feature "([^"]*)"(?: file)?:$`, c.aFeatureFile) - s.Step(`^the suite should have (passed|failed)$`, c.theSuiteShouldHave) - - s.Step(`^I should have ([\d]+) features? files?:$`, c.iShouldHaveNumFeatureFiles) - s.Step(`^I should have ([\d]+) scenarios? registered$`, c.numScenariosRegistered) - s.Step(`^there (was|were) ([\d]+) "([^"]*)" events? fired$`, c.thereWereNumEventsFired) - s.Step(`^there was event triggered before scenario "([^"]*)"$`, c.thereWasEventTriggeredBeforeScenario) - s.Step(`^these events had to be fired for a number of times:$`, c.theseEventsHadToBeFiredForNumberOfTimes) - - s.Step(`^(?:a )?failing step`, c.aFailingStep) - s.Step(`^this step should fail`, c.aFailingStep) - s.Step(`^the following steps? should be (passed|failed|skipped|undefined|pending):`, c.followingStepsShouldHave) - s.Step(`^all steps should (?:be|have|have been) (passed|failed|skipped|undefined|pending)$`, c.allStepsShouldHave) - s.Step(`^the undefined step snippets should be:$`, c.theUndefinedStepSnippetsShouldBe) - - // event stream - s.Step(`^the following events should be fired:$`, c.thereShouldBeEventsFired) - - // lt - s.Step(`^savybių aplankas "([^"]*)"$`, c.featurePath) - s.Step(`^aš išskaitau savybes$`, c.parseFeatures) - s.Step(`^aš turėčiau turėti ([\d]+) savybių failus:$`, c.iShouldHaveNumFeatureFiles) - - s.Step(`^(?:a )?pending step$`, func() error { - return ErrPending - }) - s.Step(`^(?:a )?passing step$`, func() error { - return nil - }) - - // Introduced to test formatter/cucumber.feature - s.Step(`^the rendered json will be as follows:$`, c.theRenderJSONWillBe) - - s.Step(`^(?:a )?failing multistep$`, func() Steps { - return Steps{"passing step", "failing step"} - }) - - s.Step(`^(?:a |an )?undefined multistep$`, func() Steps { - return Steps{"passing step", "undefined step", "passing step"} - }) - - s.Step(`^(?:a )?passing multistep$`, func() Steps { - return Steps{"passing step", "passing step", "passing step"} - }) - - s.Step(`^(?:a )?failing nested multistep$`, func() Steps { - return Steps{"passing step", "passing multistep", "failing multistep"} - }) -} - -type firedEvent struct { - name string - args []interface{} -} - -type suiteContext struct { - paths []string - testedSuite *Suite - extraCIs []func(suite *Suite) - events []*firedEvent - out bytes.Buffer -} - -func (s *suiteContext) ResetBeforeEachScenario(interface{}) { - // reset whole suite with the state - s.out.Reset() - s.paths = []string{} - s.testedSuite = &Suite{} - // our tested suite will have the same context registered - SuiteContext(s.testedSuite, s.extraCIs...) - // reset all fired events - s.events = []*firedEvent{} -} - -func (s *suiteContext) iRunFeatureSuiteWithFormatter(name string) error { - f := findFmt(name) - if f == nil { - return fmt.Errorf(`formatter "%s" is not available`, name) - } - s.testedSuite.fmt = f("godog", &s.out) - if err := s.parseFeatures(); err != nil { - return err - } - s.testedSuite.run() - s.testedSuite.fmt.Summary() - return nil -} - -func (s *suiteContext) thereShouldBeEventsFired(doc *gherkin.DocString) error { - actual := strings.Split(strings.TrimSpace(s.out.String()), "\n") - expect := strings.Split(strings.TrimSpace(doc.Content), "\n") - if len(expect) != len(actual) { - return fmt.Errorf("expected %d events, but got %d", len(expect), len(actual)) - } - - type ev struct { - Event string - } - - for i, event := range actual { - exp := strings.TrimSpace(expect[i]) - var act ev - if err := json.Unmarshal([]byte(event), &act); err != nil { - return fmt.Errorf("failed to read event data: %v", err) - } - - if act.Event != exp { - return fmt.Errorf(`expected event: "%s" at position: %d, but actual was "%s"`, exp, i, act.Event) - } - } - return nil -} - -func (s *suiteContext) cleanupSnippet(snip string) string { - lines := strings.Split(strings.TrimSpace(snip), "\n") - for i := 0; i < len(lines); i++ { - lines[i] = strings.TrimSpace(lines[i]) - } - return strings.Join(lines, "\n") -} - -func (s *suiteContext) theUndefinedStepSnippetsShouldBe(body *gherkin.DocString) error { - f, ok := s.testedSuite.fmt.(*testFormatter) - if !ok { - return fmt.Errorf("this step requires testFormatter, but there is: %T", s.testedSuite.fmt) - } - actual := s.cleanupSnippet(f.snippets()) - expected := s.cleanupSnippet(body.Content) - if actual != expected { - return fmt.Errorf("snippets do not match actual: %s", f.snippets()) - } - return nil -} - -func (s *suiteContext) followingStepsShouldHave(status string, steps *gherkin.DocString) error { - var expected = strings.Split(steps.Content, "\n") - var actual, unmatched, matched []string - - f, ok := s.testedSuite.fmt.(*testFormatter) - if !ok { - return fmt.Errorf("this step requires testFormatter, but there is: %T", s.testedSuite.fmt) - } - switch status { - case "passed": - for _, st := range f.passed { - actual = append(actual, st.step.Text) - } - case "failed": - for _, st := range f.failed { - actual = append(actual, st.step.Text) - } - case "skipped": - for _, st := range f.skipped { - actual = append(actual, st.step.Text) - } - case "undefined": - for _, st := range f.undefined { - actual = append(actual, st.step.Text) - } - case "pending": - for _, st := range f.pending { - actual = append(actual, st.step.Text) - } - default: - return fmt.Errorf("unexpected step status wanted: %s", status) - } - - if len(expected) > len(actual) { - return fmt.Errorf("number of expected %s steps: %d is less than actual %s steps: %d", status, len(expected), status, len(actual)) - } - - for _, a := range actual { - for _, e := range expected { - if a == e { - matched = append(matched, e) - break - } - } - } - - if len(matched) >= len(expected) { - return nil - } - for _, s := range expected { - var found bool - for _, m := range matched { - if s == m { - found = true - break - } - } - if !found { - unmatched = append(unmatched, s) - } - } - - return fmt.Errorf("the steps: %s - are not %s", strings.Join(unmatched, ", "), status) -} - -func (s *suiteContext) allStepsShouldHave(status string) error { - f, ok := s.testedSuite.fmt.(*testFormatter) - if !ok { - return fmt.Errorf("this step requires testFormatter, but there is: %T", s.testedSuite.fmt) - } - - total := len(f.passed) + len(f.failed) + len(f.skipped) + len(f.undefined) + len(f.pending) - var actual int - switch status { - case "passed": - actual = len(f.passed) - case "failed": - actual = len(f.failed) - case "skipped": - actual = len(f.skipped) - case "undefined": - actual = len(f.undefined) - case "pending": - actual = len(f.pending) - default: - return fmt.Errorf("unexpected step status wanted: %s", status) - } - - if total > actual { - return fmt.Errorf("number of expected %s steps: %d is less than actual %s steps: %d", status, total, status, actual) - } - return nil -} - -func (s *suiteContext) iAmListeningToSuiteEvents() error { - s.testedSuite.BeforeSuite(func() { - s.events = append(s.events, &firedEvent{"BeforeSuite", []interface{}{}}) - }) - s.testedSuite.AfterSuite(func() { - s.events = append(s.events, &firedEvent{"AfterSuite", []interface{}{}}) - }) - s.testedSuite.BeforeFeature(func(ft *gherkin.Feature) { - s.events = append(s.events, &firedEvent{"BeforeFeature", []interface{}{ft}}) - }) - s.testedSuite.AfterFeature(func(ft *gherkin.Feature) { - s.events = append(s.events, &firedEvent{"AfterFeature", []interface{}{ft}}) - }) - s.testedSuite.BeforeScenario(func(scenario interface{}) { - s.events = append(s.events, &firedEvent{"BeforeScenario", []interface{}{scenario}}) - }) - s.testedSuite.AfterScenario(func(scenario interface{}, err error) { - s.events = append(s.events, &firedEvent{"AfterScenario", []interface{}{scenario, err}}) - }) - s.testedSuite.BeforeStep(func(step *gherkin.Step) { - s.events = append(s.events, &firedEvent{"BeforeStep", []interface{}{step}}) - }) - s.testedSuite.AfterStep(func(step *gherkin.Step, err error) { - s.events = append(s.events, &firedEvent{"AfterStep", []interface{}{step, err}}) - }) - return nil -} - -func (s *suiteContext) aFailingStep() error { - return fmt.Errorf("intentional failure") -} - -// parse a given feature file body as a feature -func (s *suiteContext) aFeatureFile(name string, body *gherkin.DocString) error { - ft, err := gherkin.ParseFeature(strings.NewReader(body.Content)) - s.testedSuite.features = append(s.testedSuite.features, &feature{Feature: ft, Path: name}) - return err -} - -func (s *suiteContext) featurePath(path string) error { - s.paths = append(s.paths, path) - return nil -} - -func (s *suiteContext) parseFeatures() error { - fts, err := parseFeatures("", s.paths) - if err != nil { - return err - } - s.testedSuite.features = append(s.testedSuite.features, fts...) - return nil -} - -func (s *suiteContext) theSuiteShouldHave(state string) error { - if s.testedSuite.failed && state == "passed" { - return fmt.Errorf("the feature suite has failed") - } - if !s.testedSuite.failed && state == "failed" { - return fmt.Errorf("the feature suite has passed") - } - return nil -} - -func (s *suiteContext) iShouldHaveNumFeatureFiles(num int, files *gherkin.DocString) error { - if len(s.testedSuite.features) != num { - return fmt.Errorf("expected %d features to be parsed, but have %d", num, len(s.testedSuite.features)) - } - expected := strings.Split(files.Content, "\n") - var actual []string - for _, ft := range s.testedSuite.features { - actual = append(actual, ft.Path) - } - if len(expected) != len(actual) { - return fmt.Errorf("expected %d feature paths to be parsed, but have %d", len(expected), len(actual)) - } - for i := 0; i < len(expected); i++ { - var matched bool - split := strings.Split(expected[i], "/") - exp := filepath.Join(split...) - for j := 0; j < len(actual); j++ { - split = strings.Split(actual[j], "/") - act := filepath.Join(split...) - if exp == act { - matched = true - break - } - } - if !matched { - return fmt.Errorf(`expected feature path "%s" at position: %d, was not parsed, actual are %+v`, exp, i, actual) - } - } - return nil -} - -func (s *suiteContext) iRunFeatureSuite() error { - if err := s.parseFeatures(); err != nil { - return err - } - s.testedSuite.fmt = testFormatterFunc("godog", &s.out) - s.testedSuite.run() - s.testedSuite.fmt.Summary() - - return nil -} - -func (s *suiteContext) numScenariosRegistered(expected int) (err error) { - var num int - for _, ft := range s.testedSuite.features { - num += len(ft.ScenarioDefinitions) - } - if num != expected { - err = fmt.Errorf("expected %d scenarios to be registered, but got %d", expected, num) - } - return -} - -func (s *suiteContext) thereWereNumEventsFired(_ string, expected int, typ string) error { - var num int - for _, event := range s.events { - if event.name == typ { - num++ - } - } - if num != expected { - return fmt.Errorf("expected %d %s events to be fired, but got %d", expected, typ, num) - } - return nil -} - -func (s *suiteContext) thereWasEventTriggeredBeforeScenario(expected string) error { - var found []string - for _, event := range s.events { - if event.name != "BeforeScenario" { - continue - } - - var name string - switch t := event.args[0].(type) { - case *gherkin.Scenario: - name = t.Name - case *gherkin.ScenarioOutline: - name = t.Name - } - if name == expected { - return nil - } - - found = append(found, name) - } - - if len(found) == 0 { - return fmt.Errorf("before scenario event was never triggered or listened") - } - - return fmt.Errorf(`expected "%s" scenario, but got these fired %s`, expected, `"`+strings.Join(found, `", "`)+`"`) -} - -func (s *suiteContext) theseEventsHadToBeFiredForNumberOfTimes(tbl *gherkin.DataTable) error { - if len(tbl.Rows[0].Cells) != 2 { - return fmt.Errorf("expected two columns for event table row, got: %d", len(tbl.Rows[0].Cells)) - } - - for _, row := range tbl.Rows { - num, err := strconv.ParseInt(row.Cells[1].Value, 10, 0) - if err != nil { - return err - } - if err := s.thereWereNumEventsFired("", int(num), row.Cells[0].Value); err != nil { - return err - } - } - return nil -} - -func (s *suiteContext) theRenderJSONWillBe(docstring *gherkin.DocString) error { - loc := regexp.MustCompile(`"suite_context.go:\d+"`) - var expected []cukeFeatureJSON - if err := json.Unmarshal([]byte(loc.ReplaceAllString(docstring.Content, `"suite_context.go:0"`)), &expected); err != nil { - return err - } - - var actual []cukeFeatureJSON - replaced := loc.ReplaceAllString(s.out.String(), `"suite_context.go:0"`) - if err := json.Unmarshal([]byte(replaced), &actual); err != nil { - return err - } - - if !reflect.DeepEqual(expected, actual) { - return fmt.Errorf("expected json does not match actual: %s", replaced) - } - return nil -} - -type testFormatter struct { - basefmt - scenarios []interface{} -} - -func testFormatterFunc(suite string, out io.Writer) Formatter { - return &testFormatter{ - basefmt: basefmt{ - started: timeNowFunc(), - indent: 2, - out: out, - }, - } -} - -func (f *testFormatter) Node(node interface{}) { - f.basefmt.Node(node) - switch t := node.(type) { - case *gherkin.Scenario: - f.scenarios = append(f.scenarios, t) - case *gherkin.ScenarioOutline: - f.scenarios = append(f.scenarios, t) - } -} - -func (f *testFormatter) Summary() {} diff --git a/vendor/github.com/DATA-DOG/godog/utils.go b/vendor/github.com/DATA-DOG/godog/utils.go deleted file mode 100644 index 3fb158829..000000000 --- a/vendor/github.com/DATA-DOG/godog/utils.go +++ /dev/null @@ -1,30 +0,0 @@ -package godog - -import ( - "strings" - "time" - - "github.com/DATA-DOG/godog/colors" -) - -// empty struct value takes no space allocation -type void struct{} - -var red = colors.Red -var redb = colors.Bold(colors.Red) -var green = colors.Green -var black = colors.Black -var blackb = colors.Bold(colors.Black) -var yellow = colors.Yellow -var cyan = colors.Cyan -var cyanb = colors.Bold(colors.Cyan) -var whiteb = colors.Bold(colors.White) - -// repeats a space n times -func s(n int) string { - return strings.Repeat(" ", n) -} - -var timeNowFunc = func() time.Time { - return time.Now() -} diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE deleted file mode 100644 index bc52e96f2..000000000 --- a/vendor/github.com/davecgh/go-spew/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -ISC License - -Copyright (c) 2012-2016 Dave Collins - -Permission to use, copy, modify, and/or 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/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go deleted file mode 100644 index 792994785..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ /dev/null @@ -1,145 +0,0 @@ -// 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. -// Go versions prior to 1.4 are disabled because they use a different layout -// for interfaces which make the implementation of unsafeReflectValue more complex. -// +build !js,!appengine,!safe,!disableunsafe,go1.4 - -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)) -) - -type flag uintptr - -var ( - // flagRO indicates whether the value field of a reflect.Value - // is read-only. - flagRO flag - - // flagAddr indicates whether the address of the reflect.Value's - // value may be taken. - flagAddr flag -) - -// flagKindMask holds the bits that make up the kind -// part of the flags field. In all the supported versions, -// it is in the lower 5 bits. -const flagKindMask = flag(0x1f) - -// Different versions of Go have used different -// bit layouts for the flags type. This table -// records the known combinations. -var okFlags = []struct { - ro, addr flag -}{{ - // From Go 1.4 to 1.5 - ro: 1 << 5, - addr: 1 << 7, -}, { - // Up to Go tip. - ro: 1<<5 | 1<<6, - addr: 1 << 8, -}} - -var flagValOffset = func() uintptr { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - return field.Offset -}() - -// flagField returns a pointer to the flag field of a reflect.Value. -func flagField(v *reflect.Value) *flag { - return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) -} - -// 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) reflect.Value { - if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { - return v - } - flagFieldPtr := flagField(&v) - *flagFieldPtr &^= flagRO - *flagFieldPtr |= flagAddr - return v -} - -// Sanity checks against future reflect package changes -// to the type or semantics of the Value.flag field. -func init() { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { - panic("reflect.Value flag field has changed kind") - } - type t0 int - var t struct { - A t0 - // t0 will have flagEmbedRO set. - t0 - // a will have flagStickyRO set - a t0 - } - vA := reflect.ValueOf(t).FieldByName("A") - va := reflect.ValueOf(t).FieldByName("a") - vt0 := reflect.ValueOf(t).FieldByName("t0") - - // Infer flagRO from the difference between the flags - // for the (otherwise identical) fields in t. - flagPublic := *flagField(&vA) - flagWithRO := *flagField(&va) | *flagField(&vt0) - flagRO = flagPublic ^ flagWithRO - - // Infer flagAddr from the difference between a value - // taken from a pointer and not. - vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") - flagNoPtr := *flagField(&vA) - flagPtr := *flagField(&vPtrA) - flagAddr = flagNoPtr ^ flagPtr - - // Check that the inferred flags tally with one of the known versions. - for _, f := range okFlags { - if flagRO == f.ro && flagAddr == f.addr { - return - } - } - panic("reflect.Value read-only flag has changed semantics") -} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go deleted file mode 100644 index 205c28d68..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ /dev/null @@ -1,38 +0,0 @@ -// 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 !go1.4 - -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 deleted file mode 100644 index 1be8ce945..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/common.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * 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 hexadecimal 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/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go deleted file mode 100644 index 2e3d22f31..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/config.go +++ /dev/null @@ -1,306 +0,0 @@ -/* - * 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 deleted file mode 100644 index aacaac6f1..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/doc.go +++ /dev/null @@ -1,211 +0,0 @@ -/* - * 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 deleted file mode 100644 index f78d89fc1..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dump.go +++ /dev/null @@ -1,509 +0,0 @@ -/* - * 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: - d.w.Write(nilAngleBytes) - - case cycleFound: - 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/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go deleted file mode 100644 index b04edb7d7..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/format.go +++ /dev/null @@ -1,419 +0,0 @@ -/* - * 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: - f.fs.Write(nilAngleBytes) - - case cycleFound: - 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/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go deleted file mode 100644 index 32c0e3388..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/spew.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * 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 ( - "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/ghodss/yaml/.gitignore b/vendor/github.com/ghodss/yaml/.gitignore deleted file mode 100644 index e256a31e0..000000000 --- a/vendor/github.com/ghodss/yaml/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -# OSX leaves these everywhere on SMB shares -._* - -# Eclipse files -.classpath -.project -.settings/** - -# Emacs save files -*~ - -# Vim-related files -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -*.un~ -Session.vim -.netrwhist - -# Go test binaries -*.test diff --git a/vendor/github.com/ghodss/yaml/.travis.yml b/vendor/github.com/ghodss/yaml/.travis.yml deleted file mode 100644 index 0e9d6edc0..000000000 --- a/vendor/github.com/ghodss/yaml/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go -go: - - 1.3 - - 1.4 -script: - - go test - - go build diff --git a/vendor/github.com/ghodss/yaml/LICENSE b/vendor/github.com/ghodss/yaml/LICENSE deleted file mode 100644 index 7805d36de..000000000 --- a/vendor/github.com/ghodss/yaml/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Sam Ghods - -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. - - -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/ghodss/yaml/README.md b/vendor/github.com/ghodss/yaml/README.md deleted file mode 100644 index 0200f75b4..000000000 --- a/vendor/github.com/ghodss/yaml/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# YAML marshaling and unmarshaling support for Go - -[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) - -## Introduction - -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. - -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). - -## Compatibility - -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). - -## Caveats - -**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: - -``` -BAD: - exampleKey: !!binary gIGC - -GOOD: - exampleKey: gIGC -... and decode the base64 data in your code. -``` - -**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. - -## Installation and usage - -To install, run: - -``` -$ go get github.com/ghodss/yaml -``` - -And import using: - -``` -import "github.com/ghodss/yaml" -``` - -Usage is very similar to the JSON library: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` -} - -func main() { - // Marshal a Person struct to YAML. - p := Person{"John", 30} - y, err := yaml.Marshal(p) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - age: 30 - name: John - */ - - // Unmarshal the YAML back into a Person struct. - var p2 Person - err = yaml.Unmarshal(y, &p2) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(p2) - /* Output: - {John 30} - */ -} -``` - -`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func main() { - j := []byte(`{"name": "John", "age": 30}`) - y, err := yaml.JSONToYAML(j) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - name: John - age: 30 - */ - j2, err := yaml.YAMLToJSON(y) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(j2)) - /* Output: - {"age":30,"name":"John"} - */ -} -``` diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go deleted file mode 100644 index 586007402..000000000 --- a/vendor/github.com/ghodss/yaml/fields.go +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -package yaml - -import ( - "bytes" - "encoding" - "encoding/json" - "reflect" - "sort" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } else { - v = reflect.New(v.Type().Elem()) - } - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(json.Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// A field represents a single field found in a struct. -type field struct { - name string - nameBytes []byte // []byte(name) - equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - - tag bool - index []int - typ reflect.Type - omitEmpty bool - quoted bool -} - -func fillField(f field) field { - f.nameBytes = []byte(f.name) - f.equalFold = foldFunc(f.nameBytes) - return f -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from json tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that JSON should recognize for the given type. -// The algorithm is breadth-first search over the set of structs to include - the top struct -// and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" { // unexported - continue - } - tag := sf.Tag.Get("json") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if !isValidTag(name) { - name = "" - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := name != "" - if name == "" { - name = sf.Name - } - fields = append(fields, fillField(field{ - name: name, - tag: tagged, - index: index, - typ: ft, - omitEmpty: opts.Contains("omitempty"), - quoted: opts.Contains("string"), - })) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with JSON tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// JSON tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -const ( - caseMask = ^byte(0x20) // Mask to ignore case in ASCII. - kelvin = '\u212a' - smallLongEss = '\u017f' -) - -// foldFunc returns one of four different case folding equivalence -// functions, from most general (and slow) to fastest: -// -// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 -// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') -// 3) asciiEqualFold, no special, but includes non-letters (including _) -// 4) simpleLetterEqualFold, no specials, no non-letters. -// -// The letters S and K are special because they map to 3 runes, not just 2: -// * S maps to s and to U+017F 'ſ' Latin small letter long s -// * k maps to K and to U+212A 'K' Kelvin sign -// See http://play.golang.org/p/tTxjOc0OGo -// -// The returned function is specialized for matching against s and -// should only be given s. It's not curried for performance reasons. -func foldFunc(s []byte) func(s, t []byte) bool { - nonLetter := false - special := false // special letter - for _, b := range s { - if b >= utf8.RuneSelf { - return bytes.EqualFold - } - upper := b & caseMask - if upper < 'A' || upper > 'Z' { - nonLetter = true - } else if upper == 'K' || upper == 'S' { - // See above for why these letters are special. - special = true - } - } - if special { - return equalFoldRight - } - if nonLetter { - return asciiEqualFold - } - return simpleLetterEqualFold -} - -// equalFoldRight is a specialization of bytes.EqualFold when s is -// known to be all ASCII (including punctuation), but contains an 's', -// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. -// See comments on foldFunc. -func equalFoldRight(s, t []byte) bool { - for _, sb := range s { - if len(t) == 0 { - return false - } - tb := t[0] - if tb < utf8.RuneSelf { - if sb != tb { - sbUpper := sb & caseMask - if 'A' <= sbUpper && sbUpper <= 'Z' { - if sbUpper != tb&caseMask { - return false - } - } else { - return false - } - } - t = t[1:] - continue - } - // sb is ASCII and t is not. t must be either kelvin - // sign or long s; sb must be s, S, k, or K. - tr, size := utf8.DecodeRune(t) - switch sb { - case 's', 'S': - if tr != smallLongEss { - return false - } - case 'k', 'K': - if tr != kelvin { - return false - } - default: - return false - } - t = t[size:] - - } - if len(t) > 0 { - return false - } - return true -} - -// asciiEqualFold is a specialization of bytes.EqualFold for use when -// s is all ASCII (but may contain non-letters) and contains no -// special-folding letters. -// See comments on foldFunc. -func asciiEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, sb := range s { - tb := t[i] - if sb == tb { - continue - } - if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { - if sb&caseMask != tb&caseMask { - return false - } - } else { - return false - } - } - return true -} - -// simpleLetterEqualFold is a specialization of bytes.EqualFold for -// use when s is all ASCII letters (no underscores, etc) and also -// doesn't contain 'k', 'K', 's', or 'S'. -// See comments on foldFunc. -func simpleLetterEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, b := range s { - if b&caseMask != t[i]&caseMask { - return false - } - } - return true -} - -// tagOptions is the string following a comma in a struct field's "json" -// tag, or the empty string. It does not include the leading comma. -type tagOptions string - -// parseTag splits a struct field's json tag into its name and -// comma-separated options. -func parseTag(tag string) (string, tagOptions) { - if idx := strings.Index(tag, ","); idx != -1 { - return tag[:idx], tagOptions(tag[idx+1:]) - } - return tag, tagOptions("") -} - -// Contains reports whether a comma-separated list of options -// contains a particular substr flag. substr must be surrounded by a -// string boundary or commas. -func (o tagOptions) Contains(optionName string) bool { - if len(o) == 0 { - return false - } - s := string(o) - for s != "" { - var next string - i := strings.Index(s, ",") - if i >= 0 { - s, next = s[:i], s[i+1:] - } - if s == optionName { - return true - } - s = next - } - return false -} diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go deleted file mode 100644 index 4fb4054a8..000000000 --- a/vendor/github.com/ghodss/yaml/yaml.go +++ /dev/null @@ -1,277 +0,0 @@ -package yaml - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strconv" - - "gopkg.in/yaml.v2" -) - -// Marshals the object into JSON then converts JSON to YAML and returns the -// YAML. -func Marshal(o interface{}) ([]byte, error) { - j, err := json.Marshal(o) - if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) - } - - y, err := JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) - } - - return y, nil -} - -// Converts YAML to JSON then uses JSON to unmarshal into an object. -func Unmarshal(y []byte, o interface{}) error { - vo := reflect.ValueOf(o) - j, err := yamlToJSON(y, &vo) - if err != nil { - return fmt.Errorf("error converting YAML to JSON: %v", err) - } - - err = json.Unmarshal(j, o) - if err != nil { - return fmt.Errorf("error unmarshaling JSON: %v", err) - } - - return nil -} - -// Convert JSON to YAML. -func JSONToYAML(j []byte) ([]byte, error) { - // Convert the JSON to an object. - var jsonObj interface{} - // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the - // Go JSON library doesn't try to pick the right number type (int, float, - // etc.) when unmarshalling to interface{}, it just picks float64 - // universally. go-yaml does go through the effort of picking the right - // number type, so we can preserve number type throughout this process. - err := yaml.Unmarshal(j, &jsonObj) - if err != nil { - return nil, err - } - - // Marshal this object into YAML. - return yaml.Marshal(jsonObj) -} - -// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through -// this method should be a no-op. -// -// Things YAML can do that are not supported by JSON: -// * In YAML you can have binary and null keys in your maps. These are invalid -// in JSON. (int and float keys are converted to strings.) -// * Binary data in YAML with the !!binary tag is not supported. If you want to -// use binary data with this library, encode the data as base64 as usual but do -// not use the !!binary tag in your YAML. This will ensure the original base64 -// encoded data makes it all the way through to the JSON. -func YAMLToJSON(y []byte) ([]byte, error) { - return yamlToJSON(y, nil) -} - -func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { - // Convert the YAML to an object. - var yamlObj interface{} - err := yaml.Unmarshal(y, &yamlObj) - if err != nil { - return nil, err - } - - // YAML objects are not completely compatible with JSON objects (e.g. you - // can have non-string keys in YAML). So, convert the YAML-compatible object - // to a JSON-compatible object, failing with an error if irrecoverable - // incompatibilties happen along the way. - jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) - if err != nil { - return nil, err - } - - // Convert this object to JSON and return the data. - return json.Marshal(jsonObj) -} - -func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { - var err error - - // Resolve jsonTarget to a concrete value (i.e. not a pointer or an - // interface). We pass decodingNull as false because we're not actually - // decoding into the value, we're just checking if the ultimate target is a - // string. - if jsonTarget != nil { - ju, tu, pv := indirect(*jsonTarget, false) - // We have a JSON or Text Umarshaler at this level, so we can't be trying - // to decode into a string. - if ju != nil || tu != nil { - jsonTarget = nil - } else { - jsonTarget = &pv - } - } - - // If yamlObj is a number or a boolean, check if jsonTarget is a string - - // if so, coerce. Else return normal. - // If yamlObj is a map or array, find the field that each key is - // unmarshaling to, and when you recurse pass the reflect.Value for that - // field back into this function. - switch typedYAMLObj := yamlObj.(type) { - case map[interface{}]interface{}: - // JSON does not support arbitrary keys in a map, so we must convert - // these keys to strings. - // - // From my reading of go-yaml v2 (specifically the resolve function), - // keys can only have the types string, int, int64, float64, binary - // (unsupported), or null (unsupported). - strMap := make(map[string]interface{}) - for k, v := range typedYAMLObj { - // Resolve the key to a string first. - var keyString string - switch typedKey := k.(type) { - case string: - keyString = typedKey - case int: - keyString = strconv.Itoa(typedKey) - case int64: - // go-yaml will only return an int64 as a key if the system - // architecture is 32-bit and the key's value is between 32-bit - // and 64-bit. Otherwise the key type will simply be int. - keyString = strconv.FormatInt(typedKey, 10) - case float64: - // Stolen from go-yaml to use the same conversion to string as - // the go-yaml library uses to convert float to string when - // Marshaling. - s := strconv.FormatFloat(typedKey, 'g', -1, 32) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - keyString = s - case bool: - if typedKey { - keyString = "true" - } else { - keyString = "false" - } - default: - return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", - reflect.TypeOf(k), k, v) - } - - // jsonTarget should be a struct or a map. If it's a struct, find - // the field it's going to map to and pass its reflect.Value. If - // it's a map, find the element type of the map and pass the - // reflect.Value created from that type. If it's neither, just pass - // nil - JSON conversion will error for us if it's a real issue. - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Struct { - keyBytes := []byte(keyString) - // Find the field that the JSON library would use. - var f *field - fields := cachedTypeFields(t.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, keyBytes) { - f = ff - break - } - // Do case-insensitive comparison. - if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { - f = ff - } - } - if f != nil { - // Find the reflect.Value of the most preferential - // struct field. - jtf := t.Field(f.index[0]) - strMap[keyString], err = convertToJSONableObject(v, &jtf) - if err != nil { - return nil, err - } - continue - } - } else if t.Kind() == reflect.Map { - // Create a zero value of the map's element type to use as - // the JSON target. - jtv := reflect.Zero(t.Type().Elem()) - strMap[keyString], err = convertToJSONableObject(v, &jtv) - if err != nil { - return nil, err - } - continue - } - } - strMap[keyString], err = convertToJSONableObject(v, nil) - if err != nil { - return nil, err - } - } - return strMap, nil - case []interface{}: - // We need to recurse into arrays in case there are any - // map[interface{}]interface{}'s inside and to convert any - // numbers to strings. - - // If jsonTarget is a slice (which it really should be), find the - // thing it's going to map to. If it's not a slice, just pass nil - // - JSON conversion will error for us if it's a real issue. - var jsonSliceElemValue *reflect.Value - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Slice { - // By default slices point to nil, but we need a reflect.Value - // pointing to a value of the slice type, so we create one here. - ev := reflect.Indirect(reflect.New(t.Type().Elem())) - jsonSliceElemValue = &ev - } - } - - // Make and use a new array. - arr := make([]interface{}, len(typedYAMLObj)) - for i, v := range typedYAMLObj { - arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) - if err != nil { - return nil, err - } - } - return arr, nil - default: - // If the target type is a string and the YAML type is a number, - // convert the YAML type to a string. - if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { - // Based on my reading of go-yaml, it may return int, int64, - // float64, or uint64. - var s string - switch typedVal := typedYAMLObj.(type) { - case int: - s = strconv.FormatInt(int64(typedVal), 10) - case int64: - s = strconv.FormatInt(typedVal, 10) - case float64: - s = strconv.FormatFloat(typedVal, 'g', -1, 32) - case uint64: - s = strconv.FormatUint(typedVal, 10) - case bool: - if typedVal { - s = "true" - } else { - s = "false" - } - } - if len(s) > 0 { - yamlObj = interface{}(s) - } - } - return yamlObj, nil - } - - return nil, nil -} diff --git a/vendor/github.com/golang/mock/AUTHORS b/vendor/github.com/golang/mock/AUTHORS deleted file mode 100644 index 660b8ccc8..000000000 --- a/vendor/github.com/golang/mock/AUTHORS +++ /dev/null @@ -1,12 +0,0 @@ -# This is the official list of GoMock authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. - -Alex Reece -Google Inc. diff --git a/vendor/github.com/golang/mock/CONTRIBUTORS b/vendor/github.com/golang/mock/CONTRIBUTORS deleted file mode 100644 index def849cab..000000000 --- a/vendor/github.com/golang/mock/CONTRIBUTORS +++ /dev/null @@ -1,37 +0,0 @@ -# This is the official list of people who can contribute (and typically -# have contributed) code to the gomock repository. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# The submission process automatically checks to make sure -# that people submitting code are listed in this file (by email address). -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# http://code.google.com/legal/individual-cla-v1.0.html -# http://code.google.com/legal/corporate-cla-v1.0.html -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. - -# Names should be added to this file like so: -# Name -# -# An entry with two email addresses specifies that the -# first address should be used in the submit logs and -# that the second address should be recognized as the -# same person when interacting with Rietveld. - -# Please keep the list sorted. - -Aaron Jacobs -Alex Reece -David Symonds -Ryan Barrett diff --git a/vendor/github.com/golang/mock/LICENSE b/vendor/github.com/golang/mock/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/golang/mock/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/golang/mock/gomock/call.go b/vendor/github.com/golang/mock/gomock/call.go deleted file mode 100644 index a3fa1ae41..000000000 --- a/vendor/github.com/golang/mock/gomock/call.go +++ /dev/null @@ -1,428 +0,0 @@ -// Copyright 2010 Google 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 gomock - -import ( - "fmt" - "reflect" - "strconv" - "strings" -) - -// Call represents an expected call to a mock. -type Call struct { - t TestReporter // for triggering test failures on invalid call setup - - receiver interface{} // the receiver of the method call - method string // the name of the method - methodType reflect.Type // the type of the method - args []Matcher // the args - origin string // file and line number of call setup - - preReqs []*Call // prerequisite calls - - // Expectations - minCalls, maxCalls int - - numCalls int // actual number made - - // actions are called when this Call is called. Each action gets the args and - // can set the return values by returning a non-nil slice. Actions run in the - // order they are created. - actions []func([]interface{}) []interface{} -} - -// newCall creates a *Call. It requires the method type in order to support -// unexported methods. -func newCall(t TestReporter, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { - if h, ok := t.(testHelper); ok { - h.Helper() - } - - // TODO: check arity, types. - margs := make([]Matcher, len(args)) - for i, arg := range args { - if m, ok := arg.(Matcher); ok { - margs[i] = m - } else if arg == nil { - // Handle nil specially so that passing a nil interface value - // will match the typed nils of concrete args. - margs[i] = Nil() - } else { - margs[i] = Eq(arg) - } - } - - origin := callerInfo(3) - actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} { - // Synthesize the zero value for each of the return args' types. - rets := make([]interface{}, methodType.NumOut()) - for i := 0; i < methodType.NumOut(); i++ { - rets[i] = reflect.Zero(methodType.Out(i)).Interface() - } - return rets - }} - return &Call{t: t, receiver: receiver, method: method, methodType: methodType, - args: margs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions} -} - -// AnyTimes allows the expectation to be called 0 or more times -func (c *Call) AnyTimes() *Call { - c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity - return c -} - -// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called, MinTimes also -// sets the maximum number of calls to infinity. -func (c *Call) MinTimes(n int) *Call { - c.minCalls = n - if c.maxCalls == 1 { - c.maxCalls = 1e8 - } - return c -} - -// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called, MaxTimes also -// sets the minimum number of calls to 0. -func (c *Call) MaxTimes(n int) *Call { - c.maxCalls = n - if c.minCalls == 1 { - c.minCalls = 0 - } - return c -} - -// DoAndReturn declares the action to run when the call is matched. -// The return values from this function are returned by the mocked function. -// It takes an interface{} argument to support n-arity functions. -func (c *Call) DoAndReturn(f interface{}) *Call { - // TODO: Check arity and types here, rather than dying badly elsewhere. - v := reflect.ValueOf(f) - - c.addAction(func(args []interface{}) []interface{} { - vargs := make([]reflect.Value, len(args)) - ft := v.Type() - for i := 0; i < len(args); i++ { - if args[i] != nil { - vargs[i] = reflect.ValueOf(args[i]) - } else { - // Use the zero value for the arg. - vargs[i] = reflect.Zero(ft.In(i)) - } - } - vrets := v.Call(vargs) - rets := make([]interface{}, len(vrets)) - for i, ret := range vrets { - rets[i] = ret.Interface() - } - return rets - }) - return c -} - -// Do declares the action to run when the call is matched. The function's -// return values are ignored to retain backward compatibility. To use the -// return values call DoAndReturn. -// It takes an interface{} argument to support n-arity functions. -func (c *Call) Do(f interface{}) *Call { - // TODO: Check arity and types here, rather than dying badly elsewhere. - v := reflect.ValueOf(f) - - c.addAction(func(args []interface{}) []interface{} { - vargs := make([]reflect.Value, len(args)) - ft := v.Type() - for i := 0; i < len(args); i++ { - if args[i] != nil { - vargs[i] = reflect.ValueOf(args[i]) - } else { - // Use the zero value for the arg. - vargs[i] = reflect.Zero(ft.In(i)) - } - } - v.Call(vargs) - return nil - }) - return c -} - -// Return declares the values to be returned by the mocked function call. -func (c *Call) Return(rets ...interface{}) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } - - mt := c.methodType - if len(rets) != mt.NumOut() { - c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]", - c.receiver, c.method, len(rets), mt.NumOut(), c.origin) - } - for i, ret := range rets { - if got, want := reflect.TypeOf(ret), mt.Out(i); got == want { - // Identical types; nothing to do. - } else if got == nil { - // Nil needs special handling. - switch want.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - // ok - default: - c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]", - i, c.receiver, c.method, want, c.origin) - } - } else if got.AssignableTo(want) { - // Assignable type relation. Make the assignment now so that the generated code - // can return the values with a type assertion. - v := reflect.New(want).Elem() - v.Set(reflect.ValueOf(ret)) - rets[i] = v.Interface() - } else { - c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]", - i, c.receiver, c.method, got, want, c.origin) - } - } - - c.addAction(func([]interface{}) []interface{} { - return rets - }) - - return c -} - -// Times declares the exact number of times a function call is expected to be executed. -func (c *Call) Times(n int) *Call { - c.minCalls, c.maxCalls = n, n - return c -} - -// SetArg declares an action that will set the nth argument's value, -// indirected through a pointer. Or, in the case of a slice, SetArg -// will copy value's elements into the nth argument. -func (c *Call) SetArg(n int, value interface{}) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } - - mt := c.methodType - // TODO: This will break on variadic methods. - // We will need to check those at invocation time. - if n < 0 || n >= mt.NumIn() { - c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]", - n, mt.NumIn(), c.origin) - } - // Permit setting argument through an interface. - // In the interface case, we don't (nay, can't) check the type here. - at := mt.In(n) - switch at.Kind() { - case reflect.Ptr: - dt := at.Elem() - if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) { - c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]", - n, vt, dt, c.origin) - } - case reflect.Interface: - // nothing to do - case reflect.Slice: - // nothing to do - default: - c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice type %v [%s]", - n, at, c.origin) - } - - c.addAction(func(args []interface{}) []interface{} { - v := reflect.ValueOf(value) - switch reflect.TypeOf(args[n]).Kind() { - case reflect.Slice: - setSlice(args[n], v) - default: - reflect.ValueOf(args[n]).Elem().Set(v) - } - return nil - }) - return c -} - -// isPreReq returns true if other is a direct or indirect prerequisite to c. -func (c *Call) isPreReq(other *Call) bool { - for _, preReq := range c.preReqs { - if other == preReq || preReq.isPreReq(other) { - return true - } - } - return false -} - -// After declares that the call may only match after preReq has been exhausted. -func (c *Call) After(preReq *Call) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } - - if c == preReq { - c.t.Fatalf("A call isn't allowed to be its own prerequisite") - } - if preReq.isPreReq(c) { - c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq) - } - - c.preReqs = append(c.preReqs, preReq) - return c -} - -// Returns true if the minimum number of calls have been made. -func (c *Call) satisfied() bool { - return c.numCalls >= c.minCalls -} - -// Returns true iff the maximum number of calls have been made. -func (c *Call) exhausted() bool { - return c.numCalls >= c.maxCalls -} - -func (c *Call) String() string { - args := make([]string, len(c.args)) - for i, arg := range c.args { - args[i] = arg.String() - } - arguments := strings.Join(args, ", ") - return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin) -} - -// Tests if the given call matches the expected call. -// If yes, returns nil. If no, returns error with message explaining why it does not match. -func (c *Call) matches(args []interface{}) error { - if !c.methodType.IsVariadic() { - if len(args) != len(c.args) { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d", - c.origin, len(args), len(c.args)) - } - - for i, m := range c.args { - if !m.Matches(args[i]) { - return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", - c.origin, strconv.Itoa(i), args[i], m) - } - } - } else { - if len(c.args) < c.methodType.NumIn()-1 { - return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d", - c.origin, len(c.args), c.methodType.NumIn()-1) - } - if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d", - c.origin, len(args), len(c.args)) - } - if len(args) < len(c.args)-1 { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d", - c.origin, len(args), len(c.args)-1) - } - - for i, m := range c.args { - if i < c.methodType.NumIn()-1 { - // Non-variadic args - if !m.Matches(args[i]) { - return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", - c.origin, strconv.Itoa(i), args[i], m) - } - continue - } - // The last arg has a possibility of a variadic argument, so let it branch - - // sample: Foo(a int, b int, c ...int) - if i < len(c.args) && i < len(args) { - if m.Matches(args[i]) { - // Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any()) - // Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher) - // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC) - // Got Foo(a, b) want Foo(matcherA, matcherB) - // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD) - continue - } - } - - // The number of actual args don't match the number of matchers, - // or the last matcher is a slice and the last arg is not. - // If this function still matches it is because the last matcher - // matches all the remaining arguments or the lack of any. - // Convert the remaining arguments, if any, into a slice of the - // expected type. - vargsType := c.methodType.In(c.methodType.NumIn() - 1) - vargs := reflect.MakeSlice(vargsType, 0, len(args)-i) - for _, arg := range args[i:] { - vargs = reflect.Append(vargs, reflect.ValueOf(arg)) - } - if m.Matches(vargs.Interface()) { - // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any()) - // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher) - // Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any()) - // Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher) - break - } - // Wrong number of matchers or not match. Fail. - // Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD) - // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD) - // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE) - // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD) - // Got Foo(a, b, c) want Foo(matcherA, matcherB) - return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", - c.origin, strconv.Itoa(i), args[i:], c.args[i]) - - } - } - - // Check that all prerequisite calls have been satisfied. - for _, preReqCall := range c.preReqs { - if !preReqCall.satisfied() { - return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v", - c.origin, preReqCall, c) - } - } - - // Check that the call is not exhausted. - if c.exhausted() { - return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin) - } - - return nil -} - -// dropPrereqs tells the expected Call to not re-check prerequisite calls any -// longer, and to return its current set. -func (c *Call) dropPrereqs() (preReqs []*Call) { - preReqs = c.preReqs - c.preReqs = nil - return -} - -func (c *Call) call(args []interface{}) []func([]interface{}) []interface{} { - c.numCalls++ - return c.actions -} - -// InOrder declares that the given calls should occur in order. -func InOrder(calls ...*Call) { - for i := 1; i < len(calls); i++ { - calls[i].After(calls[i-1]) - } -} - -func setSlice(arg interface{}, v reflect.Value) { - va := reflect.ValueOf(arg) - for i := 0; i < v.Len(); i++ { - va.Index(i).Set(v.Index(i)) - } -} - -func (c *Call) addAction(action func([]interface{}) []interface{}) { - c.actions = append(c.actions, action) -} diff --git a/vendor/github.com/golang/mock/gomock/callset.go b/vendor/github.com/golang/mock/gomock/callset.go deleted file mode 100644 index c44a8a585..000000000 --- a/vendor/github.com/golang/mock/gomock/callset.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2011 Google 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 gomock - -import ( - "bytes" - "fmt" -) - -// callSet represents a set of expected calls, indexed by receiver and method -// name. -type callSet struct { - // Calls that are still expected. - expected map[callSetKey][]*Call - // Calls that have been exhausted. - exhausted map[callSetKey][]*Call -} - -// callSetKey is the key in the maps in callSet -type callSetKey struct { - receiver interface{} - fname string -} - -func newCallSet() *callSet { - return &callSet{make(map[callSetKey][]*Call), make(map[callSetKey][]*Call)} -} - -// Add adds a new expected call. -func (cs callSet) Add(call *Call) { - key := callSetKey{call.receiver, call.method} - m := cs.expected - if call.exhausted() { - m = cs.exhausted - } - m[key] = append(m[key], call) -} - -// Remove removes an expected call. -func (cs callSet) Remove(call *Call) { - key := callSetKey{call.receiver, call.method} - calls := cs.expected[key] - for i, c := range calls { - if c == call { - // maintain order for remaining calls - cs.expected[key] = append(calls[:i], calls[i+1:]...) - cs.exhausted[key] = append(cs.exhausted[key], call) - break - } - } -} - -// FindMatch searches for a matching call. Returns error with explanation message if no call matched. -func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) { - key := callSetKey{receiver, method} - - // Search through the expected calls. - expected := cs.expected[key] - var callsErrors bytes.Buffer - for _, call := range expected { - err := call.matches(args) - if err != nil { - fmt.Fprintf(&callsErrors, "\n%v", err) - } else { - return call, nil - } - } - - // If we haven't found a match then search through the exhausted calls so we - // get useful error messages. - exhausted := cs.exhausted[key] - for _, call := range exhausted { - if err := call.matches(args); err != nil { - fmt.Fprintf(&callsErrors, "\n%v", err) - } - } - - if len(expected)+len(exhausted) == 0 { - fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method) - } - - return nil, fmt.Errorf(callsErrors.String()) -} - -// Failures returns the calls that are not satisfied. -func (cs callSet) Failures() []*Call { - failures := make([]*Call, 0, len(cs.expected)) - for _, calls := range cs.expected { - for _, call := range calls { - if !call.satisfied() { - failures = append(failures, call) - } - } - } - return failures -} diff --git a/vendor/github.com/golang/mock/gomock/controller.go b/vendor/github.com/golang/mock/gomock/controller.go deleted file mode 100644 index a7b79188b..000000000 --- a/vendor/github.com/golang/mock/gomock/controller.go +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2010 Google 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. - -// GoMock - a mock framework for Go. -// -// Standard usage: -// (1) Define an interface that you wish to mock. -// type MyInterface interface { -// SomeMethod(x int64, y string) -// } -// (2) Use mockgen to generate a mock from the interface. -// (3) Use the mock in a test: -// func TestMyThing(t *testing.T) { -// mockCtrl := gomock.NewController(t) -// defer mockCtrl.Finish() -// -// mockObj := something.NewMockMyInterface(mockCtrl) -// mockObj.EXPECT().SomeMethod(4, "blah") -// // pass mockObj to a real object and play with it. -// } -// -// By default, expected calls are not enforced to run in any particular order. -// Call order dependency can be enforced by use of InOrder and/or Call.After. -// Call.After can create more varied call order dependencies, but InOrder is -// often more convenient. -// -// The following examples create equivalent call order dependencies. -// -// Example of using Call.After to chain expected call order: -// -// firstCall := mockObj.EXPECT().SomeMethod(1, "first") -// secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall) -// mockObj.EXPECT().SomeMethod(3, "third").After(secondCall) -// -// Example of using InOrder to declare expected call order: -// -// gomock.InOrder( -// mockObj.EXPECT().SomeMethod(1, "first"), -// mockObj.EXPECT().SomeMethod(2, "second"), -// mockObj.EXPECT().SomeMethod(3, "third"), -// ) -// -// TODO: -// - Handle different argument/return types (e.g. ..., chan, map, interface). -package gomock - -import ( - "fmt" - "golang.org/x/net/context" - "reflect" - "runtime" - "sync" -) - -// A TestReporter is something that can be used to report test failures. -// It is satisfied by the standard library's *testing.T. -type TestReporter interface { - Errorf(format string, args ...interface{}) - Fatalf(format string, args ...interface{}) -} - -// A Controller represents the top-level control of a mock ecosystem. -// It defines the scope and lifetime of mock objects, as well as their expectations. -// It is safe to call Controller's methods from multiple goroutines. -type Controller struct { - mu sync.Mutex - t TestReporter - expectedCalls *callSet - finished bool -} - -func NewController(t TestReporter) *Controller { - return &Controller{ - t: t, - expectedCalls: newCallSet(), - } -} - -type cancelReporter struct { - t TestReporter - cancel func() -} - -func (r *cancelReporter) Errorf(format string, args ...interface{}) { r.t.Errorf(format, args...) } -func (r *cancelReporter) Fatalf(format string, args ...interface{}) { - defer r.cancel() - r.t.Fatalf(format, args...) -} - -// WithContext returns a new Controller and a Context, which is cancelled on any -// fatal failure. -func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) { - ctx, cancel := context.WithCancel(ctx) - return NewController(&cancelReporter{t, cancel}), ctx -} - -func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } - - recv := reflect.ValueOf(receiver) - for i := 0; i < recv.Type().NumMethod(); i++ { - if recv.Type().Method(i).Name == method { - return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...) - } - } - ctrl.t.Fatalf("gomock: failed finding method %s on %T", method, receiver) - panic("unreachable") -} - -func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } - - call := newCall(ctrl.t, receiver, method, methodType, args...) - - ctrl.mu.Lock() - defer ctrl.mu.Unlock() - ctrl.expectedCalls.Add(call) - - return call -} - -func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } - - // Nest this code so we can use defer to make sure the lock is released. - actions := func() []func([]interface{}) []interface{} { - ctrl.mu.Lock() - defer ctrl.mu.Unlock() - - expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args) - if err != nil { - origin := callerInfo(2) - ctrl.t.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err) - } - - // Two things happen here: - // * the matching call no longer needs to check prerequite calls, - // * and the prerequite calls are no longer expected, so remove them. - preReqCalls := expected.dropPrereqs() - for _, preReqCall := range preReqCalls { - ctrl.expectedCalls.Remove(preReqCall) - } - - actions := expected.call(args) - if expected.exhausted() { - ctrl.expectedCalls.Remove(expected) - } - return actions - }() - - var rets []interface{} - for _, action := range actions { - if r := action(args); r != nil { - rets = r - } - } - - return rets -} - -func (ctrl *Controller) Finish() { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } - - ctrl.mu.Lock() - defer ctrl.mu.Unlock() - - if ctrl.finished { - ctrl.t.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.") - } - ctrl.finished = true - - // If we're currently panicking, probably because this is a deferred call, - // pass through the panic. - if err := recover(); err != nil { - panic(err) - } - - // Check that all remaining expected calls are satisfied. - failures := ctrl.expectedCalls.Failures() - for _, call := range failures { - ctrl.t.Errorf("missing call(s) to %v", call) - } - if len(failures) != 0 { - ctrl.t.Fatalf("aborting test due to missing call(s)") - } -} - -func callerInfo(skip int) string { - if _, file, line, ok := runtime.Caller(skip + 1); ok { - return fmt.Sprintf("%s:%d", file, line) - } - return "unknown file" -} - -type testHelper interface { - TestReporter - Helper() -} diff --git a/vendor/github.com/golang/mock/gomock/matchers.go b/vendor/github.com/golang/mock/gomock/matchers.go deleted file mode 100644 index e8b1ddccf..000000000 --- a/vendor/github.com/golang/mock/gomock/matchers.go +++ /dev/null @@ -1,99 +0,0 @@ -//go:generate mockgen -destination mock_matcher/mock_matcher.go github.com/golang/mock/gomock Matcher - -// Copyright 2010 Google 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 gomock - -import ( - "fmt" - "reflect" -) - -// A Matcher is a representation of a class of values. -// It is used to represent the valid or expected arguments to a mocked method. -type Matcher interface { - // Matches returns whether x is a match. - Matches(x interface{}) bool - - // String describes what the matcher matches. - String() string -} - -type anyMatcher struct{} - -func (anyMatcher) Matches(x interface{}) bool { - return true -} - -func (anyMatcher) String() string { - return "is anything" -} - -type eqMatcher struct { - x interface{} -} - -func (e eqMatcher) Matches(x interface{}) bool { - return reflect.DeepEqual(e.x, x) -} - -func (e eqMatcher) String() string { - return fmt.Sprintf("is equal to %v", e.x) -} - -type nilMatcher struct{} - -func (nilMatcher) Matches(x interface{}) bool { - if x == nil { - return true - } - - v := reflect.ValueOf(x) - switch v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, - reflect.Ptr, reflect.Slice: - return v.IsNil() - } - - return false -} - -func (nilMatcher) String() string { - return "is nil" -} - -type notMatcher struct { - m Matcher -} - -func (n notMatcher) Matches(x interface{}) bool { - return !n.m.Matches(x) -} - -func (n notMatcher) String() string { - // TODO: Improve this if we add a NotString method to the Matcher interface. - return "not(" + n.m.String() + ")" -} - -// Constructors -func Any() Matcher { return anyMatcher{} } -func Eq(x interface{}) Matcher { return eqMatcher{x} } -func Nil() Matcher { return nilMatcher{} } -func Not(x interface{}) Matcher { - if m, ok := x.(Matcher); ok { - return notMatcher{m} - } - return notMatcher{Eq(x)} -} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b1b..000000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 588ceca18..000000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.4.3 - - 1.5.4 - - 1.6.2 - - 1.7.1 - - tip - -script: - - go test -v ./... diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e75..000000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -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. - -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/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 273db3c98..000000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## Licence - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade0..000000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 842ee8045..000000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,269 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// and the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required the errors.WithStack and errors.WithMessage -// functions destructure errors.Wrap into its component operations of annotating -// an error with a stack trace and an a message, respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error which does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// causer interface is not exported by this package, but is considered a part -// of stable public API. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported -// -// %s print the error. If the error has a Cause it will be -// printed recursively -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface. -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// Where errors.StackTrace is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d", f) -// } -// } -// -// stackTracer interface is not exported by this package, but is considered a part -// of stable public API. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is call, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 6b1f2891a..000000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,178 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - fmt.Fprintf(s, "\n%+v", f) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - fmt.Fprintf(s, "%v", []Frame(st)) - } - case 's': - fmt.Fprintf(s, "%s", []Frame(st)) - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} - -func trimGOPATH(name, file string) string { - // Here we want to get the source file path relative to the compile time - // GOPATH. As of Go 1.6.x there is no direct way to know the compiled - // GOPATH at runtime, but we can infer the number of path segments in the - // GOPATH. We note that fn.Name() returns the function name qualified by - // the import path, which does not include the GOPATH. Thus we can trim - // segments from the beginning of the file path until the number of path - // separators remaining is one more than the number of path separators in - // the function name. For example, given: - // - // GOPATH /home/user - // file /home/user/src/pkg/sub/file.go - // fn.Name() pkg/sub.Type.Method - // - // We want to produce: - // - // pkg/sub/file.go - // - // From this we can easily see that fn.Name() has one less path separator - // than our desired output. We count separators from the end of the file - // path until it finds two more than in the function name and then move - // one character forward to preserve the initial path segment without a - // leading separator. - const sep = "/" - goal := strings.Count(name, sep) + 2 - i := len(file) - for n := 0; n < goal; n++ { - i = strings.LastIndex(file[:i], sep) - if i == -1 { - // not enough separators found, set i so that the slice expression - // below leaves file unmodified - i = -len(sep) - break - } - } - // get back to 0 or trim the leading separator - file = file[i+len(sep):] - return file -} diff --git a/vendor/github.com/pmezard/go-difflib/LICENSE b/vendor/github.com/pmezard/go-difflib/LICENSE deleted file mode 100644 index c67dad612..000000000 --- a/vendor/github.com/pmezard/go-difflib/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013, Patrick Mezard -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. - The names of its contributors may not 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/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go deleted file mode 100644 index 003e99fad..000000000 --- a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go +++ /dev/null @@ -1,772 +0,0 @@ -// Package difflib is a partial port of Python difflib module. -// -// It provides tools to compare sequences of strings and generate textual diffs. -// -// The following class and functions have been ported: -// -// - SequenceMatcher -// -// - unified_diff -// -// - context_diff -// -// Getting unified diffs was the main goal of the port. Keep in mind this code -// is mostly suitable to output text differences in a human friendly way, there -// are no guarantees generated diffs are consumable by patch(1). -package difflib - -import ( - "bufio" - "bytes" - "fmt" - "io" - "strings" -) - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func max(a, b int) int { - if a > b { - return a - } - return b -} - -func calculateRatio(matches, length int) float64 { - if length > 0 { - return 2.0 * float64(matches) / float64(length) - } - return 1.0 -} - -type Match struct { - A int - B int - Size int -} - -type OpCode struct { - Tag byte - I1 int - I2 int - J1 int - J2 int -} - -// SequenceMatcher compares sequence of strings. The basic -// algorithm predates, and is a little fancier than, an algorithm -// published in the late 1980's by Ratcliff and Obershelp under the -// hyperbolic name "gestalt pattern matching". The basic idea is to find -// the longest contiguous matching subsequence that contains no "junk" -// elements (R-O doesn't address junk). The same idea is then applied -// recursively to the pieces of the sequences to the left and to the right -// of the matching subsequence. This does not yield minimal edit -// sequences, but does tend to yield matches that "look right" to people. -// -// SequenceMatcher tries to compute a "human-friendly diff" between two -// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the -// longest *contiguous* & junk-free matching subsequence. That's what -// catches peoples' eyes. The Windows(tm) windiff has another interesting -// notion, pairing up elements that appear uniquely in each sequence. -// That, and the method here, appear to yield more intuitive difference -// reports than does diff. This method appears to be the least vulnerable -// to synching up on blocks of "junk lines", though (like blank lines in -// ordinary text files, or maybe "

" lines in HTML files). That may be -// because this is the only method of the 3 that has a *concept* of -// "junk" . -// -// Timing: Basic R-O is cubic time worst case and quadratic time expected -// case. SequenceMatcher is quadratic time for the worst case and has -// expected-case behavior dependent in a complicated way on how many -// elements the sequences have in common; best case time is linear. -type SequenceMatcher struct { - a []string - b []string - b2j map[string][]int - IsJunk func(string) bool - autoJunk bool - bJunk map[string]struct{} - matchingBlocks []Match - fullBCount map[string]int - bPopular map[string]struct{} - opCodes []OpCode -} - -func NewMatcher(a, b []string) *SequenceMatcher { - m := SequenceMatcher{autoJunk: true} - m.SetSeqs(a, b) - return &m -} - -func NewMatcherWithJunk(a, b []string, autoJunk bool, - isJunk func(string) bool) *SequenceMatcher { - - m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} - m.SetSeqs(a, b) - return &m -} - -// Set two sequences to be compared. -func (m *SequenceMatcher) SetSeqs(a, b []string) { - m.SetSeq1(a) - m.SetSeq2(b) -} - -// Set the first sequence to be compared. The second sequence to be compared is -// not changed. -// -// SequenceMatcher computes and caches detailed information about the second -// sequence, so if you want to compare one sequence S against many sequences, -// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other -// sequences. -// -// See also SetSeqs() and SetSeq2(). -func (m *SequenceMatcher) SetSeq1(a []string) { - if &a == &m.a { - return - } - m.a = a - m.matchingBlocks = nil - m.opCodes = nil -} - -// Set the second sequence to be compared. The first sequence to be compared is -// not changed. -func (m *SequenceMatcher) SetSeq2(b []string) { - if &b == &m.b { - return - } - m.b = b - m.matchingBlocks = nil - m.opCodes = nil - m.fullBCount = nil - m.chainB() -} - -func (m *SequenceMatcher) chainB() { - // Populate line -> index mapping - b2j := map[string][]int{} - for i, s := range m.b { - indices := b2j[s] - indices = append(indices, i) - b2j[s] = indices - } - - // Purge junk elements - m.bJunk = map[string]struct{}{} - if m.IsJunk != nil { - junk := m.bJunk - for s, _ := range b2j { - if m.IsJunk(s) { - junk[s] = struct{}{} - } - } - for s, _ := range junk { - delete(b2j, s) - } - } - - // Purge remaining popular elements - popular := map[string]struct{}{} - n := len(m.b) - if m.autoJunk && n >= 200 { - ntest := n/100 + 1 - for s, indices := range b2j { - if len(indices) > ntest { - popular[s] = struct{}{} - } - } - for s, _ := range popular { - delete(b2j, s) - } - } - m.bPopular = popular - m.b2j = b2j -} - -func (m *SequenceMatcher) isBJunk(s string) bool { - _, ok := m.bJunk[s] - return ok -} - -// Find longest matching block in a[alo:ahi] and b[blo:bhi]. -// -// If IsJunk is not defined: -// -// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where -// alo <= i <= i+k <= ahi -// blo <= j <= j+k <= bhi -// and for all (i',j',k') meeting those conditions, -// k >= k' -// i <= i' -// and if i == i', j <= j' -// -// In other words, of all maximal matching blocks, return one that -// starts earliest in a, and of all those maximal matching blocks that -// start earliest in a, return the one that starts earliest in b. -// -// If IsJunk is defined, first the longest matching block is -// determined as above, but with the additional restriction that no -// junk element appears in the block. Then that block is extended as -// far as possible by matching (only) junk elements on both sides. So -// the resulting block never matches on junk except as identical junk -// happens to be adjacent to an "interesting" match. -// -// If no blocks match, return (alo, blo, 0). -func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { - // CAUTION: stripping common prefix or suffix would be incorrect. - // E.g., - // ab - // acab - // Longest matching block is "ab", but if common prefix is - // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so - // strip, so ends up claiming that ab is changed to acab by - // inserting "ca" in the middle. That's minimal but unintuitive: - // "it's obvious" that someone inserted "ac" at the front. - // Windiff ends up at the same place as diff, but by pairing up - // the unique 'b's and then matching the first two 'a's. - besti, bestj, bestsize := alo, blo, 0 - - // find longest junk-free match - // during an iteration of the loop, j2len[j] = length of longest - // junk-free match ending with a[i-1] and b[j] - j2len := map[int]int{} - for i := alo; i != ahi; i++ { - // look at all instances of a[i] in b; note that because - // b2j has no junk keys, the loop is skipped if a[i] is junk - newj2len := map[int]int{} - for _, j := range m.b2j[m.a[i]] { - // a[i] matches b[j] - if j < blo { - continue - } - if j >= bhi { - break - } - k := j2len[j-1] + 1 - newj2len[j] = k - if k > bestsize { - besti, bestj, bestsize = i-k+1, j-k+1, k - } - } - j2len = newj2len - } - - // Extend the best by non-junk elements on each end. In particular, - // "popular" non-junk elements aren't in b2j, which greatly speeds - // the inner loop above, but also means "the best" match so far - // doesn't contain any junk *or* popular non-junk elements. - for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && - m.a[besti-1] == m.b[bestj-1] { - besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 - } - for besti+bestsize < ahi && bestj+bestsize < bhi && - !m.isBJunk(m.b[bestj+bestsize]) && - m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 - } - - // Now that we have a wholly interesting match (albeit possibly - // empty!), we may as well suck up the matching junk on each - // side of it too. Can't think of a good reason not to, and it - // saves post-processing the (possibly considerable) expense of - // figuring out what to do with it. In the case of an empty - // interesting match, this is clearly the right thing to do, - // because no other kind of match is possible in the regions. - for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && - m.a[besti-1] == m.b[bestj-1] { - besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 - } - for besti+bestsize < ahi && bestj+bestsize < bhi && - m.isBJunk(m.b[bestj+bestsize]) && - m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 - } - - return Match{A: besti, B: bestj, Size: bestsize} -} - -// Return list of triples describing matching subsequences. -// -// Each triple is of the form (i, j, n), and means that -// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in -// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are -// adjacent triples in the list, and the second is not the last triple in the -// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe -// adjacent equal blocks. -// -// The last triple is a dummy, (len(a), len(b), 0), and is the only -// triple with n==0. -func (m *SequenceMatcher) GetMatchingBlocks() []Match { - if m.matchingBlocks != nil { - return m.matchingBlocks - } - - var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match - matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { - match := m.findLongestMatch(alo, ahi, blo, bhi) - i, j, k := match.A, match.B, match.Size - if match.Size > 0 { - if alo < i && blo < j { - matched = matchBlocks(alo, i, blo, j, matched) - } - matched = append(matched, match) - if i+k < ahi && j+k < bhi { - matched = matchBlocks(i+k, ahi, j+k, bhi, matched) - } - } - return matched - } - matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) - - // It's possible that we have adjacent equal blocks in the - // matching_blocks list now. - nonAdjacent := []Match{} - i1, j1, k1 := 0, 0, 0 - for _, b := range matched { - // Is this block adjacent to i1, j1, k1? - i2, j2, k2 := b.A, b.B, b.Size - if i1+k1 == i2 && j1+k1 == j2 { - // Yes, so collapse them -- this just increases the length of - // the first block by the length of the second, and the first - // block so lengthened remains the block to compare against. - k1 += k2 - } else { - // Not adjacent. Remember the first block (k1==0 means it's - // the dummy we started with), and make the second block the - // new block to compare against. - if k1 > 0 { - nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) - } - i1, j1, k1 = i2, j2, k2 - } - } - if k1 > 0 { - nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) - } - - nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) - m.matchingBlocks = nonAdjacent - return m.matchingBlocks -} - -// Return list of 5-tuples describing how to turn a into b. -// -// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple -// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the -// tuple preceding it, and likewise for j1 == the previous j2. -// -// The tags are characters, with these meanings: -// -// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] -// -// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. -// -// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. -// -// 'e' (equal): a[i1:i2] == b[j1:j2] -func (m *SequenceMatcher) GetOpCodes() []OpCode { - if m.opCodes != nil { - return m.opCodes - } - i, j := 0, 0 - matching := m.GetMatchingBlocks() - opCodes := make([]OpCode, 0, len(matching)) - for _, m := range matching { - // invariant: we've pumped out correct diffs to change - // a[:i] into b[:j], and the next matching block is - // a[ai:ai+size] == b[bj:bj+size]. So we need to pump - // out a diff to change a[i:ai] into b[j:bj], pump out - // the matching block, and move (i,j) beyond the match - ai, bj, size := m.A, m.B, m.Size - tag := byte(0) - if i < ai && j < bj { - tag = 'r' - } else if i < ai { - tag = 'd' - } else if j < bj { - tag = 'i' - } - if tag > 0 { - opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) - } - i, j = ai+size, bj+size - // the list of matching blocks is terminated by a - // sentinel with size 0 - if size > 0 { - opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) - } - } - m.opCodes = opCodes - return m.opCodes -} - -// Isolate change clusters by eliminating ranges with no changes. -// -// Return a generator of groups with up to n lines of context. -// Each group is in the same format as returned by GetOpCodes(). -func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { - if n < 0 { - n = 3 - } - codes := m.GetOpCodes() - if len(codes) == 0 { - codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} - } - // Fixup leading and trailing groups if they show no changes. - if codes[0].Tag == 'e' { - c := codes[0] - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} - } - if codes[len(codes)-1].Tag == 'e' { - c := codes[len(codes)-1] - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} - } - nn := n + n - groups := [][]OpCode{} - group := []OpCode{} - for _, c := range codes { - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - // End the current group and start a new one whenever - // there is a large range with no changes. - if c.Tag == 'e' && i2-i1 > nn { - group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), - j1, min(j2, j1+n)}) - groups = append(groups, group) - group = []OpCode{} - i1, j1 = max(i1, i2-n), max(j1, j2-n) - } - group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) - } - if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { - groups = append(groups, group) - } - return groups -} - -// Return a measure of the sequences' similarity (float in [0,1]). -// -// Where T is the total number of elements in both sequences, and -// M is the number of matches, this is 2.0*M / T. -// Note that this is 1 if the sequences are identical, and 0 if -// they have nothing in common. -// -// .Ratio() is expensive to compute if you haven't already computed -// .GetMatchingBlocks() or .GetOpCodes(), in which case you may -// want to try .QuickRatio() or .RealQuickRation() first to get an -// upper bound. -func (m *SequenceMatcher) Ratio() float64 { - matches := 0 - for _, m := range m.GetMatchingBlocks() { - matches += m.Size - } - return calculateRatio(matches, len(m.a)+len(m.b)) -} - -// Return an upper bound on ratio() relatively quickly. -// -// This isn't defined beyond that it is an upper bound on .Ratio(), and -// is faster to compute. -func (m *SequenceMatcher) QuickRatio() float64 { - // viewing a and b as multisets, set matches to the cardinality - // of their intersection; this counts the number of matches - // without regard to order, so is clearly an upper bound - if m.fullBCount == nil { - m.fullBCount = map[string]int{} - for _, s := range m.b { - m.fullBCount[s] = m.fullBCount[s] + 1 - } - } - - // avail[x] is the number of times x appears in 'b' less the - // number of times we've seen it in 'a' so far ... kinda - avail := map[string]int{} - matches := 0 - for _, s := range m.a { - n, ok := avail[s] - if !ok { - n = m.fullBCount[s] - } - avail[s] = n - 1 - if n > 0 { - matches += 1 - } - } - return calculateRatio(matches, len(m.a)+len(m.b)) -} - -// Return an upper bound on ratio() very quickly. -// -// This isn't defined beyond that it is an upper bound on .Ratio(), and -// is faster to compute than either .Ratio() or .QuickRatio(). -func (m *SequenceMatcher) RealQuickRatio() float64 { - la, lb := len(m.a), len(m.b) - return calculateRatio(min(la, lb), la+lb) -} - -// Convert range to the "ed" format -func formatRangeUnified(start, stop int) string { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - beginning := start + 1 // lines start numbering with one - length := stop - start - if length == 1 { - return fmt.Sprintf("%d", beginning) - } - if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range - } - return fmt.Sprintf("%d,%d", beginning, length) -} - -// Unified diff parameters -type UnifiedDiff struct { - A []string // First sequence lines - FromFile string // First file name - FromDate string // First file time - B []string // Second sequence lines - ToFile string // Second file name - ToDate string // Second file time - Eol string // Headers end of line, defaults to LF - Context int // Number of context lines -} - -// Compare two sequences of lines; generate the delta as a unified diff. -// -// Unified diffs are a compact way of showing line changes and a few -// lines of context. The number of context lines is set by 'n' which -// defaults to three. -// -// By default, the diff control lines (those with ---, +++, or @@) are -// created with a trailing newline. This is helpful so that inputs -// created from file.readlines() result in diffs that are suitable for -// file.writelines() since both the inputs and outputs have trailing -// newlines. -// -// For inputs that do not have trailing newlines, set the lineterm -// argument to "" so that the output will be uniformly newline free. -// -// The unidiff format normally has a header for filenames and modification -// times. Any or all of these may be specified using strings for -// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. -// The modification times are normally expressed in the ISO 8601 format. -func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { - buf := bufio.NewWriter(writer) - defer buf.Flush() - wf := func(format string, args ...interface{}) error { - _, err := buf.WriteString(fmt.Sprintf(format, args...)) - return err - } - ws := func(s string) error { - _, err := buf.WriteString(s) - return err - } - - if len(diff.Eol) == 0 { - diff.Eol = "\n" - } - - started := false - m := NewMatcher(diff.A, diff.B) - for _, g := range m.GetGroupedOpCodes(diff.Context) { - if !started { - started = true - fromDate := "" - if len(diff.FromDate) > 0 { - fromDate = "\t" + diff.FromDate - } - toDate := "" - if len(diff.ToDate) > 0 { - toDate = "\t" + diff.ToDate - } - if diff.FromFile != "" || diff.ToFile != "" { - err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) - if err != nil { - return err - } - err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) - if err != nil { - return err - } - } - } - first, last := g[0], g[len(g)-1] - range1 := formatRangeUnified(first.I1, last.I2) - range2 := formatRangeUnified(first.J1, last.J2) - if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { - return err - } - for _, c := range g { - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - if c.Tag == 'e' { - for _, line := range diff.A[i1:i2] { - if err := ws(" " + line); err != nil { - return err - } - } - continue - } - if c.Tag == 'r' || c.Tag == 'd' { - for _, line := range diff.A[i1:i2] { - if err := ws("-" + line); err != nil { - return err - } - } - } - if c.Tag == 'r' || c.Tag == 'i' { - for _, line := range diff.B[j1:j2] { - if err := ws("+" + line); err != nil { - return err - } - } - } - } - } - return nil -} - -// Like WriteUnifiedDiff but returns the diff a string. -func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { - w := &bytes.Buffer{} - err := WriteUnifiedDiff(w, diff) - return string(w.Bytes()), err -} - -// Convert range to the "ed" format. -func formatRangeContext(start, stop int) string { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - beginning := start + 1 // lines start numbering with one - length := stop - start - if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range - } - if length <= 1 { - return fmt.Sprintf("%d", beginning) - } - return fmt.Sprintf("%d,%d", beginning, beginning+length-1) -} - -type ContextDiff UnifiedDiff - -// Compare two sequences of lines; generate the delta as a context diff. -// -// Context diffs are a compact way of showing line changes and a few -// lines of context. The number of context lines is set by diff.Context -// which defaults to three. -// -// By default, the diff control lines (those with *** or ---) are -// created with a trailing newline. -// -// For inputs that do not have trailing newlines, set the diff.Eol -// argument to "" so that the output will be uniformly newline free. -// -// The context diff format normally has a header for filenames and -// modification times. Any or all of these may be specified using -// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. -// The modification times are normally expressed in the ISO 8601 format. -// If not specified, the strings default to blanks. -func WriteContextDiff(writer io.Writer, diff ContextDiff) error { - buf := bufio.NewWriter(writer) - defer buf.Flush() - var diffErr error - wf := func(format string, args ...interface{}) { - _, err := buf.WriteString(fmt.Sprintf(format, args...)) - if diffErr == nil && err != nil { - diffErr = err - } - } - ws := func(s string) { - _, err := buf.WriteString(s) - if diffErr == nil && err != nil { - diffErr = err - } - } - - if len(diff.Eol) == 0 { - diff.Eol = "\n" - } - - prefix := map[byte]string{ - 'i': "+ ", - 'd': "- ", - 'r': "! ", - 'e': " ", - } - - started := false - m := NewMatcher(diff.A, diff.B) - for _, g := range m.GetGroupedOpCodes(diff.Context) { - if !started { - started = true - fromDate := "" - if len(diff.FromDate) > 0 { - fromDate = "\t" + diff.FromDate - } - toDate := "" - if len(diff.ToDate) > 0 { - toDate = "\t" + diff.ToDate - } - if diff.FromFile != "" || diff.ToFile != "" { - wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) - wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol) - } - } - - first, last := g[0], g[len(g)-1] - ws("***************" + diff.Eol) - - range1 := formatRangeContext(first.I1, last.I2) - wf("*** %s ****%s", range1, diff.Eol) - for _, c := range g { - if c.Tag == 'r' || c.Tag == 'd' { - for _, cc := range g { - if cc.Tag == 'i' { - continue - } - for _, line := range diff.A[cc.I1:cc.I2] { - ws(prefix[cc.Tag] + line) - } - } - break - } - } - - range2 := formatRangeContext(first.J1, last.J2) - wf("--- %s ----%s", range2, diff.Eol) - for _, c := range g { - if c.Tag == 'r' || c.Tag == 'i' { - for _, cc := range g { - if cc.Tag == 'd' { - continue - } - for _, line := range diff.B[cc.J1:cc.J2] { - ws(prefix[cc.Tag] + line) - } - } - break - } - } - } - return diffErr -} - -// Like WriteContextDiff but returns the diff a string. -func GetContextDiffString(diff ContextDiff) (string, error) { - w := &bytes.Buffer{} - err := WriteContextDiff(w, diff) - return string(w.Bytes()), err -} - -// Split a string on "\n" while preserving them. The output can be used -// as input for UnifiedDiff and ContextDiff structures. -func SplitLines(s string) []string { - lines := strings.SplitAfter(s, "\n") - lines[len(lines)-1] += "\n" - return lines -} diff --git a/vendor/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE deleted file mode 100644 index 473b670a7..000000000 --- a/vendor/github.com/stretchr/testify/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell - -Please consider promoting this project if you find it useful. - -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/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go deleted file mode 100644 index aa1c2b95c..000000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_format.go +++ /dev/null @@ -1,484 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package assert - -import ( - http "net/http" - url "net/url" - time "time" -) - -// Conditionf uses a Comparison to assert a complex condition. -func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Condition(t, comp, append([]interface{}{msg}, args...)...) -} - -// Containsf asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") -// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") -// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") -func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Contains(t, s, contains, append([]interface{}{msg}, args...)...) -} - -// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. -func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return DirExists(t, path, append([]interface{}{msg}, args...)...) -} - -// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") -func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...) -} - -// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Emptyf(t, obj, "error message %s", "formatted") -func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Empty(t, object, append([]interface{}{msg}, args...)...) -} - -// Equalf asserts that two objects are equal. -// -// assert.Equalf(t, 123, 123, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Equal(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// EqualErrorf asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") -func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) -} - -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) -func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// Errorf asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Errorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } -func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Error(t, err, append([]interface{}{msg}, args...)...) -} - -// Exactlyf asserts that two objects are equal in value and type. -// -// assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) -func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// Failf reports a failure through -func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Fail(t, failureMessage, append([]interface{}{msg}, args...)...) -} - -// FailNowf fails test -func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...) -} - -// Falsef asserts that the specified value is false. -// -// assert.Falsef(t, myBool, "error message %s", "formatted") -func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return False(t, value, append([]interface{}{msg}, args...)...) -} - -// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. -func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return FileExists(t, path, append([]interface{}{msg}, args...)...) -} - -// HTTPBodyContainsf asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPBodyContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) -} - -// HTTPBodyNotContainsf asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPBodyNotContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) -} - -// HTTPErrorf asserts that a specified handler returns an error status code. -// -// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). -func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPError(t, handler, method, url, values, append([]interface{}{msg}, args...)...) -} - -// HTTPRedirectf asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). -func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...) -} - -// HTTPSuccessf asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPSuccess(t, handler, method, url, values, append([]interface{}{msg}, args...)...) -} - -// Implementsf asserts that an object is implemented by the specified interface. -// -// assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) -func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) -} - -// InDeltaf asserts that the two numerals are within delta of each other. -// -// assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) -func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...) -} - -// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InDeltaMapValues(t, expected, actual, delta, append([]interface{}{msg}, args...)...) -} - -// InDeltaSlicef is the same as InDelta, except it compares two slices. -func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...) -} - -// InEpsilonf asserts that expected and actual have a relative error less than epsilon -func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) -} - -// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) -} - -// IsTypef asserts that the specified objects are of the same type. -func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...) -} - -// JSONEqf asserts that two JSON strings are equivalent. -// -// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") -func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// Lenf asserts that the specified object has specific length. -// Lenf also fails if the object has a type that len() not accept. -// -// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") -func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Len(t, object, length, append([]interface{}{msg}, args...)...) -} - -// Nilf asserts that the specified object is nil. -// -// assert.Nilf(t, err, "error message %s", "formatted") -func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Nil(t, object, append([]interface{}{msg}, args...)...) -} - -// NoErrorf asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoErrorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } -func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NoError(t, err, append([]interface{}{msg}, args...)...) -} - -// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") -func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) -} - -// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } -func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotEmpty(t, object, append([]interface{}{msg}, args...)...) -} - -// NotEqualf asserts that the specified values are NOT equal. -// -// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// NotNilf asserts that the specified object is not nil. -// -// assert.NotNilf(t, err, "error message %s", "formatted") -func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotNil(t, object, append([]interface{}{msg}, args...)...) -} - -// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") -func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotPanics(t, f, append([]interface{}{msg}, args...)...) -} - -// NotRegexpf asserts that a specified regexp does not match a string. -// -// assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") -// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") -func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...) -} - -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") -func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...) -} - -// NotZerof asserts that i is not the zero value for its type. -func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotZero(t, i, append([]interface{}{msg}, args...)...) -} - -// Panicsf asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") -func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Panics(t, f, append([]interface{}{msg}, args...)...) -} - -// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...) -} - -// Regexpf asserts that a specified regexp matches a string. -// -// assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") -// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") -func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Regexp(t, rx, str, append([]interface{}{msg}, args...)...) -} - -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") -func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Subset(t, list, subset, append([]interface{}{msg}, args...)...) -} - -// Truef asserts that the specified value is true. -// -// assert.Truef(t, myBool, "error message %s", "formatted") -func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return True(t, value, append([]interface{}{msg}, args...)...) -} - -// WithinDurationf asserts that the two times are within duration delta of each other. -// -// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") -func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) -} - -// Zerof asserts that i is the zero value for its type. -func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Zero(t, i, append([]interface{}{msg}, args...)...) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl deleted file mode 100644 index d2bb0b817..000000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl +++ /dev/null @@ -1,5 +0,0 @@ -{{.CommentFormat}} -func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool { - if h, ok := t.(tHelper); ok { h.Helper() } - return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}}) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go deleted file mode 100644 index de39f794e..000000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ /dev/null @@ -1,956 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package assert - -import ( - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Condition(a.t, comp, msgAndArgs...) -} - -// Conditionf uses a Comparison to assert a complex condition. -func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Conditionf(a.t, comp, msg, args...) -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Contains("Hello World", "World") -// a.Contains(["Hello", "World"], "World") -// a.Contains({"Hello": "World"}, "Hello") -func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Contains(a.t, s, contains, msgAndArgs...) -} - -// Containsf asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Containsf("Hello World", "World", "error message %s", "formatted") -// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") -// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") -func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Containsf(a.t, s, contains, msg, args...) -} - -// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. -func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return DirExists(a.t, path, msgAndArgs...) -} - -// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. -func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return DirExistsf(a.t, path, msg, args...) -} - -// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) -func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ElementsMatch(a.t, listA, listB, msgAndArgs...) -} - -// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") -func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ElementsMatchf(a.t, listA, listB, msg, args...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Empty(obj) -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Empty(a.t, object, msgAndArgs...) -} - -// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Emptyf(obj, "error message %s", "formatted") -func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Emptyf(a.t, object, msg, args...) -} - -// Equal asserts that two objects are equal. -// -// a.Equal(123, 123) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString) -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return EqualError(a.t, theError, errString, msgAndArgs...) -} - -// EqualErrorf asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") -func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return EqualErrorf(a.t, theError, errString, msg, args...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValues(uint32(123), int32(123)) -func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) -func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return EqualValuesf(a.t, expected, actual, msg, args...) -} - -// Equalf asserts that two objects are equal. -// -// a.Equalf(123, 123, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Equalf(a.t, expected, actual, msg, args...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Error(err) { -// assert.Equal(t, expectedError, err) -// } -func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Error(a.t, err, msgAndArgs...) -} - -// Errorf asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Errorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } -func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Errorf(a.t, err, msg, args...) -} - -// Exactly asserts that two objects are equal in value and type. -// -// a.Exactly(int32(123), int64(123)) -func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Exactly(a.t, expected, actual, msgAndArgs...) -} - -// Exactlyf asserts that two objects are equal in value and type. -// -// a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) -func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Exactlyf(a.t, expected, actual, msg, args...) -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Fail(a.t, failureMessage, msgAndArgs...) -} - -// FailNow fails test -func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return FailNow(a.t, failureMessage, msgAndArgs...) -} - -// FailNowf fails test -func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return FailNowf(a.t, failureMessage, msg, args...) -} - -// Failf reports a failure through -func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Failf(a.t, failureMessage, msg, args...) -} - -// False asserts that the specified value is false. -// -// a.False(myBool) -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return False(a.t, value, msgAndArgs...) -} - -// Falsef asserts that the specified value is false. -// -// a.Falsef(myBool, "error message %s", "formatted") -func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Falsef(a.t, value, msg, args...) -} - -// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. -func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return FileExists(a.t, path, msgAndArgs...) -} - -// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. -func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return FileExistsf(a.t, path, msg, args...) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) -} - -// HTTPBodyContainsf asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) -} - -// HTTPBodyNotContainsf asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPError(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPErrorf asserts that a specified handler returns an error status code. -// -// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). -func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPErrorf(a.t, handler, method, url, values, msg, args...) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPRedirectf asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). -func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPRedirectf(a.t, handler, method, url, values, msg, args...) -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPSuccessf asserts that a specified handler returns a success status code. -// -// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPSuccessf(a.t, handler, method, url, values, msg, args...) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// a.Implements((*MyInterface)(nil), new(MyObject)) -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// Implementsf asserts that an object is implemented by the specified interface. -// -// a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) -func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Implementsf(a.t, interfaceObject, object, msg, args...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// a.InDelta(math.Pi, (22 / 7.0), 0.01) -func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaSlicef is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaSlicef(a.t, expected, actual, delta, msg, args...) -} - -// InDeltaf asserts that the two numerals are within delta of each other. -// -// a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) -func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaf(a.t, expected, actual, delta, msg, args...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) -} - -// InEpsilonf asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InEpsilonf(a.t, expected, actual, epsilon, msg, args...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsType(a.t, expectedType, object, msgAndArgs...) -} - -// IsTypef asserts that the specified objects are of the same type. -func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsTypef(a.t, expectedType, object, msg, args...) -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return JSONEq(a.t, expected, actual, msgAndArgs...) -} - -// JSONEqf asserts that two JSON strings are equivalent. -// -// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") -func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return JSONEqf(a.t, expected, actual, msg, args...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// a.Len(mySlice, 3) -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Len(a.t, object, length, msgAndArgs...) -} - -// Lenf asserts that the specified object has specific length. -// Lenf also fails if the object has a type that len() not accept. -// -// a.Lenf(mySlice, 3, "error message %s", "formatted") -func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Lenf(a.t, object, length, msg, args...) -} - -// Nil asserts that the specified object is nil. -// -// a.Nil(err) -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Nil(a.t, object, msgAndArgs...) -} - -// Nilf asserts that the specified object is nil. -// -// a.Nilf(err, "error message %s", "formatted") -func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Nilf(a.t, object, msg, args...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, expectedObj, actualObj) -// } -func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NoError(a.t, err, msgAndArgs...) -} - -// NoErrorf asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoErrorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } -func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NoErrorf(a.t, err, msg, args...) -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContains("Hello World", "Earth") -// a.NotContains(["Hello", "World"], "Earth") -// a.NotContains({"Hello": "World"}, "Earth") -func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotContains(a.t, s, contains, msgAndArgs...) -} - -// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") -// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") -// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") -func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotContainsf(a.t, s, contains, msg, args...) -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEmpty(a.t, object, msgAndArgs...) -} - -// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmptyf(obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } -func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEmptyf(a.t, object, msg, args...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// a.NotEqual(obj1, obj2) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// NotEqualf asserts that the specified values are NOT equal. -// -// a.NotEqualf(obj1, obj2, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEqualf(a.t, expected, actual, msg, args...) -} - -// NotNil asserts that the specified object is not nil. -// -// a.NotNil(err) -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotNil(a.t, object, msgAndArgs...) -} - -// NotNilf asserts that the specified object is not nil. -// -// a.NotNilf(err, "error message %s", "formatted") -func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotNilf(a.t, object, msg, args...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanics(func(){ RemainCalm() }) -func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotPanics(a.t, f, msgAndArgs...) -} - -// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") -func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotPanicsf(a.t, f, msg, args...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotRegexp(a.t, rx, str, msgAndArgs...) -} - -// NotRegexpf asserts that a specified regexp does not match a string. -// -// a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") -// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") -func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotRegexpf(a.t, rx, str, msg, args...) -} - -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") -func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotSubset(a.t, list, subset, msgAndArgs...) -} - -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") -func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotSubsetf(a.t, list, subset, msg, args...) -} - -// NotZero asserts that i is not the zero value for its type. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotZero(a.t, i, msgAndArgs...) -} - -// NotZerof asserts that i is not the zero value for its type. -func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotZerof(a.t, i, msg, args...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panics(func(){ GoCrazy() }) -func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Panics(a.t, f, msgAndArgs...) -} - -// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) -func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return PanicsWithValue(a.t, expected, f, msgAndArgs...) -} - -// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return PanicsWithValuef(a.t, expected, f, msg, args...) -} - -// Panicsf asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Panicsf(a.t, f, msg, args...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Regexp(a.t, rx, str, msgAndArgs...) -} - -// Regexpf asserts that a specified regexp matches a string. -// -// a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") -// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") -func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Regexpf(a.t, rx, str, msg, args...) -} - -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") -func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Subset(a.t, list, subset, msgAndArgs...) -} - -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") -func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Subsetf(a.t, list, subset, msg, args...) -} - -// True asserts that the specified value is true. -// -// a.True(myBool) -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return True(a.t, value, msgAndArgs...) -} - -// Truef asserts that the specified value is true. -// -// a.Truef(myBool, "error message %s", "formatted") -func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Truef(a.t, value, msg, args...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) -func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// WithinDurationf asserts that the two times are within duration delta of each other. -// -// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") -func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return WithinDurationf(a.t, expected, actual, delta, msg, args...) -} - -// Zero asserts that i is the zero value for its type. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Zero(a.t, i, msgAndArgs...) -} - -// Zerof asserts that i is the zero value for its type. -func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Zerof(a.t, i, msg, args...) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl deleted file mode 100644 index 188bb9e17..000000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl +++ /dev/null @@ -1,5 +0,0 @@ -{{.CommentWithoutT "a"}} -func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { - if h, ok := a.t.(tHelper); ok { h.Helper() } - return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go deleted file mode 100644 index 5bdec56cd..000000000 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ /dev/null @@ -1,1394 +0,0 @@ -package assert - -import ( - "bufio" - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "os" - "reflect" - "regexp" - "runtime" - "strings" - "time" - "unicode" - "unicode/utf8" - - "github.com/davecgh/go-spew/spew" - "github.com/pmezard/go-difflib/difflib" -) - -//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) -} - -// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful -// for table driven tests. -type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool - -// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful -// for table driven tests. -type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool - -// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful -// for table driven tests. -type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool - -// ValuesAssertionFunc is a common function prototype when validating an error value. Can be useful -// for table driven tests. -type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool - -// Comparison a custom function that returns true on success and false on failure -type Comparison func() (success bool) - -/* - Helper functions -*/ - -// ObjectsAreEqual determines if two objects are considered equal. -// -// This function does no assertion of any kind. -func ObjectsAreEqual(expected, actual interface{}) bool { - if expected == nil || actual == nil { - return expected == actual - } - - exp, ok := expected.([]byte) - if !ok { - return reflect.DeepEqual(expected, actual) - } - - act, ok := actual.([]byte) - if !ok { - return false - } - if exp == nil || act == nil { - return exp == nil && act == nil - } - return bytes.Equal(exp, act) -} - -// ObjectsAreEqualValues gets whether two objects are equal, or if their -// values are equal. -func ObjectsAreEqualValues(expected, actual interface{}) bool { - if ObjectsAreEqual(expected, actual) { - return true - } - - actualType := reflect.TypeOf(actual) - if actualType == nil { - return false - } - expectedValue := reflect.ValueOf(expected) - if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { - // Attempt comparison after type conversion - return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) - } - - return false -} - -/* CallerInfo is necessary because the assert functions use the testing object -internally, causing it to print the file:line of the assert method, rather than where -the problem actually occurred in calling code.*/ - -// CallerInfo returns an array of strings containing the file and line number -// of each stack frame leading from the current test to the assert call that -// failed. -func CallerInfo() []string { - - pc := uintptr(0) - file := "" - line := 0 - ok := false - name := "" - - callers := []string{} - for i := 0; ; i++ { - pc, file, line, ok = runtime.Caller(i) - if !ok { - // The breaks below failed to terminate the loop, and we ran off the - // end of the call stack. - break - } - - // This is a huge edge case, but it will panic if this is the case, see #180 - if file == "" { - break - } - - f := runtime.FuncForPC(pc) - if f == nil { - break - } - name = f.Name() - - // testing.tRunner is the standard library function that calls - // tests. Subtests are called directly by tRunner, without going through - // the Test/Benchmark/Example function that contains the t.Run calls, so - // with subtests we should break when we hit tRunner, without adding it - // to the list of callers. - if name == "testing.tRunner" { - break - } - - parts := strings.Split(file, "/") - file = parts[len(parts)-1] - if len(parts) > 1 { - dir := parts[len(parts)-2] - if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { - callers = append(callers, fmt.Sprintf("%s:%d", file, line)) - } - } - - // Drop the package - segments := strings.Split(name, ".") - name = segments[len(segments)-1] - if isTest(name, "Test") || - isTest(name, "Benchmark") || - isTest(name, "Example") { - break - } - } - - return callers -} - -// Stolen from the `go test` tool. -// isTest tells whether name looks like a test (or benchmark, according to prefix). -// It is a Test (say) if there is a character after Test that is not a lower-case letter. -// We don't want TesticularCancer. -func isTest(name, prefix string) bool { - if !strings.HasPrefix(name, prefix) { - return false - } - if len(name) == len(prefix) { // "Test" is ok - return true - } - rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) - return !unicode.IsLower(rune) -} - -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { - if len(msgAndArgs) == 0 || msgAndArgs == nil { - return "" - } - if len(msgAndArgs) == 1 { - return msgAndArgs[0].(string) - } - if len(msgAndArgs) > 1 { - return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) - } - return "" -} - -// Aligns the provided message so that all lines after the first line start at the same location as the first line. -// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). -// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the -// basis on which the alignment occurs). -func indentMessageLines(message string, longestLabelLen int) string { - outBuf := new(bytes.Buffer) - - for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { - // no need to align first line because it starts at the correct location (after the label) - if i != 0 { - // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab - outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") - } - outBuf.WriteString(scanner.Text()) - } - - return outBuf.String() -} - -type failNower interface { - FailNow() -} - -// FailNow fails test -func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - Fail(t, failureMessage, msgAndArgs...) - - // We cannot extend TestingT with FailNow() and - // maintain backwards compatibility, so we fallback - // to panicking when FailNow is not available in - // TestingT. - // See issue #263 - - if t, ok := t.(failNower); ok { - t.FailNow() - } else { - panic("test failed and t is missing `FailNow()`") - } - return false -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - content := []labeledContent{ - {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")}, - {"Error", failureMessage}, - } - - // Add test name if the Go version supports it - if n, ok := t.(interface { - Name() string - }); ok { - content = append(content, labeledContent{"Test", n.Name()}) - } - - message := messageFromMsgAndArgs(msgAndArgs...) - if len(message) > 0 { - content = append(content, labeledContent{"Messages", message}) - } - - t.Errorf("\n%s", ""+labeledOutput(content...)) - - return false -} - -type labeledContent struct { - label string - content string -} - -// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: -// -// \t{{label}}:{{align_spaces}}\t{{content}}\n -// -// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. -// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this -// alignment is achieved, "\t{{content}}\n" is added for the output. -// -// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. -func labeledOutput(content ...labeledContent) string { - longestLabel := 0 - for _, v := range content { - if len(v.label) > longestLabel { - longestLabel = len(v.label) - } - } - var output string - for _, v := range content { - output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" - } - return output -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - interfaceType := reflect.TypeOf(interfaceObject).Elem() - - if object == nil { - return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...) - } - if !reflect.TypeOf(object).Implements(interfaceType) { - return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) - } - - return true -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { - return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) - } - - return true -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if err := validateEqualArgs(expected, actual); err != nil { - return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", - expected, actual, err), msgAndArgs...) - } - - if !ObjectsAreEqual(expected, actual) { - diff := diff(expected, actual) - expected, actual = formatUnequalValues(expected, actual) - return Fail(t, fmt.Sprintf("Not equal: \n"+ - "expected: %s\n"+ - "actual : %s%s", expected, actual, diff), msgAndArgs...) - } - - return true - -} - -// formatUnequalValues takes two values of arbitrary types and returns string -// representations appropriate to be presented to the user. -// -// If the values are not of like type, the returned strings will be prefixed -// with the type name, and the value will be enclosed in parenthesis similar -// to a type conversion in the Go grammar. -func formatUnequalValues(expected, actual interface{}) (e string, a string) { - if reflect.TypeOf(expected) != reflect.TypeOf(actual) { - return fmt.Sprintf("%T(%#v)", expected, expected), - fmt.Sprintf("%T(%#v)", actual, actual) - } - - return fmt.Sprintf("%#v", expected), - fmt.Sprintf("%#v", actual) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123)) -func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if !ObjectsAreEqualValues(expected, actual) { - diff := diff(expected, actual) - expected, actual = formatUnequalValues(expected, actual) - return Fail(t, fmt.Sprintf("Not equal: \n"+ - "expected: %s\n"+ - "actual : %s%s", expected, actual, diff), msgAndArgs...) - } - - return true - -} - -// Exactly asserts that two objects are equal in value and type. -// -// assert.Exactly(t, int32(123), int64(123)) -func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - aType := reflect.TypeOf(expected) - bType := reflect.TypeOf(actual) - - if aType != bType { - return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) - } - - return Equal(t, expected, actual, msgAndArgs...) - -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err) -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if !isNil(object) { - return true - } - return Fail(t, "Expected value not to be nil.", msgAndArgs...) -} - -// isNil checks if a specified object is nil or not, without Failing. -func isNil(object interface{}) bool { - if object == nil { - return true - } - - value := reflect.ValueOf(object) - kind := value.Kind() - if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { - return true - } - - return false -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err) -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if isNil(object) { - return true - } - return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) -} - -// isEmpty gets whether the specified object is considered empty or not. -func isEmpty(object interface{}) bool { - - // get nil case out of the way - if object == nil { - return true - } - - objValue := reflect.ValueOf(object) - - switch objValue.Kind() { - // collection types are empty when they have no element - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - return objValue.Len() == 0 - // pointers are empty if nil or if the value they point to is empty - case reflect.Ptr: - if objValue.IsNil() { - return true - } - deref := objValue.Elem().Interface() - return isEmpty(deref) - // for all other types, compare against the zero value - default: - zero := reflect.Zero(objValue.Type()) - return reflect.DeepEqual(object, zero.Interface()) - } -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - pass := isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - pass := !isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { - v := reflect.ValueOf(x) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - return true, v.Len() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3) -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - ok, l := getLen(object) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) - } - - if l != length { - return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) - } - return true -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool) -func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if h, ok := t.(interface { - Helper() - }); ok { - h.Helper() - } - - if value != true { - return Fail(t, "Should be true", msgAndArgs...) - } - - return true - -} - -// False asserts that the specified value is false. -// -// assert.False(t, myBool) -func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if value != false { - return Fail(t, "Should be false", msgAndArgs...) - } - - return true - -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if err := validateEqualArgs(expected, actual); err != nil { - return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)", - expected, actual, err), msgAndArgs...) - } - - if ObjectsAreEqual(expected, actual) { - return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) - } - - return true - -} - -// containsElement try loop over the list check if the list includes the element. -// return (false, false) if impossible. -// return (true, false) if element was not found. -// return (true, true) if element was found. -func includeElement(list interface{}, element interface{}) (ok, found bool) { - - listValue := reflect.ValueOf(list) - elementValue := reflect.ValueOf(element) - defer func() { - if e := recover(); e != nil { - ok = false - found = false - } - }() - - if reflect.TypeOf(list).Kind() == reflect.String { - return true, strings.Contains(listValue.String(), elementValue.String()) - } - - if reflect.TypeOf(list).Kind() == reflect.Map { - mapKeys := listValue.MapKeys() - for i := 0; i < len(mapKeys); i++ { - if ObjectsAreEqual(mapKeys[i].Interface(), element) { - return true, true - } - } - return true, false - } - - for i := 0; i < listValue.Len(); i++ { - if ObjectsAreEqual(listValue.Index(i).Interface(), element) { - return true, true - } - } - return true, false - -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World") -// assert.Contains(t, ["Hello", "World"], "World") -// assert.Contains(t, {"Hello": "World"}, "Hello") -func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if !found { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth") -// assert.NotContains(t, ["Hello", "World"], "Earth") -// assert.NotContains(t, {"Hello": "World"}, "Earth") -func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if found { - return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") -func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if subset == nil { - return true // we consider nil to be equal to the nil set - } - - subsetValue := reflect.ValueOf(subset) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - - listKind := reflect.TypeOf(list).Kind() - subsetKind := reflect.TypeOf(subset).Kind() - - if listKind != reflect.Array && listKind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) - } - - if subsetKind != reflect.Array && subsetKind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) - } - - for i := 0; i < subsetValue.Len(); i++ { - element := subsetValue.Index(i).Interface() - ok, found := includeElement(list, element) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) - } - if !found { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...) - } - } - - return true -} - -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") -func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if subset == nil { - return Fail(t, fmt.Sprintf("nil is the empty set which is a subset of every set"), msgAndArgs...) - } - - subsetValue := reflect.ValueOf(subset) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - - listKind := reflect.TypeOf(list).Kind() - subsetKind := reflect.TypeOf(subset).Kind() - - if listKind != reflect.Array && listKind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) - } - - if subsetKind != reflect.Array && subsetKind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) - } - - for i := 0; i < subsetValue.Len(); i++ { - element := subsetValue.Index(i).Interface() - ok, found := includeElement(list, element) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) - } - if !found { - return true - } - } - - return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) -} - -// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) -func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if isEmpty(listA) && isEmpty(listB) { - return true - } - - aKind := reflect.TypeOf(listA).Kind() - bKind := reflect.TypeOf(listB).Kind() - - if aKind != reflect.Array && aKind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listA, aKind), msgAndArgs...) - } - - if bKind != reflect.Array && bKind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listB, bKind), msgAndArgs...) - } - - aValue := reflect.ValueOf(listA) - bValue := reflect.ValueOf(listB) - - aLen := aValue.Len() - bLen := bValue.Len() - - if aLen != bLen { - return Fail(t, fmt.Sprintf("lengths don't match: %d != %d", aLen, bLen), msgAndArgs...) - } - - // Mark indexes in bValue that we already used - visited := make([]bool, bLen) - for i := 0; i < aLen; i++ { - element := aValue.Index(i).Interface() - found := false - for j := 0; j < bLen; j++ { - if visited[j] { - continue - } - if ObjectsAreEqual(bValue.Index(j).Interface(), element) { - visited[j] = true - found = true - break - } - } - if !found { - return Fail(t, fmt.Sprintf("element %s appears more times in %s than in %s", element, aValue, bValue), msgAndArgs...) - } - } - - return true -} - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - result := comp() - if !result { - Fail(t, "Condition failed!", msgAndArgs...) - } - return result -} - -// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics -// methods, and represents a simple func that takes no arguments, and returns nothing. -type PanicTestFunc func() - -// didPanic returns true if the function passed to it panics. Otherwise, it returns false. -func didPanic(f PanicTestFunc) (bool, interface{}) { - - didPanic := false - var message interface{} - func() { - - defer func() { - if message = recover(); message != nil { - didPanic = true - } - }() - - // call the target function - f() - - }() - - return didPanic, message - -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ GoCrazy() }) -func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) - } - - return true -} - -// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) -func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - funcDidPanic, panicValue := didPanic(f) - if !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) - } - if panicValue != expected { - return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v", f, expected, panicValue), msgAndArgs...) - } - - return true -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ RemainCalm() }) -func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if funcDidPanic, panicValue := didPanic(f); funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) -func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - dt := expected.Sub(actual) - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -func toFloat(x interface{}) (float64, bool) { - var xf float64 - xok := true - - switch xn := x.(type) { - case uint8: - xf = float64(xn) - case uint16: - xf = float64(xn) - case uint32: - xf = float64(xn) - case uint64: - xf = float64(xn) - case int: - xf = float64(xn) - case int8: - xf = float64(xn) - case int16: - xf = float64(xn) - case int32: - xf = float64(xn) - case int64: - xf = float64(xn) - case float32: - xf = float64(xn) - case float64: - xf = float64(xn) - case time.Duration: - xf = float64(xn) - default: - xok = false - } - - return xf, xok -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) - } - - if math.IsNaN(af) { - return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...) - } - - if math.IsNaN(bf) { - return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) - } - - dt := af - bf - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...) - if !result { - return result - } - } - - return true -} - -// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Map || - reflect.TypeOf(expected).Kind() != reflect.Map { - return Fail(t, "Arguments must be maps", msgAndArgs...) - } - - expectedMap := reflect.ValueOf(expected) - actualMap := reflect.ValueOf(actual) - - if expectedMap.Len() != actualMap.Len() { - return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) - } - - for _, k := range expectedMap.MapKeys() { - ev := expectedMap.MapIndex(k) - av := actualMap.MapIndex(k) - - if !ev.IsValid() { - return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...) - } - - if !av.IsValid() { - return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...) - } - - if !InDelta( - t, - ev.Interface(), - av.Interface(), - delta, - msgAndArgs..., - ) { - return false - } - } - - return true -} - -func calcRelativeError(expected, actual interface{}) (float64, error) { - af, aok := toFloat(expected) - if !aok { - return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) - } - if af == 0 { - return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") - } - bf, bok := toFloat(actual) - if !bok { - return 0, fmt.Errorf("actual value %q cannot be converted to float", actual) - } - - return math.Abs(af-bf) / math.Abs(af), nil -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - actualEpsilon, err := calcRelativeError(expected, actual) - if err != nil { - return Fail(t, err.Error(), msgAndArgs...) - } - if actualEpsilon > epsilon { - return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ - " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...) - } - - return true -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) - if !result { - return result - } - } - - return true -} - -/* - Errors -*/ - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, expectedObj, actualObj) -// } -func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if err != nil { - return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) - } - - return true -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err) { -// assert.Equal(t, expectedError, err) -// } -func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if err == nil { - return Fail(t, "An error is expected but got nil.", msgAndArgs...) - } - - return true -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString) -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if !Error(t, theError, msgAndArgs...) { - return false - } - expected := errString - actual := theError.Error() - // don't need to use deep equals here, we know they are both strings - if expected != actual { - return Fail(t, fmt.Sprintf("Error message not equal:\n"+ - "expected: %q\n"+ - "actual : %q", expected, actual), msgAndArgs...) - } - return true -} - -// matchRegexp return true if a specified regexp matches a string. -func matchRegexp(rx interface{}, str interface{}) bool { - - var r *regexp.Regexp - if rr, ok := rx.(*regexp.Regexp); ok { - r = rr - } else { - r = regexp.MustCompile(fmt.Sprint(rx)) - } - - return (r.FindStringIndex(fmt.Sprint(str)) != nil) - -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - match := matchRegexp(rx, str) - - if !match { - Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) - } - - return match -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - match := matchRegexp(rx, str) - - if match { - Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) - } - - return !match - -} - -// Zero asserts that i is the zero value for its type. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// NotZero asserts that i is not the zero value for its type. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. -func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - info, err := os.Lstat(path) - if err != nil { - if os.IsNotExist(err) { - return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) - } - return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) - } - if info.IsDir() { - return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...) - } - return true -} - -// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. -func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - info, err := os.Lstat(path) - if err != nil { - if os.IsNotExist(err) { - return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) - } - return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) - } - if !info.IsDir() { - return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...) - } - return true -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - var expectedJSONAsInterface, actualJSONAsInterface interface{} - - if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) - } - - if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) - } - - return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) -} - -func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { - t := reflect.TypeOf(v) - k := t.Kind() - - if k == reflect.Ptr { - t = t.Elem() - k = t.Kind() - } - return t, k -} - -// diff returns a diff of both values as long as both are of the same type and -// are a struct, map, slice or array. Otherwise it returns an empty string. -func diff(expected interface{}, actual interface{}) string { - if expected == nil || actual == nil { - return "" - } - - et, ek := typeAndKind(expected) - at, _ := typeAndKind(actual) - - if et != at { - return "" - } - - if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String { - return "" - } - - var e, a string - if ek != reflect.String { - e = spewConfig.Sdump(expected) - a = spewConfig.Sdump(actual) - } else { - e = expected.(string) - a = actual.(string) - } - - diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ - A: difflib.SplitLines(e), - B: difflib.SplitLines(a), - FromFile: "Expected", - FromDate: "", - ToFile: "Actual", - ToDate: "", - Context: 1, - }) - - return "\n\nDiff:\n" + diff -} - -// validateEqualArgs checks whether provided arguments can be safely used in the -// Equal/NotEqual functions. -func validateEqualArgs(expected, actual interface{}) error { - if isFunction(expected) || isFunction(actual) { - return errors.New("cannot take func type as argument") - } - return nil -} - -func isFunction(arg interface{}) bool { - if arg == nil { - return false - } - return reflect.TypeOf(arg).Kind() == reflect.Func -} - -var spewConfig = spew.ConfigState{ - Indent: " ", - DisablePointerAddresses: true, - DisableCapacities: true, - SortKeys: true, -} - -type tHelper interface { - Helper() -} diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go deleted file mode 100644 index c9dccc4d6..000000000 --- a/vendor/github.com/stretchr/testify/assert/doc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. -// -// Example Usage -// -// The following is a complete example using assert in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// if you assert many times, use the format below: -// -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// assert := assert.New(t) -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(a, b, "The two words should be the same.") -// } -// -// Assertions -// -// Assertions allow you to easily write test code, and are global funcs in the `assert` package. -// All assertion functions take, as the first argument, the `*testing.T` object provided by the -// testing framework. This allows the assertion funcs to write the failings and other details to -// the correct place. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package assert diff --git a/vendor/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go deleted file mode 100644 index ac9dc9d1d..000000000 --- a/vendor/github.com/stretchr/testify/assert/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package assert - -import ( - "errors" -) - -// AnError is an error instance useful for testing. If the code does not care -// about error specifics, and only needs to return the error for example, this -// error should be used to make the test code more readable. -var AnError = errors.New("assert.AnError general error for testing") diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go deleted file mode 100644 index 9ad56851d..000000000 --- a/vendor/github.com/stretchr/testify/assert/forward_assertions.go +++ /dev/null @@ -1,16 +0,0 @@ -package assert - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go deleted file mode 100644 index df46fa777..000000000 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ /dev/null @@ -1,143 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "strings" -) - -// httpCode is a helper that returns HTTP code of the response. It returns -1 and -// an error if building a new request fails. -func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url, nil) - if err != nil { - return -1, err - } - req.URL.RawQuery = values.Encode() - handler(w, req) - return w.Code, nil -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - code, err := httpCode(handler, method, url, values) - if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - return false - } - - isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent - if !isSuccessCode { - Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) - } - - return isSuccessCode -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - code, err := httpCode(handler, method, url, values) - if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - return false - } - - isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect - if !isRedirectCode { - Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) - } - - return isRedirectCode -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - code, err := httpCode(handler, method, url, values) - if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - return false - } - - isErrorCode := code >= http.StatusBadRequest - if !isErrorCode { - Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) - } - - return isErrorCode -} - -// HTTPBody is a helper that returns HTTP body of the response. It returns -// empty string if building a new request fails. -func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return "" - } - handler(w, req) - return w.Body.String() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return contains -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return !contains -} diff --git a/vendor/github.com/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go deleted file mode 100644 index 169de3922..000000000 --- a/vendor/github.com/stretchr/testify/require/doc.go +++ /dev/null @@ -1,28 +0,0 @@ -// Package require implements the same assertions as the `assert` package but -// stops test execution when a test fails. -// -// Example Usage -// -// The following is a complete example using require in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/require" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// require.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// Assertions -// -// The `require` package have same global functions as in the `assert` package, -// but instead of returning a boolean result they call `t.FailNow()`. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package require diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go deleted file mode 100644 index ac71d4058..000000000 --- a/vendor/github.com/stretchr/testify/require/forward_requirements.go +++ /dev/null @@ -1,16 +0,0 @@ -package require - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -//go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl -include-format-funcs diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go deleted file mode 100644 index 535f29349..000000000 --- a/vendor/github.com/stretchr/testify/require/require.go +++ /dev/null @@ -1,1227 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package require - -import ( - assert "github.com/stretchr/testify/assert" - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { - if assert.Condition(t, comp, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Conditionf uses a Comparison to assert a complex condition. -func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{}) { - if assert.Conditionf(t, comp, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World") -// assert.Contains(t, ["Hello", "World"], "World") -// assert.Contains(t, {"Hello": "World"}, "Hello") -func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if assert.Contains(t, s, contains, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Containsf asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") -// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") -// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") -func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { - if assert.Containsf(t, s, contains, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. -func DirExists(t TestingT, path string, msgAndArgs ...interface{}) { - if assert.DirExists(t, path, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. -func DirExistsf(t TestingT, path string, msg string, args ...interface{}) { - if assert.DirExistsf(t, path, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) -func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) { - if assert.ElementsMatch(t, listA, listB, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") -func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) { - if assert.ElementsMatchf(t, listA, listB, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if assert.Empty(t, object, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Emptyf(t, obj, "error message %s", "formatted") -func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { - if assert.Emptyf(t, object, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if assert.Equal(t, expected, actual, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString) -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { - if assert.EqualError(t, theError, errString, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// EqualErrorf asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") -func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { - if assert.EqualErrorf(t, theError, errString, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123)) -func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if assert.EqualValues(t, expected, actual, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) -func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if assert.EqualValuesf(t, expected, actual, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Equalf asserts that two objects are equal. -// -// assert.Equalf(t, 123, 123, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if assert.Equalf(t, expected, actual, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err) { -// assert.Equal(t, expectedError, err) -// } -func Error(t TestingT, err error, msgAndArgs ...interface{}) { - if assert.Error(t, err, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Errorf asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Errorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } -func Errorf(t TestingT, err error, msg string, args ...interface{}) { - if assert.Errorf(t, err, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Exactly asserts that two objects are equal in value and type. -// -// assert.Exactly(t, int32(123), int64(123)) -func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if assert.Exactly(t, expected, actual, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Exactlyf asserts that two objects are equal in value and type. -// -// assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) -func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if assert.Exactlyf(t, expected, actual, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { - if assert.Fail(t, failureMessage, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// FailNow fails test -func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { - if assert.FailNow(t, failureMessage, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// FailNowf fails test -func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { - if assert.FailNowf(t, failureMessage, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Failf reports a failure through -func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { - if assert.Failf(t, failureMessage, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// False asserts that the specified value is false. -// -// assert.False(t, myBool) -func False(t TestingT, value bool, msgAndArgs ...interface{}) { - if assert.False(t, value, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Falsef asserts that the specified value is false. -// -// assert.Falsef(t, myBool, "error message %s", "formatted") -func Falsef(t TestingT, value bool, msg string, args ...interface{}) { - if assert.Falsef(t, value, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. -func FileExists(t TestingT, path string, msgAndArgs ...interface{}) { - if assert.FileExists(t, path, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. -func FileExistsf(t TestingT, path string, msg string, args ...interface{}) { - if assert.FileExistsf(t, path, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { - if assert.HTTPBodyContains(t, handler, method, url, values, str, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPBodyContainsf asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { - if assert.HTTPBodyContainsf(t, handler, method, url, values, str, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { - if assert.HTTPBodyNotContains(t, handler, method, url, values, str, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPBodyNotContainsf asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { - if assert.HTTPBodyNotContainsf(t, handler, method, url, values, str, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if assert.HTTPError(t, handler, method, url, values, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPErrorf asserts that a specified handler returns an error status code. -// -// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). -func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if assert.HTTPErrorf(t, handler, method, url, values, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if assert.HTTPRedirect(t, handler, method, url, values, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPRedirectf asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). -func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if assert.HTTPRedirectf(t, handler, method, url, values, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if assert.HTTPSuccess(t, handler, method, url, values, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// HTTPSuccessf asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if assert.HTTPSuccessf(t, handler, method, url, values, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - if assert.Implements(t, interfaceObject, object, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Implementsf asserts that an object is implemented by the specified interface. -// -// assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) -func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { - if assert.Implementsf(t, interfaceObject, object, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if assert.InDelta(t, expected, actual, delta, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func InDeltaMapValues(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if assert.InDeltaMapValues(t, expected, actual, delta, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if assert.InDeltaMapValuesf(t, expected, actual, delta, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InDeltaSlicef is the same as InDelta, except it compares two slices. -func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if assert.InDeltaSlicef(t, expected, actual, delta, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InDeltaf asserts that the two numerals are within delta of each other. -// -// assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) -func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if assert.InDeltaf(t, expected, actual, delta, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { - if assert.InEpsilonSlicef(t, expected, actual, epsilon, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// InEpsilonf asserts that expected and actual have a relative error less than epsilon -func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { - if assert.InEpsilonf(t, expected, actual, epsilon, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - if assert.IsType(t, expectedType, object, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// IsTypef asserts that the specified objects are of the same type. -func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) { - if assert.IsTypef(t, expectedType, object, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { - if assert.JSONEq(t, expected, actual, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// JSONEqf asserts that two JSON strings are equivalent. -// -// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") -func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { - if assert.JSONEqf(t, expected, actual, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3) -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { - if assert.Len(t, object, length, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Lenf asserts that the specified object has specific length. -// Lenf also fails if the object has a type that len() not accept. -// -// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") -func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { - if assert.Lenf(t, object, length, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err) -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if assert.Nil(t, object, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Nilf asserts that the specified object is nil. -// -// assert.Nilf(t, err, "error message %s", "formatted") -func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { - if assert.Nilf(t, object, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, expectedObj, actualObj) -// } -func NoError(t TestingT, err error, msgAndArgs ...interface{}) { - if assert.NoError(t, err, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NoErrorf asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoErrorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } -func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { - if assert.NoErrorf(t, err, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth") -// assert.NotContains(t, ["Hello", "World"], "Earth") -// assert.NotContains(t, {"Hello": "World"}, "Earth") -func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if assert.NotContains(t, s, contains, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") -func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { - if assert.NotContainsf(t, s, contains, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if assert.NotEmpty(t, object, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } -func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { - if assert.NotEmptyf(t, object, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if assert.NotEqual(t, expected, actual, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotEqualf asserts that the specified values are NOT equal. -// -// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if assert.NotEqualf(t, expected, actual, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err) -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if assert.NotNil(t, object, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotNilf asserts that the specified object is not nil. -// -// assert.NotNilf(t, err, "error message %s", "formatted") -func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { - if assert.NotNilf(t, object, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ RemainCalm() }) -func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if assert.NotPanics(t, f, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") -func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { - if assert.NotPanicsf(t, f, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if assert.NotRegexp(t, rx, str, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotRegexpf asserts that a specified regexp does not match a string. -// -// assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") -// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") -func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { - if assert.NotRegexpf(t, rx, str, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") -func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { - if assert.NotSubset(t, list, subset, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") -func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { - if assert.NotSubsetf(t, list, subset, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotZero asserts that i is not the zero value for its type. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { - if assert.NotZero(t, i, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// NotZerof asserts that i is not the zero value for its type. -func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { - if assert.NotZerof(t, i, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ GoCrazy() }) -func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if assert.Panics(t, f, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) -func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if assert.PanicsWithValue(t, expected, f, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { - if assert.PanicsWithValuef(t, expected, f, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Panicsf asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") -func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { - if assert.Panicsf(t, f, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if assert.Regexp(t, rx, str, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Regexpf asserts that a specified regexp matches a string. -// -// assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") -// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") -func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { - if assert.Regexpf(t, rx, str, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") -func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { - if assert.Subset(t, list, subset, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") -func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { - if assert.Subsetf(t, list, subset, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool) -func True(t TestingT, value bool, msgAndArgs ...interface{}) { - if assert.True(t, value, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Truef asserts that the specified value is true. -// -// assert.Truef(t, myBool, "error message %s", "formatted") -func Truef(t TestingT, value bool, msg string, args ...interface{}) { - if assert.Truef(t, value, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) -func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - if assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// WithinDurationf asserts that the two times are within duration delta of each other. -// -// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") -func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { - if assert.WithinDurationf(t, expected, actual, delta, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Zero asserts that i is the zero value for its type. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { - if assert.Zero(t, i, msgAndArgs...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} - -// Zerof asserts that i is the zero value for its type. -func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) { - if assert.Zerof(t, i, msg, args...) { - return - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - t.FailNow() -} diff --git a/vendor/github.com/stretchr/testify/require/require.go.tmpl b/vendor/github.com/stretchr/testify/require/require.go.tmpl deleted file mode 100644 index 6ffc751b5..000000000 --- a/vendor/github.com/stretchr/testify/require/require.go.tmpl +++ /dev/null @@ -1,6 +0,0 @@ -{{.Comment}} -func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { - if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return } - if h, ok := t.(tHelper); ok { h.Helper() } - t.FailNow() -} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go deleted file mode 100644 index 9fe41dbdc..000000000 --- a/vendor/github.com/stretchr/testify/require/require_forward.go +++ /dev/null @@ -1,957 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package require - -import ( - assert "github.com/stretchr/testify/assert" - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Condition(a.t, comp, msgAndArgs...) -} - -// Conditionf uses a Comparison to assert a complex condition. -func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Conditionf(a.t, comp, msg, args...) -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Contains("Hello World", "World") -// a.Contains(["Hello", "World"], "World") -// a.Contains({"Hello": "World"}, "Hello") -func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Contains(a.t, s, contains, msgAndArgs...) -} - -// Containsf asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Containsf("Hello World", "World", "error message %s", "formatted") -// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") -// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") -func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Containsf(a.t, s, contains, msg, args...) -} - -// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. -func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - DirExists(a.t, path, msgAndArgs...) -} - -// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. -func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - DirExistsf(a.t, path, msg, args...) -} - -// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) -func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ElementsMatch(a.t, listA, listB, msgAndArgs...) -} - -// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") -func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ElementsMatchf(a.t, listA, listB, msg, args...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Empty(obj) -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Empty(a.t, object, msgAndArgs...) -} - -// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Emptyf(obj, "error message %s", "formatted") -func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Emptyf(a.t, object, msg, args...) -} - -// Equal asserts that two objects are equal. -// -// a.Equal(123, 123) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString) -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - EqualError(a.t, theError, errString, msgAndArgs...) -} - -// EqualErrorf asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") -func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - EqualErrorf(a.t, theError, errString, msg, args...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValues(uint32(123), int32(123)) -func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) -func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - EqualValuesf(a.t, expected, actual, msg, args...) -} - -// Equalf asserts that two objects are equal. -// -// a.Equalf(123, 123, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Equalf(a.t, expected, actual, msg, args...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Error(err) { -// assert.Equal(t, expectedError, err) -// } -func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Error(a.t, err, msgAndArgs...) -} - -// Errorf asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Errorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } -func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Errorf(a.t, err, msg, args...) -} - -// Exactly asserts that two objects are equal in value and type. -// -// a.Exactly(int32(123), int64(123)) -func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Exactly(a.t, expected, actual, msgAndArgs...) -} - -// Exactlyf asserts that two objects are equal in value and type. -// -// a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) -func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Exactlyf(a.t, expected, actual, msg, args...) -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Fail(a.t, failureMessage, msgAndArgs...) -} - -// FailNow fails test -func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - FailNow(a.t, failureMessage, msgAndArgs...) -} - -// FailNowf fails test -func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - FailNowf(a.t, failureMessage, msg, args...) -} - -// Failf reports a failure through -func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Failf(a.t, failureMessage, msg, args...) -} - -// False asserts that the specified value is false. -// -// a.False(myBool) -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - False(a.t, value, msgAndArgs...) -} - -// Falsef asserts that the specified value is false. -// -// a.Falsef(myBool, "error message %s", "formatted") -func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Falsef(a.t, value, msg, args...) -} - -// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. -func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - FileExists(a.t, path, msgAndArgs...) -} - -// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. -func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - FileExistsf(a.t, path, msg, args...) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) -} - -// HTTPBodyContainsf asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) -} - -// HTTPBodyNotContainsf asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPError(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPErrorf asserts that a specified handler returns an error status code. -// -// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). -func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPErrorf(a.t, handler, method, url, values, msg, args...) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPRedirectf asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). -func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPRedirectf(a.t, handler, method, url, values, msg, args...) -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPSuccessf asserts that a specified handler returns a success status code. -// -// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPSuccessf(a.t, handler, method, url, values, msg, args...) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// a.Implements((*MyInterface)(nil), new(MyObject)) -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// Implementsf asserts that an object is implemented by the specified interface. -// -// a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) -func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Implementsf(a.t, interfaceObject, object, msg, args...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// a.InDelta(math.Pi, (22 / 7.0), 0.01) -func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaSlicef is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaSlicef(a.t, expected, actual, delta, msg, args...) -} - -// InDeltaf asserts that the two numerals are within delta of each other. -// -// a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) -func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaf(a.t, expected, actual, delta, msg, args...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) -} - -// InEpsilonf asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InEpsilonf(a.t, expected, actual, epsilon, msg, args...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsType(a.t, expectedType, object, msgAndArgs...) -} - -// IsTypef asserts that the specified objects are of the same type. -func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsTypef(a.t, expectedType, object, msg, args...) -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - JSONEq(a.t, expected, actual, msgAndArgs...) -} - -// JSONEqf asserts that two JSON strings are equivalent. -// -// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") -func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - JSONEqf(a.t, expected, actual, msg, args...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// a.Len(mySlice, 3) -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Len(a.t, object, length, msgAndArgs...) -} - -// Lenf asserts that the specified object has specific length. -// Lenf also fails if the object has a type that len() not accept. -// -// a.Lenf(mySlice, 3, "error message %s", "formatted") -func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Lenf(a.t, object, length, msg, args...) -} - -// Nil asserts that the specified object is nil. -// -// a.Nil(err) -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Nil(a.t, object, msgAndArgs...) -} - -// Nilf asserts that the specified object is nil. -// -// a.Nilf(err, "error message %s", "formatted") -func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Nilf(a.t, object, msg, args...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, expectedObj, actualObj) -// } -func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NoError(a.t, err, msgAndArgs...) -} - -// NoErrorf asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoErrorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } -func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NoErrorf(a.t, err, msg, args...) -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContains("Hello World", "Earth") -// a.NotContains(["Hello", "World"], "Earth") -// a.NotContains({"Hello": "World"}, "Earth") -func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotContains(a.t, s, contains, msgAndArgs...) -} - -// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") -// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") -// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") -func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotContainsf(a.t, s, contains, msg, args...) -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEmpty(a.t, object, msgAndArgs...) -} - -// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmptyf(obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } -func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEmptyf(a.t, object, msg, args...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// a.NotEqual(obj1, obj2) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// NotEqualf asserts that the specified values are NOT equal. -// -// a.NotEqualf(obj1, obj2, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEqualf(a.t, expected, actual, msg, args...) -} - -// NotNil asserts that the specified object is not nil. -// -// a.NotNil(err) -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotNil(a.t, object, msgAndArgs...) -} - -// NotNilf asserts that the specified object is not nil. -// -// a.NotNilf(err, "error message %s", "formatted") -func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotNilf(a.t, object, msg, args...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanics(func(){ RemainCalm() }) -func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotPanics(a.t, f, msgAndArgs...) -} - -// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") -func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotPanicsf(a.t, f, msg, args...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotRegexp(a.t, rx, str, msgAndArgs...) -} - -// NotRegexpf asserts that a specified regexp does not match a string. -// -// a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") -// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") -func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotRegexpf(a.t, rx, str, msg, args...) -} - -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") -func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotSubset(a.t, list, subset, msgAndArgs...) -} - -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") -func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotSubsetf(a.t, list, subset, msg, args...) -} - -// NotZero asserts that i is not the zero value for its type. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotZero(a.t, i, msgAndArgs...) -} - -// NotZerof asserts that i is not the zero value for its type. -func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotZerof(a.t, i, msg, args...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panics(func(){ GoCrazy() }) -func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Panics(a.t, f, msgAndArgs...) -} - -// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) -func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - PanicsWithValue(a.t, expected, f, msgAndArgs...) -} - -// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - PanicsWithValuef(a.t, expected, f, msg, args...) -} - -// Panicsf asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Panicsf(a.t, f, msg, args...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Regexp(a.t, rx, str, msgAndArgs...) -} - -// Regexpf asserts that a specified regexp matches a string. -// -// a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") -// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") -func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Regexpf(a.t, rx, str, msg, args...) -} - -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") -func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Subset(a.t, list, subset, msgAndArgs...) -} - -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") -func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Subsetf(a.t, list, subset, msg, args...) -} - -// True asserts that the specified value is true. -// -// a.True(myBool) -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - True(a.t, value, msgAndArgs...) -} - -// Truef asserts that the specified value is true. -// -// a.Truef(myBool, "error message %s", "formatted") -func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Truef(a.t, value, msg, args...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) -func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// WithinDurationf asserts that the two times are within duration delta of each other. -// -// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") -func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - WithinDurationf(a.t, expected, actual, delta, msg, args...) -} - -// Zero asserts that i is the zero value for its type. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Zero(a.t, i, msgAndArgs...) -} - -// Zerof asserts that i is the zero value for its type. -func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Zerof(a.t, i, msg, args...) -} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl deleted file mode 100644 index 54124df1d..000000000 --- a/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl +++ /dev/null @@ -1,5 +0,0 @@ -{{.CommentWithoutT "a"}} -func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) { - if h, ok := a.t.(tHelper); ok { h.Helper() } - {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) -} diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go deleted file mode 100644 index 690583a8e..000000000 --- a/vendor/github.com/stretchr/testify/require/requirements.go +++ /dev/null @@ -1,29 +0,0 @@ -package require - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) - FailNow() -} - -type tHelper interface { - Helper() -} - -// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful -// for table driven tests. -type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) - -// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful -// for table driven tests. -type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) - -// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful -// for table driven tests. -type BoolAssertionFunc func(TestingT, bool, ...interface{}) - -// ValuesAssertionFunc is a common function prototype when validating an error value. Can be useful -// for table driven tests. -type ErrorAssertionFunc func(TestingT, error, ...interface{}) - -//go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl -include-format-funcs diff --git a/vendor/golang.org/x/net/AUTHORS b/vendor/golang.org/x/net/AUTHORS deleted file mode 100644 index 15167cd74..000000000 --- a/vendor/golang.org/x/net/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/golang.org/x/net/CONTRIBUTORS b/vendor/golang.org/x/net/CONTRIBUTORS deleted file mode 100644 index 1c4577e96..000000000 --- a/vendor/golang.org/x/net/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/golang.org/x/net/LICENSE b/vendor/golang.org/x/net/LICENSE deleted file mode 100644 index 6a66aea5e..000000000 --- a/vendor/golang.org/x/net/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 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/golang.org/x/net/PATENTS b/vendor/golang.org/x/net/PATENTS deleted file mode 100644 index 733099041..000000000 --- a/vendor/golang.org/x/net/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go deleted file mode 100644 index a3c021d3f..000000000 --- a/vendor/golang.org/x/net/context/context.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package context defines the Context type, which carries deadlines, -// cancelation signals, and other request-scoped values across API boundaries -// and between processes. -// As of Go 1.7 this package is available in the standard library under the -// name context. https://golang.org/pkg/context. -// -// Incoming requests to a server should create a Context, and outgoing calls to -// servers should accept a Context. The chain of function calls between must -// propagate the Context, optionally replacing it with a modified copy created -// using WithDeadline, WithTimeout, WithCancel, or WithValue. -// -// Programs that use Contexts should follow these rules to keep interfaces -// consistent across packages and enable static analysis tools to check context -// propagation: -// -// Do not store Contexts inside a struct type; instead, pass a Context -// explicitly to each function that needs it. The Context should be the first -// parameter, typically named ctx: -// -// func DoSomething(ctx context.Context, arg Arg) error { -// // ... use ctx ... -// } -// -// Do not pass a nil Context, even if a function permits it. Pass context.TODO -// if you are unsure about which Context to use. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The same Context may be passed to functions running in different goroutines; -// Contexts are safe for simultaneous use by multiple goroutines. -// -// See http://blog.golang.org/context for example code for a server that uses -// Contexts. -package context // import "golang.org/x/net/context" - -// Background returns a non-nil, empty Context. It is never canceled, has no -// values, and has no deadline. It is typically used by the main function, -// initialization, and tests, and as the top-level Context for incoming -// requests. -func Background() Context { - return background -} - -// TODO returns a non-nil, empty Context. Code should use context.TODO when -// it's unclear which Context to use or it is not yet available (because the -// surrounding function has not yet been extended to accept a Context -// parameter). TODO is recognized by static analysis tools that determine -// whether Contexts are propagated correctly in a program. -func TODO() Context { - return todo -} diff --git a/vendor/golang.org/x/net/context/go17.go b/vendor/golang.org/x/net/context/go17.go deleted file mode 100644 index d20f52b7d..000000000 --- a/vendor/golang.org/x/net/context/go17.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 - -package context - -import ( - "context" // standard library's context, as of Go 1.7 - "time" -) - -var ( - todo = context.TODO() - background = context.Background() -) - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = context.Canceled - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = context.DeadlineExceeded - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - ctx, f := context.WithCancel(parent) - return ctx, CancelFunc(f) -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - ctx, f := context.WithDeadline(parent, deadline) - return ctx, CancelFunc(f) -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return context.WithValue(parent, key, val) -} diff --git a/vendor/golang.org/x/net/context/go19.go b/vendor/golang.org/x/net/context/go19.go deleted file mode 100644 index d88bd1db1..000000000 --- a/vendor/golang.org/x/net/context/go19.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package context - -import "context" // standard library's context, as of Go 1.7 - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context = context.Context - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc = context.CancelFunc diff --git a/vendor/golang.org/x/net/context/pre_go17.go b/vendor/golang.org/x/net/context/pre_go17.go deleted file mode 100644 index 0f35592df..000000000 --- a/vendor/golang.org/x/net/context/pre_go17.go +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package context - -import ( - "errors" - "fmt" - "sync" - "time" -) - -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case background: - return "context.Background" - case todo: - return "context.TODO" - } - return "unknown empty Context" -} - -var ( - background = new(emptyCtx) - todo = new(emptyCtx) -) - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = errors.New("context canceled") - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = errors.New("context deadline exceeded") - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - c := newCancelCtx(parent) - propagateCancel(parent, c) - return c, func() { c.cancel(true, Canceled) } -} - -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) *cancelCtx { - return &cancelCtx{ - Context: parent, - done: make(chan struct{}), - } -} - -// propagateCancel arranges for child to be canceled when parent is. -func propagateCancel(parent Context, child canceler) { - if parent.Done() == nil { - return // parent is never canceled - } - if p, ok := parentCancelCtx(parent); ok { - p.mu.Lock() - if p.err != nil { - // parent has already been canceled - child.cancel(false, p.err) - } else { - if p.children == nil { - p.children = make(map[canceler]bool) - } - p.children[child] = true - } - p.mu.Unlock() - } else { - go func() { - select { - case <-parent.Done(): - child.cancel(false, parent.Err()) - case <-child.Done(): - } - }() - } -} - -// parentCancelCtx follows a chain of parent references until it finds a -// *cancelCtx. This function understands how each of the concrete types in this -// package represents its parent. -func parentCancelCtx(parent Context) (*cancelCtx, bool) { - for { - switch c := parent.(type) { - case *cancelCtx: - return c, true - case *timerCtx: - return c.cancelCtx, true - case *valueCtx: - parent = c.Context - default: - return nil, false - } - } -} - -// removeChild removes a context from its parent. -func removeChild(parent Context, child canceler) { - p, ok := parentCancelCtx(parent) - if !ok { - return - } - p.mu.Lock() - if p.children != nil { - delete(p.children, child) - } - p.mu.Unlock() -} - -// A canceler is a context type that can be canceled directly. The -// implementations are *cancelCtx and *timerCtx. -type canceler interface { - cancel(removeFromParent bool, err error) - Done() <-chan struct{} -} - -// A cancelCtx can be canceled. When canceled, it also cancels any children -// that implement canceler. -type cancelCtx struct { - Context - - done chan struct{} // closed by the first cancel call. - - mu sync.Mutex - children map[canceler]bool // set to nil by the first cancel call - err error // set to non-nil by the first cancel call -} - -func (c *cancelCtx) Done() <-chan struct{} { - return c.done -} - -func (c *cancelCtx) Err() error { - c.mu.Lock() - defer c.mu.Unlock() - return c.err -} - -func (c *cancelCtx) String() string { - return fmt.Sprintf("%v.WithCancel", c.Context) -} - -// cancel closes c.done, cancels each of c's children, and, if -// removeFromParent is true, removes c from its parent's children. -func (c *cancelCtx) cancel(removeFromParent bool, err error) { - if err == nil { - panic("context: internal error: missing cancel error") - } - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return // already canceled - } - c.err = err - close(c.done) - for child := range c.children { - // NOTE: acquiring the child's lock while holding parent's lock. - child.cancel(false, err) - } - c.children = nil - c.mu.Unlock() - - if removeFromParent { - removeChild(c.Context, c) - } -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { - // The current deadline is already sooner than the new one. - return WithCancel(parent) - } - c := &timerCtx{ - cancelCtx: newCancelCtx(parent), - deadline: deadline, - } - propagateCancel(parent, c) - d := deadline.Sub(time.Now()) - if d <= 0 { - c.cancel(true, DeadlineExceeded) // deadline has already passed - return c, func() { c.cancel(true, Canceled) } - } - c.mu.Lock() - defer c.mu.Unlock() - if c.err == nil { - c.timer = time.AfterFunc(d, func() { - c.cancel(true, DeadlineExceeded) - }) - } - return c, func() { c.cancel(true, Canceled) } -} - -// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to -// implement Done and Err. It implements cancel by stopping its timer then -// delegating to cancelCtx.cancel. -type timerCtx struct { - *cancelCtx - timer *time.Timer // Under cancelCtx.mu. - - deadline time.Time -} - -func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { - return c.deadline, true -} - -func (c *timerCtx) String() string { - return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) -} - -func (c *timerCtx) cancel(removeFromParent bool, err error) { - c.cancelCtx.cancel(false, err) - if removeFromParent { - // Remove this timerCtx from its parent cancelCtx's children. - removeChild(c.cancelCtx.Context, c) - } - c.mu.Lock() - if c.timer != nil { - c.timer.Stop() - c.timer = nil - } - c.mu.Unlock() -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return &valueCtx{parent, key, val} -} - -// A valueCtx carries a key-value pair. It implements Value for that key and -// delegates all other calls to the embedded Context. -type valueCtx struct { - Context - key, val interface{} -} - -func (c *valueCtx) String() string { - return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) -} - -func (c *valueCtx) Value(key interface{}) interface{} { - if c.key == key { - return c.val - } - return c.Context.Value(key) -} diff --git a/vendor/golang.org/x/net/context/pre_go19.go b/vendor/golang.org/x/net/context/pre_go19.go deleted file mode 100644 index b105f80be..000000000 --- a/vendor/golang.org/x/net/context/pre_go19.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.9 - -package context - -import "time" - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - // - // WithCancel arranges for Done to be closed when cancel is called; - // WithDeadline arranges for Done to be closed when the deadline - // expires; WithTimeout arranges for Done to be closed when the timeout - // elapses. - // - // Done is provided for use in select statements: - // - // // Stream generates values with DoSomething and sends them to out - // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out chan<- Value) error { - // for { - // v, err := DoSomething(ctx) - // if err != nil { - // return err - // } - // select { - // case <-ctx.Done(): - // return ctx.Err() - // case out <- v: - // } - // } - // } - // - // See http://blog.golang.org/pipelines for more examples of how to use - // a Done channel for cancelation. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - // - // A key identifies a specific value in a Context. Functions that wish - // to store values in Context typically allocate a key in a global - // variable then use that key as the argument to context.WithValue and - // Context.Value. A key can be any type that supports equality; - // packages should define keys as an unexported type to avoid - // collisions. - // - // Packages that define a Context key should provide type-safe accessors - // for the values stores using that key: - // - // // Package user defines a User type that's stored in Contexts. - // package user - // - // import "golang.org/x/net/context" - // - // // User is the type of value stored in the Contexts. - // type User struct {...} - // - // // key is an unexported type for keys defined in this package. - // // This prevents collisions with keys defined in other packages. - // type key int - // - // // userKey is the key for user.User values in Contexts. It is - // // unexported; clients use user.NewContext and user.FromContext - // // instead of using this key directly. - // var userKey key = 0 - // - // // NewContext returns a new Context that carries value u. - // func NewContext(ctx context.Context, u *User) context.Context { - // return context.WithValue(ctx, userKey, u) - // } - // - // // FromContext returns the User value stored in ctx, if any. - // func FromContext(ctx context.Context) (*User, bool) { - // u, ok := ctx.Value(userKey).(*User) - // return u, ok - // } - Value(key interface{}) interface{} -} - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc func() diff --git a/vendor/gopkg.in/yaml.v2/.travis.yml b/vendor/gopkg.in/yaml.v2/.travis.yml deleted file mode 100644 index 9f556934d..000000000 --- a/vendor/gopkg.in/yaml.v2/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go - -go: - - 1.4 - - 1.5 - - 1.6 - - 1.7 - - 1.8 - - 1.9 - - tip - -go_import_path: gopkg.in/yaml.v2 diff --git a/vendor/gopkg.in/yaml.v2/LICENSE b/vendor/gopkg.in/yaml.v2/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/gopkg.in/yaml.v2/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/gopkg.in/yaml.v2/LICENSE.libyaml b/vendor/gopkg.in/yaml.v2/LICENSE.libyaml deleted file mode 100644 index 8da58fbf6..000000000 --- a/vendor/gopkg.in/yaml.v2/LICENSE.libyaml +++ /dev/null @@ -1,31 +0,0 @@ -The following files were ported to Go from C files of libyaml, and thus -are still covered by their original copyright and license: - - apic.go - emitterc.go - parserc.go - readerc.go - scannerc.go - writerc.go - yamlh.go - yamlprivateh.go - -Copyright (c) 2006 Kirill Simonov - -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/gopkg.in/yaml.v2/NOTICE b/vendor/gopkg.in/yaml.v2/NOTICE deleted file mode 100644 index 866d74a7a..000000000 --- a/vendor/gopkg.in/yaml.v2/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2011-2016 Canonical Ltd. - -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/gopkg.in/yaml.v2/README.md b/vendor/gopkg.in/yaml.v2/README.md deleted file mode 100644 index b50c6e877..000000000 --- a/vendor/gopkg.in/yaml.v2/README.md +++ /dev/null @@ -1,133 +0,0 @@ -# YAML support for the Go language - -Introduction ------------- - -The yaml package enables Go programs to comfortably encode and decode YAML -values. It was developed within [Canonical](https://www.canonical.com) as -part of the [juju](https://juju.ubuntu.com) project, and is based on a -pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) -C library to parse and generate YAML data quickly and reliably. - -Compatibility -------------- - -The yaml package supports most of YAML 1.1 and 1.2, including support for -anchors, tags, map merging, etc. Multi-document unmarshalling is not yet -implemented, and base-60 floats from YAML 1.1 are purposefully not -supported since they're a poor design and are gone in YAML 1.2. - -Installation and usage ----------------------- - -The import path for the package is *gopkg.in/yaml.v2*. - -To install it, run: - - go get gopkg.in/yaml.v2 - -API documentation ------------------ - -If opened in a browser, the import path itself leads to the API documentation: - - * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) - -API stability -------------- - -The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). - - -License -------- - -The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. - - -Example -------- - -```Go -package main - -import ( - "fmt" - "log" - - "gopkg.in/yaml.v2" -) - -var data = ` -a: Easy! -b: - c: 2 - d: [3, 4] -` - -// Note: struct fields must be public in order for unmarshal to -// correctly populate the data. -type T struct { - A string - B struct { - RenamedC int `yaml:"c"` - D []int `yaml:",flow"` - } -} - -func main() { - t := T{} - - err := yaml.Unmarshal([]byte(data), &t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t:\n%v\n\n", t) - - d, err := yaml.Marshal(&t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t dump:\n%s\n\n", string(d)) - - m := make(map[interface{}]interface{}) - - err = yaml.Unmarshal([]byte(data), &m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m:\n%v\n\n", m) - - d, err = yaml.Marshal(&m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m dump:\n%s\n\n", string(d)) -} -``` - -This example will generate the following output: - -``` ---- t: -{Easy! {2 [3 4]}} - ---- t dump: -a: Easy! -b: - c: 2 - d: [3, 4] - - ---- m: -map[a:Easy! b:map[c:2 d:[3 4]]] - ---- m dump: -a: Easy! -b: - c: 2 - d: - - 3 - - 4 -``` - diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go deleted file mode 100644 index 1f7e87e67..000000000 --- a/vendor/gopkg.in/yaml.v2/apic.go +++ /dev/null @@ -1,739 +0,0 @@ -package yaml - -import ( - "io" -) - -func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { - //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) - - // Check if we can move the queue at the beginning of the buffer. - if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { - if parser.tokens_head != len(parser.tokens) { - copy(parser.tokens, parser.tokens[parser.tokens_head:]) - } - parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] - parser.tokens_head = 0 - } - parser.tokens = append(parser.tokens, *token) - if pos < 0 { - return - } - copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) - parser.tokens[parser.tokens_head+pos] = *token -} - -// Create a new parser object. -func yaml_parser_initialize(parser *yaml_parser_t) bool { - *parser = yaml_parser_t{ - raw_buffer: make([]byte, 0, input_raw_buffer_size), - buffer: make([]byte, 0, input_buffer_size), - } - return true -} - -// Destroy a parser object. -func yaml_parser_delete(parser *yaml_parser_t) { - *parser = yaml_parser_t{} -} - -// String read handler. -func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - if parser.input_pos == len(parser.input) { - return 0, io.EOF - } - n = copy(buffer, parser.input[parser.input_pos:]) - parser.input_pos += n - return n, nil -} - -// Reader read handler. -func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - return parser.input_reader.Read(buffer) -} - -// Set a string input. -func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_string_read_handler - parser.input = input - parser.input_pos = 0 -} - -// Set a file input. -func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_reader_read_handler - parser.input_reader = r -} - -// Set the source encoding. -func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { - if parser.encoding != yaml_ANY_ENCODING { - panic("must set the encoding only once") - } - parser.encoding = encoding -} - -// Create a new emitter object. -func yaml_emitter_initialize(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{ - buffer: make([]byte, output_buffer_size), - raw_buffer: make([]byte, 0, output_raw_buffer_size), - states: make([]yaml_emitter_state_t, 0, initial_stack_size), - events: make([]yaml_event_t, 0, initial_queue_size), - } -} - -// Destroy an emitter object. -func yaml_emitter_delete(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{} -} - -// String write handler. -func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - *emitter.output_buffer = append(*emitter.output_buffer, buffer...) - return nil -} - -// yaml_writer_write_handler uses emitter.output_writer to write the -// emitted text. -func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - _, err := emitter.output_writer.Write(buffer) - return err -} - -// Set a string output. -func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_string_write_handler - emitter.output_buffer = output_buffer -} - -// Set a file output. -func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_writer_write_handler - emitter.output_writer = w -} - -// Set the output encoding. -func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { - if emitter.encoding != yaml_ANY_ENCODING { - panic("must set the output encoding only once") - } - emitter.encoding = encoding -} - -// Set the canonical output style. -func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { - emitter.canonical = canonical -} - -//// Set the indentation increment. -func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { - if indent < 2 || indent > 9 { - indent = 2 - } - emitter.best_indent = indent -} - -// Set the preferred line width. -func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { - if width < 0 { - width = -1 - } - emitter.best_width = width -} - -// Set if unescaped non-ASCII characters are allowed. -func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { - emitter.unicode = unicode -} - -// Set the preferred line break character. -func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { - emitter.line_break = line_break -} - -///* -// * Destroy a token object. -// */ -// -//YAML_DECLARE(void) -//yaml_token_delete(yaml_token_t *token) -//{ -// assert(token); // Non-NULL token object expected. -// -// switch (token.type) -// { -// case YAML_TAG_DIRECTIVE_TOKEN: -// yaml_free(token.data.tag_directive.handle); -// yaml_free(token.data.tag_directive.prefix); -// break; -// -// case YAML_ALIAS_TOKEN: -// yaml_free(token.data.alias.value); -// break; -// -// case YAML_ANCHOR_TOKEN: -// yaml_free(token.data.anchor.value); -// break; -// -// case YAML_TAG_TOKEN: -// yaml_free(token.data.tag.handle); -// yaml_free(token.data.tag.suffix); -// break; -// -// case YAML_SCALAR_TOKEN: -// yaml_free(token.data.scalar.value); -// break; -// -// default: -// break; -// } -// -// memset(token, 0, sizeof(yaml_token_t)); -//} -// -///* -// * Check if a string is a valid UTF-8 sequence. -// * -// * Check 'reader.c' for more details on UTF-8 encoding. -// */ -// -//static int -//yaml_check_utf8(yaml_char_t *start, size_t length) -//{ -// yaml_char_t *end = start+length; -// yaml_char_t *pointer = start; -// -// while (pointer < end) { -// unsigned char octet; -// unsigned int width; -// unsigned int value; -// size_t k; -// -// octet = pointer[0]; -// width = (octet & 0x80) == 0x00 ? 1 : -// (octet & 0xE0) == 0xC0 ? 2 : -// (octet & 0xF0) == 0xE0 ? 3 : -// (octet & 0xF8) == 0xF0 ? 4 : 0; -// value = (octet & 0x80) == 0x00 ? octet & 0x7F : -// (octet & 0xE0) == 0xC0 ? octet & 0x1F : -// (octet & 0xF0) == 0xE0 ? octet & 0x0F : -// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; -// if (!width) return 0; -// if (pointer+width > end) return 0; -// for (k = 1; k < width; k ++) { -// octet = pointer[k]; -// if ((octet & 0xC0) != 0x80) return 0; -// value = (value << 6) + (octet & 0x3F); -// } -// if (!((width == 1) || -// (width == 2 && value >= 0x80) || -// (width == 3 && value >= 0x800) || -// (width == 4 && value >= 0x10000))) return 0; -// -// pointer += width; -// } -// -// return 1; -//} -// - -// Create STREAM-START. -func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - encoding: encoding, - } -} - -// Create STREAM-END. -func yaml_stream_end_event_initialize(event *yaml_event_t) { - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - } -} - -// Create DOCUMENT-START. -func yaml_document_start_event_initialize( - event *yaml_event_t, - version_directive *yaml_version_directive_t, - tag_directives []yaml_tag_directive_t, - implicit bool, -) { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: implicit, - } -} - -// Create DOCUMENT-END. -func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - implicit: implicit, - } -} - -///* -// * Create ALIAS. -// */ -// -//YAML_DECLARE(int) -//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) -//{ -// mark yaml_mark_t = { 0, 0, 0 } -// anchor_copy *yaml_char_t = NULL -// -// assert(event) // Non-NULL event object is expected. -// assert(anchor) // Non-NULL anchor is expected. -// -// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 -// -// anchor_copy = yaml_strdup(anchor) -// if (!anchor_copy) -// return 0 -// -// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) -// -// return 1 -//} - -// Create SCALAR. -func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - anchor: anchor, - tag: tag, - value: value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-START. -func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-END. -func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - } - return true -} - -// Create MAPPING-START. -func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } -} - -// Create MAPPING-END. -func yaml_mapping_end_event_initialize(event *yaml_event_t) { - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - } -} - -// Destroy an event object. -func yaml_event_delete(event *yaml_event_t) { - *event = yaml_event_t{} -} - -///* -// * Create a document object. -// */ -// -//YAML_DECLARE(int) -//yaml_document_initialize(document *yaml_document_t, -// version_directive *yaml_version_directive_t, -// tag_directives_start *yaml_tag_directive_t, -// tag_directives_end *yaml_tag_directive_t, -// start_implicit int, end_implicit int) -//{ -// struct { -// error yaml_error_type_t -// } context -// struct { -// start *yaml_node_t -// end *yaml_node_t -// top *yaml_node_t -// } nodes = { NULL, NULL, NULL } -// version_directive_copy *yaml_version_directive_t = NULL -// struct { -// start *yaml_tag_directive_t -// end *yaml_tag_directive_t -// top *yaml_tag_directive_t -// } tag_directives_copy = { NULL, NULL, NULL } -// value yaml_tag_directive_t = { NULL, NULL } -// mark yaml_mark_t = { 0, 0, 0 } -// -// assert(document) // Non-NULL document object is expected. -// assert((tag_directives_start && tag_directives_end) || -// (tag_directives_start == tag_directives_end)) -// // Valid tag directives are expected. -// -// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error -// -// if (version_directive) { -// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) -// if (!version_directive_copy) goto error -// version_directive_copy.major = version_directive.major -// version_directive_copy.minor = version_directive.minor -// } -// -// if (tag_directives_start != tag_directives_end) { -// tag_directive *yaml_tag_directive_t -// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) -// goto error -// for (tag_directive = tag_directives_start -// tag_directive != tag_directives_end; tag_directive ++) { -// assert(tag_directive.handle) -// assert(tag_directive.prefix) -// if (!yaml_check_utf8(tag_directive.handle, -// strlen((char *)tag_directive.handle))) -// goto error -// if (!yaml_check_utf8(tag_directive.prefix, -// strlen((char *)tag_directive.prefix))) -// goto error -// value.handle = yaml_strdup(tag_directive.handle) -// value.prefix = yaml_strdup(tag_directive.prefix) -// if (!value.handle || !value.prefix) goto error -// if (!PUSH(&context, tag_directives_copy, value)) -// goto error -// value.handle = NULL -// value.prefix = NULL -// } -// } -// -// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, -// tag_directives_copy.start, tag_directives_copy.top, -// start_implicit, end_implicit, mark, mark) -// -// return 1 -// -//error: -// STACK_DEL(&context, nodes) -// yaml_free(version_directive_copy) -// while (!STACK_EMPTY(&context, tag_directives_copy)) { -// value yaml_tag_directive_t = POP(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// } -// STACK_DEL(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// -// return 0 -//} -// -///* -// * Destroy a document object. -// */ -// -//YAML_DECLARE(void) -//yaml_document_delete(document *yaml_document_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// tag_directive *yaml_tag_directive_t -// -// context.error = YAML_NO_ERROR // Eliminate a compiler warning. -// -// assert(document) // Non-NULL document object is expected. -// -// while (!STACK_EMPTY(&context, document.nodes)) { -// node yaml_node_t = POP(&context, document.nodes) -// yaml_free(node.tag) -// switch (node.type) { -// case YAML_SCALAR_NODE: -// yaml_free(node.data.scalar.value) -// break -// case YAML_SEQUENCE_NODE: -// STACK_DEL(&context, node.data.sequence.items) -// break -// case YAML_MAPPING_NODE: -// STACK_DEL(&context, node.data.mapping.pairs) -// break -// default: -// assert(0) // Should not happen. -// } -// } -// STACK_DEL(&context, document.nodes) -// -// yaml_free(document.version_directive) -// for (tag_directive = document.tag_directives.start -// tag_directive != document.tag_directives.end -// tag_directive++) { -// yaml_free(tag_directive.handle) -// yaml_free(tag_directive.prefix) -// } -// yaml_free(document.tag_directives.start) -// -// memset(document, 0, sizeof(yaml_document_t)) -//} -// -///** -// * Get a document node. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_node(document *yaml_document_t, index int) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (index > 0 && document.nodes.start + index <= document.nodes.top) { -// return document.nodes.start + index - 1 -// } -// return NULL -//} -// -///** -// * Get the root object. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_root_node(document *yaml_document_t) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (document.nodes.top != document.nodes.start) { -// return document.nodes.start -// } -// return NULL -//} -// -///* -// * Add a scalar node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_scalar(document *yaml_document_t, -// tag *yaml_char_t, value *yaml_char_t, length int, -// style yaml_scalar_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// value_copy *yaml_char_t = NULL -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// assert(value) // Non-NULL value is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (length < 0) { -// length = strlen((char *)value) -// } -// -// if (!yaml_check_utf8(value, length)) goto error -// value_copy = yaml_malloc(length+1) -// if (!value_copy) goto error -// memcpy(value_copy, value, length) -// value_copy[length] = '\0' -// -// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// yaml_free(tag_copy) -// yaml_free(value_copy) -// -// return 0 -//} -// -///* -// * Add a sequence node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_sequence(document *yaml_document_t, -// tag *yaml_char_t, style yaml_sequence_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_item_t -// end *yaml_node_item_t -// top *yaml_node_item_t -// } items = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error -// -// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, items) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Add a mapping node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_mapping(document *yaml_document_t, -// tag *yaml_char_t, style yaml_mapping_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_pair_t -// end *yaml_node_pair_t -// top *yaml_node_pair_t -// } pairs = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error -// -// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, pairs) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Append an item to a sequence node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_sequence_item(document *yaml_document_t, -// sequence int, item int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// assert(document) // Non-NULL document is required. -// assert(sequence > 0 -// && document.nodes.start + sequence <= document.nodes.top) -// // Valid sequence id is required. -// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) -// // A sequence node is required. -// assert(item > 0 && document.nodes.start + item <= document.nodes.top) -// // Valid item id is required. -// -// if (!PUSH(&context, -// document.nodes.start[sequence-1].data.sequence.items, item)) -// return 0 -// -// return 1 -//} -// -///* -// * Append a pair of a key and a value to a mapping node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_mapping_pair(document *yaml_document_t, -// mapping int, key int, value int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// pair yaml_node_pair_t -// -// assert(document) // Non-NULL document is required. -// assert(mapping > 0 -// && document.nodes.start + mapping <= document.nodes.top) -// // Valid mapping id is required. -// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) -// // A mapping node is required. -// assert(key > 0 && document.nodes.start + key <= document.nodes.top) -// // Valid key id is required. -// assert(value > 0 && document.nodes.start + value <= document.nodes.top) -// // Valid value id is required. -// -// pair.key = key -// pair.value = value -// -// if (!PUSH(&context, -// document.nodes.start[mapping-1].data.mapping.pairs, pair)) -// return 0 -// -// return 1 -//} -// -// diff --git a/vendor/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go deleted file mode 100644 index e4e56e28e..000000000 --- a/vendor/gopkg.in/yaml.v2/decode.go +++ /dev/null @@ -1,775 +0,0 @@ -package yaml - -import ( - "encoding" - "encoding/base64" - "fmt" - "io" - "math" - "reflect" - "strconv" - "time" -) - -const ( - documentNode = 1 << iota - mappingNode - sequenceNode - scalarNode - aliasNode -) - -type node struct { - kind int - line, column int - tag string - // For an alias node, alias holds the resolved alias. - alias *node - value string - implicit bool - children []*node - anchors map[string]*node -} - -// ---------------------------------------------------------------------------- -// Parser, produces a node tree out of a libyaml event stream. - -type parser struct { - parser yaml_parser_t - event yaml_event_t - doc *node - doneInit bool -} - -func newParser(b []byte) *parser { - p := parser{} - if !yaml_parser_initialize(&p.parser) { - panic("failed to initialize YAML emitter") - } - if len(b) == 0 { - b = []byte{'\n'} - } - yaml_parser_set_input_string(&p.parser, b) - return &p -} - -func newParserFromReader(r io.Reader) *parser { - p := parser{} - if !yaml_parser_initialize(&p.parser) { - panic("failed to initialize YAML emitter") - } - yaml_parser_set_input_reader(&p.parser, r) - return &p -} - -func (p *parser) init() { - if p.doneInit { - return - } - p.expect(yaml_STREAM_START_EVENT) - p.doneInit = true -} - -func (p *parser) destroy() { - if p.event.typ != yaml_NO_EVENT { - yaml_event_delete(&p.event) - } - yaml_parser_delete(&p.parser) -} - -// expect consumes an event from the event stream and -// checks that it's of the expected type. -func (p *parser) expect(e yaml_event_type_t) { - if p.event.typ == yaml_NO_EVENT { - if !yaml_parser_parse(&p.parser, &p.event) { - p.fail() - } - } - if p.event.typ == yaml_STREAM_END_EVENT { - failf("attempted to go past the end of stream; corrupted value?") - } - if p.event.typ != e { - p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) - p.fail() - } - yaml_event_delete(&p.event) - p.event.typ = yaml_NO_EVENT -} - -// peek peeks at the next event in the event stream, -// puts the results into p.event and returns the event type. -func (p *parser) peek() yaml_event_type_t { - if p.event.typ != yaml_NO_EVENT { - return p.event.typ - } - if !yaml_parser_parse(&p.parser, &p.event) { - p.fail() - } - return p.event.typ -} - -func (p *parser) fail() { - var where string - var line int - if p.parser.problem_mark.line != 0 { - line = p.parser.problem_mark.line - // Scanner errors don't iterate line before returning error - if p.parser.error == yaml_SCANNER_ERROR { - line++ - } - } else if p.parser.context_mark.line != 0 { - line = p.parser.context_mark.line - } - if line != 0 { - where = "line " + strconv.Itoa(line) + ": " - } - var msg string - if len(p.parser.problem) > 0 { - msg = p.parser.problem - } else { - msg = "unknown problem parsing YAML content" - } - failf("%s%s", where, msg) -} - -func (p *parser) anchor(n *node, anchor []byte) { - if anchor != nil { - p.doc.anchors[string(anchor)] = n - } -} - -func (p *parser) parse() *node { - p.init() - switch p.peek() { - case yaml_SCALAR_EVENT: - return p.scalar() - case yaml_ALIAS_EVENT: - return p.alias() - case yaml_MAPPING_START_EVENT: - return p.mapping() - case yaml_SEQUENCE_START_EVENT: - return p.sequence() - case yaml_DOCUMENT_START_EVENT: - return p.document() - case yaml_STREAM_END_EVENT: - // Happens when attempting to decode an empty buffer. - return nil - default: - panic("attempted to parse unknown event: " + p.event.typ.String()) - } -} - -func (p *parser) node(kind int) *node { - return &node{ - kind: kind, - line: p.event.start_mark.line, - column: p.event.start_mark.column, - } -} - -func (p *parser) document() *node { - n := p.node(documentNode) - n.anchors = make(map[string]*node) - p.doc = n - p.expect(yaml_DOCUMENT_START_EVENT) - n.children = append(n.children, p.parse()) - p.expect(yaml_DOCUMENT_END_EVENT) - return n -} - -func (p *parser) alias() *node { - n := p.node(aliasNode) - n.value = string(p.event.anchor) - n.alias = p.doc.anchors[n.value] - if n.alias == nil { - failf("unknown anchor '%s' referenced", n.value) - } - p.expect(yaml_ALIAS_EVENT) - return n -} - -func (p *parser) scalar() *node { - n := p.node(scalarNode) - n.value = string(p.event.value) - n.tag = string(p.event.tag) - n.implicit = p.event.implicit - p.anchor(n, p.event.anchor) - p.expect(yaml_SCALAR_EVENT) - return n -} - -func (p *parser) sequence() *node { - n := p.node(sequenceNode) - p.anchor(n, p.event.anchor) - p.expect(yaml_SEQUENCE_START_EVENT) - for p.peek() != yaml_SEQUENCE_END_EVENT { - n.children = append(n.children, p.parse()) - } - p.expect(yaml_SEQUENCE_END_EVENT) - return n -} - -func (p *parser) mapping() *node { - n := p.node(mappingNode) - p.anchor(n, p.event.anchor) - p.expect(yaml_MAPPING_START_EVENT) - for p.peek() != yaml_MAPPING_END_EVENT { - n.children = append(n.children, p.parse(), p.parse()) - } - p.expect(yaml_MAPPING_END_EVENT) - return n -} - -// ---------------------------------------------------------------------------- -// Decoder, unmarshals a node into a provided value. - -type decoder struct { - doc *node - aliases map[*node]bool - mapType reflect.Type - terrors []string - strict bool -} - -var ( - mapItemType = reflect.TypeOf(MapItem{}) - durationType = reflect.TypeOf(time.Duration(0)) - defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) - ifaceType = defaultMapType.Elem() - timeType = reflect.TypeOf(time.Time{}) - ptrTimeType = reflect.TypeOf(&time.Time{}) -) - -func newDecoder(strict bool) *decoder { - d := &decoder{mapType: defaultMapType, strict: strict} - d.aliases = make(map[*node]bool) - return d -} - -func (d *decoder) terror(n *node, tag string, out reflect.Value) { - if n.tag != "" { - tag = n.tag - } - value := n.value - if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { - if len(value) > 10 { - value = " `" + value[:7] + "...`" - } else { - value = " `" + value + "`" - } - } - d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type())) -} - -func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { - terrlen := len(d.terrors) - err := u.UnmarshalYAML(func(v interface{}) (err error) { - defer handleErr(&err) - d.unmarshal(n, reflect.ValueOf(v)) - if len(d.terrors) > terrlen { - issues := d.terrors[terrlen:] - d.terrors = d.terrors[:terrlen] - return &TypeError{issues} - } - return nil - }) - if e, ok := err.(*TypeError); ok { - d.terrors = append(d.terrors, e.Errors...) - return false - } - if err != nil { - fail(err) - } - return true -} - -// d.prepare initializes and dereferences pointers and calls UnmarshalYAML -// if a value is found to implement it. -// It returns the initialized and dereferenced out value, whether -// unmarshalling was already done by UnmarshalYAML, and if so whether -// its types unmarshalled appropriately. -// -// If n holds a null value, prepare returns before doing anything. -func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { - if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) { - return out, false, false - } - again := true - for again { - again = false - if out.Kind() == reflect.Ptr { - if out.IsNil() { - out.Set(reflect.New(out.Type().Elem())) - } - out = out.Elem() - again = true - } - if out.CanAddr() { - if u, ok := out.Addr().Interface().(Unmarshaler); ok { - good = d.callUnmarshaler(n, u) - return out, true, good - } - } - } - return out, false, false -} - -func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) { - switch n.kind { - case documentNode: - return d.document(n, out) - case aliasNode: - return d.alias(n, out) - } - out, unmarshaled, good := d.prepare(n, out) - if unmarshaled { - return good - } - switch n.kind { - case scalarNode: - good = d.scalar(n, out) - case mappingNode: - good = d.mapping(n, out) - case sequenceNode: - good = d.sequence(n, out) - default: - panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) - } - return good -} - -func (d *decoder) document(n *node, out reflect.Value) (good bool) { - if len(n.children) == 1 { - d.doc = n - d.unmarshal(n.children[0], out) - return true - } - return false -} - -func (d *decoder) alias(n *node, out reflect.Value) (good bool) { - if d.aliases[n] { - // TODO this could actually be allowed in some circumstances. - failf("anchor '%s' value contains itself", n.value) - } - d.aliases[n] = true - good = d.unmarshal(n.alias, out) - delete(d.aliases, n) - return good -} - -var zeroValue reflect.Value - -func resetMap(out reflect.Value) { - for _, k := range out.MapKeys() { - out.SetMapIndex(k, zeroValue) - } -} - -func (d *decoder) scalar(n *node, out reflect.Value) bool { - var tag string - var resolved interface{} - if n.tag == "" && !n.implicit { - tag = yaml_STR_TAG - resolved = n.value - } else { - tag, resolved = resolve(n.tag, n.value) - if tag == yaml_BINARY_TAG { - data, err := base64.StdEncoding.DecodeString(resolved.(string)) - if err != nil { - failf("!!binary value contains invalid base64 data") - } - resolved = string(data) - } - } - if resolved == nil { - if out.Kind() == reflect.Map && !out.CanAddr() { - resetMap(out) - } else { - out.Set(reflect.Zero(out.Type())) - } - return true - } - if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { - // We've resolved to exactly the type we want, so use that. - out.Set(resolvedv) - return true - } - // Perhaps we can use the value as a TextUnmarshaler to - // set its value. - if out.CanAddr() { - u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) - if ok { - var text []byte - if tag == yaml_BINARY_TAG { - text = []byte(resolved.(string)) - } else { - // We let any value be unmarshaled into TextUnmarshaler. - // That might be more lax than we'd like, but the - // TextUnmarshaler itself should bowl out any dubious values. - text = []byte(n.value) - } - err := u.UnmarshalText(text) - if err != nil { - fail(err) - } - return true - } - } - switch out.Kind() { - case reflect.String: - if tag == yaml_BINARY_TAG { - out.SetString(resolved.(string)) - return true - } - if resolved != nil { - out.SetString(n.value) - return true - } - case reflect.Interface: - if resolved == nil { - out.Set(reflect.Zero(out.Type())) - } else if tag == yaml_TIMESTAMP_TAG { - // It looks like a timestamp but for backward compatibility - // reasons we set it as a string, so that code that unmarshals - // timestamp-like values into interface{} will continue to - // see a string and not a time.Time. - // TODO(v3) Drop this. - out.Set(reflect.ValueOf(n.value)) - } else { - out.Set(reflect.ValueOf(resolved)) - } - return true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - switch resolved := resolved.(type) { - case int: - if !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case int64: - if !out.OverflowInt(resolved) { - out.SetInt(resolved) - return true - } - case uint64: - if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case float64: - if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case string: - if out.Type() == durationType { - d, err := time.ParseDuration(resolved) - if err == nil { - out.SetInt(int64(d)) - return true - } - } - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - switch resolved := resolved.(type) { - case int: - if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case int64: - if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case uint64: - if !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case float64: - if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - } - case reflect.Bool: - switch resolved := resolved.(type) { - case bool: - out.SetBool(resolved) - return true - } - case reflect.Float32, reflect.Float64: - switch resolved := resolved.(type) { - case int: - out.SetFloat(float64(resolved)) - return true - case int64: - out.SetFloat(float64(resolved)) - return true - case uint64: - out.SetFloat(float64(resolved)) - return true - case float64: - out.SetFloat(resolved) - return true - } - case reflect.Struct: - if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { - out.Set(resolvedv) - return true - } - case reflect.Ptr: - if out.Type().Elem() == reflect.TypeOf(resolved) { - // TODO DOes this make sense? When is out a Ptr except when decoding a nil value? - elem := reflect.New(out.Type().Elem()) - elem.Elem().Set(reflect.ValueOf(resolved)) - out.Set(elem) - return true - } - } - d.terror(n, tag, out) - return false -} - -func settableValueOf(i interface{}) reflect.Value { - v := reflect.ValueOf(i) - sv := reflect.New(v.Type()).Elem() - sv.Set(v) - return sv -} - -func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { - l := len(n.children) - - var iface reflect.Value - switch out.Kind() { - case reflect.Slice: - out.Set(reflect.MakeSlice(out.Type(), l, l)) - case reflect.Array: - if l != out.Len() { - failf("invalid array: want %d elements but got %d", out.Len(), l) - } - case reflect.Interface: - // No type hints. Will have to use a generic sequence. - iface = out - out = settableValueOf(make([]interface{}, l)) - default: - d.terror(n, yaml_SEQ_TAG, out) - return false - } - et := out.Type().Elem() - - j := 0 - for i := 0; i < l; i++ { - e := reflect.New(et).Elem() - if ok := d.unmarshal(n.children[i], e); ok { - out.Index(j).Set(e) - j++ - } - } - if out.Kind() != reflect.Array { - out.Set(out.Slice(0, j)) - } - if iface.IsValid() { - iface.Set(out) - } - return true -} - -func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { - switch out.Kind() { - case reflect.Struct: - return d.mappingStruct(n, out) - case reflect.Slice: - return d.mappingSlice(n, out) - case reflect.Map: - // okay - case reflect.Interface: - if d.mapType.Kind() == reflect.Map { - iface := out - out = reflect.MakeMap(d.mapType) - iface.Set(out) - } else { - slicev := reflect.New(d.mapType).Elem() - if !d.mappingSlice(n, slicev) { - return false - } - out.Set(slicev) - return true - } - default: - d.terror(n, yaml_MAP_TAG, out) - return false - } - outt := out.Type() - kt := outt.Key() - et := outt.Elem() - - mapType := d.mapType - if outt.Key() == ifaceType && outt.Elem() == ifaceType { - d.mapType = outt - } - - if out.IsNil() { - out.Set(reflect.MakeMap(outt)) - } - l := len(n.children) - for i := 0; i < l; i += 2 { - if isMerge(n.children[i]) { - d.merge(n.children[i+1], out) - continue - } - k := reflect.New(kt).Elem() - if d.unmarshal(n.children[i], k) { - kkind := k.Kind() - if kkind == reflect.Interface { - kkind = k.Elem().Kind() - } - if kkind == reflect.Map || kkind == reflect.Slice { - failf("invalid map key: %#v", k.Interface()) - } - e := reflect.New(et).Elem() - if d.unmarshal(n.children[i+1], e) { - d.setMapIndex(n.children[i+1], out, k, e) - } - } - } - d.mapType = mapType - return true -} - -func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) { - if d.strict && out.MapIndex(k) != zeroValue { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface())) - return - } - out.SetMapIndex(k, v) -} - -func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { - outt := out.Type() - if outt.Elem() != mapItemType { - d.terror(n, yaml_MAP_TAG, out) - return false - } - - mapType := d.mapType - d.mapType = outt - - var slice []MapItem - var l = len(n.children) - for i := 0; i < l; i += 2 { - if isMerge(n.children[i]) { - d.merge(n.children[i+1], out) - continue - } - item := MapItem{} - k := reflect.ValueOf(&item.Key).Elem() - if d.unmarshal(n.children[i], k) { - v := reflect.ValueOf(&item.Value).Elem() - if d.unmarshal(n.children[i+1], v) { - slice = append(slice, item) - } - } - } - out.Set(reflect.ValueOf(slice)) - d.mapType = mapType - return true -} - -func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { - sinfo, err := getStructInfo(out.Type()) - if err != nil { - panic(err) - } - name := settableValueOf("") - l := len(n.children) - - var inlineMap reflect.Value - var elemType reflect.Type - if sinfo.InlineMap != -1 { - inlineMap = out.Field(sinfo.InlineMap) - inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) - elemType = inlineMap.Type().Elem() - } - - var doneFields []bool - if d.strict { - doneFields = make([]bool, len(sinfo.FieldsList)) - } - for i := 0; i < l; i += 2 { - ni := n.children[i] - if isMerge(ni) { - d.merge(n.children[i+1], out) - continue - } - if !d.unmarshal(ni, name) { - continue - } - if info, ok := sinfo.FieldsMap[name.String()]; ok { - if d.strict { - if doneFields[info.Id] { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type())) - continue - } - doneFields[info.Id] = true - } - var field reflect.Value - if info.Inline == nil { - field = out.Field(info.Num) - } else { - field = out.FieldByIndex(info.Inline) - } - d.unmarshal(n.children[i+1], field) - } else if sinfo.InlineMap != -1 { - if inlineMap.IsNil() { - inlineMap.Set(reflect.MakeMap(inlineMap.Type())) - } - value := reflect.New(elemType).Elem() - d.unmarshal(n.children[i+1], value) - d.setMapIndex(n.children[i+1], inlineMap, name, value) - } else if d.strict { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type())) - } - } - return true -} - -func failWantMap() { - failf("map merge requires map or sequence of maps as the value") -} - -func (d *decoder) merge(n *node, out reflect.Value) { - switch n.kind { - case mappingNode: - d.unmarshal(n, out) - case aliasNode: - an, ok := d.doc.anchors[n.value] - if ok && an.kind != mappingNode { - failWantMap() - } - d.unmarshal(n, out) - case sequenceNode: - // Step backwards as earlier nodes take precedence. - for i := len(n.children) - 1; i >= 0; i-- { - ni := n.children[i] - if ni.kind == aliasNode { - an, ok := d.doc.anchors[ni.value] - if ok && an.kind != mappingNode { - failWantMap() - } - } else if ni.kind != mappingNode { - failWantMap() - } - d.unmarshal(ni, out) - } - default: - failWantMap() - } -} - -func isMerge(n *node) bool { - return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) -} diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go deleted file mode 100644 index a1c2cc526..000000000 --- a/vendor/gopkg.in/yaml.v2/emitterc.go +++ /dev/null @@ -1,1685 +0,0 @@ -package yaml - -import ( - "bytes" - "fmt" -) - -// Flush the buffer if needed. -func flush(emitter *yaml_emitter_t) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) { - return yaml_emitter_flush(emitter) - } - return true -} - -// Put a character to the output buffer. -func put(emitter *yaml_emitter_t, value byte) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - emitter.buffer[emitter.buffer_pos] = value - emitter.buffer_pos++ - emitter.column++ - return true -} - -// Put a line break to the output buffer. -func put_break(emitter *yaml_emitter_t) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - switch emitter.line_break { - case yaml_CR_BREAK: - emitter.buffer[emitter.buffer_pos] = '\r' - emitter.buffer_pos += 1 - case yaml_LN_BREAK: - emitter.buffer[emitter.buffer_pos] = '\n' - emitter.buffer_pos += 1 - case yaml_CRLN_BREAK: - emitter.buffer[emitter.buffer_pos+0] = '\r' - emitter.buffer[emitter.buffer_pos+1] = '\n' - emitter.buffer_pos += 2 - default: - panic("unknown line break setting") - } - emitter.column = 0 - emitter.line++ - return true -} - -// Copy a character from a string into buffer. -func write(emitter *yaml_emitter_t, s []byte, i *int) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - p := emitter.buffer_pos - w := width(s[*i]) - switch w { - case 4: - emitter.buffer[p+3] = s[*i+3] - fallthrough - case 3: - emitter.buffer[p+2] = s[*i+2] - fallthrough - case 2: - emitter.buffer[p+1] = s[*i+1] - fallthrough - case 1: - emitter.buffer[p+0] = s[*i+0] - default: - panic("unknown character width") - } - emitter.column++ - emitter.buffer_pos += w - *i += w - return true -} - -// Write a whole string into buffer. -func write_all(emitter *yaml_emitter_t, s []byte) bool { - for i := 0; i < len(s); { - if !write(emitter, s, &i) { - return false - } - } - return true -} - -// Copy a line break character from a string into buffer. -func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { - if s[*i] == '\n' { - if !put_break(emitter) { - return false - } - *i++ - } else { - if !write(emitter, s, i) { - return false - } - emitter.column = 0 - emitter.line++ - } - return true -} - -// Set an emitter error and return false. -func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_EMITTER_ERROR - emitter.problem = problem - return false -} - -// Emit an event. -func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.events = append(emitter.events, *event) - for !yaml_emitter_need_more_events(emitter) { - event := &emitter.events[emitter.events_head] - if !yaml_emitter_analyze_event(emitter, event) { - return false - } - if !yaml_emitter_state_machine(emitter, event) { - return false - } - yaml_event_delete(event) - emitter.events_head++ - } - return true -} - -// Check if we need to accumulate more events before emitting. -// -// We accumulate extra -// - 1 event for DOCUMENT-START -// - 2 events for SEQUENCE-START -// - 3 events for MAPPING-START -// -func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { - if emitter.events_head == len(emitter.events) { - return true - } - var accumulate int - switch emitter.events[emitter.events_head].typ { - case yaml_DOCUMENT_START_EVENT: - accumulate = 1 - break - case yaml_SEQUENCE_START_EVENT: - accumulate = 2 - break - case yaml_MAPPING_START_EVENT: - accumulate = 3 - break - default: - return false - } - if len(emitter.events)-emitter.events_head > accumulate { - return false - } - var level int - for i := emitter.events_head; i < len(emitter.events); i++ { - switch emitter.events[i].typ { - case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: - level++ - case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: - level-- - } - if level == 0 { - return false - } - } - return true -} - -// Append a directive to the directives stack. -func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { - for i := 0; i < len(emitter.tag_directives); i++ { - if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") - } - } - - // [Go] Do we actually need to copy this given garbage collection - // and the lack of deallocating destructors? - tag_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(tag_copy.handle, value.handle) - copy(tag_copy.prefix, value.prefix) - emitter.tag_directives = append(emitter.tag_directives, tag_copy) - return true -} - -// Increase the indentation level. -func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { - emitter.indents = append(emitter.indents, emitter.indent) - if emitter.indent < 0 { - if flow { - emitter.indent = emitter.best_indent - } else { - emitter.indent = 0 - } - } else if !indentless { - emitter.indent += emitter.best_indent - } - return true -} - -// State dispatcher. -func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { - switch emitter.state { - default: - case yaml_EMIT_STREAM_START_STATE: - return yaml_emitter_emit_stream_start(emitter, event) - - case yaml_EMIT_FIRST_DOCUMENT_START_STATE: - return yaml_emitter_emit_document_start(emitter, event, true) - - case yaml_EMIT_DOCUMENT_START_STATE: - return yaml_emitter_emit_document_start(emitter, event, false) - - case yaml_EMIT_DOCUMENT_CONTENT_STATE: - return yaml_emitter_emit_document_content(emitter, event) - - case yaml_EMIT_DOCUMENT_END_STATE: - return yaml_emitter_emit_document_end(emitter, event) - - case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, true) - - case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, false) - - case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, true) - - case yaml_EMIT_FLOW_MAPPING_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, false) - - case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: - return yaml_emitter_emit_flow_mapping_value(emitter, event, true) - - case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: - return yaml_emitter_emit_flow_mapping_value(emitter, event, false) - - case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_block_sequence_item(emitter, event, true) - - case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_block_sequence_item(emitter, event, false) - - case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_block_mapping_key(emitter, event, true) - - case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: - return yaml_emitter_emit_block_mapping_key(emitter, event, false) - - case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: - return yaml_emitter_emit_block_mapping_value(emitter, event, true) - - case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: - return yaml_emitter_emit_block_mapping_value(emitter, event, false) - - case yaml_EMIT_END_STATE: - return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") - } - panic("invalid emitter state") -} - -// Expect STREAM-START. -func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if event.typ != yaml_STREAM_START_EVENT { - return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") - } - if emitter.encoding == yaml_ANY_ENCODING { - emitter.encoding = event.encoding - if emitter.encoding == yaml_ANY_ENCODING { - emitter.encoding = yaml_UTF8_ENCODING - } - } - if emitter.best_indent < 2 || emitter.best_indent > 9 { - emitter.best_indent = 2 - } - if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { - emitter.best_width = 80 - } - if emitter.best_width < 0 { - emitter.best_width = 1<<31 - 1 - } - if emitter.line_break == yaml_ANY_BREAK { - emitter.line_break = yaml_LN_BREAK - } - - emitter.indent = -1 - emitter.line = 0 - emitter.column = 0 - emitter.whitespace = true - emitter.indention = true - - if emitter.encoding != yaml_UTF8_ENCODING { - if !yaml_emitter_write_bom(emitter) { - return false - } - } - emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE - return true -} - -// Expect DOCUMENT-START or STREAM-END. -func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - - if event.typ == yaml_DOCUMENT_START_EVENT { - - if event.version_directive != nil { - if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { - return false - } - } - - for i := 0; i < len(event.tag_directives); i++ { - tag_directive := &event.tag_directives[i] - if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { - return false - } - if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { - return false - } - } - - for i := 0; i < len(default_tag_directives); i++ { - tag_directive := &default_tag_directives[i] - if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { - return false - } - } - - implicit := event.implicit - if !first || emitter.canonical { - implicit = false - } - - if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if event.version_directive != nil { - implicit = false - if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if len(event.tag_directives) > 0 { - implicit = false - for i := 0; i < len(event.tag_directives); i++ { - tag_directive := &event.tag_directives[i] - if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { - return false - } - if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { - return false - } - if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - } - - if yaml_emitter_check_empty_document(emitter) { - implicit = false - } - if !implicit { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { - return false - } - if emitter.canonical { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - } - - emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE - return true - } - - if event.typ == yaml_STREAM_END_EVENT { - if emitter.open_ended { - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_flush(emitter) { - return false - } - emitter.state = yaml_EMIT_END_STATE - return true - } - - return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") -} - -// Expect the root node. -func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) - return yaml_emitter_emit_node(emitter, event, true, false, false, false) -} - -// Expect DOCUMENT-END. -func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if event.typ != yaml_DOCUMENT_END_EVENT { - return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !event.implicit { - // [Go] Allocate the slice elsewhere. - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_flush(emitter) { - return false - } - emitter.state = yaml_EMIT_DOCUMENT_START_STATE - emitter.tag_directives = emitter.tag_directives[:0] - return true -} - -// Expect a flow item node. -func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - emitter.flow_level++ - } - - if event.typ == yaml_SEQUENCE_END_EVENT { - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.canonical && !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - - return true - } - - if !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) - return yaml_emitter_emit_node(emitter, event, false, true, false, false) -} - -// Expect a flow key node. -func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - emitter.flow_level++ - } - - if event.typ == yaml_MAPPING_END_EVENT { - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.canonical && !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - - if !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, true) - } - if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a flow value node. -func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { - if simple { - if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { - return false - } - } else { - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { - return false - } - } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a block item node. -func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { - return false - } - } - if event.typ == yaml_SEQUENCE_END_EVENT { - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) - return yaml_emitter_emit_node(emitter, event, false, true, false, false) -} - -// Expect a block key node. -func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_increase_indent(emitter, false, false) { - return false - } - } - if event.typ == yaml_MAPPING_END_EVENT { - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if yaml_emitter_check_simple_key(emitter) { - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, true) - } - if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a block value node. -func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { - if simple { - if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { - return false - } - } else { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { - return false - } - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a node. -func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, - root bool, sequence bool, mapping bool, simple_key bool) bool { - - emitter.root_context = root - emitter.sequence_context = sequence - emitter.mapping_context = mapping - emitter.simple_key_context = simple_key - - switch event.typ { - case yaml_ALIAS_EVENT: - return yaml_emitter_emit_alias(emitter, event) - case yaml_SCALAR_EVENT: - return yaml_emitter_emit_scalar(emitter, event) - case yaml_SEQUENCE_START_EVENT: - return yaml_emitter_emit_sequence_start(emitter, event) - case yaml_MAPPING_START_EVENT: - return yaml_emitter_emit_mapping_start(emitter, event) - default: - return yaml_emitter_set_emitter_error(emitter, - fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) - } -} - -// Expect ALIAS. -func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true -} - -// Expect SCALAR. -func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_select_scalar_style(emitter, event) { - return false - } - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - if !yaml_emitter_process_scalar(emitter) { - return false - } - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true -} - -// Expect SEQUENCE-START. -func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || - yaml_emitter_check_empty_sequence(emitter) { - emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE - } else { - emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE - } - return true -} - -// Expect MAPPING-START. -func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || - yaml_emitter_check_empty_mapping(emitter) { - emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE - } else { - emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE - } - return true -} - -// Check if the document content is an empty scalar. -func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { - return false // [Go] Huh? -} - -// Check if the next events represent an empty sequence. -func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { - if len(emitter.events)-emitter.events_head < 2 { - return false - } - return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && - emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT -} - -// Check if the next events represent an empty mapping. -func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { - if len(emitter.events)-emitter.events_head < 2 { - return false - } - return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && - emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT -} - -// Check if the next node can be expressed as a simple key. -func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { - length := 0 - switch emitter.events[emitter.events_head].typ { - case yaml_ALIAS_EVENT: - length += len(emitter.anchor_data.anchor) - case yaml_SCALAR_EVENT: - if emitter.scalar_data.multiline { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) + - len(emitter.scalar_data.value) - case yaml_SEQUENCE_START_EVENT: - if !yaml_emitter_check_empty_sequence(emitter) { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) - case yaml_MAPPING_START_EVENT: - if !yaml_emitter_check_empty_mapping(emitter) { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) - default: - return false - } - return length <= 128 -} - -// Determine an acceptable scalar style. -func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { - - no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 - if no_tag && !event.implicit && !event.quoted_implicit { - return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") - } - - style := event.scalar_style() - if style == yaml_ANY_SCALAR_STYLE { - style = yaml_PLAIN_SCALAR_STYLE - } - if emitter.canonical { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - if emitter.simple_key_context && emitter.scalar_data.multiline { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - - if style == yaml_PLAIN_SCALAR_STYLE { - if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || - emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - if no_tag && !event.implicit { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - } - if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { - if !emitter.scalar_data.single_quoted_allowed { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - } - if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { - if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - } - - if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { - emitter.tag_data.handle = []byte{'!'} - } - emitter.scalar_data.style = style - return true -} - -// Write an anchor. -func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { - if emitter.anchor_data.anchor == nil { - return true - } - c := []byte{'&'} - if emitter.anchor_data.alias { - c[0] = '*' - } - if !yaml_emitter_write_indicator(emitter, c, true, false, false) { - return false - } - return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) -} - -// Write a tag. -func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { - if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { - return true - } - if len(emitter.tag_data.handle) > 0 { - if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { - return false - } - if len(emitter.tag_data.suffix) > 0 { - if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { - return false - } - } - } else { - // [Go] Allocate these slices elsewhere. - if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { - return false - } - if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { - return false - } - } - return true -} - -// Write a scalar. -func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { - switch emitter.scalar_data.style { - case yaml_PLAIN_SCALAR_STYLE: - return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_SINGLE_QUOTED_SCALAR_STYLE: - return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_DOUBLE_QUOTED_SCALAR_STYLE: - return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_LITERAL_SCALAR_STYLE: - return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) - - case yaml_FOLDED_SCALAR_STYLE: - return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) - } - panic("unknown scalar style") -} - -// Check if a %YAML directive is valid. -func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { - if version_directive.major != 1 || version_directive.minor != 1 { - return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") - } - return true -} - -// Check if a %TAG directive is valid. -func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { - handle := tag_directive.handle - prefix := tag_directive.prefix - if len(handle) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") - } - if handle[0] != '!' { - return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") - } - if handle[len(handle)-1] != '!' { - return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") - } - for i := 1; i < len(handle)-1; i += width(handle[i]) { - if !is_alpha(handle, i) { - return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") - } - } - if len(prefix) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") - } - return true -} - -// Check if an anchor is valid. -func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { - if len(anchor) == 0 { - problem := "anchor value must not be empty" - if alias { - problem = "alias value must not be empty" - } - return yaml_emitter_set_emitter_error(emitter, problem) - } - for i := 0; i < len(anchor); i += width(anchor[i]) { - if !is_alpha(anchor, i) { - problem := "anchor value must contain alphanumerical characters only" - if alias { - problem = "alias value must contain alphanumerical characters only" - } - return yaml_emitter_set_emitter_error(emitter, problem) - } - } - emitter.anchor_data.anchor = anchor - emitter.anchor_data.alias = alias - return true -} - -// Check if a tag is valid. -func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { - if len(tag) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") - } - for i := 0; i < len(emitter.tag_directives); i++ { - tag_directive := &emitter.tag_directives[i] - if bytes.HasPrefix(tag, tag_directive.prefix) { - emitter.tag_data.handle = tag_directive.handle - emitter.tag_data.suffix = tag[len(tag_directive.prefix):] - return true - } - } - emitter.tag_data.suffix = tag - return true -} - -// Check if a scalar is valid. -func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { - var ( - block_indicators = false - flow_indicators = false - line_breaks = false - special_characters = false - - leading_space = false - leading_break = false - trailing_space = false - trailing_break = false - break_space = false - space_break = false - - preceded_by_whitespace = false - followed_by_whitespace = false - previous_space = false - previous_break = false - ) - - emitter.scalar_data.value = value - - if len(value) == 0 { - emitter.scalar_data.multiline = false - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = true - emitter.scalar_data.single_quoted_allowed = true - emitter.scalar_data.block_allowed = false - return true - } - - if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { - block_indicators = true - flow_indicators = true - } - - preceded_by_whitespace = true - for i, w := 0, 0; i < len(value); i += w { - w = width(value[i]) - followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) - - if i == 0 { - switch value[i] { - case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': - flow_indicators = true - block_indicators = true - case '?', ':': - flow_indicators = true - if followed_by_whitespace { - block_indicators = true - } - case '-': - if followed_by_whitespace { - flow_indicators = true - block_indicators = true - } - } - } else { - switch value[i] { - case ',', '?', '[', ']', '{', '}': - flow_indicators = true - case ':': - flow_indicators = true - if followed_by_whitespace { - block_indicators = true - } - case '#': - if preceded_by_whitespace { - flow_indicators = true - block_indicators = true - } - } - } - - if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { - special_characters = true - } - if is_space(value, i) { - if i == 0 { - leading_space = true - } - if i+width(value[i]) == len(value) { - trailing_space = true - } - if previous_break { - break_space = true - } - previous_space = true - previous_break = false - } else if is_break(value, i) { - line_breaks = true - if i == 0 { - leading_break = true - } - if i+width(value[i]) == len(value) { - trailing_break = true - } - if previous_space { - space_break = true - } - previous_space = false - previous_break = true - } else { - previous_space = false - previous_break = false - } - - // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. - preceded_by_whitespace = is_blankz(value, i) - } - - emitter.scalar_data.multiline = line_breaks - emitter.scalar_data.flow_plain_allowed = true - emitter.scalar_data.block_plain_allowed = true - emitter.scalar_data.single_quoted_allowed = true - emitter.scalar_data.block_allowed = true - - if leading_space || leading_break || trailing_space || trailing_break { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - } - if trailing_space { - emitter.scalar_data.block_allowed = false - } - if break_space { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - emitter.scalar_data.single_quoted_allowed = false - } - if space_break || special_characters { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - emitter.scalar_data.single_quoted_allowed = false - emitter.scalar_data.block_allowed = false - } - if line_breaks { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - } - if flow_indicators { - emitter.scalar_data.flow_plain_allowed = false - } - if block_indicators { - emitter.scalar_data.block_plain_allowed = false - } - return true -} - -// Check if the event data is valid. -func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { - - emitter.anchor_data.anchor = nil - emitter.tag_data.handle = nil - emitter.tag_data.suffix = nil - emitter.scalar_data.value = nil - - switch event.typ { - case yaml_ALIAS_EVENT: - if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { - return false - } - - case yaml_SCALAR_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - if !yaml_emitter_analyze_scalar(emitter, event.value) { - return false - } - - case yaml_SEQUENCE_START_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - - case yaml_MAPPING_START_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - } - return true -} - -// Write the BOM character. -func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { - if !flush(emitter) { - return false - } - pos := emitter.buffer_pos - emitter.buffer[pos+0] = '\xEF' - emitter.buffer[pos+1] = '\xBB' - emitter.buffer[pos+2] = '\xBF' - emitter.buffer_pos += 3 - return true -} - -func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { - indent := emitter.indent - if indent < 0 { - indent = 0 - } - if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { - if !put_break(emitter) { - return false - } - } - for emitter.column < indent { - if !put(emitter, ' ') { - return false - } - } - emitter.whitespace = true - emitter.indention = true - return true -} - -func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { - if need_whitespace && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !write_all(emitter, indicator) { - return false - } - emitter.whitespace = is_whitespace - emitter.indention = (emitter.indention && is_indention) - emitter.open_ended = false - return true -} - -func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { - if !write_all(emitter, value) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { - if !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !write_all(emitter, value) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { - if need_whitespace && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - for i := 0; i < len(value); { - var must_write bool - switch value[i] { - case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': - must_write = true - default: - must_write = is_alpha(value, i) - } - if must_write { - if !write(emitter, value, &i) { - return false - } - } else { - w := width(value[i]) - for k := 0; k < w; k++ { - octet := value[i] - i++ - if !put(emitter, '%') { - return false - } - - c := octet >> 4 - if c < 10 { - c += '0' - } else { - c += 'A' - 10 - } - if !put(emitter, c) { - return false - } - - c = octet & 0x0f - if c < 10 { - c += '0' - } else { - c += 'A' - 10 - } - if !put(emitter, c) { - return false - } - } - } - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - if !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - - spaces := false - breaks := false - for i := 0; i < len(value); { - if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - spaces = true - } else if is_break(value, i) { - if !breaks && value[i] == '\n' { - if !put_break(emitter) { - return false - } - } - if !write_break(emitter, value, &i) { - return false - } - emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - spaces = false - breaks = false - } - } - - emitter.whitespace = false - emitter.indention = false - if emitter.root_context { - emitter.open_ended = true - } - - return true -} - -func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { - return false - } - - spaces := false - breaks := false - for i := 0; i < len(value); { - if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - spaces = true - } else if is_break(value, i) { - if !breaks && value[i] == '\n' { - if !put_break(emitter) { - return false - } - } - if !write_break(emitter, value, &i) { - return false - } - emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if value[i] == '\'' { - if !put(emitter, '\'') { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - spaces = false - breaks = false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - spaces := false - if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { - return false - } - - for i := 0; i < len(value); { - if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || - is_bom(value, i) || is_break(value, i) || - value[i] == '"' || value[i] == '\\' { - - octet := value[i] - - var w int - var v rune - switch { - case octet&0x80 == 0x00: - w, v = 1, rune(octet&0x7F) - case octet&0xE0 == 0xC0: - w, v = 2, rune(octet&0x1F) - case octet&0xF0 == 0xE0: - w, v = 3, rune(octet&0x0F) - case octet&0xF8 == 0xF0: - w, v = 4, rune(octet&0x07) - } - for k := 1; k < w; k++ { - octet = value[i+k] - v = (v << 6) + (rune(octet) & 0x3F) - } - i += w - - if !put(emitter, '\\') { - return false - } - - var ok bool - switch v { - case 0x00: - ok = put(emitter, '0') - case 0x07: - ok = put(emitter, 'a') - case 0x08: - ok = put(emitter, 'b') - case 0x09: - ok = put(emitter, 't') - case 0x0A: - ok = put(emitter, 'n') - case 0x0b: - ok = put(emitter, 'v') - case 0x0c: - ok = put(emitter, 'f') - case 0x0d: - ok = put(emitter, 'r') - case 0x1b: - ok = put(emitter, 'e') - case 0x22: - ok = put(emitter, '"') - case 0x5c: - ok = put(emitter, '\\') - case 0x85: - ok = put(emitter, 'N') - case 0xA0: - ok = put(emitter, '_') - case 0x2028: - ok = put(emitter, 'L') - case 0x2029: - ok = put(emitter, 'P') - default: - if v <= 0xFF { - ok = put(emitter, 'x') - w = 2 - } else if v <= 0xFFFF { - ok = put(emitter, 'u') - w = 4 - } else { - ok = put(emitter, 'U') - w = 8 - } - for k := (w - 1) * 4; ok && k >= 0; k -= 4 { - digit := byte((v >> uint(k)) & 0x0F) - if digit < 10 { - ok = put(emitter, digit+'0') - } else { - ok = put(emitter, digit+'A'-10) - } - } - } - if !ok { - return false - } - spaces = false - } else if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { - if !yaml_emitter_write_indent(emitter) { - return false - } - if is_space(value, i+1) { - if !put(emitter, '\\') { - return false - } - } - i += width(value[i]) - } else if !write(emitter, value, &i) { - return false - } - spaces = true - } else { - if !write(emitter, value, &i) { - return false - } - spaces = false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { - if is_space(value, 0) || is_break(value, 0) { - indent_hint := []byte{'0' + byte(emitter.best_indent)} - if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { - return false - } - } - - emitter.open_ended = false - - var chomp_hint [1]byte - if len(value) == 0 { - chomp_hint[0] = '-' - } else { - i := len(value) - 1 - for value[i]&0xC0 == 0x80 { - i-- - } - if !is_break(value, i) { - chomp_hint[0] = '-' - } else if i == 0 { - chomp_hint[0] = '+' - emitter.open_ended = true - } else { - i-- - for value[i]&0xC0 == 0x80 { - i-- - } - if is_break(value, i) { - chomp_hint[0] = '+' - emitter.open_ended = true - } - } - } - if chomp_hint[0] != 0 { - if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { - return false - } - } - return true -} - -func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { - return false - } - if !yaml_emitter_write_block_scalar_hints(emitter, value) { - return false - } - if !put_break(emitter) { - return false - } - emitter.indention = true - emitter.whitespace = true - breaks := true - for i := 0; i < len(value); { - if is_break(value, i) { - if !write_break(emitter, value, &i) { - return false - } - emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - breaks = false - } - } - - return true -} - -func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { - return false - } - if !yaml_emitter_write_block_scalar_hints(emitter, value) { - return false - } - - if !put_break(emitter) { - return false - } - emitter.indention = true - emitter.whitespace = true - - breaks := true - leading_spaces := true - for i := 0; i < len(value); { - if is_break(value, i) { - if !breaks && !leading_spaces && value[i] == '\n' { - k := 0 - for is_break(value, k) { - k += width(value[k]) - } - if !is_blankz(value, k) { - if !put_break(emitter) { - return false - } - } - } - if !write_break(emitter, value, &i) { - return false - } - emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - leading_spaces = is_blank(value, i) - } - if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - emitter.indention = false - breaks = false - } - } - return true -} diff --git a/vendor/gopkg.in/yaml.v2/encode.go b/vendor/gopkg.in/yaml.v2/encode.go deleted file mode 100644 index a14435e82..000000000 --- a/vendor/gopkg.in/yaml.v2/encode.go +++ /dev/null @@ -1,362 +0,0 @@ -package yaml - -import ( - "encoding" - "fmt" - "io" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -type encoder struct { - emitter yaml_emitter_t - event yaml_event_t - out []byte - flow bool - // doneInit holds whether the initial stream_start_event has been - // emitted. - doneInit bool -} - -func newEncoder() *encoder { - e := &encoder{} - yaml_emitter_initialize(&e.emitter) - yaml_emitter_set_output_string(&e.emitter, &e.out) - yaml_emitter_set_unicode(&e.emitter, true) - return e -} - -func newEncoderWithWriter(w io.Writer) *encoder { - e := &encoder{} - yaml_emitter_initialize(&e.emitter) - yaml_emitter_set_output_writer(&e.emitter, w) - yaml_emitter_set_unicode(&e.emitter, true) - return e -} - -func (e *encoder) init() { - if e.doneInit { - return - } - yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) - e.emit() - e.doneInit = true -} - -func (e *encoder) finish() { - e.emitter.open_ended = false - yaml_stream_end_event_initialize(&e.event) - e.emit() -} - -func (e *encoder) destroy() { - yaml_emitter_delete(&e.emitter) -} - -func (e *encoder) emit() { - // This will internally delete the e.event value. - e.must(yaml_emitter_emit(&e.emitter, &e.event)) -} - -func (e *encoder) must(ok bool) { - if !ok { - msg := e.emitter.problem - if msg == "" { - msg = "unknown problem generating YAML content" - } - failf("%s", msg) - } -} - -func (e *encoder) marshalDoc(tag string, in reflect.Value) { - e.init() - yaml_document_start_event_initialize(&e.event, nil, nil, true) - e.emit() - e.marshal(tag, in) - yaml_document_end_event_initialize(&e.event, true) - e.emit() -} - -func (e *encoder) marshal(tag string, in reflect.Value) { - if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { - e.nilv() - return - } - iface := in.Interface() - switch m := iface.(type) { - case time.Time, *time.Time: - // Although time.Time implements TextMarshaler, - // we don't want to treat it as a string for YAML - // purposes because YAML has special support for - // timestamps. - case Marshaler: - v, err := m.MarshalYAML() - if err != nil { - fail(err) - } - if v == nil { - e.nilv() - return - } - in = reflect.ValueOf(v) - case encoding.TextMarshaler: - text, err := m.MarshalText() - if err != nil { - fail(err) - } - in = reflect.ValueOf(string(text)) - case nil: - e.nilv() - return - } - switch in.Kind() { - case reflect.Interface: - e.marshal(tag, in.Elem()) - case reflect.Map: - e.mapv(tag, in) - case reflect.Ptr: - if in.Type() == ptrTimeType { - e.timev(tag, in.Elem()) - } else { - e.marshal(tag, in.Elem()) - } - case reflect.Struct: - if in.Type() == timeType { - e.timev(tag, in) - } else { - e.structv(tag, in) - } - case reflect.Slice, reflect.Array: - if in.Type().Elem() == mapItemType { - e.itemsv(tag, in) - } else { - e.slicev(tag, in) - } - case reflect.String: - e.stringv(tag, in) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if in.Type() == durationType { - e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String())) - } else { - e.intv(tag, in) - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - e.uintv(tag, in) - case reflect.Float32, reflect.Float64: - e.floatv(tag, in) - case reflect.Bool: - e.boolv(tag, in) - default: - panic("cannot marshal type: " + in.Type().String()) - } -} - -func (e *encoder) mapv(tag string, in reflect.Value) { - e.mappingv(tag, func() { - keys := keyList(in.MapKeys()) - sort.Sort(keys) - for _, k := range keys { - e.marshal("", k) - e.marshal("", in.MapIndex(k)) - } - }) -} - -func (e *encoder) itemsv(tag string, in reflect.Value) { - e.mappingv(tag, func() { - slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem) - for _, item := range slice { - e.marshal("", reflect.ValueOf(item.Key)) - e.marshal("", reflect.ValueOf(item.Value)) - } - }) -} - -func (e *encoder) structv(tag string, in reflect.Value) { - sinfo, err := getStructInfo(in.Type()) - if err != nil { - panic(err) - } - e.mappingv(tag, func() { - for _, info := range sinfo.FieldsList { - var value reflect.Value - if info.Inline == nil { - value = in.Field(info.Num) - } else { - value = in.FieldByIndex(info.Inline) - } - if info.OmitEmpty && isZero(value) { - continue - } - e.marshal("", reflect.ValueOf(info.Key)) - e.flow = info.Flow - e.marshal("", value) - } - if sinfo.InlineMap >= 0 { - m := in.Field(sinfo.InlineMap) - if m.Len() > 0 { - e.flow = false - keys := keyList(m.MapKeys()) - sort.Sort(keys) - for _, k := range keys { - if _, found := sinfo.FieldsMap[k.String()]; found { - panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String())) - } - e.marshal("", k) - e.flow = false - e.marshal("", m.MapIndex(k)) - } - } - } - }) -} - -func (e *encoder) mappingv(tag string, f func()) { - implicit := tag == "" - style := yaml_BLOCK_MAPPING_STYLE - if e.flow { - e.flow = false - style = yaml_FLOW_MAPPING_STYLE - } - yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) - e.emit() - f() - yaml_mapping_end_event_initialize(&e.event) - e.emit() -} - -func (e *encoder) slicev(tag string, in reflect.Value) { - implicit := tag == "" - style := yaml_BLOCK_SEQUENCE_STYLE - if e.flow { - e.flow = false - style = yaml_FLOW_SEQUENCE_STYLE - } - e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) - e.emit() - n := in.Len() - for i := 0; i < n; i++ { - e.marshal("", in.Index(i)) - } - e.must(yaml_sequence_end_event_initialize(&e.event)) - e.emit() -} - -// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. -// -// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported -// in YAML 1.2 and by this package, but these should be marshalled quoted for -// the time being for compatibility with other parsers. -func isBase60Float(s string) (result bool) { - // Fast path. - if s == "" { - return false - } - c := s[0] - if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { - return false - } - // Do the full match. - return base60float.MatchString(s) -} - -// From http://yaml.org/type/float.html, except the regular expression there -// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. -var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) - -func (e *encoder) stringv(tag string, in reflect.Value) { - var style yaml_scalar_style_t - s := in.String() - canUsePlain := true - switch { - case !utf8.ValidString(s): - if tag == yaml_BINARY_TAG { - failf("explicitly tagged !!binary data must be base64-encoded") - } - if tag != "" { - failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) - } - // It can't be encoded directly as YAML so use a binary tag - // and encode it as base64. - tag = yaml_BINARY_TAG - s = encodeBase64(s) - case tag == "": - // Check to see if it would resolve to a specific - // tag when encoded unquoted. If it doesn't, - // there's no need to quote it. - rtag, _ := resolve("", s) - canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s) - } - // Note: it's possible for user code to emit invalid YAML - // if they explicitly specify a tag and a string containing - // text that's incompatible with that tag. - switch { - case strings.Contains(s, "\n"): - style = yaml_LITERAL_SCALAR_STYLE - case canUsePlain: - style = yaml_PLAIN_SCALAR_STYLE - default: - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - e.emitScalar(s, "", tag, style) -} - -func (e *encoder) boolv(tag string, in reflect.Value) { - var s string - if in.Bool() { - s = "true" - } else { - s = "false" - } - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) intv(tag string, in reflect.Value) { - s := strconv.FormatInt(in.Int(), 10) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) uintv(tag string, in reflect.Value) { - s := strconv.FormatUint(in.Uint(), 10) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) timev(tag string, in reflect.Value) { - t := in.Interface().(time.Time) - s := t.Format(time.RFC3339Nano) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) floatv(tag string, in reflect.Value) { - // Issue #352: When formatting, use the precision of the underlying value - precision := 64 - if in.Kind() == reflect.Float32 { - precision = 32 - } - - s := strconv.FormatFloat(in.Float(), 'g', -1, precision) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) nilv() { - e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { - implicit := tag == "" - e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) - e.emit() -} diff --git a/vendor/gopkg.in/yaml.v2/go.mod b/vendor/gopkg.in/yaml.v2/go.mod deleted file mode 100644 index 1934e8769..000000000 --- a/vendor/gopkg.in/yaml.v2/go.mod +++ /dev/null @@ -1,5 +0,0 @@ -module "gopkg.in/yaml.v2" - -require ( - "gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405 -) diff --git a/vendor/gopkg.in/yaml.v2/parserc.go b/vendor/gopkg.in/yaml.v2/parserc.go deleted file mode 100644 index 81d05dfe5..000000000 --- a/vendor/gopkg.in/yaml.v2/parserc.go +++ /dev/null @@ -1,1095 +0,0 @@ -package yaml - -import ( - "bytes" -) - -// The parser implements the following grammar: -// -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// implicit_document ::= block_node DOCUMENT-END* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// block_node_or_indentless_sequence ::= -// ALIAS -// | properties (block_content | indentless_block_sequence)? -// | block_content -// | indentless_block_sequence -// block_node ::= ALIAS -// | properties block_content? -// | block_content -// flow_node ::= ALIAS -// | properties flow_content? -// | flow_content -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// block_content ::= block_collection | flow_collection | SCALAR -// flow_content ::= flow_collection | SCALAR -// block_collection ::= block_sequence | block_mapping -// flow_collection ::= flow_sequence | flow_mapping -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// block_mapping ::= BLOCK-MAPPING_START -// ((KEY block_node_or_indentless_sequence?)? -// (VALUE block_node_or_indentless_sequence?)?)* -// BLOCK-END -// flow_sequence ::= FLOW-SEQUENCE-START -// (flow_sequence_entry FLOW-ENTRY)* -// flow_sequence_entry? -// FLOW-SEQUENCE-END -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// flow_mapping ::= FLOW-MAPPING-START -// (flow_mapping_entry FLOW-ENTRY)* -// flow_mapping_entry? -// FLOW-MAPPING-END -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? - -// Peek the next token in the token queue. -func peek_token(parser *yaml_parser_t) *yaml_token_t { - if parser.token_available || yaml_parser_fetch_more_tokens(parser) { - return &parser.tokens[parser.tokens_head] - } - return nil -} - -// Remove the next token from the queue (must be called after peek_token). -func skip_token(parser *yaml_parser_t) { - parser.token_available = false - parser.tokens_parsed++ - parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN - parser.tokens_head++ -} - -// Get the next event. -func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { - // Erase the event object. - *event = yaml_event_t{} - - // No events after the end of the stream or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { - return true - } - - // Generate the next event. - return yaml_parser_state_machine(parser, event) -} - -// Set parser error. -func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -// State dispatcher. -func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { - //trace("yaml_parser_state_machine", "state:", parser.state.String()) - - switch parser.state { - case yaml_PARSE_STREAM_START_STATE: - return yaml_parser_parse_stream_start(parser, event) - - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, true) - - case yaml_PARSE_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, false) - - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return yaml_parser_parse_document_content(parser, event) - - case yaml_PARSE_DOCUMENT_END_STATE: - return yaml_parser_parse_document_end(parser, event) - - case yaml_PARSE_BLOCK_NODE_STATE: - return yaml_parser_parse_node(parser, event, true, false) - - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return yaml_parser_parse_node(parser, event, true, true) - - case yaml_PARSE_FLOW_NODE_STATE: - return yaml_parser_parse_node(parser, event, false, false) - - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, true) - - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, false) - - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_indentless_sequence_entry(parser, event) - - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, true) - - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, false) - - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return yaml_parser_parse_block_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, true) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, false) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) - - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, true) - - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, true) - - default: - panic("invalid parser state") - } -} - -// Parse the production: -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// ************ -func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_STREAM_START_TOKEN { - return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) - } - parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - encoding: token.encoding, - } - skip_token(parser) - return true -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// * -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// ************************* -func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { - - token := peek_token(parser) - if token == nil { - return false - } - - // Parse extra document end indicators. - if !implicit { - for token.typ == yaml_DOCUMENT_END_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && - token.typ != yaml_TAG_DIRECTIVE_TOKEN && - token.typ != yaml_DOCUMENT_START_TOKEN && - token.typ != yaml_STREAM_END_TOKEN { - // Parse an implicit document. - if !yaml_parser_process_directives(parser, nil, nil) { - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_BLOCK_NODE_STATE - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - } else if token.typ != yaml_STREAM_END_TOKEN { - // Parse an explicit document. - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - start_mark := token.start_mark - if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { - return false - } - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_DOCUMENT_START_TOKEN { - yaml_parser_set_parser_error(parser, - "did not find expected ", token.start_mark) - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE - end_mark := token.end_mark - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: false, - } - skip_token(parser) - - } else { - // Parse the stream end. - parser.state = yaml_PARSE_END_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - } - - return true -} - -// Parse the productions: -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// *********** -// -func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || - token.typ == yaml_TAG_DIRECTIVE_TOKEN || - token.typ == yaml_DOCUMENT_START_TOKEN || - token.typ == yaml_DOCUMENT_END_TOKEN || - token.typ == yaml_STREAM_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - return yaml_parser_process_empty_scalar(parser, event, - token.start_mark) - } - return yaml_parser_parse_node(parser, event, true, false) -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// ************* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - start_mark := token.start_mark - end_mark := token.start_mark - - implicit := true - if token.typ == yaml_DOCUMENT_END_TOKEN { - end_mark = token.end_mark - skip_token(parser) - implicit = false - } - - parser.tag_directives = parser.tag_directives[:0] - - parser.state = yaml_PARSE_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - start_mark: start_mark, - end_mark: end_mark, - implicit: implicit, - } - return true -} - -// Parse the productions: -// block_node_or_indentless_sequence ::= -// ALIAS -// ***** -// | properties (block_content | indentless_block_sequence)? -// ********** * -// | block_content | indentless_block_sequence -// * -// block_node ::= ALIAS -// ***** -// | properties block_content? -// ********** * -// | block_content -// * -// flow_node ::= ALIAS -// ***** -// | properties flow_content? -// ********** * -// | flow_content -// * -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// ************************* -// block_content ::= block_collection | flow_collection | SCALAR -// ****** -// flow_content ::= flow_collection | SCALAR -// ****** -func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { - //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_ALIAS_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - *event = yaml_event_t{ - typ: yaml_ALIAS_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - anchor: token.value, - } - skip_token(parser) - return true - } - - start_mark := token.start_mark - end_mark := token.start_mark - - var tag_token bool - var tag_handle, tag_suffix, anchor []byte - var tag_mark yaml_mark_t - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - start_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } else if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - start_mark = token.start_mark - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - var tag []byte - if tag_token { - if len(tag_handle) == 0 { - tag = tag_suffix - tag_suffix = nil - } else { - for i := range parser.tag_directives { - if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { - tag = append([]byte(nil), parser.tag_directives[i].prefix...) - tag = append(tag, tag_suffix...) - break - } - } - if len(tag) == 0 { - yaml_parser_set_parser_error_context(parser, - "while parsing a node", start_mark, - "found undefined tag handle", tag_mark) - return false - } - } - } - - implicit := len(tag) == 0 - if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - return true - } - if token.typ == yaml_SCALAR_TOKEN { - var plain_implicit, quoted_implicit bool - end_mark = token.end_mark - if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { - plain_implicit = true - } else if len(tag) == 0 { - quoted_implicit = true - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - value: token.value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(token.style), - } - skip_token(parser) - return true - } - if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { - // [Go] Some of the events below can be merged as they differ only on style. - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), - } - return true - } - if token.typ == yaml_FLOW_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - return true - } - if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - return true - } - if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), - } - return true - } - if len(anchor) > 0 || len(tag) > 0 { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - quoted_implicit: false, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true - } - - context := "while parsing a flow node" - if block { - context = "while parsing a block node" - } - yaml_parser_set_parser_error_context(parser, context, start_mark, - "did not find expected node content", token.start_mark) - return false -} - -// Parse the productions: -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// ******************** *********** * ********* -// -func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } else { - parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } - if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block collection", context_mark, - "did not find expected '-' indicator", token.start_mark) -} - -// Parse the productions: -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// *********** * -func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && - token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? - } - return true -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// ******************* -// ((KEY block_node_or_indentless_sequence?)? -// *** * -// (VALUE block_node_or_indentless_sequence?)?)* -// -// BLOCK-END -// ********* -// -func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_KEY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } else { - parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } else if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block mapping", context_mark, - "did not find expected key", token.start_mark) -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// -// ((KEY block_node_or_indentless_sequence?)? -// -// (VALUE block_node_or_indentless_sequence?)?)* -// ***** * -// BLOCK-END -// -// -func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence ::= FLOW-SEQUENCE-START -// ******************* -// (flow_sequence_entry FLOW-ENTRY)* -// * ********** -// flow_sequence_entry? -// * -// FLOW-SEQUENCE-END -// ***************** -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * -// -func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow sequence", context_mark, - "did not find expected ',' or ']'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - implicit: true, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - skip_token(parser) - return true - } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - skip_token(parser) - return true -} - -// -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// *** * -// -func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - mark := token.end_mark - skip_token(parser) - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// ***** * -// -func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * -// -func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? - } - return true -} - -// Parse the productions: -// flow_mapping ::= FLOW-MAPPING-START -// ****************** -// (flow_mapping_entry FLOW-ENTRY)* -// * ********** -// flow_mapping_entry? -// ****************** -// FLOW-MAPPING-END -// **************** -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * *** * -// -func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow mapping", context_mark, - "did not find expected ',' or '}'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } else { - parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - return true -} - -// Parse the productions: -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * ***** * -// -func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { - token := peek_token(parser) - if token == nil { - return false - } - if empty { - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Generate an empty scalar event. -func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: mark, - end_mark: mark, - value: nil, // Empty - implicit: true, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true -} - -var default_tag_directives = []yaml_tag_directive_t{ - {[]byte("!"), []byte("!")}, - {[]byte("!!"), []byte("tag:yaml.org,2002:")}, -} - -// Parse directives. -func yaml_parser_process_directives(parser *yaml_parser_t, - version_directive_ref **yaml_version_directive_t, - tag_directives_ref *[]yaml_tag_directive_t) bool { - - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - - token := peek_token(parser) - if token == nil { - return false - } - - for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { - if version_directive != nil { - yaml_parser_set_parser_error(parser, - "found duplicate %YAML directive", token.start_mark) - return false - } - if token.major != 1 || token.minor != 1 { - yaml_parser_set_parser_error(parser, - "found incompatible YAML document", token.start_mark) - return false - } - version_directive = &yaml_version_directive_t{ - major: token.major, - minor: token.minor, - } - } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { - value := yaml_tag_directive_t{ - handle: token.value, - prefix: token.prefix, - } - if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { - return false - } - tag_directives = append(tag_directives, value) - } - - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - - for i := range default_tag_directives { - if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { - return false - } - } - - if version_directive_ref != nil { - *version_directive_ref = version_directive - } - if tag_directives_ref != nil { - *tag_directives_ref = tag_directives - } - return true -} - -// Append a tag directive to the directives stack. -func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { - for i := range parser.tag_directives { - if bytes.Equal(value.handle, parser.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) - } - } - - // [Go] I suspect the copy is unnecessary. This was likely done - // because there was no way to track ownership of the data. - value_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(value_copy.handle, value.handle) - copy(value_copy.prefix, value.prefix) - parser.tag_directives = append(parser.tag_directives, value_copy) - return true -} diff --git a/vendor/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go deleted file mode 100644 index 7c1f5fac3..000000000 --- a/vendor/gopkg.in/yaml.v2/readerc.go +++ /dev/null @@ -1,412 +0,0 @@ -package yaml - -import ( - "io" -) - -// Set the reader error and return 0. -func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { - parser.error = yaml_READER_ERROR - parser.problem = problem - parser.problem_offset = offset - parser.problem_value = value - return false -} - -// Byte order marks. -const ( - bom_UTF8 = "\xef\xbb\xbf" - bom_UTF16LE = "\xff\xfe" - bom_UTF16BE = "\xfe\xff" -) - -// Determine the input stream encoding by checking the BOM symbol. If no BOM is -// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. -func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { - // Ensure that we had enough bytes in the raw buffer. - for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { - if !yaml_parser_update_raw_buffer(parser) { - return false - } - } - - // Determine the encoding. - buf := parser.raw_buffer - pos := parser.raw_buffer_pos - avail := len(buf) - pos - if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { - parser.encoding = yaml_UTF16LE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { - parser.encoding = yaml_UTF16BE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { - parser.encoding = yaml_UTF8_ENCODING - parser.raw_buffer_pos += 3 - parser.offset += 3 - } else { - parser.encoding = yaml_UTF8_ENCODING - } - return true -} - -// Update the raw buffer. -func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { - size_read := 0 - - // Return if the raw buffer is full. - if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { - return true - } - - // Return on EOF. - if parser.eof { - return true - } - - // Move the remaining bytes in the raw buffer to the beginning. - if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { - copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) - } - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] - parser.raw_buffer_pos = 0 - - // Call the read handler to fill the buffer. - size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] - if err == io.EOF { - parser.eof = true - } else if err != nil { - return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) - } - return true -} - -// Ensure that the buffer contains at least `length` characters. -// Return true on success, false on failure. -// -// The length is supposed to be significantly less that the buffer size. -func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { - if parser.read_handler == nil { - panic("read handler must be set") - } - - // [Go] This function was changed to guarantee the requested length size at EOF. - // The fact we need to do this is pretty awful, but the description above implies - // for that to be the case, and there are tests - - // If the EOF flag is set and the raw buffer is empty, do nothing. - if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { - // [Go] ACTUALLY! Read the documentation of this function above. - // This is just broken. To return true, we need to have the - // given length in the buffer. Not doing that means every single - // check that calls this function to make sure the buffer has a - // given length is Go) panicking; or C) accessing invalid memory. - //return true - } - - // Return if the buffer contains enough characters. - if parser.unread >= length { - return true - } - - // Determine the input encoding if it is not known yet. - if parser.encoding == yaml_ANY_ENCODING { - if !yaml_parser_determine_encoding(parser) { - return false - } - } - - // Move the unread characters to the beginning of the buffer. - buffer_len := len(parser.buffer) - if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { - copy(parser.buffer, parser.buffer[parser.buffer_pos:]) - buffer_len -= parser.buffer_pos - parser.buffer_pos = 0 - } else if parser.buffer_pos == buffer_len { - buffer_len = 0 - parser.buffer_pos = 0 - } - - // Open the whole buffer for writing, and cut it before returning. - parser.buffer = parser.buffer[:cap(parser.buffer)] - - // Fill the buffer until it has enough characters. - first := true - for parser.unread < length { - - // Fill the raw buffer if necessary. - if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { - if !yaml_parser_update_raw_buffer(parser) { - parser.buffer = parser.buffer[:buffer_len] - return false - } - } - first = false - - // Decode the raw buffer. - inner: - for parser.raw_buffer_pos != len(parser.raw_buffer) { - var value rune - var width int - - raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos - - // Decode the next character. - switch parser.encoding { - case yaml_UTF8_ENCODING: - // Decode a UTF-8 character. Check RFC 3629 - // (http://www.ietf.org/rfc/rfc3629.txt) for more details. - // - // The following table (taken from the RFC) is used for - // decoding. - // - // Char. number range | UTF-8 octet sequence - // (hexadecimal) | (binary) - // --------------------+------------------------------------ - // 0000 0000-0000 007F | 0xxxxxxx - // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx - // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx - // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - // - // Additionally, the characters in the range 0xD800-0xDFFF - // are prohibited as they are reserved for use with UTF-16 - // surrogate pairs. - - // Determine the length of the UTF-8 sequence. - octet := parser.raw_buffer[parser.raw_buffer_pos] - switch { - case octet&0x80 == 0x00: - width = 1 - case octet&0xE0 == 0xC0: - width = 2 - case octet&0xF0 == 0xE0: - width = 3 - case octet&0xF8 == 0xF0: - width = 4 - default: - // The leading octet is invalid. - return yaml_parser_set_reader_error(parser, - "invalid leading UTF-8 octet", - parser.offset, int(octet)) - } - - // Check if the raw buffer contains an incomplete character. - if width > raw_unread { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-8 octet sequence", - parser.offset, -1) - } - break inner - } - - // Decode the leading octet. - switch { - case octet&0x80 == 0x00: - value = rune(octet & 0x7F) - case octet&0xE0 == 0xC0: - value = rune(octet & 0x1F) - case octet&0xF0 == 0xE0: - value = rune(octet & 0x0F) - case octet&0xF8 == 0xF0: - value = rune(octet & 0x07) - default: - value = 0 - } - - // Check and decode the trailing octets. - for k := 1; k < width; k++ { - octet = parser.raw_buffer[parser.raw_buffer_pos+k] - - // Check if the octet is valid. - if (octet & 0xC0) != 0x80 { - return yaml_parser_set_reader_error(parser, - "invalid trailing UTF-8 octet", - parser.offset+k, int(octet)) - } - - // Decode the octet. - value = (value << 6) + rune(octet&0x3F) - } - - // Check the length of the sequence against the value. - switch { - case width == 1: - case width == 2 && value >= 0x80: - case width == 3 && value >= 0x800: - case width == 4 && value >= 0x10000: - default: - return yaml_parser_set_reader_error(parser, - "invalid length of a UTF-8 sequence", - parser.offset, -1) - } - - // Check the range of the value. - if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { - return yaml_parser_set_reader_error(parser, - "invalid Unicode character", - parser.offset, int(value)) - } - - case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: - var low, high int - if parser.encoding == yaml_UTF16LE_ENCODING { - low, high = 0, 1 - } else { - low, high = 1, 0 - } - - // The UTF-16 encoding is not as simple as one might - // naively think. Check RFC 2781 - // (http://www.ietf.org/rfc/rfc2781.txt). - // - // Normally, two subsequent bytes describe a Unicode - // character. However a special technique (called a - // surrogate pair) is used for specifying character - // values larger than 0xFFFF. - // - // A surrogate pair consists of two pseudo-characters: - // high surrogate area (0xD800-0xDBFF) - // low surrogate area (0xDC00-0xDFFF) - // - // The following formulas are used for decoding - // and encoding characters using surrogate pairs: - // - // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) - // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) - // W1 = 110110yyyyyyyyyy - // W2 = 110111xxxxxxxxxx - // - // where U is the character value, W1 is the high surrogate - // area, W2 is the low surrogate area. - - // Check for incomplete UTF-16 character. - if raw_unread < 2 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 character", - parser.offset, -1) - } - break inner - } - - // Get the character. - value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) - - // Check for unexpected low surrogate area. - if value&0xFC00 == 0xDC00 { - return yaml_parser_set_reader_error(parser, - "unexpected low surrogate area", - parser.offset, int(value)) - } - - // Check for a high surrogate area. - if value&0xFC00 == 0xD800 { - width = 4 - - // Check for incomplete surrogate pair. - if raw_unread < 4 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 surrogate pair", - parser.offset, -1) - } - break inner - } - - // Get the next character. - value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) - - // Check for a low surrogate area. - if value2&0xFC00 != 0xDC00 { - return yaml_parser_set_reader_error(parser, - "expected low surrogate area", - parser.offset+2, int(value2)) - } - - // Generate the value of the surrogate pair. - value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) - } else { - width = 2 - } - - default: - panic("impossible") - } - - // Check if the character is in the allowed range: - // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) - // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) - // | [#x10000-#x10FFFF] (32 bit) - switch { - case value == 0x09: - case value == 0x0A: - case value == 0x0D: - case value >= 0x20 && value <= 0x7E: - case value == 0x85: - case value >= 0xA0 && value <= 0xD7FF: - case value >= 0xE000 && value <= 0xFFFD: - case value >= 0x10000 && value <= 0x10FFFF: - default: - return yaml_parser_set_reader_error(parser, - "control characters are not allowed", - parser.offset, int(value)) - } - - // Move the raw pointers. - parser.raw_buffer_pos += width - parser.offset += width - - // Finally put the character into the buffer. - if value <= 0x7F { - // 0000 0000-0000 007F . 0xxxxxxx - parser.buffer[buffer_len+0] = byte(value) - buffer_len += 1 - } else if value <= 0x7FF { - // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) - parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) - buffer_len += 2 - } else if value <= 0xFFFF { - // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) - buffer_len += 3 - } else { - // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) - buffer_len += 4 - } - - parser.unread++ - } - - // On EOF, put NUL into the buffer and return. - if parser.eof { - parser.buffer[buffer_len] = 0 - buffer_len++ - parser.unread++ - break - } - } - // [Go] Read the documentation of this function above. To return true, - // we need to have the given length in the buffer. Not doing that means - // every single check that calls this function to make sure the buffer - // has a given length is Go) panicking; or C) accessing invalid memory. - // This happens here due to the EOF above breaking early. - for buffer_len < length { - parser.buffer[buffer_len] = 0 - buffer_len++ - } - parser.buffer = parser.buffer[:buffer_len] - return true -} diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go deleted file mode 100644 index 6c151db6f..000000000 --- a/vendor/gopkg.in/yaml.v2/resolve.go +++ /dev/null @@ -1,258 +0,0 @@ -package yaml - -import ( - "encoding/base64" - "math" - "regexp" - "strconv" - "strings" - "time" -) - -type resolveMapItem struct { - value interface{} - tag string -} - -var resolveTable = make([]byte, 256) -var resolveMap = make(map[string]resolveMapItem) - -func init() { - t := resolveTable - t[int('+')] = 'S' // Sign - t[int('-')] = 'S' - for _, c := range "0123456789" { - t[int(c)] = 'D' // Digit - } - for _, c := range "yYnNtTfFoO~" { - t[int(c)] = 'M' // In map - } - t[int('.')] = '.' // Float (potentially in map) - - var resolveMapList = []struct { - v interface{} - tag string - l []string - }{ - {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, - {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, - {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, - {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, - {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, - {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, - {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, - {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, - {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, - {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, - {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, - {"<<", yaml_MERGE_TAG, []string{"<<"}}, - } - - m := resolveMap - for _, item := range resolveMapList { - for _, s := range item.l { - m[s] = resolveMapItem{item.v, item.tag} - } - } -} - -const longTagPrefix = "tag:yaml.org,2002:" - -func shortTag(tag string) string { - // TODO This can easily be made faster and produce less garbage. - if strings.HasPrefix(tag, longTagPrefix) { - return "!!" + tag[len(longTagPrefix):] - } - return tag -} - -func longTag(tag string) string { - if strings.HasPrefix(tag, "!!") { - return longTagPrefix + tag[2:] - } - return tag -} - -func resolvableTag(tag string) bool { - switch tag { - case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG: - return true - } - return false -} - -var yamlStyleFloat = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+][0-9]+)?$`) - -func resolve(tag string, in string) (rtag string, out interface{}) { - if !resolvableTag(tag) { - return tag, in - } - - defer func() { - switch tag { - case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: - return - case yaml_FLOAT_TAG: - if rtag == yaml_INT_TAG { - switch v := out.(type) { - case int64: - rtag = yaml_FLOAT_TAG - out = float64(v) - return - case int: - rtag = yaml_FLOAT_TAG - out = float64(v) - return - } - } - } - failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) - }() - - // Any data is accepted as a !!str or !!binary. - // Otherwise, the prefix is enough of a hint about what it might be. - hint := byte('N') - if in != "" { - hint = resolveTable[in[0]] - } - if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { - // Handle things we can lookup in a map. - if item, ok := resolveMap[in]; ok { - return item.tag, item.value - } - - // Base 60 floats are a bad idea, were dropped in YAML 1.2, and - // are purposefully unsupported here. They're still quoted on - // the way out for compatibility with other parser, though. - - switch hint { - case 'M': - // We've already checked the map above. - - case '.': - // Not in the map, so maybe a normal float. - floatv, err := strconv.ParseFloat(in, 64) - if err == nil { - return yaml_FLOAT_TAG, floatv - } - - case 'D', 'S': - // Int, float, or timestamp. - // Only try values as a timestamp if the value is unquoted or there's an explicit - // !!timestamp tag. - if tag == "" || tag == yaml_TIMESTAMP_TAG { - t, ok := parseTimestamp(in) - if ok { - return yaml_TIMESTAMP_TAG, t - } - } - - plain := strings.Replace(in, "_", "", -1) - intv, err := strconv.ParseInt(plain, 0, 64) - if err == nil { - if intv == int64(int(intv)) { - return yaml_INT_TAG, int(intv) - } else { - return yaml_INT_TAG, intv - } - } - uintv, err := strconv.ParseUint(plain, 0, 64) - if err == nil { - return yaml_INT_TAG, uintv - } - if yamlStyleFloat.MatchString(plain) { - floatv, err := strconv.ParseFloat(plain, 64) - if err == nil { - return yaml_FLOAT_TAG, floatv - } - } - if strings.HasPrefix(plain, "0b") { - intv, err := strconv.ParseInt(plain[2:], 2, 64) - if err == nil { - if intv == int64(int(intv)) { - return yaml_INT_TAG, int(intv) - } else { - return yaml_INT_TAG, intv - } - } - uintv, err := strconv.ParseUint(plain[2:], 2, 64) - if err == nil { - return yaml_INT_TAG, uintv - } - } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt("-" + plain[3:], 2, 64) - if err == nil { - if true || intv == int64(int(intv)) { - return yaml_INT_TAG, int(intv) - } else { - return yaml_INT_TAG, intv - } - } - } - default: - panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") - } - } - return yaml_STR_TAG, in -} - -// encodeBase64 encodes s as base64 that is broken up into multiple lines -// as appropriate for the resulting length. -func encodeBase64(s string) string { - const lineLen = 70 - encLen := base64.StdEncoding.EncodedLen(len(s)) - lines := encLen/lineLen + 1 - buf := make([]byte, encLen*2+lines) - in := buf[0:encLen] - out := buf[encLen:] - base64.StdEncoding.Encode(in, []byte(s)) - k := 0 - for i := 0; i < len(in); i += lineLen { - j := i + lineLen - if j > len(in) { - j = len(in) - } - k += copy(out[k:], in[i:j]) - if lines > 1 { - out[k] = '\n' - k++ - } - } - return string(out[:k]) -} - -// This is a subset of the formats allowed by the regular expression -// defined at http://yaml.org/type/timestamp.html. -var allowedTimestampFormats = []string{ - "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. - "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". - "2006-1-2 15:4:5.999999999", // space separated with no time zone - "2006-1-2", // date only - // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" - // from the set of examples. -} - -// parseTimestamp parses s as a timestamp string and -// returns the timestamp and reports whether it succeeded. -// Timestamp formats are defined at http://yaml.org/type/timestamp.html -func parseTimestamp(s string) (time.Time, bool) { - // TODO write code to check all the formats supported by - // http://yaml.org/type/timestamp.html instead of using time.Parse. - - // Quick check: all date formats start with YYYY-. - i := 0 - for ; i < len(s); i++ { - if c := s[i]; c < '0' || c > '9' { - break - } - } - if i != 4 || i == len(s) || s[i] != '-' { - return time.Time{}, false - } - for _, format := range allowedTimestampFormats { - if t, err := time.Parse(format, s); err == nil { - return t, true - } - } - return time.Time{}, false -} diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go deleted file mode 100644 index 077fd1dd2..000000000 --- a/vendor/gopkg.in/yaml.v2/scannerc.go +++ /dev/null @@ -1,2696 +0,0 @@ -package yaml - -import ( - "bytes" - "fmt" -) - -// Introduction -// ************ -// -// The following notes assume that you are familiar with the YAML specification -// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in -// some cases we are less restrictive that it requires. -// -// The process of transforming a YAML stream into a sequence of events is -// divided on two steps: Scanning and Parsing. -// -// The Scanner transforms the input stream into a sequence of tokens, while the -// parser transform the sequence of tokens produced by the Scanner into a -// sequence of parsing events. -// -// The Scanner is rather clever and complicated. The Parser, on the contrary, -// is a straightforward implementation of a recursive-descendant parser (or, -// LL(1) parser, as it is usually called). -// -// Actually there are two issues of Scanning that might be called "clever", the -// rest is quite straightforward. The issues are "block collection start" and -// "simple keys". Both issues are explained below in details. -// -// Here the Scanning step is explained and implemented. We start with the list -// of all the tokens produced by the Scanner together with short descriptions. -// -// Now, tokens: -// -// STREAM-START(encoding) # The stream start. -// STREAM-END # The stream end. -// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. -// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. -// DOCUMENT-START # '---' -// DOCUMENT-END # '...' -// BLOCK-SEQUENCE-START # Indentation increase denoting a block -// BLOCK-MAPPING-START # sequence or a block mapping. -// BLOCK-END # Indentation decrease. -// FLOW-SEQUENCE-START # '[' -// FLOW-SEQUENCE-END # ']' -// BLOCK-SEQUENCE-START # '{' -// BLOCK-SEQUENCE-END # '}' -// BLOCK-ENTRY # '-' -// FLOW-ENTRY # ',' -// KEY # '?' or nothing (simple keys). -// VALUE # ':' -// ALIAS(anchor) # '*anchor' -// ANCHOR(anchor) # '&anchor' -// TAG(handle,suffix) # '!handle!suffix' -// SCALAR(value,style) # A scalar. -// -// The following two tokens are "virtual" tokens denoting the beginning and the -// end of the stream: -// -// STREAM-START(encoding) -// STREAM-END -// -// We pass the information about the input stream encoding with the -// STREAM-START token. -// -// The next two tokens are responsible for tags: -// -// VERSION-DIRECTIVE(major,minor) -// TAG-DIRECTIVE(handle,prefix) -// -// Example: -// -// %YAML 1.1 -// %TAG ! !foo -// %TAG !yaml! tag:yaml.org,2002: -// --- -// -// The correspoding sequence of tokens: -// -// STREAM-START(utf-8) -// VERSION-DIRECTIVE(1,1) -// TAG-DIRECTIVE("!","!foo") -// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") -// DOCUMENT-START -// STREAM-END -// -// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole -// line. -// -// The document start and end indicators are represented by: -// -// DOCUMENT-START -// DOCUMENT-END -// -// Note that if a YAML stream contains an implicit document (without '---' -// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be -// produced. -// -// In the following examples, we present whole documents together with the -// produced tokens. -// -// 1. An implicit document: -// -// 'a scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// STREAM-END -// -// 2. An explicit document: -// -// --- -// 'a scalar' -// ... -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// SCALAR("a scalar",single-quoted) -// DOCUMENT-END -// STREAM-END -// -// 3. Several documents in a stream: -// -// 'a scalar' -// --- -// 'another scalar' -// --- -// 'yet another scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// DOCUMENT-START -// SCALAR("another scalar",single-quoted) -// DOCUMENT-START -// SCALAR("yet another scalar",single-quoted) -// STREAM-END -// -// We have already introduced the SCALAR token above. The following tokens are -// used to describe aliases, anchors, tag, and scalars: -// -// ALIAS(anchor) -// ANCHOR(anchor) -// TAG(handle,suffix) -// SCALAR(value,style) -// -// The following series of examples illustrate the usage of these tokens: -// -// 1. A recursive sequence: -// -// &A [ *A ] -// -// Tokens: -// -// STREAM-START(utf-8) -// ANCHOR("A") -// FLOW-SEQUENCE-START -// ALIAS("A") -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A tagged scalar: -// -// !!float "3.14" # A good approximation. -// -// Tokens: -// -// STREAM-START(utf-8) -// TAG("!!","float") -// SCALAR("3.14",double-quoted) -// STREAM-END -// -// 3. Various scalar styles: -// -// --- # Implicit empty plain scalars do not produce tokens. -// --- a plain scalar -// --- 'a single-quoted scalar' -// --- "a double-quoted scalar" -// --- |- -// a literal scalar -// --- >- -// a folded -// scalar -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// DOCUMENT-START -// SCALAR("a plain scalar",plain) -// DOCUMENT-START -// SCALAR("a single-quoted scalar",single-quoted) -// DOCUMENT-START -// SCALAR("a double-quoted scalar",double-quoted) -// DOCUMENT-START -// SCALAR("a literal scalar",literal) -// DOCUMENT-START -// SCALAR("a folded scalar",folded) -// STREAM-END -// -// Now it's time to review collection-related tokens. We will start with -// flow collections: -// -// FLOW-SEQUENCE-START -// FLOW-SEQUENCE-END -// FLOW-MAPPING-START -// FLOW-MAPPING-END -// FLOW-ENTRY -// KEY -// VALUE -// -// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and -// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' -// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the -// indicators '?' and ':', which are used for denoting mapping keys and values, -// are represented by the KEY and VALUE tokens. -// -// The following examples show flow collections: -// -// 1. A flow sequence: -// -// [item 1, item 2, item 3] -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-SEQUENCE-START -// SCALAR("item 1",plain) -// FLOW-ENTRY -// SCALAR("item 2",plain) -// FLOW-ENTRY -// SCALAR("item 3",plain) -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A flow mapping: -// -// { -// a simple key: a value, # Note that the KEY token is produced. -// ? a complex key: another value, -// } -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// FLOW-ENTRY -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// FLOW-ENTRY -// FLOW-MAPPING-END -// STREAM-END -// -// A simple key is a key which is not denoted by the '?' indicator. Note that -// the Scanner still produce the KEY token whenever it encounters a simple key. -// -// For scanning block collections, the following tokens are used (note that we -// repeat KEY and VALUE here): -// -// BLOCK-SEQUENCE-START -// BLOCK-MAPPING-START -// BLOCK-END -// BLOCK-ENTRY -// KEY -// VALUE -// -// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation -// increase that precedes a block collection (cf. the INDENT token in Python). -// The token BLOCK-END denote indentation decrease that ends a block collection -// (cf. the DEDENT token in Python). However YAML has some syntax pecularities -// that makes detections of these tokens more complex. -// -// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators -// '-', '?', and ':' correspondingly. -// -// The following examples show how the tokens BLOCK-SEQUENCE-START, -// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: -// -// 1. Block sequences: -// -// - item 1 -// - item 2 -// - -// - item 3.1 -// - item 3.2 -// - -// key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 3.1",plain) -// BLOCK-ENTRY -// SCALAR("item 3.2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Block mappings: -// -// a simple key: a value # The KEY token is produced here. -// ? a complex key -// : another value -// a mapping: -// key 1: value 1 -// key 2: value 2 -// a sequence: -// - item 1 -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// KEY -// SCALAR("a mapping",plain) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML does not always require to start a new block collection from a new -// line. If the current line contains only '-', '?', and ':' indicators, a new -// block collection may start at the current line. The following examples -// illustrate this case: -// -// 1. Collections in a sequence: -// -// - - item 1 -// - item 2 -// - key 1: value 1 -// key 2: value 2 -// - ? complex key -// : complex value -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("complex key") -// VALUE -// SCALAR("complex value") -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Collections in a mapping: -// -// ? a sequence -// : - item 1 -// - item 2 -// ? a mapping -// : key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// KEY -// SCALAR("a mapping",plain) -// VALUE -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML also permits non-indented sequences if they are included into a block -// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: -// -// key: -// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key",plain) -// VALUE -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// - -// Ensure that the buffer contains the required number of characters. -// Return true on success, false on failure (reader error or memory error). -func cache(parser *yaml_parser_t, length int) bool { - // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) - return parser.unread >= length || yaml_parser_update_buffer(parser, length) -} - -// Advance the buffer pointer. -func skip(parser *yaml_parser_t) { - parser.mark.index++ - parser.mark.column++ - parser.unread-- - parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) -} - -func skip_line(parser *yaml_parser_t) { - if is_crlf(parser.buffer, parser.buffer_pos) { - parser.mark.index += 2 - parser.mark.column = 0 - parser.mark.line++ - parser.unread -= 2 - parser.buffer_pos += 2 - } else if is_break(parser.buffer, parser.buffer_pos) { - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) - } -} - -// Copy a character to a string buffer and advance pointers. -func read(parser *yaml_parser_t, s []byte) []byte { - w := width(parser.buffer[parser.buffer_pos]) - if w == 0 { - panic("invalid character sequence") - } - if len(s) == 0 { - s = make([]byte, 0, 32) - } - if w == 1 && len(s)+w <= cap(s) { - s = s[:len(s)+1] - s[len(s)-1] = parser.buffer[parser.buffer_pos] - parser.buffer_pos++ - } else { - s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) - parser.buffer_pos += w - } - parser.mark.index++ - parser.mark.column++ - parser.unread-- - return s -} - -// Copy a line break character to a string buffer and advance pointers. -func read_line(parser *yaml_parser_t, s []byte) []byte { - buf := parser.buffer - pos := parser.buffer_pos - switch { - case buf[pos] == '\r' && buf[pos+1] == '\n': - // CR LF . LF - s = append(s, '\n') - parser.buffer_pos += 2 - parser.mark.index++ - parser.unread-- - case buf[pos] == '\r' || buf[pos] == '\n': - // CR|LF . LF - s = append(s, '\n') - parser.buffer_pos += 1 - case buf[pos] == '\xC2' && buf[pos+1] == '\x85': - // NEL . LF - s = append(s, '\n') - parser.buffer_pos += 2 - case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): - // LS|PS . LS|PS - s = append(s, buf[parser.buffer_pos:pos+3]...) - parser.buffer_pos += 3 - default: - return s - } - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - return s -} - -// Get the next token. -func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { - // Erase the token object. - *token = yaml_token_t{} // [Go] Is this necessary? - - // No tokens after STREAM-END or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR { - return true - } - - // Ensure that the tokens queue contains enough tokens. - if !parser.token_available { - if !yaml_parser_fetch_more_tokens(parser) { - return false - } - } - - // Fetch the next token from the queue. - *token = parser.tokens[parser.tokens_head] - parser.tokens_head++ - parser.tokens_parsed++ - parser.token_available = false - - if token.typ == yaml_STREAM_END_TOKEN { - parser.stream_end_produced = true - } - return true -} - -// Set the scanner error and return false. -func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { - parser.error = yaml_SCANNER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = parser.mark - return false -} - -func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { - context := "while parsing a tag" - if directive { - context = "while parsing a %TAG directive" - } - return yaml_parser_set_scanner_error(parser, context, context_mark, problem) -} - -func trace(args ...interface{}) func() { - pargs := append([]interface{}{"+++"}, args...) - fmt.Println(pargs...) - pargs = append([]interface{}{"---"}, args...) - return func() { fmt.Println(pargs...) } -} - -// Ensure that the tokens queue contains at least one token which can be -// returned to the Parser. -func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { - // While we need more tokens to fetch, do it. - for { - // Check if we really need to fetch more tokens. - need_more_tokens := false - - if parser.tokens_head == len(parser.tokens) { - // Queue is empty. - need_more_tokens = true - } else { - // Check if any potential simple key may occupy the head position. - if !yaml_parser_stale_simple_keys(parser) { - return false - } - - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - if simple_key.possible && simple_key.token_number == parser.tokens_parsed { - need_more_tokens = true - break - } - } - } - - // We are finished. - if !need_more_tokens { - break - } - // Fetch the next token. - if !yaml_parser_fetch_next_token(parser) { - return false - } - } - - parser.token_available = true - return true -} - -// The dispatcher for token fetchers. -func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { - // Ensure that the buffer is initialized. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we just started scanning. Fetch STREAM-START then. - if !parser.stream_start_produced { - return yaml_parser_fetch_stream_start(parser) - } - - // Eat whitespaces and comments until we reach the next token. - if !yaml_parser_scan_to_next_token(parser) { - return false - } - - // Remove obsolete potential simple keys. - if !yaml_parser_stale_simple_keys(parser) { - return false - } - - // Check the indentation level against the current column. - if !yaml_parser_unroll_indent(parser, parser.mark.column) { - return false - } - - // Ensure that the buffer contains at least 4 characters. 4 is the length - // of the longest indicators ('--- ' and '... '). - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - // Is it the end of the stream? - if is_z(parser.buffer, parser.buffer_pos) { - return yaml_parser_fetch_stream_end(parser) - } - - // Is it a directive? - if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { - return yaml_parser_fetch_directive(parser) - } - - buf := parser.buffer - pos := parser.buffer_pos - - // Is it the document start indicator? - if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) - } - - // Is it the document end indicator? - if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) - } - - // Is it the flow sequence start indicator? - if buf[pos] == '[' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) - } - - // Is it the flow mapping start indicator? - if parser.buffer[parser.buffer_pos] == '{' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) - } - - // Is it the flow sequence end indicator? - if parser.buffer[parser.buffer_pos] == ']' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_SEQUENCE_END_TOKEN) - } - - // Is it the flow mapping end indicator? - if parser.buffer[parser.buffer_pos] == '}' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_MAPPING_END_TOKEN) - } - - // Is it the flow entry indicator? - if parser.buffer[parser.buffer_pos] == ',' { - return yaml_parser_fetch_flow_entry(parser) - } - - // Is it the block entry indicator? - if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { - return yaml_parser_fetch_block_entry(parser) - } - - // Is it the key indicator? - if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_key(parser) - } - - // Is it the value indicator? - if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_value(parser) - } - - // Is it an alias? - if parser.buffer[parser.buffer_pos] == '*' { - return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) - } - - // Is it an anchor? - if parser.buffer[parser.buffer_pos] == '&' { - return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) - } - - // Is it a tag? - if parser.buffer[parser.buffer_pos] == '!' { - return yaml_parser_fetch_tag(parser) - } - - // Is it a literal scalar? - if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, true) - } - - // Is it a folded scalar? - if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, false) - } - - // Is it a single-quoted scalar? - if parser.buffer[parser.buffer_pos] == '\'' { - return yaml_parser_fetch_flow_scalar(parser, true) - } - - // Is it a double-quoted scalar? - if parser.buffer[parser.buffer_pos] == '"' { - return yaml_parser_fetch_flow_scalar(parser, false) - } - - // Is it a plain scalar? - // - // A plain scalar may start with any non-blank characters except - // - // '-', '?', ':', ',', '[', ']', '{', '}', - // '#', '&', '*', '!', '|', '>', '\'', '\"', - // '%', '@', '`'. - // - // In the block context (and, for the '-' indicator, in the flow context - // too), it may also start with the characters - // - // '-', '?', ':' - // - // if it is followed by a non-space character. - // - // The last rule is more restrictive than the specification requires. - // [Go] Make this logic more reasonable. - //switch parser.buffer[parser.buffer_pos] { - //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': - //} - if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || - parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || - parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || - (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level == 0 && - (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && - !is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_plain_scalar(parser) - } - - // If we don't determine the token type so far, it is an error. - return yaml_parser_set_scanner_error(parser, - "while scanning for the next token", parser.mark, - "found character that cannot start any token") -} - -// Check the list of potential simple keys and remove the positions that -// cannot contain simple keys anymore. -func yaml_parser_stale_simple_keys(parser *yaml_parser_t) bool { - // Check for a potential simple key for each flow level. - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - - // The specification requires that a simple key - // - // - is limited to a single line, - // - is shorter than 1024 characters. - if simple_key.possible && (simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index) { - - // Check if the potential simple key to be removed is required. - if simple_key.required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", simple_key.mark, - "could not find expected ':'") - } - simple_key.possible = false - } - } - return true -} - -// Check if a simple key may start at the current position and add it if -// needed. -func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { - // A simple key is required at the current position if the scanner is in - // the block context and the current column coincides with the indentation - // level. - - required := parser.flow_level == 0 && parser.indent == parser.mark.column - - // - // If the current position may start a simple key, save it. - // - if parser.simple_key_allowed { - simple_key := yaml_simple_key_t{ - possible: true, - required: required, - token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - } - simple_key.mark = parser.mark - - if !yaml_parser_remove_simple_key(parser) { - return false - } - parser.simple_keys[len(parser.simple_keys)-1] = simple_key - } - return true -} - -// Remove a potential simple key at the current flow level. -func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { - i := len(parser.simple_keys) - 1 - if parser.simple_keys[i].possible { - // If the key is required, it is an error. - if parser.simple_keys[i].required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", parser.simple_keys[i].mark, - "could not find expected ':'") - } - } - // Remove the key from the stack. - parser.simple_keys[i].possible = false - return true -} - -// Increase the flow level and resize the simple key list if needed. -func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { - // Reset the simple key on the next level. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) - - // Increase the flow level. - parser.flow_level++ - return true -} - -// Decrease the flow level. -func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { - if parser.flow_level > 0 { - parser.flow_level-- - parser.simple_keys = parser.simple_keys[:len(parser.simple_keys)-1] - } - return true -} - -// Push the current indentation level to the stack and set the new level -// the current column is greater than the indentation level. In this case, -// append or insert the specified token into the token queue. -func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - if parser.indent < column { - // Push the current indentation level to the stack and set the new - // indentation level. - parser.indents = append(parser.indents, parser.indent) - parser.indent = column - - // Create a token and insert it into the queue. - token := yaml_token_t{ - typ: typ, - start_mark: mark, - end_mark: mark, - } - if number > -1 { - number -= parser.tokens_parsed - } - yaml_insert_token(parser, number, &token) - } - return true -} - -// Pop indentation levels from the indents stack until the current level -// becomes less or equal to the column. For each indentation level, append -// the BLOCK-END token. -func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - // Loop through the indentation levels in the stack. - for parser.indent > column { - // Create a token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - } - yaml_insert_token(parser, -1, &token) - - // Pop the indentation level. - parser.indent = parser.indents[len(parser.indents)-1] - parser.indents = parser.indents[:len(parser.indents)-1] - } - return true -} - -// Initialize the scanner and produce the STREAM-START token. -func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { - - // Set the initial indentation. - parser.indent = -1 - - // Initialize the simple key stack. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) - - // A simple key is allowed at the beginning of the stream. - parser.simple_key_allowed = true - - // We have started. - parser.stream_start_produced = true - - // Create the STREAM-START token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_START_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - encoding: parser.encoding, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the STREAM-END token and shut down the scanner. -func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { - - // Force new line. - if parser.mark.column != 0 { - parser.mark.column = 0 - parser.mark.line++ - } - - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the STREAM-END token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. -func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. - token := yaml_token_t{} - if !yaml_parser_scan_directive(parser, &token) { - return false - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the DOCUMENT-START or DOCUMENT-END token. -func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Consume the token. - start_mark := parser.mark - - skip(parser) - skip(parser) - skip(parser) - - end_mark := parser.mark - - // Create the DOCUMENT-START or DOCUMENT-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. -func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // The indicators '[' and '{' may start a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // Increase the flow level. - if !yaml_parser_increase_flow_level(parser) { - return false - } - - // A simple key may follow the indicators '[' and '{'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. -func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset any potential simple key on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Decrease the flow level. - if !yaml_parser_decrease_flow_level(parser) { - return false - } - - // No simple keys after the indicators ']' and '}'. - parser.simple_key_allowed = false - - // Consume the token. - - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-ENTRY token. -func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after ','. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_FLOW_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the BLOCK-ENTRY token. -func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { - // Check if the scanner is in the block context. - if parser.flow_level == 0 { - // Check if we are allowed to start a new entry. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "block sequence entries are not allowed in this context") - } - // Add the BLOCK-SEQUENCE-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { - return false - } - } else { - // It is an error for the '-' indicator to occur in the flow context, - // but we let the Parser detect and report about it because the Parser - // is able to point to the context. - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '-'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the BLOCK-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the KEY token. -func yaml_parser_fetch_key(parser *yaml_parser_t) bool { - - // In the block context, additional checks are required. - if parser.flow_level == 0 { - // Check if we are allowed to start a new key (not nessesary simple). - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping keys are not allowed in this context") - } - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '?' in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the KEY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the VALUE token. -func yaml_parser_fetch_value(parser *yaml_parser_t) bool { - - simple_key := &parser.simple_keys[len(parser.simple_keys)-1] - - // Have we found a simple key? - if simple_key.possible { - // Create the KEY token and insert it into the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: simple_key.mark, - end_mark: simple_key.mark, - } - yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) - - // In the block context, we may need to add the BLOCK-MAPPING-START token. - if !yaml_parser_roll_indent(parser, simple_key.mark.column, - simple_key.token_number, - yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { - return false - } - - // Remove the simple key. - simple_key.possible = false - - // A simple key cannot follow another simple key. - parser.simple_key_allowed = false - - } else { - // The ':' indicator follows a complex key. - - // In the block context, extra checks are required. - if parser.flow_level == 0 { - - // Check if we are allowed to start a complex value. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping values are not allowed in this context") - } - - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Simple keys after ':' are allowed in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - } - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the VALUE token and append it to the queue. - token := yaml_token_t{ - typ: yaml_VALUE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the ALIAS or ANCHOR token. -func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // An anchor or an alias could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow an anchor or an alias. - parser.simple_key_allowed = false - - // Create the ALIAS or ANCHOR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_anchor(parser, &token, typ) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the TAG token. -func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { - // A tag could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a tag. - parser.simple_key_allowed = false - - // Create the TAG token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_tag(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. -func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { - // Remove any potential simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // A simple key may follow a block scalar. - parser.simple_key_allowed = true - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_block_scalar(parser, &token, literal) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. -func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_flow_scalar(parser, &token, single) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,plain) token. -func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_plain_scalar(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Eat whitespaces and comments until the next token is found. -func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { - - // Until the next token is not found. - for { - // Allow the BOM mark to start a line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { - skip(parser) - } - - // Eat whitespaces. - // Tabs are allowed: - // - in the flow context - // - in the block context, but not at the beginning of the line or - // after '-', '?', or ':' (complex value). - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Eat a comment until a line break. - if parser.buffer[parser.buffer_pos] == '#' { - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // If it is a line break, eat it. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - - // In the block context, a new line may start a simple key. - if parser.flow_level == 0 { - parser.simple_key_allowed = true - } - } else { - break // We have found a token. - } - } - - return true -} - -// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// -func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { - // Eat '%'. - start_mark := parser.mark - skip(parser) - - // Scan the directive name. - var name []byte - if !yaml_parser_scan_directive_name(parser, start_mark, &name) { - return false - } - - // Is it a YAML directive? - if bytes.Equal(name, []byte("YAML")) { - // Scan the VERSION directive value. - var major, minor int8 - if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { - return false - } - end_mark := parser.mark - - // Create a VERSION-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_VERSION_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - major: major, - minor: minor, - } - - // Is it a TAG directive? - } else if bytes.Equal(name, []byte("TAG")) { - // Scan the TAG directive value. - var handle, prefix []byte - if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { - return false - } - end_mark := parser.mark - - // Create a TAG-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_TAG_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - prefix: prefix, - } - - // Unknown directive. - } else { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unknown directive name") - return false - } - - // Eat the rest of the line including any comments. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - if parser.buffer[parser.buffer_pos] == '#' { - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - return true -} - -// Scan the directive name. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^ -// -func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { - // Consume the directive name. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - var s []byte - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the name is empty. - if len(s) == 0 { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "could not find expected directive name") - return false - } - - // Check for an blank character after the name. - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unexpected non-alphabetical character") - return false - } - *name = s - return true -} - -// Scan the value of VERSION-DIRECTIVE. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^^^ -func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the major version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { - return false - } - - // Eat '.'. - if parser.buffer[parser.buffer_pos] != '.' { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected digit or '.' character") - } - - skip(parser) - - // Consume the minor version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { - return false - } - return true -} - -const max_number_length = 2 - -// Scan the version number of VERSION-DIRECTIVE. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^ -// %YAML 1.1 # a comment \n -// ^ -func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { - - // Repeat while the next character is digit. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var value, length int8 - for is_digit(parser.buffer, parser.buffer_pos) { - // Check if the number is too long. - length++ - if length > max_number_length { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "found extremely long version number") - } - value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the number was present. - if length == 0 { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected version number") - } - *number = value - return true -} - -// Scan the value of a TAG-DIRECTIVE token. -// -// Scope: -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// -func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { - var handle_value, prefix_value []byte - - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a handle. - if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { - return false - } - - // Expect a whitespace. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blank(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace") - return false - } - - // Eat whitespaces. - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a prefix. - if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { - return false - } - - // Expect a whitespace or line break. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace or line break") - return false - } - - *handle = handle_value - *prefix = prefix_value - return true -} - -func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { - var s []byte - - // Eat the indicator character. - start_mark := parser.mark - skip(parser) - - // Consume the value. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - end_mark := parser.mark - - /* - * Check if length of the anchor is greater than 0 and it is followed by - * a whitespace character or one of the indicators: - * - * '?', ':', ',', ']', '}', '%', '@', '`'. - */ - - if len(s) == 0 || - !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || - parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '`') { - context := "while scanning an alias" - if typ == yaml_ANCHOR_TOKEN { - context = "while scanning an anchor" - } - yaml_parser_set_scanner_error(parser, context, start_mark, - "did not find expected alphabetic or numeric character") - return false - } - - // Create a token. - *token = yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - value: s, - } - - return true -} - -/* - * Scan a TAG token. - */ - -func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { - var handle, suffix []byte - - start_mark := parser.mark - - // Check if the tag is in the canonical form. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - if parser.buffer[parser.buffer_pos+1] == '<' { - // Keep the handle as '' - - // Eat '!<' - skip(parser) - skip(parser) - - // Consume the tag value. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - - // Check for '>' and eat it. - if parser.buffer[parser.buffer_pos] != '>' { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find the expected '>'") - return false - } - - skip(parser) - } else { - // The tag has either the '!suffix' or the '!handle!suffix' form. - - // First, try to scan a handle. - if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { - return false - } - - // Check if it is, indeed, handle. - if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { - // Scan the suffix now. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - } else { - // It wasn't a handle after all. Scan the rest of the tag. - if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { - return false - } - - // Set the handle to '!'. - handle = []byte{'!'} - - // A special case: the '!' tag. Set the handle to '' and the - // suffix to '!'. - if len(suffix) == 0 { - handle, suffix = suffix, handle - } - } - } - - // Check the character which ends the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find expected whitespace or line break") - return false - } - - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_TAG_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - suffix: suffix, - } - return true -} - -// Scan a tag handle. -func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { - // Check the initial '!' character. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] != '!' { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - - var s []byte - - // Copy the '!' character. - s = read(parser, s) - - // Copy all subsequent alphabetical and numerical characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the trailing character is '!' and copy it. - if parser.buffer[parser.buffer_pos] == '!' { - s = read(parser, s) - } else { - // It's either the '!' tag or not really a tag handle. If it's a %TAG - // directive, it's an error. If it's a tag token, it must be a part of URI. - if directive && string(s) != "!" { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - } - - *handle = s - return true -} - -// Scan a tag. -func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { - //size_t length = head ? strlen((char *)head) : 0 - var s []byte - hasTag := len(head) > 0 - - // Copy the head if needed. - // - // Note that we don't copy the leading '!' character. - if len(head) > 1 { - s = append(s, head[1:]...) - } - - // Scan the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // The set of characters that may appear in URI is as follows: - // - // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', - // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', - // '%'. - // [Go] Convert this into more reasonable logic. - for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || - parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || - parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || - parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || - parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || - parser.buffer[parser.buffer_pos] == '%' { - // Check if it is a URI-escape sequence. - if parser.buffer[parser.buffer_pos] == '%' { - if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { - return false - } - } else { - s = read(parser, s) - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - hasTag = true - } - - if !hasTag { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected tag URI") - return false - } - *uri = s - return true -} - -// Decode an URI-escape sequence corresponding to a single UTF-8 character. -func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { - - // Decode the required number of characters. - w := 1024 - for w > 0 { - // Check for a URI-escaped octet. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - - if !(parser.buffer[parser.buffer_pos] == '%' && - is_hex(parser.buffer, parser.buffer_pos+1) && - is_hex(parser.buffer, parser.buffer_pos+2)) { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find URI escaped octet") - } - - // Get the octet. - octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) - - // If it is the leading octet, determine the length of the UTF-8 sequence. - if w == 1024 { - w = width(octet) - if w == 0 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect leading UTF-8 octet") - } - } else { - // Check if the trailing octet is correct. - if octet&0xC0 != 0x80 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect trailing UTF-8 octet") - } - } - - // Copy the octet and move the pointers. - *s = append(*s, octet) - skip(parser) - skip(parser) - skip(parser) - w-- - } - return true -} - -// Scan a block scalar. -func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { - // Eat the indicator '|' or '>'. - start_mark := parser.mark - skip(parser) - - // Scan the additional block scalar indicators. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check for a chomping indicator. - var chomping, increment int - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - // Set the chomping method and eat the indicator. - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - - // Check for an indentation indicator. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_digit(parser.buffer, parser.buffer_pos) { - // Check that the indentation is greater than 0. - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - - // Get the indentation level and eat the indicator. - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - } - - } else if is_digit(parser.buffer, parser.buffer_pos) { - // Do the same as above, but in the opposite order. - - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - } - } - - // Eat whitespaces and comments to the end of the line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.buffer[parser.buffer_pos] == '#' { - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - end_mark := parser.mark - - // Set the indentation level if it was specified. - var indent int - if increment > 0 { - if parser.indent >= 0 { - indent = parser.indent + increment - } else { - indent = increment - } - } - - // Scan the leading line breaks and determine the indentation level if needed. - var s, leading_break, trailing_breaks []byte - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - - // Scan the block scalar content. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var leading_blank, trailing_blank bool - for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { - // We are at the beginning of a non-empty line. - - // Is it a trailing whitespace? - trailing_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Check if we need to fold the leading line break. - if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { - // Do we need to join the lines by space? - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } - } else { - s = append(s, leading_break...) - } - leading_break = leading_break[:0] - - // Append the remaining line breaks. - s = append(s, trailing_breaks...) - trailing_breaks = trailing_breaks[:0] - - // Is it a leading whitespace? - leading_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Consume the current line. - for !is_breakz(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - leading_break = read_line(parser, leading_break) - - // Eat the following indentation spaces and line breaks. - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - } - - // Chomp the tail. - if chomping != -1 { - s = append(s, leading_break...) - } - if chomping == 1 { - s = append(s, trailing_breaks...) - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_LITERAL_SCALAR_STYLE, - } - if !literal { - token.style = yaml_FOLDED_SCALAR_STYLE - } - return true -} - -// Scan indentation spaces and line breaks for a block scalar. Determine the -// indentation level if needed. -func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { - *end_mark = parser.mark - - // Eat the indentation spaces and line breaks. - max_indent := 0 - for { - // Eat the indentation spaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.mark.column > max_indent { - max_indent = parser.mark.column - } - - // Check for a tab character messing the indentation. - if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { - return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found a tab character where an indentation space is expected") - } - - // Have we found a non-empty line? - if !is_break(parser.buffer, parser.buffer_pos) { - break - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - // [Go] Should really be returning breaks instead. - *breaks = read_line(parser, *breaks) - *end_mark = parser.mark - } - - // Determine the indentation level if needed. - if *indent == 0 { - *indent = max_indent - if *indent < parser.indent+1 { - *indent = parser.indent + 1 - } - if *indent < 1 { - *indent = 1 - } - } - return true -} - -// Scan a quoted scalar. -func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { - // Eat the left quote. - start_mark := parser.mark - skip(parser) - - // Consume the content of the quoted scalar. - var s, leading_break, trailing_breaks, whitespaces []byte - for { - // Check that there are no document indicators at the beginning of the line. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected document indicator") - return false - } - - // Check for EOF. - if is_z(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected end of stream") - return false - } - - // Consume non-blank characters. - leading_blanks := false - for !is_blankz(parser.buffer, parser.buffer_pos) { - if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { - // Is is an escaped single quote. - s = append(s, '\'') - skip(parser) - skip(parser) - - } else if single && parser.buffer[parser.buffer_pos] == '\'' { - // It is a right single quote. - break - } else if !single && parser.buffer[parser.buffer_pos] == '"' { - // It is a right double quote. - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { - // It is an escaped line break. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - skip(parser) - skip_line(parser) - leading_blanks = true - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' { - // It is an escape sequence. - code_length := 0 - - // Check the escape character. - switch parser.buffer[parser.buffer_pos+1] { - case '0': - s = append(s, 0) - case 'a': - s = append(s, '\x07') - case 'b': - s = append(s, '\x08') - case 't', '\t': - s = append(s, '\x09') - case 'n': - s = append(s, '\x0A') - case 'v': - s = append(s, '\x0B') - case 'f': - s = append(s, '\x0C') - case 'r': - s = append(s, '\x0D') - case 'e': - s = append(s, '\x1B') - case ' ': - s = append(s, '\x20') - case '"': - s = append(s, '"') - case '\'': - s = append(s, '\'') - case '\\': - s = append(s, '\\') - case 'N': // NEL (#x85) - s = append(s, '\xC2') - s = append(s, '\x85') - case '_': // #xA0 - s = append(s, '\xC2') - s = append(s, '\xA0') - case 'L': // LS (#x2028) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA8') - case 'P': // PS (#x2029) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA9') - case 'x': - code_length = 2 - case 'u': - code_length = 4 - case 'U': - code_length = 8 - default: - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found unknown escape character") - return false - } - - skip(parser) - skip(parser) - - // Consume an arbitrary escape code. - if code_length > 0 { - var value int - - // Scan the character value. - if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { - return false - } - for k := 0; k < code_length; k++ { - if !is_hex(parser.buffer, parser.buffer_pos+k) { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "did not find expected hexdecimal number") - return false - } - value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) - } - - // Check the value and write the character. - if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found invalid Unicode character escape code") - return false - } - if value <= 0x7F { - s = append(s, byte(value)) - } else if value <= 0x7FF { - s = append(s, byte(0xC0+(value>>6))) - s = append(s, byte(0x80+(value&0x3F))) - } else if value <= 0xFFFF { - s = append(s, byte(0xE0+(value>>12))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } else { - s = append(s, byte(0xF0+(value>>18))) - s = append(s, byte(0x80+((value>>12)&0x3F))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } - - // Advance the pointer. - for k := 0; k < code_length; k++ { - skip(parser) - } - } - } else { - // It is a non-escaped non-blank character. - s = read(parser, s) - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we are at the end of the scalar. - if single { - if parser.buffer[parser.buffer_pos] == '\'' { - break - } - } else { - if parser.buffer[parser.buffer_pos] == '"' { - break - } - } - - // Consume blank characters. - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Join the whitespaces or fold line breaks. - if leading_blanks { - // Do we need to fold line breaks? - if len(leading_break) > 0 && leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Eat the right quote. - skip(parser) - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_SINGLE_QUOTED_SCALAR_STYLE, - } - if !single { - token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - return true -} - -// Scan a plain scalar. -func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { - - var s, leading_break, trailing_breaks, whitespaces []byte - var leading_blanks bool - var indent = parser.indent + 1 - - start_mark := parser.mark - end_mark := parser.mark - - // Consume the content of the plain scalar. - for { - // Check for a document indicator. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - break - } - - // Check for a comment. - if parser.buffer[parser.buffer_pos] == '#' { - break - } - - // Consume non-blank characters. - for !is_blankz(parser.buffer, parser.buffer_pos) { - - // Check for indicators that may end a plain scalar. - if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level > 0 && - (parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}')) { - break - } - - // Check if we need to join whitespaces and breaks. - if leading_blanks || len(whitespaces) > 0 { - if leading_blanks { - // Do we need to fold line breaks? - if leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - leading_blanks = false - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Copy the character. - s = read(parser, s) - - end_mark = parser.mark - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - // Is it the end? - if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { - break - } - - // Consume blank characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - - // Check for tab characters that abuse indentation. - if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", - start_mark, "found a tab character that violates indentation") - return false - } - - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check indentation level. - if parser.flow_level == 0 && parser.mark.column < indent { - break - } - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_PLAIN_SCALAR_STYLE, - } - - // Note that we change the 'simple_key_allowed' flag. - if leading_blanks { - parser.simple_key_allowed = true - } - return true -} diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go deleted file mode 100644 index 4c45e660a..000000000 --- a/vendor/gopkg.in/yaml.v2/sorter.go +++ /dev/null @@ -1,113 +0,0 @@ -package yaml - -import ( - "reflect" - "unicode" -) - -type keyList []reflect.Value - -func (l keyList) Len() int { return len(l) } -func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } -func (l keyList) Less(i, j int) bool { - a := l[i] - b := l[j] - ak := a.Kind() - bk := b.Kind() - for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { - a = a.Elem() - ak = a.Kind() - } - for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { - b = b.Elem() - bk = b.Kind() - } - af, aok := keyFloat(a) - bf, bok := keyFloat(b) - if aok && bok { - if af != bf { - return af < bf - } - if ak != bk { - return ak < bk - } - return numLess(a, b) - } - if ak != reflect.String || bk != reflect.String { - return ak < bk - } - ar, br := []rune(a.String()), []rune(b.String()) - for i := 0; i < len(ar) && i < len(br); i++ { - if ar[i] == br[i] { - continue - } - al := unicode.IsLetter(ar[i]) - bl := unicode.IsLetter(br[i]) - if al && bl { - return ar[i] < br[i] - } - if al || bl { - return bl - } - var ai, bi int - var an, bn int64 - if ar[i] == '0' || br[i] == '0' { - for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { - if ar[j] != '0' { - an = 1 - bn = 1 - break - } - } - } - for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { - an = an*10 + int64(ar[ai]-'0') - } - for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { - bn = bn*10 + int64(br[bi]-'0') - } - if an != bn { - return an < bn - } - if ai != bi { - return ai < bi - } - return ar[i] < br[i] - } - return len(ar) < len(br) -} - -// keyFloat returns a float value for v if it is a number/bool -// and whether it is a number/bool or not. -func keyFloat(v reflect.Value) (f float64, ok bool) { - switch v.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return float64(v.Int()), true - case reflect.Float32, reflect.Float64: - return v.Float(), true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return float64(v.Uint()), true - case reflect.Bool: - if v.Bool() { - return 1, true - } - return 0, true - } - return 0, false -} - -// numLess returns whether a < b. -// a and b must necessarily have the same kind. -func numLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return a.Int() < b.Int() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Bool: - return !a.Bool() && b.Bool() - } - panic("not a number") -} diff --git a/vendor/gopkg.in/yaml.v2/writerc.go b/vendor/gopkg.in/yaml.v2/writerc.go deleted file mode 100644 index a2dde608c..000000000 --- a/vendor/gopkg.in/yaml.v2/writerc.go +++ /dev/null @@ -1,26 +0,0 @@ -package yaml - -// Set the writer error and return false. -func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_WRITER_ERROR - emitter.problem = problem - return false -} - -// Flush the output buffer. -func yaml_emitter_flush(emitter *yaml_emitter_t) bool { - if emitter.write_handler == nil { - panic("write handler not set") - } - - // Check if the buffer is empty. - if emitter.buffer_pos == 0 { - return true - } - - if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { - return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) - } - emitter.buffer_pos = 0 - return true -} diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go deleted file mode 100644 index de85aa4cd..000000000 --- a/vendor/gopkg.in/yaml.v2/yaml.go +++ /dev/null @@ -1,466 +0,0 @@ -// Package yaml implements YAML support for the Go language. -// -// Source code and other details for the project are available at GitHub: -// -// https://github.com/go-yaml/yaml -// -package yaml - -import ( - "errors" - "fmt" - "io" - "reflect" - "strings" - "sync" -) - -// MapSlice encodes and decodes as a YAML map. -// The order of keys is preserved when encoding and decoding. -type MapSlice []MapItem - -// MapItem is an item in a MapSlice. -type MapItem struct { - Key, Value interface{} -} - -// The Unmarshaler interface may be implemented by types to customize their -// behavior when being unmarshaled from a YAML document. The UnmarshalYAML -// method receives a function that may be called to unmarshal the original -// YAML value into a field or variable. It is safe to call the unmarshal -// function parameter more than once if necessary. -type Unmarshaler interface { - UnmarshalYAML(unmarshal func(interface{}) error) error -} - -// The Marshaler interface may be implemented by types to customize their -// behavior when being marshaled into a YAML document. The returned value -// is marshaled in place of the original value implementing Marshaler. -// -// If an error is returned by MarshalYAML, the marshaling procedure stops -// and returns with the provided error. -type Marshaler interface { - MarshalYAML() (interface{}, error) -} - -// Unmarshal decodes the first document found within the in byte slice -// and assigns decoded values into the out value. -// -// Maps and pointers (to a struct, string, int, etc) are accepted as out -// values. If an internal pointer within a struct is not initialized, -// the yaml package will initialize it if necessary for unmarshalling -// the provided data. The out parameter must not be nil. -// -// The type of the decoded values should be compatible with the respective -// values in out. If one or more values cannot be decoded due to a type -// mismatches, decoding continues partially until the end of the YAML -// content, and a *yaml.TypeError is returned with details for all -// missed values. -// -// Struct fields are only unmarshalled if they are exported (have an -// upper case first letter), and are unmarshalled using the field name -// lowercased as the default key. Custom keys may be defined via the -// "yaml" name in the field tag: the content preceding the first comma -// is used as the key, and the following comma-separated options are -// used to tweak the marshalling process (see Marshal). -// Conflicting names result in a runtime error. -// -// For example: -// -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// var t T -// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) -// -// See the documentation of Marshal for the format of tags and a list of -// supported tag options. -// -func Unmarshal(in []byte, out interface{}) (err error) { - return unmarshal(in, out, false) -} - -// UnmarshalStrict is like Unmarshal except that any fields that are found -// in the data that do not have corresponding struct members, or mapping -// keys that are duplicates, will result in -// an error. -func UnmarshalStrict(in []byte, out interface{}) (err error) { - return unmarshal(in, out, true) -} - -// A Decorder reads and decodes YAML values from an input stream. -type Decoder struct { - strict bool - parser *parser -} - -// NewDecoder returns a new decoder that reads from r. -// -// The decoder introduces its own buffering and may read -// data from r beyond the YAML values requested. -func NewDecoder(r io.Reader) *Decoder { - return &Decoder{ - parser: newParserFromReader(r), - } -} - -// SetStrict sets whether strict decoding behaviour is enabled when -// decoding items in the data (see UnmarshalStrict). By default, decoding is not strict. -func (dec *Decoder) SetStrict(strict bool) { - dec.strict = strict -} - -// Decode reads the next YAML-encoded value from its input -// and stores it in the value pointed to by v. -// -// See the documentation for Unmarshal for details about the -// conversion of YAML into a Go value. -func (dec *Decoder) Decode(v interface{}) (err error) { - d := newDecoder(dec.strict) - defer handleErr(&err) - node := dec.parser.parse() - if node == nil { - return io.EOF - } - out := reflect.ValueOf(v) - if out.Kind() == reflect.Ptr && !out.IsNil() { - out = out.Elem() - } - d.unmarshal(node, out) - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -func unmarshal(in []byte, out interface{}, strict bool) (err error) { - defer handleErr(&err) - d := newDecoder(strict) - p := newParser(in) - defer p.destroy() - node := p.parse() - if node != nil { - v := reflect.ValueOf(out) - if v.Kind() == reflect.Ptr && !v.IsNil() { - v = v.Elem() - } - d.unmarshal(node, v) - } - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -// Marshal serializes the value provided into a YAML document. The structure -// of the generated document will reflect the structure of the value itself. -// Maps and pointers (to struct, string, int, etc) are accepted as the in value. -// -// Struct fields are only marshalled if they are exported (have an upper case -// first letter), and are marshalled using the field name lowercased as the -// default key. Custom keys may be defined via the "yaml" name in the field -// tag: the content preceding the first comma is used as the key, and the -// following comma-separated options are used to tweak the marshalling process. -// Conflicting names result in a runtime error. -// -// The field tag format accepted is: -// -// `(...) yaml:"[][,[,]]" (...)` -// -// The following flags are currently supported: -// -// omitempty Only include the field if it's not set to the zero -// value for the type or to empty slices or maps. -// Zero valued structs will be omitted if all their public -// fields are zero, unless they implement an IsZero -// method (see the IsZeroer interface type), in which -// case the field will be included if that method returns true. -// -// flow Marshal using a flow style (useful for structs, -// sequences and maps). -// -// inline Inline the field, which must be a struct or a map, -// causing all of its fields or keys to be processed as if -// they were part of the outer struct. For maps, keys must -// not conflict with the yaml keys of other struct fields. -// -// In addition, if the key is "-", the field is ignored. -// -// For example: -// -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" -// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" -// -func Marshal(in interface{}) (out []byte, err error) { - defer handleErr(&err) - e := newEncoder() - defer e.destroy() - e.marshalDoc("", reflect.ValueOf(in)) - e.finish() - out = e.out - return -} - -// An Encoder writes YAML values to an output stream. -type Encoder struct { - encoder *encoder -} - -// NewEncoder returns a new encoder that writes to w. -// The Encoder should be closed after use to flush all data -// to w. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{ - encoder: newEncoderWithWriter(w), - } -} - -// Encode writes the YAML encoding of v to the stream. -// If multiple items are encoded to the stream, the -// second and subsequent document will be preceded -// with a "---" document separator, but the first will not. -// -// See the documentation for Marshal for details about the conversion of Go -// values to YAML. -func (e *Encoder) Encode(v interface{}) (err error) { - defer handleErr(&err) - e.encoder.marshalDoc("", reflect.ValueOf(v)) - return nil -} - -// Close closes the encoder by writing any remaining data. -// It does not write a stream terminating string "...". -func (e *Encoder) Close() (err error) { - defer handleErr(&err) - e.encoder.finish() - return nil -} - -func handleErr(err *error) { - if v := recover(); v != nil { - if e, ok := v.(yamlError); ok { - *err = e.err - } else { - panic(v) - } - } -} - -type yamlError struct { - err error -} - -func fail(err error) { - panic(yamlError{err}) -} - -func failf(format string, args ...interface{}) { - panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) -} - -// A TypeError is returned by Unmarshal when one or more fields in -// the YAML document cannot be properly decoded into the requested -// types. When this error is returned, the value is still -// unmarshaled partially. -type TypeError struct { - Errors []string -} - -func (e *TypeError) Error() string { - return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) -} - -// -------------------------------------------------------------------------- -// Maintain a mapping of keys to structure field indexes - -// The code in this section was copied from mgo/bson. - -// structInfo holds details for the serialization of fields of -// a given struct. -type structInfo struct { - FieldsMap map[string]fieldInfo - FieldsList []fieldInfo - - // InlineMap is the number of the field in the struct that - // contains an ,inline map, or -1 if there's none. - InlineMap int -} - -type fieldInfo struct { - Key string - Num int - OmitEmpty bool - Flow bool - // Id holds the unique field identifier, so we can cheaply - // check for field duplicates without maintaining an extra map. - Id int - - // Inline holds the field index if the field is part of an inlined struct. - Inline []int -} - -var structMap = make(map[reflect.Type]*structInfo) -var fieldMapMutex sync.RWMutex - -func getStructInfo(st reflect.Type) (*structInfo, error) { - fieldMapMutex.RLock() - sinfo, found := structMap[st] - fieldMapMutex.RUnlock() - if found { - return sinfo, nil - } - - n := st.NumField() - fieldsMap := make(map[string]fieldInfo) - fieldsList := make([]fieldInfo, 0, n) - inlineMap := -1 - for i := 0; i != n; i++ { - field := st.Field(i) - if field.PkgPath != "" && !field.Anonymous { - continue // Private field - } - - info := fieldInfo{Num: i} - - tag := field.Tag.Get("yaml") - if tag == "" && strings.Index(string(field.Tag), ":") < 0 { - tag = string(field.Tag) - } - if tag == "-" { - continue - } - - inline := false - fields := strings.Split(tag, ",") - if len(fields) > 1 { - for _, flag := range fields[1:] { - switch flag { - case "omitempty": - info.OmitEmpty = true - case "flow": - info.Flow = true - case "inline": - inline = true - default: - return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) - } - } - tag = fields[0] - } - - if inline { - switch field.Type.Kind() { - case reflect.Map: - if inlineMap >= 0 { - return nil, errors.New("Multiple ,inline maps in struct " + st.String()) - } - if field.Type.Key() != reflect.TypeOf("") { - return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) - } - inlineMap = info.Num - case reflect.Struct: - sinfo, err := getStructInfo(field.Type) - if err != nil { - return nil, err - } - for _, finfo := range sinfo.FieldsList { - if _, found := fieldsMap[finfo.Key]; found { - msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - if finfo.Inline == nil { - finfo.Inline = []int{i, finfo.Num} - } else { - finfo.Inline = append([]int{i}, finfo.Inline...) - } - finfo.Id = len(fieldsList) - fieldsMap[finfo.Key] = finfo - fieldsList = append(fieldsList, finfo) - } - default: - //return nil, errors.New("Option ,inline needs a struct value or map field") - return nil, errors.New("Option ,inline needs a struct value field") - } - continue - } - - if tag != "" { - info.Key = tag - } else { - info.Key = strings.ToLower(field.Name) - } - - if _, found = fieldsMap[info.Key]; found { - msg := "Duplicated key '" + info.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - - info.Id = len(fieldsList) - fieldsList = append(fieldsList, info) - fieldsMap[info.Key] = info - } - - sinfo = &structInfo{ - FieldsMap: fieldsMap, - FieldsList: fieldsList, - InlineMap: inlineMap, - } - - fieldMapMutex.Lock() - structMap[st] = sinfo - fieldMapMutex.Unlock() - return sinfo, nil -} - -// IsZeroer is used to check whether an object is zero to -// determine whether it should be omitted when marshaling -// with the omitempty flag. One notable implementation -// is time.Time. -type IsZeroer interface { - IsZero() bool -} - -func isZero(v reflect.Value) bool { - kind := v.Kind() - if z, ok := v.Interface().(IsZeroer); ok { - if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { - return true - } - return z.IsZero() - } - switch kind { - case reflect.String: - return len(v.String()) == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - case reflect.Slice: - return v.Len() == 0 - case reflect.Map: - return v.Len() == 0 - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Struct: - vt := v.Type() - for i := v.NumField() - 1; i >= 0; i-- { - if vt.Field(i).PkgPath != "" { - continue // Private field - } - if !isZero(v.Field(i)) { - return false - } - } - return true - } - return false -} diff --git a/vendor/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go deleted file mode 100644 index e25cee563..000000000 --- a/vendor/gopkg.in/yaml.v2/yamlh.go +++ /dev/null @@ -1,738 +0,0 @@ -package yaml - -import ( - "fmt" - "io" -) - -// The version directive data. -type yaml_version_directive_t struct { - major int8 // The major version number. - minor int8 // The minor version number. -} - -// The tag directive data. -type yaml_tag_directive_t struct { - handle []byte // The tag handle. - prefix []byte // The tag prefix. -} - -type yaml_encoding_t int - -// The stream encoding. -const ( - // Let the parser choose the encoding. - yaml_ANY_ENCODING yaml_encoding_t = iota - - yaml_UTF8_ENCODING // The default UTF-8 encoding. - yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. - yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. -) - -type yaml_break_t int - -// Line break types. -const ( - // Let the parser choose the break type. - yaml_ANY_BREAK yaml_break_t = iota - - yaml_CR_BREAK // Use CR for line breaks (Mac style). - yaml_LN_BREAK // Use LN for line breaks (Unix style). - yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). -) - -type yaml_error_type_t int - -// Many bad things could happen with the parser and emitter. -const ( - // No error is produced. - yaml_NO_ERROR yaml_error_type_t = iota - - yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. - yaml_READER_ERROR // Cannot read or decode the input stream. - yaml_SCANNER_ERROR // Cannot scan the input stream. - yaml_PARSER_ERROR // Cannot parse the input stream. - yaml_COMPOSER_ERROR // Cannot compose a YAML document. - yaml_WRITER_ERROR // Cannot write to the output stream. - yaml_EMITTER_ERROR // Cannot emit a YAML stream. -) - -// The pointer position. -type yaml_mark_t struct { - index int // The position index. - line int // The position line. - column int // The position column. -} - -// Node Styles - -type yaml_style_t int8 - -type yaml_scalar_style_t yaml_style_t - -// Scalar styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota - - yaml_PLAIN_SCALAR_STYLE // The plain scalar style. - yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. - yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. - yaml_LITERAL_SCALAR_STYLE // The literal scalar style. - yaml_FOLDED_SCALAR_STYLE // The folded scalar style. -) - -type yaml_sequence_style_t yaml_style_t - -// Sequence styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota - - yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. - yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. -) - -type yaml_mapping_style_t yaml_style_t - -// Mapping styles. -const ( - // Let the emitter choose the style. - yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota - - yaml_BLOCK_MAPPING_STYLE // The block mapping style. - yaml_FLOW_MAPPING_STYLE // The flow mapping style. -) - -// Tokens - -type yaml_token_type_t int - -// Token types. -const ( - // An empty token. - yaml_NO_TOKEN yaml_token_type_t = iota - - yaml_STREAM_START_TOKEN // A STREAM-START token. - yaml_STREAM_END_TOKEN // A STREAM-END token. - - yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. - yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. - yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. - yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. - - yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. - yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. - yaml_BLOCK_END_TOKEN // A BLOCK-END token. - - yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. - yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. - yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. - yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. - - yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. - yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. - yaml_KEY_TOKEN // A KEY token. - yaml_VALUE_TOKEN // A VALUE token. - - yaml_ALIAS_TOKEN // An ALIAS token. - yaml_ANCHOR_TOKEN // An ANCHOR token. - yaml_TAG_TOKEN // A TAG token. - yaml_SCALAR_TOKEN // A SCALAR token. -) - -func (tt yaml_token_type_t) String() string { - switch tt { - case yaml_NO_TOKEN: - return "yaml_NO_TOKEN" - case yaml_STREAM_START_TOKEN: - return "yaml_STREAM_START_TOKEN" - case yaml_STREAM_END_TOKEN: - return "yaml_STREAM_END_TOKEN" - case yaml_VERSION_DIRECTIVE_TOKEN: - return "yaml_VERSION_DIRECTIVE_TOKEN" - case yaml_TAG_DIRECTIVE_TOKEN: - return "yaml_TAG_DIRECTIVE_TOKEN" - case yaml_DOCUMENT_START_TOKEN: - return "yaml_DOCUMENT_START_TOKEN" - case yaml_DOCUMENT_END_TOKEN: - return "yaml_DOCUMENT_END_TOKEN" - case yaml_BLOCK_SEQUENCE_START_TOKEN: - return "yaml_BLOCK_SEQUENCE_START_TOKEN" - case yaml_BLOCK_MAPPING_START_TOKEN: - return "yaml_BLOCK_MAPPING_START_TOKEN" - case yaml_BLOCK_END_TOKEN: - return "yaml_BLOCK_END_TOKEN" - case yaml_FLOW_SEQUENCE_START_TOKEN: - return "yaml_FLOW_SEQUENCE_START_TOKEN" - case yaml_FLOW_SEQUENCE_END_TOKEN: - return "yaml_FLOW_SEQUENCE_END_TOKEN" - case yaml_FLOW_MAPPING_START_TOKEN: - return "yaml_FLOW_MAPPING_START_TOKEN" - case yaml_FLOW_MAPPING_END_TOKEN: - return "yaml_FLOW_MAPPING_END_TOKEN" - case yaml_BLOCK_ENTRY_TOKEN: - return "yaml_BLOCK_ENTRY_TOKEN" - case yaml_FLOW_ENTRY_TOKEN: - return "yaml_FLOW_ENTRY_TOKEN" - case yaml_KEY_TOKEN: - return "yaml_KEY_TOKEN" - case yaml_VALUE_TOKEN: - return "yaml_VALUE_TOKEN" - case yaml_ALIAS_TOKEN: - return "yaml_ALIAS_TOKEN" - case yaml_ANCHOR_TOKEN: - return "yaml_ANCHOR_TOKEN" - case yaml_TAG_TOKEN: - return "yaml_TAG_TOKEN" - case yaml_SCALAR_TOKEN: - return "yaml_SCALAR_TOKEN" - } - return "" -} - -// The token structure. -type yaml_token_t struct { - // The token type. - typ yaml_token_type_t - - // The start/end of the token. - start_mark, end_mark yaml_mark_t - - // The stream encoding (for yaml_STREAM_START_TOKEN). - encoding yaml_encoding_t - - // The alias/anchor/scalar value or tag/tag directive handle - // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). - value []byte - - // The tag suffix (for yaml_TAG_TOKEN). - suffix []byte - - // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). - prefix []byte - - // The scalar style (for yaml_SCALAR_TOKEN). - style yaml_scalar_style_t - - // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). - major, minor int8 -} - -// Events - -type yaml_event_type_t int8 - -// Event types. -const ( - // An empty event. - yaml_NO_EVENT yaml_event_type_t = iota - - yaml_STREAM_START_EVENT // A STREAM-START event. - yaml_STREAM_END_EVENT // A STREAM-END event. - yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. - yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. - yaml_ALIAS_EVENT // An ALIAS event. - yaml_SCALAR_EVENT // A SCALAR event. - yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. - yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. - yaml_MAPPING_START_EVENT // A MAPPING-START event. - yaml_MAPPING_END_EVENT // A MAPPING-END event. -) - -var eventStrings = []string{ - yaml_NO_EVENT: "none", - yaml_STREAM_START_EVENT: "stream start", - yaml_STREAM_END_EVENT: "stream end", - yaml_DOCUMENT_START_EVENT: "document start", - yaml_DOCUMENT_END_EVENT: "document end", - yaml_ALIAS_EVENT: "alias", - yaml_SCALAR_EVENT: "scalar", - yaml_SEQUENCE_START_EVENT: "sequence start", - yaml_SEQUENCE_END_EVENT: "sequence end", - yaml_MAPPING_START_EVENT: "mapping start", - yaml_MAPPING_END_EVENT: "mapping end", -} - -func (e yaml_event_type_t) String() string { - if e < 0 || int(e) >= len(eventStrings) { - return fmt.Sprintf("unknown event %d", e) - } - return eventStrings[e] -} - -// The event structure. -type yaml_event_t struct { - - // The event type. - typ yaml_event_type_t - - // The start and end of the event. - start_mark, end_mark yaml_mark_t - - // The document encoding (for yaml_STREAM_START_EVENT). - encoding yaml_encoding_t - - // The version directive (for yaml_DOCUMENT_START_EVENT). - version_directive *yaml_version_directive_t - - // The list of tag directives (for yaml_DOCUMENT_START_EVENT). - tag_directives []yaml_tag_directive_t - - // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). - anchor []byte - - // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - tag []byte - - // The scalar value (for yaml_SCALAR_EVENT). - value []byte - - // Is the document start/end indicator implicit, or the tag optional? - // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). - implicit bool - - // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). - quoted_implicit bool - - // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - style yaml_style_t -} - -func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } -func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } -func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } - -// Nodes - -const ( - yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. - yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. - yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. - yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. - yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. - yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. - - yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. - yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. - - // Not in original libyaml. - yaml_BINARY_TAG = "tag:yaml.org,2002:binary" - yaml_MERGE_TAG = "tag:yaml.org,2002:merge" - - yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. - yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. - yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. -) - -type yaml_node_type_t int - -// Node types. -const ( - // An empty node. - yaml_NO_NODE yaml_node_type_t = iota - - yaml_SCALAR_NODE // A scalar node. - yaml_SEQUENCE_NODE // A sequence node. - yaml_MAPPING_NODE // A mapping node. -) - -// An element of a sequence node. -type yaml_node_item_t int - -// An element of a mapping node. -type yaml_node_pair_t struct { - key int // The key of the element. - value int // The value of the element. -} - -// The node structure. -type yaml_node_t struct { - typ yaml_node_type_t // The node type. - tag []byte // The node tag. - - // The node data. - - // The scalar parameters (for yaml_SCALAR_NODE). - scalar struct { - value []byte // The scalar value. - length int // The length of the scalar value. - style yaml_scalar_style_t // The scalar style. - } - - // The sequence parameters (for YAML_SEQUENCE_NODE). - sequence struct { - items_data []yaml_node_item_t // The stack of sequence items. - style yaml_sequence_style_t // The sequence style. - } - - // The mapping parameters (for yaml_MAPPING_NODE). - mapping struct { - pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). - pairs_start *yaml_node_pair_t // The beginning of the stack. - pairs_end *yaml_node_pair_t // The end of the stack. - pairs_top *yaml_node_pair_t // The top of the stack. - style yaml_mapping_style_t // The mapping style. - } - - start_mark yaml_mark_t // The beginning of the node. - end_mark yaml_mark_t // The end of the node. - -} - -// The document structure. -type yaml_document_t struct { - - // The document nodes. - nodes []yaml_node_t - - // The version directive. - version_directive *yaml_version_directive_t - - // The list of tag directives. - tag_directives_data []yaml_tag_directive_t - tag_directives_start int // The beginning of the tag directives list. - tag_directives_end int // The end of the tag directives list. - - start_implicit int // Is the document start indicator implicit? - end_implicit int // Is the document end indicator implicit? - - // The start/end of the document. - start_mark, end_mark yaml_mark_t -} - -// The prototype of a read handler. -// -// The read handler is called when the parser needs to read more bytes from the -// source. The handler should write not more than size bytes to the buffer. -// The number of written bytes should be set to the size_read variable. -// -// [in,out] data A pointer to an application data specified by -// yaml_parser_set_input(). -// [out] buffer The buffer to write the data from the source. -// [in] size The size of the buffer. -// [out] size_read The actual number of bytes read from the source. -// -// On success, the handler should return 1. If the handler failed, -// the returned value should be 0. On EOF, the handler should set the -// size_read to 0 and return 1. -type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) - -// This structure holds information about a potential simple key. -type yaml_simple_key_t struct { - possible bool // Is a simple key possible? - required bool // Is a simple key required? - token_number int // The number of the token. - mark yaml_mark_t // The position mark. -} - -// The states of the parser. -type yaml_parser_state_t int - -const ( - yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota - - yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. - yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. - yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. - yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. - yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. - yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. - yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. - yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. - yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. - yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. - yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. - yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. - yaml_PARSE_END_STATE // Expect nothing. -) - -func (ps yaml_parser_state_t) String() string { - switch ps { - case yaml_PARSE_STREAM_START_STATE: - return "yaml_PARSE_STREAM_START_STATE" - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_START_STATE: - return "yaml_PARSE_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return "yaml_PARSE_DOCUMENT_CONTENT_STATE" - case yaml_PARSE_DOCUMENT_END_STATE: - return "yaml_PARSE_DOCUMENT_END_STATE" - case yaml_PARSE_BLOCK_NODE_STATE: - return "yaml_PARSE_BLOCK_NODE_STATE" - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" - case yaml_PARSE_FLOW_NODE_STATE: - return "yaml_PARSE_FLOW_NODE_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" - case yaml_PARSE_END_STATE: - return "yaml_PARSE_END_STATE" - } - return "" -} - -// This structure holds aliases data. -type yaml_alias_data_t struct { - anchor []byte // The anchor. - index int // The node id. - mark yaml_mark_t // The anchor mark. -} - -// The parser structure. -// -// All members are internal. Manage the structure using the -// yaml_parser_ family of functions. -type yaml_parser_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - - problem string // Error description. - - // The byte about which the problem occurred. - problem_offset int - problem_value int - problem_mark yaml_mark_t - - // The error context. - context string - context_mark yaml_mark_t - - // Reader stuff - - read_handler yaml_read_handler_t // Read handler. - - input_reader io.Reader // File input data. - input []byte // String input data. - input_pos int - - eof bool // EOF flag - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - unread int // The number of unread characters in the buffer. - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The input encoding. - - offset int // The offset of the current position (in bytes). - mark yaml_mark_t // The mark of the current position. - - // Scanner stuff - - stream_start_produced bool // Have we started to scan the input stream? - stream_end_produced bool // Have we reached the end of the input stream? - - flow_level int // The number of unclosed '[' and '{' indicators. - - tokens []yaml_token_t // The tokens queue. - tokens_head int // The head of the tokens queue. - tokens_parsed int // The number of tokens fetched from the queue. - token_available bool // Does the tokens queue contain a token ready for dequeueing. - - indent int // The current indentation level. - indents []int // The indentation levels stack. - - simple_key_allowed bool // May a simple key occur at the current position? - simple_keys []yaml_simple_key_t // The stack of simple keys. - - // Parser stuff - - state yaml_parser_state_t // The current parser state. - states []yaml_parser_state_t // The parser states stack. - marks []yaml_mark_t // The stack of marks. - tag_directives []yaml_tag_directive_t // The list of TAG directives. - - // Dumper stuff - - aliases []yaml_alias_data_t // The alias data. - - document *yaml_document_t // The currently parsed document. -} - -// Emitter Definitions - -// The prototype of a write handler. -// -// The write handler is called when the emitter needs to flush the accumulated -// characters to the output. The handler should write @a size bytes of the -// @a buffer to the output. -// -// @param[in,out] data A pointer to an application data specified by -// yaml_emitter_set_output(). -// @param[in] buffer The buffer with bytes to be written. -// @param[in] size The size of the buffer. -// -// @returns On success, the handler should return @c 1. If the handler failed, -// the returned value should be @c 0. -// -type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error - -type yaml_emitter_state_t int - -// The emitter states. -const ( - // Expect STREAM-START. - yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota - - yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. - yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. - yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. - yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. - yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. - yaml_EMIT_END_STATE // Expect nothing. -) - -// The emitter structure. -// -// All members are internal. Manage the structure using the @c yaml_emitter_ -// family of functions. -type yaml_emitter_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - problem string // Error description. - - // Writer stuff - - write_handler yaml_write_handler_t // Write handler. - - output_buffer *[]byte // String output data. - output_writer io.Writer // File output data. - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The stream encoding. - - // Emitter stuff - - canonical bool // If the output is in the canonical style? - best_indent int // The number of indentation spaces. - best_width int // The preferred width of the output lines. - unicode bool // Allow unescaped non-ASCII characters? - line_break yaml_break_t // The preferred line break. - - state yaml_emitter_state_t // The current emitter state. - states []yaml_emitter_state_t // The stack of states. - - events []yaml_event_t // The event queue. - events_head int // The head of the event queue. - - indents []int // The stack of indentation levels. - - tag_directives []yaml_tag_directive_t // The list of tag directives. - - indent int // The current indentation level. - - flow_level int // The current flow level. - - root_context bool // Is it the document root context? - sequence_context bool // Is it a sequence context? - mapping_context bool // Is it a mapping context? - simple_key_context bool // Is it a simple mapping key context? - - line int // The current line. - column int // The current column. - whitespace bool // If the last character was a whitespace? - indention bool // If the last character was an indentation character (' ', '-', '?', ':')? - open_ended bool // If an explicit document end is required? - - // Anchor analysis. - anchor_data struct { - anchor []byte // The anchor value. - alias bool // Is it an alias? - } - - // Tag analysis. - tag_data struct { - handle []byte // The tag handle. - suffix []byte // The tag suffix. - } - - // Scalar analysis. - scalar_data struct { - value []byte // The scalar value. - multiline bool // Does the scalar contain line breaks? - flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? - block_plain_allowed bool // Can the scalar be expressed in the block plain style? - single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? - block_allowed bool // Can the scalar be expressed in the literal or folded styles? - style yaml_scalar_style_t // The output style. - } - - // Dumper stuff - - opened bool // If the stream was already opened? - closed bool // If the stream was already closed? - - // The information associated with the document nodes. - anchors *struct { - references int // The number of references. - anchor int // The anchor id. - serialized bool // If the node has been emitted? - } - - last_anchor_id int // The last assigned anchor id. - - document *yaml_document_t // The currently emitted document. -} diff --git a/vendor/gopkg.in/yaml.v2/yamlprivateh.go b/vendor/gopkg.in/yaml.v2/yamlprivateh.go deleted file mode 100644 index 8110ce3c3..000000000 --- a/vendor/gopkg.in/yaml.v2/yamlprivateh.go +++ /dev/null @@ -1,173 +0,0 @@ -package yaml - -const ( - // The size of the input raw buffer. - input_raw_buffer_size = 512 - - // The size of the input buffer. - // It should be possible to decode the whole raw buffer. - input_buffer_size = input_raw_buffer_size * 3 - - // The size of the output buffer. - output_buffer_size = 128 - - // The size of the output raw buffer. - // It should be possible to encode the whole output buffer. - output_raw_buffer_size = (output_buffer_size*2 + 2) - - // The size of other stacks and queues. - initial_stack_size = 16 - initial_queue_size = 16 - initial_string_size = 16 -) - -// Check if the character at the specified position is an alphabetical -// character, a digit, '_', or '-'. -func is_alpha(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' -} - -// Check if the character at the specified position is a digit. -func is_digit(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' -} - -// Get the value of a digit. -func as_digit(b []byte, i int) int { - return int(b[i]) - '0' -} - -// Check if the character at the specified position is a hex-digit. -func is_hex(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' -} - -// Get the value of a hex-digit. -func as_hex(b []byte, i int) int { - bi := b[i] - if bi >= 'A' && bi <= 'F' { - return int(bi) - 'A' + 10 - } - if bi >= 'a' && bi <= 'f' { - return int(bi) - 'a' + 10 - } - return int(bi) - '0' -} - -// Check if the character is ASCII. -func is_ascii(b []byte, i int) bool { - return b[i] <= 0x7F -} - -// Check if the character at the start of the buffer can be printed unescaped. -func is_printable(b []byte, i int) bool { - return ((b[i] == 0x0A) || // . == #x0A - (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E - (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF - (b[i] > 0xC2 && b[i] < 0xED) || - (b[i] == 0xED && b[i+1] < 0xA0) || - (b[i] == 0xEE) || - (b[i] == 0xEF && // #xE000 <= . <= #xFFFD - !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF - !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) -} - -// Check if the character at the specified position is NUL. -func is_z(b []byte, i int) bool { - return b[i] == 0x00 -} - -// Check if the beginning of the buffer is a BOM. -func is_bom(b []byte, i int) bool { - return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF -} - -// Check if the character at the specified position is space. -func is_space(b []byte, i int) bool { - return b[i] == ' ' -} - -// Check if the character at the specified position is tab. -func is_tab(b []byte, i int) bool { - return b[i] == '\t' -} - -// Check if the character at the specified position is blank (space or tab). -func is_blank(b []byte, i int) bool { - //return is_space(b, i) || is_tab(b, i) - return b[i] == ' ' || b[i] == '\t' -} - -// Check if the character at the specified position is a line break. -func is_break(b []byte, i int) bool { - return (b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) -} - -func is_crlf(b []byte, i int) bool { - return b[i] == '\r' && b[i+1] == '\n' -} - -// Check if the character is a line break or NUL. -func is_breakz(b []byte, i int) bool { - //return is_break(b, i) || is_z(b, i) - return ( // is_break: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - // is_z: - b[i] == 0) -} - -// Check if the character is a line break, space, or NUL. -func is_spacez(b []byte, i int) bool { - //return is_space(b, i) || is_breakz(b, i) - return ( // is_space: - b[i] == ' ' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Check if the character is a line break, space, tab, or NUL. -func is_blankz(b []byte, i int) bool { - //return is_blank(b, i) || is_breakz(b, i) - return ( // is_blank: - b[i] == ' ' || b[i] == '\t' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Determine the width of the character. -func width(b byte) int { - // Don't replace these by a switch without first - // confirming that it is being inlined. - if b&0x80 == 0x00 { - return 1 - } - if b&0xE0 == 0xC0 { - return 2 - } - if b&0xF0 == 0xE0 { - return 3 - } - if b&0xF8 == 0xF0 { - return 4 - } - return 0 - -}