From 9ff66c42832654fea9629e0aefbfcf731a757179 Mon Sep 17 00:00:00 2001 From: Riley Karson Date: Thu, 28 Feb 2019 16:33:44 -0800 Subject: [PATCH] Revert the 0.12 SDK (#3158) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We aren't ready to release a `0.12` SDK based build because of these issues: • https://github.com/hashicorp/terraform/issues/20505 • https://github.com/hashicorp/terraform/issues/20507 • https://github.com/hashicorp/terraform/issues/20506 • https://github.com/hashicorp/terraform/issues/20504 --- go.mod | 32 +- go.sum | 269 +- vendor/cloud.google.com/go/bigtable/admin.go | 10 +- .../cloud.google.com/go/bigtable/bigtable.go | 2 +- .../go/bigtable/internal/gax/call_option.go | 2 +- .../go/bigtable/internal/gax/invoke.go | 2 +- .../go/compute/metadata/metadata.go | 24 +- vendor/cloud.google.com/go/iam/iam.go | 25 +- .../go/longrunning/autogen/doc.go | 6 +- .../longrunning/autogen/operations_client.go | 6 +- .../go/longrunning/longrunning.go | 2 +- .../github.com/agext/levenshtein/.gitignore | 51 - .../github.com/agext/levenshtein/.travis.yml | 85 +- vendor/github.com/agext/levenshtein/README.md | 2 +- vendor/github.com/agext/levenshtein/go.mod | 1 - vendor/github.com/agext/levenshtein/test.sh | 10 - vendor/github.com/armon/go-radix/go.mod | 1 - .../aws/aws-sdk-go/aws/endpoints/defaults.go | 290 +- .../github.com/aws/aws-sdk-go/aws/version.go | 2 +- .../github.com/googleapis/gax-go/.gitignore | 1 + .../github.com/googleapis/gax-go/.travis.yml | 12 + .../googleapis/gax-go/CODE_OF_CONDUCT.md | 43 + .../googleapis/gax-go/CONTRIBUTING.md | 27 + .../googleapis/gax-go/{v2 => }/LICENSE | 0 vendor/github.com/googleapis/gax-go/README.md | 29 + .../googleapis/gax-go/{v2 => }/call_option.go | 12 +- .../googleapis/gax-go/{v2 => }/gax.go | 3 +- vendor/github.com/googleapis/gax-go/header.go | 24 + .../googleapis/gax-go/{v2 => }/invoke.go | 12 +- vendor/github.com/googleapis/gax-go/v2/go.mod | 3 - vendor/github.com/googleapis/gax-go/v2/go.sum | 26 - .../github.com/googleapis/gax-go/v2/header.go | 53 - .../hashicorp/go-getter/.travis.yml | 4 - .../github.com/hashicorp/go-getter/README.md | 3 - .../hashicorp/go-getter/appveyor.yml | 2 +- .../hashicorp/go-getter/checksum.go | 30 +- .../github.com/hashicorp/go-getter/common.go | 1 - .../hashicorp/go-getter/get_file.go | 4 +- .../hashicorp/go-getter/get_file_windows.go | 17 +- .../github.com/hashicorp/go-getter/get_git.go | 58 +- .../hashicorp/go-getter/get_http.go | 4 +- vendor/github.com/hashicorp/go-getter/go.mod | 2 +- vendor/github.com/hashicorp/go-getter/go.sum | 2 - .../go-getter/helper/url/url_windows.go | 15 +- .../github.com/hashicorp/go-plugin/client.go | 46 +- vendor/github.com/hashicorp/go-plugin/go.mod | 4 - vendor/github.com/hashicorp/go-plugin/go.sum | 13 - .../hashicorp/go-plugin/grpc_broker.go | 38 +- .../hashicorp/go-plugin/grpc_client.go | 8 +- .../hashicorp/go-plugin/grpc_controller.go | 6 +- .../hashicorp/go-plugin/grpc_server.go | 6 +- .../internal/{plugin => proto}/gen.go | 2 +- .../{plugin => proto}/grpc_broker.pb.go | 30 +- .../{plugin => proto}/grpc_broker.proto | 3 +- .../{plugin => proto}/grpc_controller.pb.go | 22 +- .../{plugin => proto}/grpc_controller.proto | 3 +- .../hashicorp/go-plugin/log_entry.go | 4 +- .../github.com/hashicorp/go-plugin/testing.go | 6 +- .../hashicorp/hcl2/ext/dynblock/README.md | 184 - .../hcl2/ext/dynblock/expand_body.go | 252 -- .../hcl2/ext/dynblock/expand_spec.go | 215 - .../hashicorp/hcl2/ext/dynblock/expr_wrap.go | 42 - .../hashicorp/hcl2/ext/dynblock/iteration.go | 66 - .../hashicorp/hcl2/ext/dynblock/public.go | 44 - .../hashicorp/hcl2/ext/dynblock/schema.go | 50 - .../hashicorp/hcl2/ext/dynblock/variables.go | 165 - .../hcl2/ext/dynblock/variables_hcldec.go | 33 - .../hashicorp/hcl2/ext/typeexpr/README.md | 67 - .../hashicorp/hcl2/ext/typeexpr/doc.go | 11 - .../hashicorp/hcl2/ext/typeexpr/get_type.go | 196 - .../hashicorp/hcl2/ext/typeexpr/public.go | 129 - .../hcl2/hcl/hclsyntax/expression.go | 37 +- .../hashicorp/hcl2/hcl/hclsyntax/parser.go | 51 +- .../hcl2/hcl/hclsyntax/scan_string_lit.go | 24 +- .../hcl2/hcl/hclsyntax/scan_tokens.go | 878 +++-- .../hcl2/hcl/hclsyntax/scan_tokens.rl | 8 +- .../hashicorp/hcl2/hcl/hclsyntax/spec.md | 128 +- .../hashicorp/hcl2/hcl/hclsyntax/structure.go | 4 +- .../hashicorp/hcl2/hcl/hclsyntax/token.go | 39 +- .../hcl2/hcl/hclsyntax/token_type_string.go | 97 +- .../hashicorp/hcl2/hcl/json/parser.go | 13 +- .../hashicorp/hcl2/hcl/json/spec.md | 14 +- vendor/github.com/hashicorp/hcl2/hcl/ops.go | 119 - vendor/github.com/hashicorp/hcl2/hcl/spec.md | 90 +- .../hashicorp/hcl2/hcl/traversal.go | 61 +- vendor/github.com/hashicorp/hcl2/hcled/doc.go | 4 - .../hashicorp/hcl2/hcled/navigation.go | 34 - .../hashicorp/hcl2/hclwrite/format.go | 4 - vendor/github.com/hashicorp/hil/convert.go | 19 +- vendor/github.com/hashicorp/hil/go.mod | 6 - vendor/github.com/hashicorp/hil/go.sum | 4 - .../terraform-config-inspect/LICENSE | 353 -- .../tfconfig/diagnostic.go | 138 - .../terraform-config-inspect/tfconfig/doc.go | 21 - .../terraform-config-inspect/tfconfig/load.go | 130 - .../tfconfig/load_hcl.go | 312 -- .../tfconfig/load_legacy.go | 322 -- .../tfconfig/module.go | 35 - .../tfconfig/module_call.go | 11 - .../tfconfig/output.go | 9 - .../tfconfig/provider_ref.go | 9 - .../tfconfig/resource.go | 64 - .../tfconfig/schema.go | 106 - .../tfconfig/source_pos.go | 50 - .../tfconfig/variable.go | 16 - .../hashicorp/terraform/addrs/count_attr.go | 12 - .../hashicorp/terraform/addrs/doc.go | 17 - .../terraform/addrs/input_variable.go | 41 - .../hashicorp/terraform/addrs/instance_key.go | 123 - .../hashicorp/terraform/addrs/local_value.go | 48 - .../hashicorp/terraform/addrs/module.go | 75 - .../hashicorp/terraform/addrs/module_call.go | 81 - .../terraform/addrs/module_instance.go | 415 -- .../hashicorp/terraform/addrs/output_value.go | 75 - .../hashicorp/terraform/addrs/parse_ref.go | 338 -- .../hashicorp/terraform/addrs/parse_target.go | 318 -- .../hashicorp/terraform/addrs/path_attr.go | 12 - .../terraform/addrs/provider_config.go | 297 -- .../terraform/addrs/referenceable.go | 20 - .../hashicorp/terraform/addrs/resource.go | 270 -- .../terraform/addrs/resource_phase.go | 105 - .../terraform/addrs/resourcemode_string.go | 24 - .../hashicorp/terraform/addrs/self.go | 14 - .../hashicorp/terraform/addrs/targetable.go | 26 - .../terraform/addrs/terraform_attr.go | 12 - .../terraform/command/format/diagnostic.go | 304 -- .../terraform/command/format/diff.go | 1088 ------ .../terraform/command/format/format.go | 8 - .../terraform/command/format/object_id.go | 123 - .../terraform/command/format/plan.go | 302 -- .../terraform/command/format/state.go | 286 -- .../config/configschema/decoder_spec.go | 97 + .../{configs => config}/configschema/doc.go | 0 .../config/configschema/implied_type.go | 21 + .../configschema/internal_validate.go | 9 - .../configschema/nestingmode_string.go | 0 .../configschema/schema.go | 6 - .../terraform/config/hcl2shim/flatmap.go | 424 -- .../terraform/config/hcl2shim/paths.go | 253 -- .../terraform/config/hcl2shim/values.go | 109 +- .../terraform/config/hcl2shim/values_equiv.go | 214 - .../terraform/config/interpolate_funcs.go | 14 - .../terraform/config/module/storage.go | 4 +- .../hashicorp/terraform/configs/backend.go | 55 - .../terraform/configs/compat_shim.go | 116 - .../hashicorp/terraform/configs/config.go | 205 - .../terraform/configs/config_build.go | 179 - .../terraform/configs/configload/copy_dir.go | 114 - .../terraform/configs/configload/doc.go | 4 - .../terraform/configs/configload/getter.go | 150 - .../terraform/configs/configload/inode.go | 21 - .../configs/configload/inode_freebsd.go | 21 - .../configs/configload/inode_windows.go | 8 - .../terraform/configs/configload/loader.go | 150 - .../configs/configload/loader_load.go | 97 - .../configs/configload/loader_snapshot.go | 504 --- .../configs/configload/module_mgr.go | 76 - .../configs/configload/source_addr.go | 45 - .../terraform/configs/configload/testing.go | 43 - .../configs/configschema/coerce_value.go | 270 -- .../configs/configschema/decoder_spec.go | 109 - .../configs/configschema/implied_type.go | 42 - .../configs/configschema/none_required.go | 38 - .../configschema/validate_traversal.go | 173 - .../hashicorp/terraform/configs/depends_on.go | 23 - .../hashicorp/terraform/configs/doc.go | 19 - .../hashicorp/terraform/configs/module.go | 404 -- .../terraform/configs/module_call.go | 188 - .../terraform/configs/module_merge.go | 247 -- .../terraform/configs/module_merge_body.go | 129 - .../terraform/configs/named_values.go | 364 -- .../hashicorp/terraform/configs/parser.go | 100 - .../terraform/configs/parser_config.go | 247 -- .../terraform/configs/parser_config_dir.go | 142 - .../terraform/configs/parser_values.go | 43 - .../hashicorp/terraform/configs/provider.go | 144 - .../terraform/configs/provisioner.go | 150 - .../configs/provisioneronfailure_string.go | 16 - .../configs/provisionerwhen_string.go | 16 - .../hashicorp/terraform/configs/resource.go | 486 --- .../hashicorp/terraform/configs/synth_body.go | 118 - .../hashicorp/terraform/configs/util.go | 45 - .../terraform/configs/variable_type_hint.go | 45 - .../configs/variabletypehint_string.go | 29 - .../terraform/configs/version_constraint.go | 61 - .../github.com/hashicorp/terraform/dag/dag.go | 10 +- .../hashicorp/terraform/dag/walk.go | 98 +- .../helper/didyoumean/name_suggestion.go | 24 - .../hashicorp/terraform/helper/plugin/doc.go | 6 - .../terraform/helper/plugin/grpc_provider.go | 1299 ------- .../helper/plugin/grpc_provisioner.go | 147 - .../terraform/helper/plugin/unknown.go | 131 - .../helper/resource/grpc_test_provider.go | 43 - .../terraform/helper/resource/state_shim.go | 162 - .../terraform/helper/resource/testing.go | 298 +- .../helper/resource/testing_config.go | 315 +- .../helper/resource/testing_import_state.go | 72 +- .../terraform/helper/schema/backend.go | 140 +- .../terraform/helper/schema/core_schema.go | 162 +- .../helper/schema/field_reader_diff.go | 3 - .../helper/schema/field_reader_map.go | 3 - .../helper/schema/field_writer_map.go | 7 +- .../terraform/helper/schema/provider.go | 22 +- .../terraform/helper/schema/provisioner.go | 10 +- .../terraform/helper/schema/resource.go | 265 +- .../terraform/helper/schema/resource_data.go | 20 - .../helper/schema/resource_timeout.go | 100 +- .../terraform/helper/schema/schema.go | 237 +- .../hashicorp/terraform/helper/schema/set.go | 10 - .../terraform/helper/schema/shims.go | 90 - .../terraform/helper/schema/testing.go | 2 +- .../terraform/helper/validation/validation.go | 54 - .../terraform/internal/earlyconfig/config.go | 123 - .../internal/earlyconfig/config_build.go | 144 - .../internal/earlyconfig/diagnostics.go | 78 - .../terraform/internal/earlyconfig/doc.go | 20 - .../terraform/internal/earlyconfig/module.go | 13 - .../terraform/internal/initwd/copy_dir.go | 114 - .../terraform/internal/initwd/doc.go | 7 - .../terraform/internal/initwd/from_module.go | 363 -- .../terraform/internal/initwd/getter.go | 188 - .../terraform/internal/initwd/inode.go | 21 - .../internal/initwd/inode_freebsd.go | 21 - .../internal/initwd/inode_windows.go | 8 - .../terraform/internal/initwd/load_config.go | 56 - .../internal/initwd/module_install.go | 519 --- .../internal/initwd/module_install_hooks.go | 36 - .../terraform/internal/initwd/testing.go | 73 - .../internal/initwd/version_required.go | 83 - .../terraform/internal/modsdir/doc.go | 3 - .../terraform/internal/modsdir/manifest.go | 138 - .../terraform/internal/modsdir/paths.go | 3 - .../terraform/internal/tfplugin5/generate.sh | 16 - .../internal/tfplugin5/tfplugin5.pb.go | 3451 ----------------- .../internal/tfplugin5/tfplugin5.proto | 350 -- .../hashicorp/terraform/lang/data.go | 33 - .../hashicorp/terraform/lang/doc.go | 5 - .../hashicorp/terraform/lang/eval.go | 470 --- .../hashicorp/terraform/lang/funcs/cidr.go | 129 - .../terraform/lang/funcs/collection.go | 1320 ------- .../terraform/lang/funcs/conversion.go | 87 - .../hashicorp/terraform/lang/funcs/crypto.go | 285 -- .../terraform/lang/funcs/datetime.go | 70 - .../terraform/lang/funcs/encoding.go | 140 - .../terraform/lang/funcs/filesystem.go | 345 -- .../hashicorp/terraform/lang/funcs/number.go | 155 - .../hashicorp/terraform/lang/funcs/string.go | 280 -- .../hashicorp/terraform/lang/functions.go | 146 - .../hashicorp/terraform/lang/references.go | 68 - .../hashicorp/terraform/lang/scope.go | 34 - .../hashicorp/terraform/plans/action.go | 22 - .../terraform/plans/action_string.go | 36 - .../hashicorp/terraform/plans/changes.go | 308 -- .../hashicorp/terraform/plans/changes_src.go | 190 - .../terraform/plans/changes_state.go | 15 - .../hashicorp/terraform/plans/changes_sync.go | 144 - .../hashicorp/terraform/plans/doc.go | 5 - .../terraform/plans/dynamic_value.go | 96 - .../terraform/plans/objchange/all_null.go | 68 - .../terraform/plans/objchange/compatible.go | 376 -- .../terraform/plans/objchange/doc.go | 4 - .../terraform/plans/objchange/lcs.go | 104 - .../terraform/plans/objchange/objchange.go | 383 -- .../terraform/plans/objchange/plan_valid.go | 267 -- .../hashicorp/terraform/plans/plan.go | 92 - .../hashicorp/terraform/plugin/client.go | 12 +- .../terraform/plugin/convert/diagnostics.go | 132 - .../terraform/plugin/convert/schema.go | 122 - .../terraform/plugin/discovery/error.go | 10 - .../terraform/plugin/discovery/get.go | 610 ++- .../plugin/discovery/requirements.go | 6 - .../terraform/plugin/discovery/signature.go | 39 +- .../terraform/plugin/discovery/version.go | 5 - .../terraform/plugin/discovery/version_set.go | 5 - .../terraform/plugin/grpc_provider.go | 558 --- .../terraform/plugin/grpc_provisioner.go | 178 - .../hashicorp/terraform/plugin/plugin.go | 9 +- .../terraform/plugin/resource_provider.go | 7 +- .../terraform/plugin/resource_provisioner.go | 13 +- .../hashicorp/terraform/plugin/serve.go | 87 +- .../terraform/providers/addressed_types.go | 47 - .../hashicorp/terraform/providers/doc.go | 3 - .../hashicorp/terraform/providers/provider.go | 351 -- .../hashicorp/terraform/providers/resolver.go | 112 - .../hashicorp/terraform/provisioners/doc.go | 3 - .../terraform/provisioners/factory.go | 19 - .../terraform/provisioners/provisioner.go | 82 - .../hashicorp/terraform/registry/client.go | 156 +- .../hashicorp/terraform/registry/errors.go | 25 - .../registry/regsrc/terraform_provider.go | 60 - .../terraform/registry/response/provider.go | 36 - .../registry/response/provider_list.go | 7 - .../registry/response/terraform_provider.go | 95 - .../hashicorp/terraform/states/doc.go | 3 - .../terraform/states/eachmode_string.go | 26 - .../terraform/states/instance_generation.go | 24 - .../terraform/states/instance_object.go | 120 - .../terraform/states/instance_object_src.go | 113 - .../hashicorp/terraform/states/module.go | 285 -- .../terraform/states/objectstatus_string.go | 24 - .../terraform/states/output_value.go | 14 - .../hashicorp/terraform/states/resource.go | 239 -- .../hashicorp/terraform/states/state.go | 229 -- .../terraform/states/state_deepcopy.go | 218 -- .../hashicorp/terraform/states/state_equal.go | 18 - .../terraform/states/state_filter.go | 180 - .../terraform/states/state_string.go | 279 -- .../terraform/states/statefile/diagnostics.go | 62 - .../terraform/states/statefile/doc.go | 3 - .../terraform/states/statefile/file.go | 62 - .../states/statefile/marshal_equal.go | 40 - .../terraform/states/statefile/read.go | 209 - .../terraform/states/statefile/version0.go | 23 - .../terraform/states/statefile/version1.go | 174 - .../states/statefile/version1_upgrade.go | 172 - .../terraform/states/statefile/version2.go | 209 - .../states/statefile/version2_upgrade.go | 145 - .../terraform/states/statefile/version3.go | 50 - .../states/statefile/version3_upgrade.go | 415 -- .../terraform/states/statefile/version4.go | 604 --- .../terraform/states/statefile/write.go | 12 - .../hashicorp/terraform/states/sync.go | 537 --- .../terraform/svchost/disco/disco.go | 174 +- .../hashicorp/terraform/svchost/disco/host.go | 265 +- .../hashicorp/terraform/terraform/context.go | 783 ++-- .../terraform/terraform/context_components.go | 19 +- .../terraform/terraform/context_graph_type.go | 4 +- .../terraform/terraform/context_import.go | 56 +- .../terraform/terraform/context_input.go | 248 -- .../hashicorp/terraform/terraform/debug.go | 523 +++ .../hashicorp/terraform/terraform/diff.go | 527 +-- .../hashicorp/terraform/terraform/eval.go | 17 +- .../terraform/terraform/eval_apply.go | 603 +-- .../terraform/eval_check_prevent_destroy.go | 39 +- .../terraform/terraform/eval_context.go | 114 +- .../terraform/eval_context_builtin.go | 294 +- .../terraform/terraform/eval_context_mock.go | 255 +- .../terraform/terraform/eval_count.go | 157 +- .../terraform/eval_count_boundary.go | 95 +- .../terraform/terraform/eval_diff.go | 908 ++--- .../terraform/terraform/eval_import_state.go | 65 +- .../terraform/terraform/eval_interpolate.go | 56 + .../terraform/terraform/eval_lang.go | 61 - .../terraform/terraform/eval_local.go | 86 +- .../terraform/terraform/eval_output.go | 173 +- .../terraform/terraform/eval_provider.go | 174 +- .../terraform/terraform/eval_provisioner.go | 10 +- .../terraform/terraform/eval_read_data.go | 499 +-- .../terraform/terraform/eval_refresh.go | 79 +- .../terraform/terraform/eval_resource.go | 13 + .../terraform/terraform/eval_sequence.go | 19 +- .../terraform/terraform/eval_state.go | 550 +-- .../terraform/terraform/eval_state_upgrade.go | 104 - .../terraform/terraform/eval_validate.go | 592 +-- .../terraform/eval_validate_selfref.go | 105 +- .../terraform/terraform/eval_variable.go | 217 +- .../terraform/terraform/evaltree_provider.go | 70 +- .../hashicorp/terraform/terraform/evaluate.go | 916 ----- .../terraform/terraform/evaluate_valid.go | 299 -- .../hashicorp/terraform/terraform/graph.go | 97 +- .../terraform/terraform/graph_builder.go | 40 +- .../terraform/graph_builder_apply.go | 116 +- .../terraform/graph_builder_destroy_plan.go | 58 +- .../terraform/terraform/graph_builder_eval.go | 108 - .../terraform/graph_builder_import.go | 48 +- .../terraform/graph_builder_input.go | 27 + .../terraform/terraform/graph_builder_plan.go | 99 +- .../terraform/graph_builder_refresh.go | 89 +- .../terraform/graph_builder_validate.go | 4 +- .../terraform/graph_interface_subgraph.go | 6 +- .../terraform/terraform/graph_walk.go | 48 +- .../terraform/terraform/graph_walk_context.go | 157 +- .../terraform/graph_walk_operation.go | 2 +- .../terraform/terraform/graphtype_string.go | 4 +- .../hashicorp/terraform/terraform/hook.go | 108 +- .../terraform/terraform/hook_mock.go | 269 +- .../terraform/terraform/hook_stop.go | 41 +- .../terraform/terraform/interpolate.go | 86 +- .../terraform/module_dependencies.go | 139 +- .../terraform/node_count_boundary.go | 18 +- .../terraform/terraform/node_data_destroy.go | 42 +- .../terraform/terraform/node_data_refresh.go | 232 +- .../terraform/terraform/node_local.go | 68 +- .../terraform/node_module_removed.go | 88 +- .../terraform/node_module_variable.go | 164 +- .../terraform/terraform/node_output.go | 185 +- .../terraform/terraform/node_output_orphan.go | 32 +- .../terraform/node_provider_abstract.go | 59 +- .../terraform/node_provider_disabled.go | 29 +- .../terraform/terraform/node_provider_eval.go | 20 - .../terraform/terraform/node_provisioner.go | 15 +- .../terraform/node_resource_abstract.go | 457 +-- .../terraform/node_resource_abstract_count.go | 50 + .../terraform/node_resource_apply.go | 421 +- .../terraform/node_resource_apply_instance.go | 411 -- .../terraform/node_resource_destroy.go | 356 +- .../node_resource_destroy_deposed.go | 313 -- .../terraform/terraform/node_resource_plan.go | 108 +- .../terraform/node_resource_plan_destroy.go | 91 +- .../terraform/node_resource_plan_instance.go | 229 +- .../terraform/node_resource_plan_orphan.go | 86 +- .../terraform/node_resource_refresh.go | 241 +- .../terraform/node_resource_validate.go | 184 +- .../terraform/terraform/node_root_variable.go | 38 +- .../hashicorp/terraform/terraform/path.go | 15 +- .../hashicorp/terraform/terraform/plan.go | 130 +- .../terraform/terraform/provider_mock.go | 496 --- .../terraform/terraform/provisioner_mock.go | 154 - .../hashicorp/terraform/terraform/resource.go | 222 +- .../terraform/terraform/resource_address.go | 175 +- .../terraform/terraform/resource_provider.go | 55 +- .../terraform/resource_provisioner.go | 16 - .../terraform/resource_provisioner_mock.go | 17 +- .../hashicorp/terraform/terraform/schemas.go | 256 +- .../terraform/terraform/semantics.go | 132 + .../hashicorp/terraform/terraform/state.go | 421 +- .../terraform/terraform/state_add.go | 374 ++ .../terraform/terraform/transform.go | 11 +- .../transform_attach_config_provider.go | 7 +- .../transform_attach_config_resource.go | 56 +- .../terraform/transform_attach_schema.go | 99 - .../terraform/transform_attach_state.go | 56 +- .../terraform/terraform/transform_config.go | 78 +- .../terraform/transform_config_flat.go | 49 +- .../terraform/transform_count_boundary.go | 9 +- .../terraform/terraform/transform_deposed.go | 178 + .../terraform/transform_destroy_cbd.go | 185 +- .../terraform/transform_destroy_edge.go | 108 +- .../terraform/terraform/transform_diff.go | 228 +- .../terraform/transform_import_provider.go | 22 +- .../terraform/transform_import_state.go | 203 +- .../terraform/terraform/transform_local.go | 30 +- .../terraform/transform_module_variable.go | 152 +- .../terraform/transform_orphan_count.go | 153 +- .../terraform/transform_orphan_output.go | 31 +- .../terraform/transform_orphan_resource.go | 171 +- .../terraform/terraform/transform_output.go | 42 +- .../terraform/terraform/transform_provider.go | 491 +-- .../terraform/transform_provisioner.go | 23 +- .../terraform/transform_reference.go | 354 +- .../terraform/transform_removed_modules.go | 17 +- .../terraform/transform_resource_count.go | 45 +- .../terraform/terraform/transform_state.go | 87 +- .../terraform/terraform/transform_targets.go | 81 +- .../terraform/terraform/transform_variable.go | 22 +- .../terraform/ui_output_provisioner.go | 12 +- .../terraform/valuesourcetype_string.go | 44 - .../terraform/terraform/variables.go | 433 +-- .../terraform/terraform/version_required.go | 101 +- .../terraform/walkoperation_string.go | 4 +- .../terraform/tfdiags/config_traversals.go | 68 - .../hashicorp/terraform/tfdiags/contextual.go | 372 -- .../hashicorp/terraform/tfdiags/diagnostic.go | 14 - .../terraform/tfdiags/diagnostic_base.go | 31 - .../terraform/tfdiags/diagnostics.go | 149 - .../hashicorp/terraform/tfdiags/error.go | 7 +- .../hashicorp/terraform/tfdiags/hcl.go | 10 - .../terraform/tfdiags/rpc_friendly.go | 6 - .../terraform/tfdiags/simple_warning.go | 7 +- .../hashicorp/terraform/tfdiags/sourceless.go | 13 - .../hashicorp/terraform/version/version.go | 8 +- .../mattn/go-colorable/colorable_windows.go | 210 +- vendor/github.com/mattn/go-colorable/go.mod | 3 - vendor/github.com/mattn/go-colorable/go.sum | 4 - vendor/github.com/mattn/go-isatty/go.mod | 3 - vendor/github.com/mattn/go-isatty/go.sum | 2 - .../mattn/go-isatty/isatty_appengine.go | 15 + .../github.com/mattn/go-isatty/isatty_bsd.go | 6 - .../mattn/go-isatty/isatty_linux.go | 20 +- .../mattn/go-isatty/isatty_linux_ppc64x.go | 19 + .../mattn/go-isatty/isatty_others.go | 11 +- .../mattn/go-isatty/isatty_solaris.go | 6 - .../mitchellh/colorstring/.travis.yml | 15 - .../github.com/mitchellh/colorstring/LICENSE | 21 - .../mitchellh/colorstring/README.md | 30 - .../mitchellh/colorstring/colorstring.go | 244 -- .../github.com/mitchellh/colorstring/go.mod | 1 - .../github.com/mitchellh/go-wordwrap/go.mod | 1 - vendor/github.com/posener/complete/.gitignore | 2 - .../github.com/posener/complete/.travis.yml | 7 +- vendor/github.com/posener/complete/args.go | 9 - vendor/github.com/posener/complete/cmd/cmd.go | 2 +- .../posener/complete/cmd/install/fish.go | 18 +- .../posener/complete/cmd/install/install.go | 2 +- .../posener/complete/cmd/install/utils.go | 5 +- .../github.com/posener/complete/complete.go | 30 +- vendor/github.com/posener/complete/go.mod | 3 - vendor/github.com/posener/complete/go.sum | 4 - vendor/github.com/posener/complete/log.go | 3 +- .../posener/complete/metalinter.json | 21 + vendor/github.com/posener/complete/readme.md | 1 - vendor/github.com/spf13/afero/.travis.yml | 21 - vendor/github.com/spf13/afero/LICENSE.txt | 174 - vendor/github.com/spf13/afero/README.md | 452 --- vendor/github.com/spf13/afero/afero.go | 108 - vendor/github.com/spf13/afero/appveyor.yml | 15 - vendor/github.com/spf13/afero/basepath.go | 180 - .../github.com/spf13/afero/cacheOnReadFs.go | 290 -- vendor/github.com/spf13/afero/const_bsds.go | 22 - .../github.com/spf13/afero/const_win_unix.go | 25 - .../github.com/spf13/afero/copyOnWriteFs.go | 293 -- vendor/github.com/spf13/afero/go.mod | 3 - vendor/github.com/spf13/afero/go.sum | 2 - vendor/github.com/spf13/afero/httpFs.go | 110 - vendor/github.com/spf13/afero/ioutil.go | 230 -- vendor/github.com/spf13/afero/lstater.go | 27 - vendor/github.com/spf13/afero/match.go | 110 - vendor/github.com/spf13/afero/mem/dir.go | 37 - vendor/github.com/spf13/afero/mem/dirmap.go | 43 - vendor/github.com/spf13/afero/mem/file.go | 317 -- vendor/github.com/spf13/afero/memmap.go | 365 -- vendor/github.com/spf13/afero/os.go | 101 - vendor/github.com/spf13/afero/path.go | 106 - vendor/github.com/spf13/afero/readonlyfs.go | 80 - vendor/github.com/spf13/afero/regexpfs.go | 214 - vendor/github.com/spf13/afero/unionFile.go | 316 -- vendor/github.com/spf13/afero/util.go | 330 -- .../vmihailenco/msgpack/.travis.yml | 17 - .../vmihailenco/msgpack/CHANGELOG.md | 24 - vendor/github.com/vmihailenco/msgpack/LICENSE | 25 - .../github.com/vmihailenco/msgpack/Makefile | 5 - .../github.com/vmihailenco/msgpack/README.md | 69 - .../vmihailenco/msgpack/appengine.go | 64 - .../vmihailenco/msgpack/codes/codes.go | 86 - .../github.com/vmihailenco/msgpack/decode.go | 546 --- .../vmihailenco/msgpack/decode_map.go | 338 -- .../vmihailenco/msgpack/decode_number.go | 307 -- .../vmihailenco/msgpack/decode_query.go | 158 - .../vmihailenco/msgpack/decode_slice.go | 193 - .../vmihailenco/msgpack/decode_string.go | 175 - .../vmihailenco/msgpack/decode_value.go | 234 -- .../github.com/vmihailenco/msgpack/encode.go | 170 - .../vmihailenco/msgpack/encode_map.go | 172 - .../vmihailenco/msgpack/encode_number.go | 230 -- .../vmihailenco/msgpack/encode_slice.go | 124 - .../vmihailenco/msgpack/encode_value.go | 167 - vendor/github.com/vmihailenco/msgpack/ext.go | 238 -- .../github.com/vmihailenco/msgpack/msgpack.go | 17 - vendor/github.com/vmihailenco/msgpack/tag.go | 42 - vendor/github.com/vmihailenco/msgpack/time.go | 145 - .../github.com/vmihailenco/msgpack/types.go | 310 -- .../cty/convert/conversion_primitive.go | 6 +- .../zclconf/go-cty/cty/json/unmarshal.go | 2 +- .../zclconf/go-cty/cty/msgpack/doc.go | 14 - .../zclconf/go-cty/cty/msgpack/dynamic.go | 31 - .../zclconf/go-cty/cty/msgpack/infinity.go | 8 - .../zclconf/go-cty/cty/msgpack/marshal.go | 207 - .../go-cty/cty/msgpack/type_implied.go | 167 - .../zclconf/go-cty/cty/msgpack/unknown.go | 16 - .../zclconf/go-cty/cty/msgpack/unmarshal.go | 334 -- vendor/github.com/zclconf/go-cty/cty/path.go | 10 +- .../zclconf/go-cty/cty/type_conform.go | 29 +- .../zclconf/go-cty/cty/value_init.go | 26 - vendor/golang.org/x/crypto/blowfish/cipher.go | 8 - vendor/golang.org/x/crypto/cast5/cast5.go | 11 +- .../x/crypto/curve25519/curve25519.go | 2 +- .../x/crypto/internal/chacha20/asm_arm64.s | 308 -- .../crypto/internal/chacha20/chacha_arm64.go | 31 - .../crypto/internal/chacha20/chacha_noasm.go | 2 +- vendor/golang.org/x/net/html/atom/atom.go | 78 + vendor/golang.org/x/net/html/atom/gen.go | 712 ++++ vendor/golang.org/x/net/html/atom/table.go | 783 ++++ vendor/golang.org/x/net/html/const.go | 112 + vendor/golang.org/x/net/html/doc.go | 106 + vendor/golang.org/x/net/html/doctype.go | 156 + vendor/golang.org/x/net/html/entity.go | 2253 +++++++++++ vendor/golang.org/x/net/html/escape.go | 258 ++ vendor/golang.org/x/net/html/foreign.go | 226 ++ vendor/golang.org/x/net/html/node.go | 220 ++ vendor/golang.org/x/net/html/parse.go | 2311 +++++++++++ vendor/golang.org/x/net/html/render.go | 271 ++ vendor/golang.org/x/net/html/token.go | 1219 ++++++ vendor/golang.org/x/oauth2/README.md | 51 + vendor/golang.org/x/oauth2/go.mod | 10 - vendor/golang.org/x/oauth2/go.sum | 12 - vendor/golang.org/x/oauth2/google/google.go | 5 +- vendor/golang.org/x/oauth2/internal/token.go | 215 +- vendor/golang.org/x/oauth2/jwt/jwt.go | 8 - vendor/golang.org/x/oauth2/oauth2.go | 47 +- vendor/golang.org/x/oauth2/token.go | 7 +- vendor/golang.org/x/sys/unix/README.md | 16 +- vendor/golang.org/x/sys/unix/mkall.sh | 2 +- vendor/golang.org/x/sys/unix/mkerrors.sh | 11 +- vendor/golang.org/x/sys/unix/mksyscall.go | 4 - .../x/sys/unix/mksyscall_solaris.go | 335 -- .../x/sys/unix/mksyscall_solaris.pl | 294 ++ vendor/golang.org/x/sys/unix/syscall_aix.go | 2 +- .../golang.org/x/sys/unix/syscall_darwin.go | 1 - vendor/golang.org/x/sys/unix/syscall_linux.go | 27 - .../x/sys/unix/zerrors_linux_386.go | 17 +- .../x/sys/unix/zerrors_linux_amd64.go | 17 +- .../x/sys/unix/zerrors_linux_arm.go | 17 +- .../x/sys/unix/zerrors_linux_arm64.go | 17 +- .../x/sys/unix/zerrors_linux_mips.go | 17 +- .../x/sys/unix/zerrors_linux_mips64.go | 17 +- .../x/sys/unix/zerrors_linux_mips64le.go | 17 +- .../x/sys/unix/zerrors_linux_mipsle.go | 17 +- .../x/sys/unix/zerrors_linux_ppc64.go | 17 +- .../x/sys/unix/zerrors_linux_ppc64le.go | 17 +- .../x/sys/unix/zerrors_linux_riscv64.go | 17 +- .../x/sys/unix/zerrors_linux_s390x.go | 17 +- .../x/sys/unix/zerrors_linux_sparc64.go | 17 +- .../x/sys/unix/zsyscall_darwin_amd64.go | 15 - .../x/sys/unix/zsyscall_darwin_amd64.s | 2 - .../x/sys/unix/zsyscall_solaris_amd64.go | 2 +- .../x/sys/unix/zsysnum_darwin_amd64.go | 6 +- .../x/sys/unix/zsysnum_freebsd_arm64.go | 2 +- .../x/sys/unix/zsysnum_netbsd_arm64.go | 2 +- .../golang.org/x/sys/unix/ztypes_linux_386.go | 47 +- .../x/sys/unix/ztypes_linux_amd64.go | 47 +- .../golang.org/x/sys/unix/ztypes_linux_arm.go | 47 +- .../x/sys/unix/ztypes_linux_arm64.go | 47 +- .../x/sys/unix/ztypes_linux_mips.go | 47 +- .../x/sys/unix/ztypes_linux_mips64.go | 47 +- .../x/sys/unix/ztypes_linux_mips64le.go | 47 +- .../x/sys/unix/ztypes_linux_mipsle.go | 47 +- .../x/sys/unix/ztypes_linux_ppc64.go | 47 +- .../x/sys/unix/ztypes_linux_ppc64le.go | 47 +- .../x/sys/unix/ztypes_linux_riscv64.go | 47 +- .../x/sys/unix/ztypes_linux_s390x.go | 47 +- .../x/sys/unix/ztypes_linux_sparc64.go | 47 +- vendor/golang.org/x/text/unicode/bidi/bidi.go | 2 +- .../golang.org/x/text/unicode/bidi/bracket.go | 2 +- vendor/golang.org/x/text/unicode/bidi/core.go | 2 +- vendor/golang.org/x/text/unicode/bidi/gen.go | 2 +- .../x/text/unicode/bidi/gen_ranges.go | 2 +- .../x/text/unicode/norm/composition.go | 4 +- .../x/text/unicode/norm/forminfo.go | 14 - .../x/text/unicode/norm/maketables.go | 20 +- .../x/text/unicode/norm/normalize.go | 4 +- .../x/text/unicode/norm/tables10.0.0.go | 1890 +++++---- .../x/text/unicode/norm/tables9.0.0.go | 1890 +++++---- .../api/appengine/v1/appengine-api.json | 6 +- .../api/appengine/v1/appengine-gen.go | 4 - .../api/bigquery/v2/bigquery-api.json | 29 +- .../api/bigquery/v2/bigquery-gen.go | 41 +- .../api/composer/v1beta1/composer-api.json | 6 +- .../api/composer/v1beta1/composer-gen.go | 20 +- .../api/logging/v2/logging-api.json | 4 +- .../api/logging/v2/logging-gen.go | 7 +- .../api/pubsub/v1/pubsub-api.json | 4 +- .../api/pubsub/v1/pubsub-gen.go | 9 +- .../api/serviceusage/v1/serviceusage-api.json | 8 +- .../api/serviceusage/v1/serviceusage-gen.go | 32 +- .../google.golang.org/appengine/appengine.go | 6 - .../appengine/datastore/datastore.go | 407 -- .../appengine/datastore/doc.go | 361 -- .../appengine/datastore/key.go | 396 -- .../appengine/datastore/load.go | 429 -- .../appengine/datastore/metadata.go | 78 - .../appengine/datastore/prop.go | 330 -- .../appengine/datastore/query.go | 757 ---- .../appengine/datastore/save.go | 333 -- .../appengine/datastore/transaction.go | 96 - .../appengine/internal/api.go | 5 +- .../appengine/internal/identity.go | 12 +- .../appengine/internal/main.go | 1 - .../appengine/internal/main_common.go | 7 - .../appengine/internal/main_vm.go | 21 - .../grpc/balancer/balancer.go | 13 - .../grpc/balancer/base/balancer.go | 47 +- .../grpc/balancer_conn_wrappers.go | 22 - .../grpc/balancer_v1_wrapper.go | 6 +- vendor/google.golang.org/grpc/clientconn.go | 499 +-- vendor/google.golang.org/grpc/dialoptions.go | 24 +- .../google.golang.org/grpc/health/server.go | 40 - .../grpc/internal/channelz/funcs.go | 89 +- .../grpc/internal/envconfig/envconfig.go | 3 +- .../grpc/internal/internal.go | 13 +- .../grpc/internal/transport/http2_client.go | 15 +- .../grpc/internal/transport/transport.go | 62 +- .../grpc/keepalive/keepalive.go | 2 +- .../grpc/resolver_conn_wrapper.go | 2 +- vendor/google.golang.org/grpc/rpc_util.go | 27 +- vendor/google.golang.org/grpc/stream.go | 5 +- .../grpc/test/bufconn/bufconn.go | 244 -- vendor/google.golang.org/grpc/version.go | 2 +- vendor/google.golang.org/grpc/vet.sh | 7 +- vendor/modules.txt | 123 +- 679 files changed, 21445 insertions(+), 68391 deletions(-) delete mode 100644 vendor/github.com/agext/levenshtein/go.mod delete mode 100644 vendor/github.com/agext/levenshtein/test.sh delete mode 100644 vendor/github.com/armon/go-radix/go.mod create mode 100644 vendor/github.com/googleapis/gax-go/.gitignore create mode 100644 vendor/github.com/googleapis/gax-go/.travis.yml create mode 100644 vendor/github.com/googleapis/gax-go/CODE_OF_CONDUCT.md create mode 100644 vendor/github.com/googleapis/gax-go/CONTRIBUTING.md rename vendor/github.com/googleapis/gax-go/{v2 => }/LICENSE (100%) create mode 100644 vendor/github.com/googleapis/gax-go/README.md rename vendor/github.com/googleapis/gax-go/{v2 => }/call_option.go (90%) rename vendor/github.com/googleapis/gax-go/{v2 => }/gax.go (96%) create mode 100644 vendor/github.com/googleapis/gax-go/header.go rename vendor/github.com/googleapis/gax-go/{v2 => }/invoke.go (83%) delete mode 100644 vendor/github.com/googleapis/gax-go/v2/go.mod delete mode 100644 vendor/github.com/googleapis/gax-go/v2/go.sum delete mode 100644 vendor/github.com/googleapis/gax-go/v2/header.go rename vendor/github.com/hashicorp/go-plugin/internal/{plugin => proto}/gen.go (86%) rename vendor/github.com/hashicorp/go-plugin/internal/{plugin => proto}/grpc_broker.pb.go (82%) rename vendor/github.com/hashicorp/go-plugin/internal/{plugin => proto}/grpc_broker.proto (81%) rename vendor/github.com/hashicorp/go-plugin/internal/{plugin => proto}/grpc_controller.pb.go (84%) rename vendor/github.com/hashicorp/go-plugin/internal/{plugin => proto}/grpc_controller.proto (80%) delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/README.md delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/expand_body.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/expand_spec.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/expr_wrap.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/iteration.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/public.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/schema.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/variables.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/dynblock/variables_hcldec.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/typeexpr/README.md delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/typeexpr/doc.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/typeexpr/get_type.go delete mode 100644 vendor/github.com/hashicorp/hcl2/ext/typeexpr/public.go delete mode 100644 vendor/github.com/hashicorp/hcl2/hcled/doc.go delete mode 100644 vendor/github.com/hashicorp/hcl2/hcled/navigation.go delete mode 100644 vendor/github.com/hashicorp/hil/go.mod delete mode 100644 vendor/github.com/hashicorp/hil/go.sum delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/LICENSE delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/diagnostic.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_hcl.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module_call.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/output.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/resource.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/schema.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/source_pos.go delete mode 100644 vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/variable.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/count_attr.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/input_variable.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/instance_key.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/local_value.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/module.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/module_call.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/module_instance.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/output_value.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/parse_ref.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/parse_target.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/path_attr.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/provider_config.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/referenceable.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/resource.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/resource_phase.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/resourcemode_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/self.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/targetable.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/terraform_attr.go delete mode 100644 vendor/github.com/hashicorp/terraform/command/format/diagnostic.go delete mode 100644 vendor/github.com/hashicorp/terraform/command/format/diff.go delete mode 100644 vendor/github.com/hashicorp/terraform/command/format/format.go delete mode 100644 vendor/github.com/hashicorp/terraform/command/format/object_id.go delete mode 100644 vendor/github.com/hashicorp/terraform/command/format/plan.go delete mode 100644 vendor/github.com/hashicorp/terraform/command/format/state.go create mode 100644 vendor/github.com/hashicorp/terraform/config/configschema/decoder_spec.go rename vendor/github.com/hashicorp/terraform/{configs => config}/configschema/doc.go (100%) create mode 100644 vendor/github.com/hashicorp/terraform/config/configschema/implied_type.go rename vendor/github.com/hashicorp/terraform/{configs => config}/configschema/internal_validate.go (88%) rename vendor/github.com/hashicorp/terraform/{configs => config}/configschema/nestingmode_string.go (100%) rename vendor/github.com/hashicorp/terraform/{configs => config}/configschema/schema.go (93%) delete mode 100644 vendor/github.com/hashicorp/terraform/config/hcl2shim/flatmap.go delete mode 100644 vendor/github.com/hashicorp/terraform/config/hcl2shim/paths.go delete mode 100644 vendor/github.com/hashicorp/terraform/config/hcl2shim/values_equiv.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/backend.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/compat_shim.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/config.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/config_build.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/copy_dir.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/getter.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/inode.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/inode_freebsd.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/inode_windows.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/loader.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/loader_load.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/loader_snapshot.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/module_mgr.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/source_addr.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configload/testing.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configschema/coerce_value.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configschema/decoder_spec.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configschema/implied_type.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configschema/none_required.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/configschema/validate_traversal.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/depends_on.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/module.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/module_call.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/module_merge.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/module_merge_body.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/named_values.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/parser.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/parser_config.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/parser_config_dir.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/parser_values.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/provisioner.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/provisioneronfailure_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/provisionerwhen_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/resource.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/synth_body.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/util.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/variable_type_hint.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/variabletypehint_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/version_constraint.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/didyoumean/name_suggestion.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/plugin/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/plugin/grpc_provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/plugin/grpc_provisioner.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/plugin/unknown.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/resource/grpc_test_provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/resource/state_shim.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/schema/shims.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/earlyconfig/config.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/earlyconfig/config_build.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/earlyconfig/diagnostics.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/earlyconfig/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/earlyconfig/module.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/copy_dir.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/from_module.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/getter.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/inode.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/inode_freebsd.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/inode_windows.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/load_config.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/module_install.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/module_install_hooks.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/testing.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/initwd/version_required.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/modsdir/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/modsdir/manifest.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/modsdir/paths.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/tfplugin5/generate.sh delete mode 100644 vendor/github.com/hashicorp/terraform/internal/tfplugin5/tfplugin5.pb.go delete mode 100644 vendor/github.com/hashicorp/terraform/internal/tfplugin5/tfplugin5.proto delete mode 100644 vendor/github.com/hashicorp/terraform/lang/data.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/eval.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/cidr.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/collection.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/conversion.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/crypto.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/datetime.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/encoding.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/filesystem.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/number.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/funcs/string.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/functions.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/references.go delete mode 100644 vendor/github.com/hashicorp/terraform/lang/scope.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/action.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/action_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/changes.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/changes_src.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/changes_state.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/changes_sync.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/dynamic_value.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/objchange/all_null.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/objchange/compatible.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/objchange/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/objchange/lcs.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/objchange/objchange.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/objchange/plan_valid.go delete mode 100644 vendor/github.com/hashicorp/terraform/plans/plan.go delete mode 100644 vendor/github.com/hashicorp/terraform/plugin/convert/diagnostics.go delete mode 100644 vendor/github.com/hashicorp/terraform/plugin/convert/schema.go delete mode 100644 vendor/github.com/hashicorp/terraform/plugin/grpc_provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/plugin/grpc_provisioner.go delete mode 100644 vendor/github.com/hashicorp/terraform/providers/addressed_types.go delete mode 100644 vendor/github.com/hashicorp/terraform/providers/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/providers/provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/providers/resolver.go delete mode 100644 vendor/github.com/hashicorp/terraform/provisioners/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/provisioners/factory.go delete mode 100644 vendor/github.com/hashicorp/terraform/provisioners/provisioner.go delete mode 100644 vendor/github.com/hashicorp/terraform/registry/regsrc/terraform_provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/registry/response/provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/registry/response/provider_list.go delete mode 100644 vendor/github.com/hashicorp/terraform/registry/response/terraform_provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/eachmode_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/instance_generation.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/instance_object.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/instance_object_src.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/module.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/objectstatus_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/output_value.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/resource.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/state.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/state_deepcopy.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/state_equal.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/state_filter.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/state_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/diagnostics.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/file.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/marshal_equal.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/read.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/version0.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/version1.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/version1_upgrade.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/version2.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/version2_upgrade.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/version3.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/version3_upgrade.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/version4.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/statefile/write.go delete mode 100644 vendor/github.com/hashicorp/terraform/states/sync.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/context_input.go create mode 100644 vendor/github.com/hashicorp/terraform/terraform/debug.go create mode 100644 vendor/github.com/hashicorp/terraform/terraform/eval_interpolate.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/eval_lang.go create mode 100644 vendor/github.com/hashicorp/terraform/terraform/eval_resource.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/eval_state_upgrade.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/evaluate.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/evaluate_valid.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/graph_builder_eval.go create mode 100644 vendor/github.com/hashicorp/terraform/terraform/graph_builder_input.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/node_provider_eval.go create mode 100644 vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract_count.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/node_resource_apply_instance.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy_deposed.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/provider_mock.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/provisioner_mock.go create mode 100644 vendor/github.com/hashicorp/terraform/terraform/semantics.go create mode 100644 vendor/github.com/hashicorp/terraform/terraform/state_add.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/transform_attach_schema.go create mode 100644 vendor/github.com/hashicorp/terraform/terraform/transform_deposed.go delete mode 100644 vendor/github.com/hashicorp/terraform/terraform/valuesourcetype_string.go delete mode 100644 vendor/github.com/hashicorp/terraform/tfdiags/config_traversals.go delete mode 100644 vendor/github.com/hashicorp/terraform/tfdiags/contextual.go delete mode 100644 vendor/github.com/hashicorp/terraform/tfdiags/diagnostic_base.go delete mode 100644 vendor/github.com/hashicorp/terraform/tfdiags/sourceless.go delete mode 100644 vendor/github.com/mattn/go-colorable/go.mod delete mode 100644 vendor/github.com/mattn/go-colorable/go.sum delete mode 100644 vendor/github.com/mattn/go-isatty/go.mod delete mode 100644 vendor/github.com/mattn/go-isatty/go.sum create mode 100644 vendor/github.com/mattn/go-isatty/isatty_appengine.go create mode 100644 vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go delete mode 100644 vendor/github.com/mitchellh/colorstring/.travis.yml delete mode 100644 vendor/github.com/mitchellh/colorstring/LICENSE delete mode 100644 vendor/github.com/mitchellh/colorstring/README.md delete mode 100644 vendor/github.com/mitchellh/colorstring/colorstring.go delete mode 100644 vendor/github.com/mitchellh/colorstring/go.mod delete mode 100644 vendor/github.com/mitchellh/go-wordwrap/go.mod delete mode 100644 vendor/github.com/posener/complete/go.mod delete mode 100644 vendor/github.com/posener/complete/go.sum create mode 100644 vendor/github.com/posener/complete/metalinter.json delete mode 100644 vendor/github.com/spf13/afero/.travis.yml delete mode 100644 vendor/github.com/spf13/afero/LICENSE.txt delete mode 100644 vendor/github.com/spf13/afero/README.md delete mode 100644 vendor/github.com/spf13/afero/afero.go delete mode 100644 vendor/github.com/spf13/afero/appveyor.yml delete mode 100644 vendor/github.com/spf13/afero/basepath.go delete mode 100644 vendor/github.com/spf13/afero/cacheOnReadFs.go delete mode 100644 vendor/github.com/spf13/afero/const_bsds.go delete mode 100644 vendor/github.com/spf13/afero/const_win_unix.go delete mode 100644 vendor/github.com/spf13/afero/copyOnWriteFs.go delete mode 100644 vendor/github.com/spf13/afero/go.mod delete mode 100644 vendor/github.com/spf13/afero/go.sum delete mode 100644 vendor/github.com/spf13/afero/httpFs.go delete mode 100644 vendor/github.com/spf13/afero/ioutil.go delete mode 100644 vendor/github.com/spf13/afero/lstater.go delete mode 100644 vendor/github.com/spf13/afero/match.go delete mode 100644 vendor/github.com/spf13/afero/mem/dir.go delete mode 100644 vendor/github.com/spf13/afero/mem/dirmap.go delete mode 100644 vendor/github.com/spf13/afero/mem/file.go delete mode 100644 vendor/github.com/spf13/afero/memmap.go delete mode 100644 vendor/github.com/spf13/afero/os.go delete mode 100644 vendor/github.com/spf13/afero/path.go delete mode 100644 vendor/github.com/spf13/afero/readonlyfs.go delete mode 100644 vendor/github.com/spf13/afero/regexpfs.go delete mode 100644 vendor/github.com/spf13/afero/unionFile.go delete mode 100644 vendor/github.com/spf13/afero/util.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/.travis.yml delete mode 100644 vendor/github.com/vmihailenco/msgpack/CHANGELOG.md delete mode 100644 vendor/github.com/vmihailenco/msgpack/LICENSE delete mode 100644 vendor/github.com/vmihailenco/msgpack/Makefile delete mode 100644 vendor/github.com/vmihailenco/msgpack/README.md delete mode 100644 vendor/github.com/vmihailenco/msgpack/appengine.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/codes/codes.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/decode.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/decode_map.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/decode_number.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/decode_query.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/decode_slice.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/decode_string.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/decode_value.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/encode.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/encode_map.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/encode_number.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/encode_slice.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/encode_value.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/ext.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/msgpack.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/tag.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/time.go delete mode 100644 vendor/github.com/vmihailenco/msgpack/types.go delete mode 100644 vendor/github.com/zclconf/go-cty/cty/msgpack/doc.go delete mode 100644 vendor/github.com/zclconf/go-cty/cty/msgpack/dynamic.go delete mode 100644 vendor/github.com/zclconf/go-cty/cty/msgpack/infinity.go delete mode 100644 vendor/github.com/zclconf/go-cty/cty/msgpack/marshal.go delete mode 100644 vendor/github.com/zclconf/go-cty/cty/msgpack/type_implied.go delete mode 100644 vendor/github.com/zclconf/go-cty/cty/msgpack/unknown.go delete mode 100644 vendor/github.com/zclconf/go-cty/cty/msgpack/unmarshal.go delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s delete mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go create mode 100644 vendor/golang.org/x/net/html/atom/atom.go create mode 100644 vendor/golang.org/x/net/html/atom/gen.go create mode 100644 vendor/golang.org/x/net/html/atom/table.go create mode 100644 vendor/golang.org/x/net/html/const.go create mode 100644 vendor/golang.org/x/net/html/doc.go create mode 100644 vendor/golang.org/x/net/html/doctype.go create mode 100644 vendor/golang.org/x/net/html/entity.go create mode 100644 vendor/golang.org/x/net/html/escape.go create mode 100644 vendor/golang.org/x/net/html/foreign.go create mode 100644 vendor/golang.org/x/net/html/node.go create mode 100644 vendor/golang.org/x/net/html/parse.go create mode 100644 vendor/golang.org/x/net/html/render.go create mode 100644 vendor/golang.org/x/net/html/token.go delete mode 100644 vendor/golang.org/x/oauth2/go.mod delete mode 100644 vendor/golang.org/x/oauth2/go.sum delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_solaris.go create mode 100644 vendor/golang.org/x/sys/unix/mksyscall_solaris.pl delete mode 100644 vendor/google.golang.org/appengine/datastore/datastore.go delete mode 100644 vendor/google.golang.org/appengine/datastore/doc.go delete mode 100644 vendor/google.golang.org/appengine/datastore/key.go delete mode 100644 vendor/google.golang.org/appengine/datastore/load.go delete mode 100644 vendor/google.golang.org/appengine/datastore/metadata.go delete mode 100644 vendor/google.golang.org/appengine/datastore/prop.go delete mode 100644 vendor/google.golang.org/appengine/datastore/query.go delete mode 100644 vendor/google.golang.org/appengine/datastore/save.go delete mode 100644 vendor/google.golang.org/appengine/datastore/transaction.go delete mode 100644 vendor/google.golang.org/appengine/internal/main_common.go delete mode 100644 vendor/google.golang.org/grpc/test/bufconn/bufconn.go diff --git a/go.mod b/go.mod index 26589dd5..3a266ea6 100644 --- a/go.mod +++ b/go.mod @@ -1,24 +1,48 @@ module github.com/terraform-providers/terraform-provider-google require ( - cloud.google.com/go v0.36.0 + cloud.google.com/go v0.34.0 github.com/apparentlymart/go-cidr v1.0.0 + github.com/aws/aws-sdk-go v1.16.24 // indirect + github.com/blang/semver v3.5.1+incompatible // indirect github.com/davecgh/go-spew v1.1.1 github.com/dustinkirkland/golang-petname v0.0.0-20170921220637-d3c2ba80e75e // indirect github.com/gammazero/deque v0.0.0-20180920172122-f6adf94963e4 // indirect github.com/gammazero/workerpool v0.0.0-20181230203049-86a96b5d5d92 + github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect + github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c // indirect + github.com/googleapis/gax-go v2.0.2+incompatible // indirect github.com/hashicorp/errwrap v1.0.0 github.com/hashicorp/go-cleanhttp v0.5.0 + github.com/hashicorp/go-getter v1.0.1 // indirect + github.com/hashicorp/go-hclog v0.0.0-20181001195459-61d530d6c27f // indirect github.com/hashicorp/go-multierror v1.0.0 + github.com/hashicorp/go-plugin v0.0.0-20181212150838-f444068e8f5a // indirect + github.com/hashicorp/go-uuid v1.0.0 // indirect github.com/hashicorp/go-version v1.1.0 github.com/hashicorp/hcl v1.0.0 // indirect - github.com/hashicorp/terraform v0.12.0-alpha4.0.20190226230829-c2f653cf1a35 + github.com/hashicorp/hcl2 v0.0.0-20181215005721-253da47fd604 // indirect + github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250 // indirect + github.com/hashicorp/logutils v1.0.0 // indirect + github.com/hashicorp/terraform v0.11.9-0.20180926212128-35d82b055591 github.com/hashicorp/vault v1.0.1 // indirect github.com/keybase/go-crypto v0.0.0-20181127160227-255a5089e85a // indirect + github.com/mitchellh/cli v1.0.0 // indirect + github.com/mitchellh/copystructure v1.0.0 // indirect github.com/mitchellh/hashstructure v1.0.0 + github.com/mitchellh/mapstructure v1.1.2 // indirect github.com/pierrec/lz4 v2.0.5+incompatible // indirect github.com/stoewer/go-strcase v1.0.2 + github.com/stretchr/testify v1.3.0 // indirect github.com/terraform-providers/terraform-provider-random v2.0.0+incompatible - golang.org/x/oauth2 v0.0.0-20190220154721-9b3c75971fc9 - google.golang.org/api v0.1.0 + github.com/zclconf/go-cty v0.0.0-20181218225846-4fe1e489ee06 // indirect + go.opencensus.io v0.18.0 // indirect + golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 // indirect + golang.org/x/net v0.0.0-20190119204137-ed066c81e75e // indirect + golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890 + golang.org/x/sys v0.0.0-20190123074212-c6b37f3e9285 // indirect + google.golang.org/api v0.0.0-20181217000635-41dc4b66e69d + google.golang.org/appengine v1.3.0 // indirect + google.golang.org/genproto v0.0.0-20181218023534-67d6565462c5 // indirect + google.golang.org/grpc v1.17.0 // indirect ) diff --git a/go.sum b/go.sum index 8d654355..b34685eb 100644 --- a/go.sum +++ b/go.sum @@ -1,46 +1,19 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0 h1:eOI3/cP2VTU6uZLDYAoic+eyzzB9YyGmJ7eIjl8rOPg= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.36.0 h1:+aCSj7tOo2LODWVEuZDZeGCckdt6MlSF+X/rB3wUiS8= -cloud.google.com/go v0.36.0/go.mod h1:RUoy9p/M4ge0HzT8L+SDZ8jg+Q6fth0CiBuhFJpSV40= -dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= -dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= -dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4= -dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU= git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= -github.com/Azure/azure-sdk-for-go v21.3.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/go-autorest v10.15.4+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= -github.com/Azure/go-ntlmssp v0.0.0-20180810175552-4a21cbd618b4/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/ChrisTrenkamp/goxpath v0.0.0-20170922090931-c385f95c6022/go.mod h1:nuWgzSkT5PnyOd+272uUmV0dnAnAn42Mk7PiQC5VzN4= -github.com/Unknwon/com v0.0.0-20151008135407-28b053d5a292/go.mod h1:KYCjqMOeHpNuTOiFQU6WEcTG7poCJrUs0YgyHNtn1no= -github.com/abdullin/seq v0.0.0-20160510034733-d5467c17e7af/go.mod h1:5Jv4cbFiHJMsVxt52+i0Ha45fjshj6wxYr1r19tB9bw= github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= -github.com/agext/levenshtein v1.2.2 h1:0S/Yg6LYmFJ5stwQeRp6EeOcCbj7xiqQSdNelsXvaqE= -github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= -github.com/agl/ed25519 v0.0.0-20150830182803-278e1ec8e8a6/go.mod h1:WPjqKcmVOxf0XSf3YxCJs6N6AOSrOx3obionmG7T0y0= -github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= -github.com/antchfx/xpath v0.0.0-20190129040759-c8489ed3251e/go.mod h1:Yee4kTMuNiPYJ7nSNorELQMr1J33uOpXDMByNYhvtNk= -github.com/antchfx/xquery v0.0.0-20180515051857-ad5b8c7a47b0/go.mod h1:LzD22aAzDP8/dyiCKFp31He4m2GPjl0AFyzDtZzUu9M= github.com/apparentlymart/go-cidr v1.0.0 h1:lGDvXx8Lv9QHjrAVP7jyzleG4F9+FkRhJcEsDFxeb8w= github.com/apparentlymart/go-cidr v1.0.0/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= -github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3 h1:ZSTrOEhiM5J5RFxEaFvMZVEAM1KvT1YzbEOwB2EAGjA= github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= -github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0 h1:MzVXffFUye+ZcSR6opIgz9Co7WcDx6ZcY+RjfFHoA0I= -github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= -github.com/armon/circbuf v0.0.0-20190214190532-5111143e8da2/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= -github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= -github.com/aws/aws-sdk-go v1.16.36 h1:POeH34ZME++pr7GBGh+ZO6Y5kOwSMQpqp5BGUgooJ6k= -github.com/aws/aws-sdk-go v1.16.36/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.16.24 h1:I/A3Hwbgs3IEAP6v1bFpHKXiT7wZDoToX9cb00nxZnM= +github.com/aws/aws-sdk-go v1.16.24/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= @@ -48,377 +21,189 @@ github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ= github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= -github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= -github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= github.com/bsm/go-vlq v0.0.0-20150828105119-ec6e8d4f5f4e/go.mod h1:N+BjUcTjSxc2mtRGSCPsat1kze3CUtvJN3/jTXlp29k= github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20161106042343-c914be64f07d/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/coreos/bbolt v1.3.0/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= -github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dimchansky/utfbom v1.0.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= -github.com/dnaeon/go-vcr v0.0.0-20180920040454-5637cf3d8a31/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustinkirkland/golang-petname v0.0.0-20170921220637-d3c2ba80e75e h1:bRcq7ruHMqCVB/ugLbBylx+LrccNACFDEaqAD/aZ80Q= github.com/dustinkirkland/golang-petname v0.0.0-20170921220637-d3c2ba80e75e/go.mod h1:V+Qd57rJe8gd4eiGzZyg4h54VLHmYVVw54iMnlAMrF8= -github.com/dylanmei/iso8601 v0.1.0/go.mod h1:w9KhXSgIyROl1DefbMYIE7UVSIvELTbMrCfx+QkYnoQ= -github.com/dylanmei/winrmtest v0.0.0-20190225150635-99b7fe2fddf1/go.mod h1:lcy9/2gH1jn/VCLouHA6tOEwLoNVd4GW6zhuKLmHC2Y= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/gammazero/deque v0.0.0-20180920172122-f6adf94963e4 h1:R+19WKQClnfMXS60cP5BmMe1wjZ4u0evY2p2Ar0ZTXo= github.com/gammazero/deque v0.0.0-20180920172122-f6adf94963e4/go.mod h1:GeIq9qoE43YdGnDXURnmKTnGg15pQz4mYkXSTChbneI= github.com/gammazero/workerpool v0.0.0-20181230203049-86a96b5d5d92 h1:EipXK6U05IQ2wtuFRn4k3h0+2lXypzItoXGVyf4r9Io= github.com/gammazero/workerpool v0.0.0-20181230203049-86a96b5d5d92/go.mod h1:w9RqFVO2BM3xwWEcAB8Fwp0OviTBBEiRmSBDfbXnd3w= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= -github.com/go-test/deep v1.0.1 h1:UQhStjbkDClarlmv0am7OXXO4/GaPdCGiUiMTvi28sg= github.com/go-test/deep v1.0.1/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20180513044358-24b0969c4cb7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0 h1:28o5sBqPkBsMGnC6b4MvE2TzSr5/AT4c/1fLqVGIwlk= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c h1:964Od4U6p2jUkFxvCydnIczKteheJEzHRToSGK3Bnlw= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= -github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/googleapis/gax-go v2.0.0+incompatible h1:j0GKcs05QVmm7yesiZq2+9cxHkNK9YM6zKx4D2qucQU= -github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= -github.com/googleapis/gax-go/v2 v2.0.3 h1:siORttZ36U2R/WjiJuDz8znElWBiAlO9rVt+mqJt0Cc= -github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= -github.com/gophercloud/gophercloud v0.0.0-20190208042652-bc37892e1968/go.mod h1:3WdhXV3rUYy9p6AUW8d94kr+HS62Y4VL9mBnFxsD8q4= -github.com/gophercloud/utils v0.0.0-20190128072930-fbb6ab446f01/go.mod h1:wjDF8z83zTeg5eMLml5EBSlAhbF7G8DobyI1YsMuyzw= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/googleapis/gax-go v2.0.2+incompatible h1:silFMLAnr330+NRuag/VjIGF7TLp/LBrV2CJKFLWEww= +github.com/googleapis/gax-go v2.0.2+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= -github.com/grpc-ecosystem/grpc-gateway v1.5.1/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= -github.com/hashicorp/aws-sdk-go-base v0.2.0/go.mod h1:ZIWACGGi0N7a4DZbf15yuE1JQORmWLtBcVM6F5SXNFU= -github.com/hashicorp/consul v0.0.0-20171026175957-610f3c86a089/go.mod h1:mFrjN1mfidgJfYP1xrJCF+AfRhr6Eaqhb2+sfyn/OOI= github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-azure-helpers v0.0.0-20190129193224-166dfd221bb2/go.mod h1:lu62V//auUow6k0IykxLK2DCNW8qTmpm8KqhYVWattA= -github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-getter v1.1.0 h1:iGVeg7L4V5FTFV3D6w+1NAyvth7BIWWSzD60pWloe2Q= -github.com/hashicorp/go-getter v1.1.0/go.mod h1:q+PoBhh16brIKwJS9kt18jEtXHTg2EGkmrA9P7HVS+U= +github.com/hashicorp/go-getter v1.0.1 h1:WlFPjyPrd34KmTQMzSPA0pn9JpRsuHjHaRTx0VPzxYw= +github.com/hashicorp/go-getter v1.0.1/go.mod h1:tkKN/c6I/LRSXLOWZ8wa/VB0LfVrryHzk/B0aZLKZI0= github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= github.com/hashicorp/go-hclog v0.0.0-20181001195459-61d530d6c27f h1:Yv9YzBlAETjy6AOX9eLBZ3nshNVRREgerT/3nvxlGho= github.com/hashicorp/go-hclog v0.0.0-20181001195459-61d530d6c27f/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= -github.com/hashicorp/go-immutable-radix v0.0.0-20180129170900-7f3cd4390caa/go.mod h1:6ij3Z20p+OhOkCSrA0gImAWoHYQRGbnlcuk6XYTiaRw= -github.com/hashicorp/go-msgpack v0.0.0-20150518234257-fa3f63826f7c/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-plugin v0.0.0-20190220160451-3f118e8ee104 h1:9iQ/zrTOJqzP+kH37s6xNb6T1RysiT7fnDD3DJbspVw= -github.com/hashicorp/go-plugin v0.0.0-20190220160451-3f118e8ee104/go.mod h1:++UyYGoz3o5w9ZzAdZxtQKrWWP+iqPBn3cQptSMzBuY= -github.com/hashicorp/go-retryablehttp v0.5.1/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= -github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-plugin v0.0.0-20181212150838-f444068e8f5a h1:z9eTtDWoxYrJvtAD+xAepmTEfEmYgouWUytJ84UWAr8= +github.com/hashicorp/go-plugin v0.0.0-20181212150838-f444068e8f5a/go.mod h1:Ft7ju2vWzhO0ETMKUVo12XmXmII6eSUS4rsPTkY/siA= github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= -github.com/hashicorp/go-slug v0.2.0/go.mod h1:+zDycQOzGqOqMW7Kn2fp9vz/NtqpMLQlgb9JUF+0km4= -github.com/hashicorp/go-sockaddr v0.0.0-20180320115054-6d291a969b86/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-tfe v0.3.10/go.mod h1:LHLchj07PCYgQqcyE5Sz+g4zrMNW+nALKbiSNTZedEs= github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.0.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0= github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/hcl2 v0.0.0-20181208003705-670926858200/go.mod h1:ShfpTh661oAaxo7VcNxg0zcZW6jvMa7Moy2oFx7e5dE= -github.com/hashicorp/hcl2 v0.0.0-20190214011454-504b92060753 h1:8wCARxVLkMdcvxSaI2F/zL31FLQuAJkzIkayl5br8TY= -github.com/hashicorp/hcl2 v0.0.0-20190214011454-504b92060753/go.mod h1:HtEzazM5AZ9fviNEof8QZB4T1Vz9UhHrGhnMPzl//Ek= -github.com/hashicorp/hil v0.0.0-20190212112733-ab17b08d6590 h1:2yzhWGdgQUWZUCNK+AoO35V+HTsgEmcM4J9IkArh7PI= -github.com/hashicorp/hil v0.0.0-20190212112733-ab17b08d6590/go.mod h1:n2TSygSNwsLJ76m8qFXTSc7beTb+auJxYdqrnoqwZWE= +github.com/hashicorp/hcl2 v0.0.0-20181215005721-253da47fd604 h1:k660QMbAqhL4vxSNPmvOAjzZJ7BQiwTrT8pa8RH3OEA= +github.com/hashicorp/hcl2 v0.0.0-20181215005721-253da47fd604/go.mod h1:ShfpTh661oAaxo7VcNxg0zcZW6jvMa7Moy2oFx7e5dE= +github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250 h1:fooK5IvDL/KIsi4LxF/JH68nVdrBSiGNPhS2JAQjtjo= +github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250/go.mod h1:KHvg/R2/dPtaePb16oW4qIyzkMxXOL38xjRN64adsts= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/memberlist v0.1.0/go.mod h1:ncdBp14cuox2iFOq3kDiquKU6fqsTBc3W6JvZwjxxsE= -github.com/hashicorp/serf v0.0.0-20160124182025-e4ec8cc423bb/go.mod h1:h/Ru6tmZazX7WO/GDmwdpS975F019L4t5ng5IgwbNrE= -github.com/hashicorp/terraform v0.12.0-alpha4.0.20190226230829-c2f653cf1a35 h1:fXWLwWzGY4u82Srhx+Sm2ecM9ySQOFbzwZ/GPTPT0do= -github.com/hashicorp/terraform v0.12.0-alpha4.0.20190226230829-c2f653cf1a35/go.mod h1:IBJbeQNPU1HTVzDLsy6NBI/W70I4SW1+AE0D2cMzLao= -github.com/hashicorp/terraform-config-inspect v0.0.0-20190208230122-b0707673339c h1:nCnsfi66NloVlmquh5dLox5yBwQk5CV5s2roWvbstnE= -github.com/hashicorp/terraform-config-inspect v0.0.0-20190208230122-b0707673339c/go.mod h1:ItvqtvbC3K23FFET62ZwnkwtpbKZm8t8eMcWjmVVjD8= -github.com/hashicorp/vault v0.10.4/go.mod h1:KfSyffbKxoVyspOdlaGVjIuwLobi07qD1bAbosPMpP0= +github.com/hashicorp/terraform v0.11.9-0.20180926212128-35d82b055591 h1:A2Bm1/dX0N2FRBqg10MgN0OYmdL/S8ZbgdmDvWmmQ7o= +github.com/hashicorp/terraform v0.11.9-0.20180926212128-35d82b055591/go.mod h1:uN1KUiT7Wdg61fPwsGXQwK3c8PmpIVZrt5Vcb1VrSoM= github.com/hashicorp/vault v1.0.1 h1:x3hcjkJLd5L4ehPhZcraokFO7dq8MJ3oKvQtrkIiIU8= github.com/hashicorp/vault v1.0.1/go.mod h1:KfSyffbKxoVyspOdlaGVjIuwLobi07qD1bAbosPMpP0= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb h1:b5rjCoWHc7eqmAS4/qyk21ZsHyb6Mxv/jykxvNTkU4M= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/joyent/triton-go v0.0.0-20180313100802-d8f9c0314926/go.mod h1:U+RSyWxWd04xTqnuOQxnai7XGS2PrPY2cfGoDKtMHjA= -github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/kardianos/osext v0.0.0-20170510131534-ae77be60afb1/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= -github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= -github.com/keybase/go-crypto v0.0.0-20161004153544-93f5b35093ba/go.mod h1:ghbZscTyKdM07+Fw3KSi0hcJm+AlEUWj8QLlPtijN/M= github.com/keybase/go-crypto v0.0.0-20181127160227-255a5089e85a h1:X/UFlwD2/UV0RCy+8ITi4DmxJwk83YUH7bXwkJIHHMo= github.com/keybase/go-crypto v0.0.0-20181127160227-255a5089e85a/go.mod h1:ghbZscTyKdM07+Fw3KSi0hcJm+AlEUWj8QLlPtijN/M= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4= github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= -github.com/lusis/go-artifactory v0.0.0-20160115162124-7e4ce345df82/go.mod h1:y54tfGmO3NKssKveTEFFzH8C/akrSOy/iW9qEAUDV84= -github.com/marstr/guid v1.1.0/go.mod h1:74gB1z2wpxxInTG6yaqA7KrtM0NZ+RbrcqDvYHefzho= -github.com/masterzen/simplexml v0.0.0-20160608183007-4572e39b1ab9/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc= -github.com/masterzen/winrm v0.0.0-20190223112901-5e5c9a7fe54b/go.mod h1:wr1VqkwW0AB5JS0QLy5GpVMS9E3VtRoSYXUYyVk46KY= github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.1 h1:G1f5SKeVxmagw/IyvzvtZE4Gybcc4Tr1tf7I8z0XgOg= -github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-shellwords v1.0.4/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= -github.com/miekg/dns v1.0.8/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0 h1:iGBIsUe3+HZ/AD/Vd7DErOt5sU9fa8Uj7A2s1aggv1Y= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ= -github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-linereader v0.0.0-20190213213312-1b945b3263eb/go.mod h1:OaY7UOoTkkrX3wRwjpYRKafIkkyeD0UtweSHAWWiqQM= github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/go-testing-interface v1.0.0 h1:fzU/JVNcaqHQEcVFAKeR41fkiLdIPrefOvVG1VZ96U0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= -github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= -github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/hashstructure v1.0.0 h1:ZkRJX1CyOoTkar7p/mLS5TZU4nJ1Rn/F8u9dGS02Q3Y= github.com/mitchellh/hashstructure v1.0.0/go.mod h1:QjSHrPWS+BGUVBYkbTZWEnOh3G1DutKwClXU/ABz6AQ= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/panicwrap v0.0.0-20190213213626-17011010aaa4/go.mod h1:YYMf4xtQnR8LRC0vKi3afvQ5QwRPQ17zjcpkBCufb+I= -github.com/mitchellh/prefixedio v0.0.0-20190213213902-5733675afd51/go.mod h1:kB1naBgV9ORnkiTVeyJOI1DavaJkG4oNIq0Af6ZVKUo= github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= -github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= -github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= -github.com/packer-community/winrmcp v0.0.0-20180102160824-81144009af58/go.mod h1:f6Izs6JvFTdnRbziASagjZ2vmf55NSIkC/weStxCHqk= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= -github.com/pkg/errors v0.0.0-20170505043639-c605e284fe17/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1 h1:ccV59UEOTzVDnDUEFdT95ZzHVZ+5+158q8+SJb2QV5w= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/posener/complete v1.2.1 h1:LrvDIY//XNo65Lq84G/akBuMGlawHvGBABv8f/ZN6DI= -github.com/posener/complete v1.2.1/go.mod h1:6gapUrK/U1TAN7ciCoNRIdVC5sbdBTUh1DKN0g6uH7E= github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= -github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY= -github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM= -github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0= -github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= -github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw= -github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI= -github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU= -github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag= -github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg= -github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw= -github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y= -github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= -github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q= -github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ= -github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I= -github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0= -github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ= -github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk= -github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4= -github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= -github.com/sirupsen/logrus v1.1.1/go.mod h1:zrgwTnHtNr00buQ1vSptGe8m1f/BbgsPukg8qsT7A+A= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= -github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA= -github.com/spf13/afero v1.2.1 h1:qgMbHoJbPbw579P+1zVY+6n4nIFuIchaIjzZ/I/Yq8M= -github.com/spf13/afero v1.2.1/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/stoewer/go-strcase v1.0.2 h1:l3iQ2FPu8+36ars/7syO1dQAkjwMCb1IE3J+Th0ohfE= github.com/stoewer/go-strcase v1.0.2/go.mod h1:eLfe5bL3qbL7ep/KafHzthxejrOF5J3xmt03uL5tzek= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/svanharmelen/jsonapi v0.0.0-20180618144545-0c0828c3f16d/go.mod h1:BSTlc8jOjh0niykqEGVXOLXdi9o0r0kR8tCYiMvjFgw= -github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= -github.com/terraform-providers/terraform-provider-openstack v1.15.0/go.mod h1:2aQ6n/BtChAl1y2S60vebhyJyZXBsuAI5G4+lHrT1Ew= github.com/terraform-providers/terraform-provider-random v2.0.0+incompatible h1:4wuExSWk/NHYS95P2H4KGv22bsabuDjGk5cFikIYzuU= github.com/terraform-providers/terraform-provider-random v2.0.0+incompatible/go.mod h1:1U2balY0mfjMnO5iotT60EuFqDJxqP433wJcybviCTw= -github.com/tmc/grpc-websocket-proxy v0.0.0-20171017195756-830351dc03c6/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/ugorji/go v0.0.0-20180813092308-00b869d2f4a5/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= github.com/ulikunitz/xz v0.5.5 h1:pFrO0lVpTBXLpYw+pnLj6TbvHuyjXMfjGeCwSqCVwok= github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/vmihailenco/msgpack v4.0.1+incompatible h1:RMF1enSPeKTlXrXdOcqjFUElywVZjjC6pqse21bKbEU= -github.com/vmihailenco/msgpack v4.0.1+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/xanzy/ssh-agent v0.2.1/go.mod h1:mLlQY/MoOhWBj+gOGMQkOeiEvkx+8pJSI+0Bx9h2kr4= -github.com/xiang90/probing v0.0.0-20160813154853-07dd2e8dfe18/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xlab/treeprint v0.0.0-20161029104018-1d6e34225557/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= github.com/zclconf/go-cty v0.0.0-20181129180422-88fbe721e0f8/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= -github.com/zclconf/go-cty v0.0.0-20190124225737-a385d646c1e9/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= -github.com/zclconf/go-cty v0.0.0-20190201220620-4ca19710f056 h1:C6LhH3JHz2k6tnw5sYXBc8rD8SD/qFp6EhiZAcVyalk= -github.com/zclconf/go-cty v0.0.0-20190201220620-4ca19710f056/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= +github.com/zclconf/go-cty v0.0.0-20181218225846-4fe1e489ee06 h1:J3bfEicd/d85VHC6bPhrKb+2jO+Uquiy2bnkhia6XBA= +github.com/zclconf/go-cty v0.0.0-20181218225846-4fe1e489ee06/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= go.opencensus.io v0.18.0 h1:Mk5rgZcggtbvtAun5aJzAtjKKN/t0R3jJPlWILlv938= go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA= -go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= -golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= golang.org/x/crypto v0.0.0-20180816225734-aabede6cba87/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181112202954-3d3f9f413869/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190222235706-ffb98f73852f h1:qWFY9ZxP3tfI37wYIs/MnIAqK0vlXp1xnYEa5HxFSSY= -golang.org/x/crypto v0.0.0-20190222235706-ffb98f73852f/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181129055619-fae4c4e3ad76/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd h1:HuTn7WObtcDo9uEEU7rEqL0jYthdXAmZ6PP+meazmaU= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190119204137-ed066c81e75e h1:MDa3fSUp6MdYHouVmCCNz/zaH2a6CRcxY3VhT/K3C5Q= +golang.org/x/net v0.0.0-20190119204137-ed066c81e75e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890 h1:uESlIz09WIHT2I+pasSXcpLYqYK8wHcdCetU3VuMBJE= golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190220154721-9b3c75971fc9 h1:pfyU+l9dEu0vZzDDMsdAKa1gZbJYEn6urYXj/+Xkz7s= -golang.org/x/oauth2 v0.0.0-20190220154721-9b3c75971fc9/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181213200352-4d1cda033e06/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc h1:WiYx1rIFmx8c0mXAFtv5D/mHyKe1+jmuP7PViuwqwuQ= -golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190221075227-b4e8571b14e0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190123074212-c6b37f3e9285 h1:b5t9HsJXzMmseFB6KtTJWSEtPP8SlVI5nFdf4hnoRFY= +golang.org/x/sys v0.0.0-20190123074212-c6b37f3e9285/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.1.0 h1:K6z2u68e86TPdSdefXdzvXgR1zEMa+459vBSfWYAZkI= -google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= +google.golang.org/api v0.0.0-20181217000635-41dc4b66e69d h1:VhRqKr7/NDe5MpNpIj6Cy1xiwcVL4ZPs2GjTYziBRRg= +google.golang.org/api v0.0.0-20181217000635-41dc4b66e69d/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.3.0 h1:FBSsiFRMz3LBeXIomRnVzrQwSDj4ibvcRexLG0LZGQk= google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= -google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922 h1:mBVYJnbrXLA/ZCBTCe7PtEgAUP+1bg92qTaFoPHdz+8= -google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922/go.mod h1:L3J43x8/uS+qIUoksaLKe6OS3nUKxOKuIFz1sl2/jx4= +google.golang.org/genproto v0.0.0-20181218023534-67d6565462c5 h1:ZcmLUbATcwP+ZlsJ5pn5qeF9O3pC7U7mYpSnHH7RFFs= +google.golang.org/genproto v0.0.0-20181218023534-67d6565462c5/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= google.golang.org/grpc v1.17.0 h1:TRJYBgMclJvGYn2rIMjj+h9KtMt5r1Ij7ODVRIZkwhk= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= -google.golang.org/grpc v1.18.0 h1:IZl7mfBGfbhYx2p2rKRtYgDFw6SBz+kclmxYrCksPPA= -google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/vmihailenco/msgpack.v2 v2.9.1/go.mod h1:/3Dn1Npt9+MYyLpYYXjInO/5jvMLamn+AEGwNEOatn8= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= howett.net/plist v0.0.0-20181124034731-591f970eefbb/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0= -labix.org/v2/mgo v0.0.0-20140701140051-000000000287/go.mod h1:Lg7AYkt1uXJoR9oeSZ3W/8IXLdvOfIITgZnommstyz4= -launchpad.net/gocheck v0.0.0-20140225173054-000000000087/go.mod h1:hj7XX3B/0A+80Vse0e+BUHsHMTEhd0O4cpUHr/e/BUM= -sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= -sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/vendor/cloud.google.com/go/bigtable/admin.go b/vendor/cloud.google.com/go/bigtable/admin.go index 35f30206..5a0c2348 100644 --- a/vendor/cloud.google.com/go/bigtable/admin.go +++ b/vendor/cloud.google.com/go/bigtable/admin.go @@ -385,7 +385,7 @@ func (ac *AdminClient) Snapshots(ctx context.Context, cluster string) *SnapshotI for _, s := range resp.Snapshots { snapshotInfo, err := newSnapshotInfo(s) if err != nil { - return "", fmt.Errorf("failed to parse snapshot proto %v", err) + return "", fmt.Errorf("Failed to parse snapshot proto %v", err) } it.items = append(it.items, snapshotInfo) } @@ -407,12 +407,12 @@ func newSnapshotInfo(snapshot *btapb.Snapshot) (*SnapshotInfo, error) { createTime, err := ptypes.Timestamp(snapshot.CreateTime) if err != nil { - return nil, fmt.Errorf("invalid createTime: %v", err) + return nil, fmt.Errorf("Invalid createTime: %v", err) } deleteTime, err := ptypes.Timestamp(snapshot.DeleteTime) if err != nil { - return nil, fmt.Errorf("invalid deleteTime: %v", err) + return nil, fmt.Errorf("Invalid deleteTime: %v", err) } return &SnapshotInfo{ @@ -1064,7 +1064,9 @@ func (iac *InstanceAdminClient) ListAppProfiles(ctx context.Context, instanceID return "", err } - pit.items = append(pit.items, profileRes.AppProfiles...) + for _, a := range profileRes.AppProfiles { + pit.items = append(pit.items, a) + } return profileRes.NextPageToken, nil } diff --git a/vendor/cloud.google.com/go/bigtable/bigtable.go b/vendor/cloud.google.com/go/bigtable/bigtable.go index 28c0c92a..07b4ee88 100644 --- a/vendor/cloud.google.com/go/bigtable/bigtable.go +++ b/vendor/cloud.google.com/go/bigtable/bigtable.go @@ -71,7 +71,7 @@ func NewClientWithConfig(ctx context.Context, project, instance string, config C o = append(o, option.WithGRPCConnectionPool(4), // Set the max size to correspond to server-side limits. - option.WithGRPCDialOption(grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(1<<28), grpc.MaxCallRecvMsgSize(1<<28))), + option.WithGRPCDialOption(grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(100<<20), grpc.MaxCallRecvMsgSize(100<<20))), // TODO(grpc/grpc-go#1388) using connection pool without WithBlock // can cause RPCs to fail randomly. We can delete this after the issue is fixed. option.WithGRPCDialOption(grpc.WithBlock())) diff --git a/vendor/cloud.google.com/go/bigtable/internal/gax/call_option.go b/vendor/cloud.google.com/go/bigtable/internal/gax/call_option.go index 3c221392..79c580b0 100644 --- a/vendor/cloud.google.com/go/bigtable/internal/gax/call_option.go +++ b/vendor/cloud.google.com/go/bigtable/internal/gax/call_option.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package gax is a snapshot from github.com/googleapis/gax-go/v2 with minor modifications. +// Package gax is a snapshot from github.com/googleapis/gax-go with minor modifications. package gax import ( diff --git a/vendor/cloud.google.com/go/bigtable/internal/gax/invoke.go b/vendor/cloud.google.com/go/bigtable/internal/gax/invoke.go index 22089702..228dd443 100644 --- a/vendor/cloud.google.com/go/bigtable/internal/gax/invoke.go +++ b/vendor/cloud.google.com/go/bigtable/internal/gax/invoke.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package gax is a snapshot from github.com/googleapis/gax-go/v2 with minor modifications. +// Package gax is a snapshot from github.com/googleapis/gax-go with minor modifications. package gax import ( diff --git a/vendor/cloud.google.com/go/compute/metadata/metadata.go b/vendor/cloud.google.com/go/compute/metadata/metadata.go index 125b7033..0d929a61 100644 --- a/vendor/cloud.google.com/go/compute/metadata/metadata.go +++ b/vendor/cloud.google.com/go/compute/metadata/metadata.go @@ -137,7 +137,7 @@ func testOnGCE() bool { resc := make(chan bool, 2) // Try two strategies in parallel. - // See https://github.com/googleapis/google-cloud-go/issues/194 + // See https://github.com/GoogleCloudPlatform/google-cloud-go/issues/194 go func() { req, _ := http.NewRequest("GET", "http://"+metadataIP, nil) req.Header.Set("User-Agent", userAgent) @@ -300,8 +300,8 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) { // being stable anyway. host = metadataIP } - u := "http://" + host + "/computeMetadata/v1/" + suffix - req, _ := http.NewRequest("GET", u, nil) + url := "http://" + host + "/computeMetadata/v1/" + suffix + req, _ := http.NewRequest("GET", url, nil) req.Header.Set("Metadata-Flavor", "Google") req.Header.Set("User-Agent", userAgent) res, err := c.hc.Do(req) @@ -312,13 +312,13 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) { if res.StatusCode == http.StatusNotFound { return "", "", NotDefinedError(suffix) } + if res.StatusCode != 200 { + return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url) + } all, err := ioutil.ReadAll(res.Body) if err != nil { return "", "", err } - if res.StatusCode != 200 { - return "", "", &Error{Code: res.StatusCode, Message: string(all)} - } return string(all), res.Header.Get("Etag"), nil } @@ -499,15 +499,3 @@ func (c *Client) Subscribe(suffix string, fn func(v string, ok bool) error) erro } } } - -// Error contains an error response from the server. -type Error struct { - // Code is the HTTP response status code. - Code int - // Message is the server response message. - Message string -} - -func (e *Error) Error() string { - return fmt.Sprintf("compute: Received %d `%s`", e.Code, e.Message) -} diff --git a/vendor/cloud.google.com/go/iam/iam.go b/vendor/cloud.google.com/go/iam/iam.go index 5232cb67..76df6356 100644 --- a/vendor/cloud.google.com/go/iam/iam.go +++ b/vendor/cloud.google.com/go/iam/iam.go @@ -23,14 +23,12 @@ package iam import ( "context" - "fmt" "time" - gax "github.com/googleapis/gax-go/v2" + gax "github.com/googleapis/gax-go" pb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" ) // client abstracts the IAMPolicy API to allow multiple implementations. @@ -58,9 +56,6 @@ var withRetry = gax.WithRetry(func() gax.Retryer { func (g *grpcClient) Get(ctx context.Context, resource string) (*pb.Policy, error) { var proto *pb.Policy - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource)) - ctx = insertMetadata(ctx, md) - err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { var err error proto, err = g.c.GetIamPolicy(ctx, &pb.GetIamPolicyRequest{Resource: resource}) @@ -73,9 +68,6 @@ func (g *grpcClient) Get(ctx context.Context, resource string) (*pb.Policy, erro } func (g *grpcClient) Set(ctx context.Context, resource string, p *pb.Policy) error { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource)) - ctx = insertMetadata(ctx, md) - return gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { _, err := g.c.SetIamPolicy(ctx, &pb.SetIamPolicyRequest{ Resource: resource, @@ -87,9 +79,6 @@ func (g *grpcClient) Set(ctx context.Context, resource string, p *pb.Policy) err func (g *grpcClient) Test(ctx context.Context, resource string, perms []string) ([]string, error) { var res *pb.TestIamPermissionsResponse - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource)) - ctx = insertMetadata(ctx, md) - err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { var err error res, err = g.c.TestIamPermissions(ctx, &pb.TestIamPermissionsRequest{ @@ -301,15 +290,3 @@ func memberIndex(m string, b *pb.Binding) int { } return -1 } - -// insertMetadata inserts metadata into the given context -func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { - out, _ := metadata.FromOutgoingContext(ctx) - out = out.Copy() - for _, md := range mds { - for k, v := range md { - out[k] = append(out[k], v...) - } - } - return metadata.NewOutgoingContext(ctx, out) -} diff --git a/vendor/cloud.google.com/go/longrunning/autogen/doc.go b/vendor/cloud.google.com/go/longrunning/autogen/doc.go index 6b6252a7..c5849a9c 100644 --- a/vendor/cloud.google.com/go/longrunning/autogen/doc.go +++ b/vendor/cloud.google.com/go/longrunning/autogen/doc.go @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC +// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Code generated by gapic-generator. DO NOT EDIT. +// AUTO-GENERATED CODE. DO NOT EDIT. // Package longrunning is an auto-generated package for the // Google Long Running Operations API. @@ -85,4 +85,4 @@ func versionGo() string { return "UNKNOWN" } -const versionClient = "20190121" +const versionClient = "20181129" diff --git a/vendor/cloud.google.com/go/longrunning/autogen/operations_client.go b/vendor/cloud.google.com/go/longrunning/autogen/operations_client.go index 73168020..ebdf6f9f 100644 --- a/vendor/cloud.google.com/go/longrunning/autogen/operations_client.go +++ b/vendor/cloud.google.com/go/longrunning/autogen/operations_client.go @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC +// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Code generated by gapic-generator. DO NOT EDIT. +// AUTO-GENERATED CODE. DO NOT EDIT. package longrunning @@ -22,7 +22,7 @@ import ( "time" "github.com/golang/protobuf/proto" - gax "github.com/googleapis/gax-go/v2" + gax "github.com/googleapis/gax-go" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/transport" diff --git a/vendor/cloud.google.com/go/longrunning/longrunning.go b/vendor/cloud.google.com/go/longrunning/longrunning.go index e1d9dcf8..639482af 100644 --- a/vendor/cloud.google.com/go/longrunning/longrunning.go +++ b/vendor/cloud.google.com/go/longrunning/longrunning.go @@ -30,7 +30,7 @@ import ( autogen "cloud.google.com/go/longrunning/autogen" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes" - gax "github.com/googleapis/gax-go/v2" + gax "github.com/googleapis/gax-go" pb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" diff --git a/vendor/github.com/agext/levenshtein/.gitignore b/vendor/github.com/agext/levenshtein/.gitignore index 4473da19..404365f6 100644 --- a/vendor/github.com/agext/levenshtein/.gitignore +++ b/vendor/github.com/agext/levenshtein/.gitignore @@ -1,53 +1,2 @@ -# Ignore docs files -_gh_pages -_site - -# Ignore temporary files README.html coverage.out -.tmp - -# Numerous always-ignore extensions -*.diff -*.err -*.log -*.orig -*.rej -*.swo -*.swp -*.vi -*.zip -*~ - -# OS or Editor folders -._* -.cache -.DS_Store -.idea -.project -.settings -.tmproj -*.esproj -*.sublime-project -*.sublime-workspace -nbproject -Thumbs.db - -# Komodo -.komodotools -*.komodoproject - -# SCSS-Lint -scss-lint-report.xml - -# grunt-contrib-sass cache -.sass-cache - -# Jekyll metadata -docs/.jekyll-metadata - -# Folders to ignore -.build -.test -bower_components -node_modules diff --git a/vendor/github.com/agext/levenshtein/.travis.yml b/vendor/github.com/agext/levenshtein/.travis.yml index a51a1446..95be94af 100644 --- a/vendor/github.com/agext/levenshtein/.travis.yml +++ b/vendor/github.com/agext/levenshtein/.travis.yml @@ -1,25 +1,70 @@ language: go sudo: false -matrix: - fast_finish: true - include: - - go: 1.11.x - env: TEST_METHOD=goveralls - - go: 1.10.x - - go: tip - - go: 1.9.x - - go: 1.8.x - - go: 1.7.x - - go: 1.6.x - - go: 1.5.x - allow_failures: - - go: tip - - go: 1.9.x - - go: 1.8.x - - go: 1.7.x - - go: 1.6.x - - go: 1.5.x -script: ./test.sh $TEST_METHOD +go: + - 1.8 + - 1.7.5 + - 1.7.4 + - 1.7.3 + - 1.7.2 + - 1.7.1 + - 1.7 + - tip + - 1.6.4 + - 1.6.3 + - 1.6.2 + - 1.6.1 + - 1.6 + - 1.5.4 + - 1.5.3 + - 1.5.2 + - 1.5.1 + - 1.5 + - 1.4.3 + - 1.4.2 + - 1.4.1 + - 1.4 + - 1.3.3 + - 1.3.2 + - 1.3.1 + - 1.3 + - 1.2.2 + - 1.2.1 + - 1.2 + - 1.1.2 + - 1.1.1 + - 1.1 +before_install: + - go get github.com/mattn/goveralls +script: + - $HOME/gopath/bin/goveralls -service=travis-ci notifications: email: on_success: never +matrix: + fast_finish: true + allow_failures: + - go: tip + - go: 1.6.4 + - go: 1.6.3 + - go: 1.6.2 + - go: 1.6.1 + - go: 1.6 + - go: 1.5.4 + - go: 1.5.3 + - go: 1.5.2 + - go: 1.5.1 + - go: 1.5 + - go: 1.4.3 + - go: 1.4.2 + - go: 1.4.1 + - go: 1.4 + - go: 1.3.3 + - go: 1.3.2 + - go: 1.3.1 + - go: 1.3 + - go: 1.2.2 + - go: 1.2.1 + - go: 1.2 + - go: 1.1.2 + - go: 1.1.1 + - go: 1.1 diff --git a/vendor/github.com/agext/levenshtein/README.md b/vendor/github.com/agext/levenshtein/README.md index 9e425587..90509c2a 100644 --- a/vendor/github.com/agext/levenshtein/README.md +++ b/vendor/github.com/agext/levenshtein/README.md @@ -11,7 +11,7 @@ This package implements distance and similarity metrics for strings, based on th ## Project Status -v1.2.2 Stable: Guaranteed no breaking changes to the API in future v1.x releases. Probably safe to use in production, though provided on "AS IS" basis. +v1.2.1 Stable: Guaranteed no breaking changes to the API in future v1.x releases. Probably safe to use in production, though provided on "AS IS" basis. This package is being actively maintained. If you encounter any problems or have any suggestions for improvement, please [open an issue](https://github.com/agext/levenshtein/issues). Pull requests are welcome. diff --git a/vendor/github.com/agext/levenshtein/go.mod b/vendor/github.com/agext/levenshtein/go.mod deleted file mode 100644 index 545d432b..00000000 --- a/vendor/github.com/agext/levenshtein/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/agext/levenshtein diff --git a/vendor/github.com/agext/levenshtein/test.sh b/vendor/github.com/agext/levenshtein/test.sh deleted file mode 100644 index c5ed7246..00000000 --- a/vendor/github.com/agext/levenshtein/test.sh +++ /dev/null @@ -1,10 +0,0 @@ -set -ev - -if [[ "$1" == "goveralls" ]]; then - echo "Testing with goveralls..." - go get github.com/mattn/goveralls - $HOME/gopath/bin/goveralls -service=travis-ci -else - echo "Testing with go test..." - go test -v ./... -fi diff --git a/vendor/github.com/armon/go-radix/go.mod b/vendor/github.com/armon/go-radix/go.mod deleted file mode 100644 index 4336aa29..00000000 --- a/vendor/github.com/armon/go-radix/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/armon/go-radix diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go index 96ddf8fc..c6355caf 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go @@ -185,107 +185,6 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "api.ecr": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{ - Hostname: "api.ecr.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - "ap-northeast-2": endpoint{ - Hostname: "api.ecr.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - "ap-south-1": endpoint{ - Hostname: "api.ecr.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - "ap-southeast-1": endpoint{ - Hostname: "api.ecr.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - "ap-southeast-2": endpoint{ - Hostname: "api.ecr.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - "ca-central-1": endpoint{ - Hostname: "api.ecr.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - "eu-central-1": endpoint{ - Hostname: "api.ecr.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - "eu-north-1": endpoint{ - Hostname: "api.ecr.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - "eu-west-1": endpoint{ - Hostname: "api.ecr.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - "eu-west-2": endpoint{ - Hostname: "api.ecr.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - "eu-west-3": endpoint{ - Hostname: "api.ecr.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - "sa-east-1": endpoint{ - Hostname: "api.ecr.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - "us-east-1": endpoint{ - Hostname: "api.ecr.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "us-east-2": endpoint{ - Hostname: "api.ecr.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "us-west-1": endpoint{ - Hostname: "api.ecr.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "us-west-2": endpoint{ - Hostname: "api.ecr.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, "api.mediatailor": service{ Endpoints: endpoints{ @@ -321,33 +220,9 @@ var awsPartition = partition{ "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "us-east-1": endpoint{}, - "us-east-1-fips": endpoint{ - Hostname: "api-fips.sagemaker.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "us-east-2": endpoint{}, - "us-east-2-fips": endpoint{ - Hostname: "api-fips.sagemaker.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "us-west-1": endpoint{}, - "us-west-1-fips": endpoint{ - Hostname: "api-fips.sagemaker.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "us-west-2": endpoint{}, - "us-west-2-fips": endpoint{ - Hostname: "api-fips.sagemaker.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "apigateway": service{ @@ -407,7 +282,6 @@ var awsPartition = partition{ }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, @@ -504,7 +378,6 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, - "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -899,9 +772,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, @@ -1019,7 +890,6 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, - "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1142,6 +1012,27 @@ var awsPartition = partition{ }, }, }, + "ecr": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "ecs": service{ Endpoints: endpoints{ @@ -1220,7 +1111,6 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -1323,17 +1213,11 @@ var awsPartition = partition{ "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "fips": endpoint{ - Hostname: "es-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "events": service{ @@ -1622,12 +1506,6 @@ var awsPartition = partition{ "kms": service{ Endpoints: endpoints{ - "ProdFips": endpoint{ - Hostname: "kms-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, @@ -1667,22 +1545,6 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "license-manager": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, "lightsail": service{ Endpoints: endpoints{ @@ -1898,12 +1760,6 @@ var awsPartition = partition{ "neptune": service{ Endpoints: endpoints{ - "ap-northeast-1": endpoint{ - Hostname: "rds.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, "ap-southeast-1": endpoint{ Hostname: "rds.ap-southeast-1.amazonaws.com", CredentialScope: credentialScope{ @@ -2082,8 +1938,6 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, @@ -2535,7 +2389,6 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, - "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2918,7 +2771,6 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, @@ -3077,23 +2929,6 @@ var awscnPartition = partition{ }, }, Services: services{ - "api.ecr": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{ - Hostname: "api.ecr.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - "cn-northwest-1": endpoint{ - Hostname: "api.ecr.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, "apigateway": service{ Endpoints: endpoints{ @@ -3214,6 +3049,13 @@ var awscnPartition = partition{ }, }, }, + "ecr": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "ecs": service{ Endpoints: endpoints{ @@ -3274,12 +3116,6 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, - "gamelift": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, "glacier": service{ Defaults: endpoint{ Protocols: []string{"http", "https"}, @@ -3518,23 +3354,6 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, - "api.ecr": service{ - - Endpoints: endpoints{ - "us-gov-east-1": endpoint{ - Hostname: "api.ecr.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - "us-gov-west-1": endpoint{ - Hostname: "api.ecr.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, "api.sagemaker": service{ Endpoints: endpoints{ @@ -3560,12 +3379,6 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, - "athena": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, "autoscaling": service{ Endpoints: endpoints{ @@ -3689,6 +3502,13 @@ var awsusgovPartition = partition{ }, }, }, + "ecr": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "ecs": service{ Endpoints: endpoints{ @@ -3743,12 +3563,6 @@ var awsusgovPartition = partition{ "es": service{ Endpoints: endpoints{ - "fips": endpoint{ - Hostname: "es-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -3775,12 +3589,6 @@ var awsusgovPartition = partition{ }, }, }, - "glue": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, "guardduty": service{ IsRegionalized: boxedTrue, Defaults: endpoint{ @@ -3830,12 +3638,6 @@ var awsusgovPartition = partition{ "kms": service{ Endpoints: endpoints{ - "ProdFips": endpoint{ - Hostname: "kms-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -4071,11 +3873,5 @@ var awsusgovPartition = partition{ }, }, }, - "workspaces": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, }, } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go index ab6cee16..8bfe6c29 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "1.16.36" +const SDKVersion = "1.16.24" diff --git a/vendor/github.com/googleapis/gax-go/.gitignore b/vendor/github.com/googleapis/gax-go/.gitignore new file mode 100644 index 00000000..289bf1eb --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/.gitignore @@ -0,0 +1 @@ +*.cover diff --git a/vendor/github.com/googleapis/gax-go/.travis.yml b/vendor/github.com/googleapis/gax-go/.travis.yml new file mode 100644 index 00000000..cc0a91e1 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/.travis.yml @@ -0,0 +1,12 @@ +sudo: false +language: go +go: + - 1.9.x + - 1.10.x + - 1.11.x +script: + - gofmt -l . + - go tool vet . + - go test -coverprofile=coverage.txt -covermode=atomic +after_success: + - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/googleapis/gax-go/CODE_OF_CONDUCT.md b/vendor/github.com/googleapis/gax-go/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..46b2a08e --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/CODE_OF_CONDUCT.md @@ -0,0 +1,43 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, +and in the interest of fostering an open and welcoming community, +we pledge to respect all people who contribute through reporting issues, +posting feature requests, updating documentation, +submitting pull requests or patches, and other activities. + +We are committed to making participation in this project +a harassment-free experience for everyone, +regardless of level of experience, gender, gender identity and expression, +sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, +such as physical or electronic +addresses, without explicit permission +* Other unethical or unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct. +By adopting this Code of Conduct, +project maintainers commit themselves to fairly and consistently +applying these principles to every aspect of managing this project. +Project maintainers who do not follow or enforce the Code of Conduct +may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by opening an issue +or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, +available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) diff --git a/vendor/github.com/googleapis/gax-go/CONTRIBUTING.md b/vendor/github.com/googleapis/gax-go/CONTRIBUTING.md new file mode 100644 index 00000000..2827b7d3 --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/CONTRIBUTING.md @@ -0,0 +1,27 @@ +Want to contribute? Great! First, read this page (including the small print at the end). + +### Before you contribute +Before we can use your code, you must sign the +[Google Individual Contributor License Agreement] +(https://cla.developers.google.com/about/google-individual) +(CLA), which you can do online. The CLA is necessary mainly because you own the +copyright to your changes, even after your contribution becomes part of our +codebase, so we need your permission to use and distribute your code. We also +need to be sure of various other things—for instance that you'll tell us if you +know that your code infringes on other people's patents. You don't have to sign +the CLA until after you've submitted your code for review and a member has +approved it, but you must do it before we can put your code into our codebase. +Before you start working on a larger contribution, you should get in touch with +us first through the issue tracker with your idea so that we can help out and +possibly guide you. Coordinating up front makes it much easier to avoid +frustration later on. + +### Code reviews +All submissions, including submissions by project members, require review. We +use Github pull requests for this purpose. + +### The small print +Contributions made by corporations are covered by a different agreement than +the one above, the +[Software Grant and Corporate Contributor License Agreement] +(https://cla.developers.google.com/about/google-corporate). diff --git a/vendor/github.com/googleapis/gax-go/v2/LICENSE b/vendor/github.com/googleapis/gax-go/LICENSE similarity index 100% rename from vendor/github.com/googleapis/gax-go/v2/LICENSE rename to vendor/github.com/googleapis/gax-go/LICENSE diff --git a/vendor/github.com/googleapis/gax-go/README.md b/vendor/github.com/googleapis/gax-go/README.md new file mode 100644 index 00000000..d6e214ef --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/README.md @@ -0,0 +1,29 @@ +Google API Extensions for Go +============================ + +[![Build Status](https://travis-ci.org/googleapis/gax-go.svg?branch=master)](https://travis-ci.org/googleapis/gax-go) +[![Code Coverage](https://img.shields.io/codecov/c/github/googleapis/gax-go.svg)](https://codecov.io/github/googleapis/gax-go) +[![GoDoc](https://godoc.org/github.com/googleapis/gax-go?status.svg)](https://godoc.org/github.com/googleapis/gax-go) + +Google API Extensions for Go (gax-go) is a set of modules which aids the +development of APIs for clients and servers based on `gRPC` and Google API +conventions. + +To install the API extensions, use: + +``` +go get -u github.com/googleapis/gax-go +``` + +**Note:** Application code will rarely need to use this library directly, +but the code generated automatically from API definition files can use it +to simplify code generation and to provide more convenient and idiomatic API surface. + +Go Versions +=========== +This library requires Go 1.6 or above. + +License +======= +BSD - please see [LICENSE](https://github.com/googleapis/gax-go/blob/master/LICENSE) +for more information. diff --git a/vendor/github.com/googleapis/gax-go/v2/call_option.go b/vendor/github.com/googleapis/gax-go/call_option.go similarity index 90% rename from vendor/github.com/googleapis/gax-go/v2/call_option.go rename to vendor/github.com/googleapis/gax-go/call_option.go index b1d53dd1..7b621643 100644 --- a/vendor/github.com/googleapis/gax-go/v2/call_option.go +++ b/vendor/github.com/googleapis/gax-go/call_option.go @@ -113,7 +113,6 @@ type Backoff struct { cur time.Duration } -// Pause returns the next time.Duration that the caller should use to backoff. func (bo *Backoff) Pause() time.Duration { if bo.Initial == 0 { bo.Initial = time.Second @@ -127,11 +126,10 @@ func (bo *Backoff) Pause() time.Duration { if bo.Multiplier < 1 { bo.Multiplier = 2 } - // Select a duration between 1ns and the current max. It might seem - // counterintuitive to have so much jitter, but - // https://www.awsarchitectureblog.com/2015/03/backoff.html argues that - // that is the best strategy. - d := time.Duration(1 + rand.Int63n(int64(bo.cur))) + // Select a duration between zero and the current max. It might seem counterintuitive to + // have so much jitter, but https://www.awsarchitectureblog.com/2015/03/backoff.html + // argues that that is the best strategy. + d := time.Duration(rand.Int63n(int64(bo.cur))) bo.cur = time.Duration(float64(bo.cur) * bo.Multiplier) if bo.cur > bo.Max { bo.cur = bo.Max @@ -145,12 +143,10 @@ func (o grpcOpt) Resolve(s *CallSettings) { s.GRPC = o } -// WithGRPCOptions allows passing gRPC call options during client creation. func WithGRPCOptions(opt ...grpc.CallOption) CallOption { return grpcOpt(append([]grpc.CallOption(nil), opt...)) } -// CallSettings allow fine-grained control over how calls are made. type CallSettings struct { // Retry returns a Retryer to be used to control retry logic of a method call. // If Retry is nil or the returned Retryer is nil, the call will not be retried. diff --git a/vendor/github.com/googleapis/gax-go/v2/gax.go b/vendor/github.com/googleapis/gax-go/gax.go similarity index 96% rename from vendor/github.com/googleapis/gax-go/v2/gax.go rename to vendor/github.com/googleapis/gax-go/gax.go index 8040dcb0..8b2900e7 100644 --- a/vendor/github.com/googleapis/gax-go/v2/gax.go +++ b/vendor/github.com/googleapis/gax-go/gax.go @@ -35,5 +35,4 @@ // to simplify code generation and to provide more convenient and idiomatic API surfaces. package gax -// Version specifies the gax-go version being used. -const Version = "2.0.3" +const Version = "2.0.0" diff --git a/vendor/github.com/googleapis/gax-go/header.go b/vendor/github.com/googleapis/gax-go/header.go new file mode 100644 index 00000000..d81455ec --- /dev/null +++ b/vendor/github.com/googleapis/gax-go/header.go @@ -0,0 +1,24 @@ +package gax + +import "bytes" + +// XGoogHeader is for use by the Google Cloud Libraries only. +// +// XGoogHeader formats key-value pairs. +// The resulting string is suitable for x-goog-api-client header. +func XGoogHeader(keyval ...string) string { + if len(keyval) == 0 { + return "" + } + if len(keyval)%2 != 0 { + panic("gax.Header: odd argument count") + } + var buf bytes.Buffer + for i := 0; i < len(keyval); i += 2 { + buf.WriteByte(' ') + buf.WriteString(keyval[i]) + buf.WriteByte('/') + buf.WriteString(keyval[i+1]) + } + return buf.String()[1:] +} diff --git a/vendor/github.com/googleapis/gax-go/v2/invoke.go b/vendor/github.com/googleapis/gax-go/invoke.go similarity index 83% rename from vendor/github.com/googleapis/gax-go/v2/invoke.go rename to vendor/github.com/googleapis/gax-go/invoke.go index fe31dd00..cb5cd2a9 100644 --- a/vendor/github.com/googleapis/gax-go/v2/invoke.go +++ b/vendor/github.com/googleapis/gax-go/invoke.go @@ -31,11 +31,10 @@ package gax import ( "context" - "strings" "time" ) -// APICall is a user defined call stub. +// A user defined call stub. type APICall func(context.Context, CallSettings) error // Invoke calls the given APICall, @@ -74,15 +73,6 @@ func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper if settings.Retry == nil { return err } - // Never retry permanent certificate errors. (e.x. if ca-certificates - // are not installed). We should only make very few, targeted - // exceptions: many (other) status=Unavailable should be retried, such - // as if there's a network hiccup, or the internet goes out for a - // minute. This is also why here we are doing string parsing instead of - // simply making Unavailable a non-retried code elsewhere. - if strings.Contains(err.Error(), "x509: certificate signed by unknown authority") { - return err - } if retryer == nil { if r := settings.Retry(); r != nil { retryer = r diff --git a/vendor/github.com/googleapis/gax-go/v2/go.mod b/vendor/github.com/googleapis/gax-go/v2/go.mod deleted file mode 100644 index c88c2052..00000000 --- a/vendor/github.com/googleapis/gax-go/v2/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/googleapis/gax-go/v2 - -require google.golang.org/grpc v1.16.0 diff --git a/vendor/github.com/googleapis/gax-go/v2/go.sum b/vendor/github.com/googleapis/gax-go/v2/go.sum deleted file mode 100644 index bad34abc..00000000 --- a/vendor/github.com/googleapis/gax-go/v2/go.sum +++ /dev/null @@ -1,26 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522 h1:Ve1ORMCxvRmSXBwJK+t3Oy+V2vRW2OetUQBq4rJIkZE= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/grpc v1.16.0 h1:dz5IJGuC2BB7qXR5AyHNwAUBhZscK2xVez7mznh72sY= -google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= -honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/github.com/googleapis/gax-go/v2/header.go b/vendor/github.com/googleapis/gax-go/v2/header.go deleted file mode 100644 index 139371a0..00000000 --- a/vendor/github.com/googleapis/gax-go/v2/header.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2018, Google Inc. -// 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. - -package gax - -import "bytes" - -// XGoogHeader is for use by the Google Cloud Libraries only. -// -// XGoogHeader formats key-value pairs. -// The resulting string is suitable for x-goog-api-client header. -func XGoogHeader(keyval ...string) string { - if len(keyval) == 0 { - return "" - } - if len(keyval)%2 != 0 { - panic("gax.Header: odd argument count") - } - var buf bytes.Buffer - for i := 0; i < len(keyval); i += 2 { - buf.WriteByte(' ') - buf.WriteString(keyval[i]) - buf.WriteByte('/') - buf.WriteString(keyval[i+1]) - } - return buf.String()[1:] -} diff --git a/vendor/github.com/hashicorp/go-getter/.travis.yml b/vendor/github.com/hashicorp/go-getter/.travis.yml index 4fe9176a..090befd1 100644 --- a/vendor/github.com/hashicorp/go-getter/.travis.yml +++ b/vendor/github.com/hashicorp/go-getter/.travis.yml @@ -9,10 +9,6 @@ addons: language: go -os: - - linux - - osx - go: - "1.11.x" diff --git a/vendor/github.com/hashicorp/go-getter/README.md b/vendor/github.com/hashicorp/go-getter/README.md index d9f8f67f..0eab9f0d 100644 --- a/vendor/github.com/hashicorp/go-getter/README.md +++ b/vendor/github.com/hashicorp/go-getter/README.md @@ -275,9 +275,6 @@ None from a private key file on disk, you would run `base64 -w0 `. **Note**: Git 2.3+ is required to use this feature. - - * `depth` - The Git clone depth. The provided number specifies the last `n` - revisions to clone from the repository. ### Mercurial (`hg`) diff --git a/vendor/github.com/hashicorp/go-getter/appveyor.yml b/vendor/github.com/hashicorp/go-getter/appveyor.yml index 1e8718e1..ec48d45e 100644 --- a/vendor/github.com/hashicorp/go-getter/appveyor.yml +++ b/vendor/github.com/hashicorp/go-getter/appveyor.yml @@ -13,4 +13,4 @@ install: go get -d -v -t ./... build_script: -- cmd: go test ./... +- cmd: go test -v ./... diff --git a/vendor/github.com/hashicorp/go-getter/checksum.go b/vendor/github.com/hashicorp/go-getter/checksum.go index ef27951b..e082e9a0 100644 --- a/vendor/github.com/hashicorp/go-getter/checksum.go +++ b/vendor/github.com/hashicorp/go-getter/checksum.go @@ -36,7 +36,6 @@ func (c *fileChecksum) checksum(source string) error { } defer f.Close() - c.Hash.Reset() if _, err := io.Copy(c.Hash, f); err != nil { return fmt.Errorf("Failed to hash: %s", err) } @@ -180,15 +179,13 @@ func (c *Client) checksumFromFile(checksumFile string, src *url.URL) (*fileCheck defer os.Remove(tempfile) c2 := &Client{ - Ctx: c.Ctx, - Getters: c.Getters, - Decompressors: c.Decompressors, - Detectors: c.Detectors, - Pwd: c.Pwd, - Dir: false, - Src: checksumFile, - Dst: tempfile, - ProgressListener: c.ProgressListener, + Getters: c.Getters, + Decompressors: c.Decompressors, + Detectors: c.Detectors, + Pwd: c.Pwd, + Dir: false, + Src: checksumFile, + Dst: tempfile, } if err = c2.Get(); err != nil { return nil, fmt.Errorf( @@ -200,15 +197,8 @@ func (c *Client) checksumFromFile(checksumFile string, src *url.URL) (*fileCheck if err != nil { return nil, err } - checksumFileDir := filepath.Dir(checksumFileURL.Path) - relpath, err := filepath.Rel(checksumFileDir, absPath) - switch { - case err == nil || - err.Error() == "Rel: can't make "+absPath+" relative to "+checksumFileDir: - // ex: on windows C:\gopath\...\content.txt cannot be relative to \ - // which is okay, may be another expected path will work. - break - default: + relpath, err := filepath.Rel(filepath.Dir(checksumFileURL.Path), absPath) + if err != nil { return nil, err } @@ -248,7 +238,7 @@ func (c *Client) checksumFromFile(checksumFile string, src *url.URL) (*fileCheck } // make sure the checksum is for the right file for _, option := range options { - if option != "" && checksum.Filename == option { + if checksum.Filename == option { // any checksum will work so we return the first one return checksum, nil } diff --git a/vendor/github.com/hashicorp/go-getter/common.go b/vendor/github.com/hashicorp/go-getter/common.go index d2afd8ad..c4e157a6 100644 --- a/vendor/github.com/hashicorp/go-getter/common.go +++ b/vendor/github.com/hashicorp/go-getter/common.go @@ -9,6 +9,5 @@ func tmpFile(dir, pattern string) (string, error) { if err != nil { return "", err } - f.Close() return f.Name(), nil } diff --git a/vendor/github.com/hashicorp/go-getter/get_file.go b/vendor/github.com/hashicorp/go-getter/get_file.go index 78660839..786219f0 100644 --- a/vendor/github.com/hashicorp/go-getter/get_file.go +++ b/vendor/github.com/hashicorp/go-getter/get_file.go @@ -10,9 +10,7 @@ import ( type FileGetter struct { getter - // Copy, if set to true, will copy data instead of using a symlink. If - // false, attempts to symlink to speed up the operation and to lower the - // disk space usage. If the symlink fails, may attempt to copy on windows. + // Copy, if set to true, will copy data instead of using a symlink Copy bool } diff --git a/vendor/github.com/hashicorp/go-getter/get_file_windows.go b/vendor/github.com/hashicorp/go-getter/get_file_windows.go index 24f1acb1..621dce7c 100644 --- a/vendor/github.com/hashicorp/go-getter/get_file_windows.go +++ b/vendor/github.com/hashicorp/go-getter/get_file_windows.go @@ -9,7 +9,6 @@ import ( "os/exec" "path/filepath" "strings" - "syscall" ) func (g *FileGetter) Get(dst string, u *url.URL) error { @@ -94,21 +93,7 @@ func (g *FileGetter) GetFile(dst string, u *url.URL) error { // If we're not copying, just symlink and we're done if !g.Copy { - if err = os.Symlink(path, dst); err == nil { - return err - } - lerr, ok := err.(*os.LinkError) - if !ok { - return err - } - switch lerr.Err { - case syscall.ERROR_PRIVILEGE_NOT_HELD: - // no symlink privilege, let's - // fallback to a copy to avoid an error. - break - default: - return err - } + return os.Symlink(path, dst) } // Copy diff --git a/vendor/github.com/hashicorp/go-getter/get_git.go b/vendor/github.com/hashicorp/go-getter/get_git.go index 2ff00d20..d27919d3 100644 --- a/vendor/github.com/hashicorp/go-getter/get_git.go +++ b/vendor/github.com/hashicorp/go-getter/get_git.go @@ -9,8 +9,6 @@ import ( "os" "os/exec" "path/filepath" - "runtime" - "strconv" "strings" urlhelper "github.com/hashicorp/go-getter/helper/url" @@ -36,7 +34,6 @@ func (g *GitGetter) Get(dst string, u *url.URL) error { // Extract some query parameters we use var ref, sshKey string - var depth int q := u.Query() if len(q) > 0 { ref = q.Get("ref") @@ -45,11 +42,6 @@ func (g *GitGetter) Get(dst string, u *url.URL) error { sshKey = q.Get("sshkey") q.Del("sshkey") - if n, err := strconv.Atoi(q.Get("depth")); err == nil { - depth = n - } - q.Del("depth") - // Copy the URL var newU url.URL = *u u = &newU @@ -116,9 +108,9 @@ func (g *GitGetter) Get(dst string, u *url.URL) error { return err } if err == nil { - err = g.update(ctx, dst, sshKeyFile, ref, depth) + err = g.update(ctx, dst, sshKeyFile, ref) } else { - err = g.clone(ctx, dst, sshKeyFile, u, depth) + err = g.clone(ctx, dst, sshKeyFile, u) } if err != nil { return err @@ -132,7 +124,7 @@ func (g *GitGetter) Get(dst string, u *url.URL) error { } // Lastly, download any/all submodules. - return g.fetchSubmodules(ctx, dst, sshKeyFile, depth) + return g.fetchSubmodules(ctx, dst, sshKeyFile) } // GetFile for Git doesn't support updating at this time. It will download @@ -170,20 +162,13 @@ func (g *GitGetter) checkout(dst string, ref string) error { return getRunCommand(cmd) } -func (g *GitGetter) clone(ctx context.Context, dst, sshKeyFile string, u *url.URL, depth int) error { - args := []string{"clone"} - - if depth > 0 { - args = append(args, "--depth", strconv.Itoa(depth)) - } - - args = append(args, u.String(), dst) - cmd := exec.CommandContext(ctx, "git", args...) +func (g *GitGetter) clone(ctx context.Context, dst, sshKeyFile string, u *url.URL) error { + cmd := exec.CommandContext(ctx, "git", "clone", u.String(), dst) setupGitEnv(cmd, sshKeyFile) return getRunCommand(cmd) } -func (g *GitGetter) update(ctx context.Context, dst, sshKeyFile, ref string, depth int) error { +func (g *GitGetter) update(ctx context.Context, dst, sshKeyFile, ref string) error { // Determine if we're a branch. If we're NOT a branch, then we just // switch to master prior to checking out cmd := exec.CommandContext(ctx, "git", "show-ref", "-q", "--verify", "refs/heads/"+ref) @@ -201,24 +186,15 @@ func (g *GitGetter) update(ctx context.Context, dst, sshKeyFile, ref string, dep return err } - if depth > 0 { - cmd = exec.Command("git", "pull", "--depth", strconv.Itoa(depth), "--ff-only") - } else { - cmd = exec.Command("git", "pull", "--ff-only") - } - + cmd = exec.Command("git", "pull", "--ff-only") cmd.Dir = dst setupGitEnv(cmd, sshKeyFile) return getRunCommand(cmd) } // fetchSubmodules downloads any configured submodules recursively. -func (g *GitGetter) fetchSubmodules(ctx context.Context, dst, sshKeyFile string, depth int) error { - args := []string{"submodule", "update", "--init", "--recursive"} - if depth > 0 { - args = append(args, "--depth", strconv.Itoa(depth)) - } - cmd := exec.CommandContext(ctx, "git", args...) +func (g *GitGetter) fetchSubmodules(ctx context.Context, dst, sshKeyFile string) error { + cmd := exec.CommandContext(ctx, "git", "submodule", "update", "--init", "--recursive") cmd.Dir = dst setupGitEnv(cmd, sshKeyFile) return getRunCommand(cmd) @@ -235,7 +211,7 @@ func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { // with versions of Go < 1.9. env := os.Environ() for i, v := range env { - if strings.HasPrefix(v, gitSSHCommand) && len(v) > len(gitSSHCommand) { + if strings.HasPrefix(v, gitSSHCommand) { sshCmd = []string{v} env[i], env[len(env)-1] = env[len(env)-1], env[i] @@ -250,9 +226,6 @@ func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { if sshKeyFile != "" { // We have an SSH key temp file configured, tell ssh about this. - if runtime.GOOS == "windows" { - sshKeyFile = strings.Replace(sshKeyFile, `\`, `/`, -1) - } sshCmd = append(sshCmd, "-i", sshKeyFile) } @@ -278,17 +251,8 @@ func checkGitVersion(min string) error { if len(fields) < 3 { return fmt.Errorf("Unexpected 'git version' output: %q", string(out)) } - v := fields[2] - if runtime.GOOS == "windows" && strings.Contains(v, ".windows.") { - // on windows, git version will return for example: - // git version 2.20.1.windows.1 - // Which does not follow the semantic versionning specs - // https://semver.org. We remove that part in order for - // go-version to not error. - v = v[:strings.Index(v, ".windows.")] - } - have, err := version.NewVersion(v) + have, err := version.NewVersion(fields[2]) if err != nil { return err } diff --git a/vendor/github.com/hashicorp/go-getter/get_http.go b/vendor/github.com/hashicorp/go-getter/get_http.go index 7c4541c6..ae04f27f 100644 --- a/vendor/github.com/hashicorp/go-getter/get_http.go +++ b/vendor/github.com/hashicorp/go-getter/get_http.go @@ -146,7 +146,6 @@ func (g *HttpGetter) GetFile(dst string, src *url.URL) error { if err != nil { return err } - defer f.Close() if g.Client == nil { g.Client = httpClient @@ -212,6 +211,9 @@ func (g *HttpGetter) GetFile(dst string, src *url.URL) error { if err == nil && n < resp.ContentLength { err = io.ErrShortWrite } + if err1 := f.Close(); err == nil { + err = err1 + } return err } diff --git a/vendor/github.com/hashicorp/go-getter/go.mod b/vendor/github.com/hashicorp/go-getter/go.mod index d9e9edd1..aae6af62 100644 --- a/vendor/github.com/hashicorp/go-getter/go.mod +++ b/vendor/github.com/hashicorp/go-getter/go.mod @@ -8,7 +8,7 @@ require ( github.com/fatih/color v1.7.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.0 github.com/hashicorp/go-safetemp v1.0.0 - github.com/hashicorp/go-version v1.1.0 + github.com/hashicorp/go-version v1.0.0 github.com/mattn/go-colorable v0.0.9 // indirect github.com/mattn/go-isatty v0.0.4 // indirect github.com/mattn/go-runewidth v0.0.4 // indirect diff --git a/vendor/github.com/hashicorp/go-getter/go.sum b/vendor/github.com/hashicorp/go-getter/go.sum index 79799fb1..44098948 100644 --- a/vendor/github.com/hashicorp/go-getter/go.sum +++ b/vendor/github.com/hashicorp/go-getter/go.sum @@ -14,8 +14,6 @@ github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhE github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= github.com/hashicorp/go-version v1.0.0 h1:21MVWPKDphxa7ineQQTrCU5brh7OuVVAzGOCnnCPtE8= github.com/hashicorp/go-version v1.0.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0= -github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8 h1:12VvqtR6Aowv3l/EQUlocDHW2Cp4G9WJVH7uyH8QFJE= github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= diff --git a/vendor/github.com/hashicorp/go-getter/helper/url/url_windows.go b/vendor/github.com/hashicorp/go-getter/helper/url/url_windows.go index 4280ec59..4655226f 100644 --- a/vendor/github.com/hashicorp/go-getter/helper/url/url_windows.go +++ b/vendor/github.com/hashicorp/go-getter/helper/url/url_windows.go @@ -11,18 +11,19 @@ func parse(rawURL string) (*url.URL, error) { // Make sure we're using "/" since URLs are "/"-based. rawURL = filepath.ToSlash(rawURL) - if len(rawURL) > 1 && rawURL[1] == ':' { - // Assume we're dealing with a drive letter. In which case we - // force the 'file' scheme to avoid "net/url" URL.String() prepending - // our url with "./". - rawURL = "file://" + rawURL - } - u, err := url.Parse(rawURL) if err != nil { return nil, err } + if len(rawURL) > 1 && rawURL[1] == ':' { + // Assume we're dealing with a drive letter file path where the drive + // letter has been parsed into the URL Scheme, and the rest of the path + // has been parsed into the URL Path without the leading ':' character. + u.Path = fmt.Sprintf("%s:%s", string(rawURL[0]), u.Path) + u.Scheme = "" + } + if len(u.Host) > 1 && u.Host[1] == ':' && strings.HasPrefix(rawURL, "file://") { // Assume we're dealing with a drive letter file path where the drive // letter has been parsed into the URL Host. diff --git a/vendor/github.com/hashicorp/go-plugin/client.go b/vendor/github.com/hashicorp/go-plugin/client.go index 2a8b42fc..42de0fc5 100644 --- a/vendor/github.com/hashicorp/go-plugin/client.go +++ b/vendor/github.com/hashicorp/go-plugin/client.go @@ -21,6 +21,7 @@ import ( "sync" "sync/atomic" "time" + "unicode" hclog "github.com/hashicorp/go-hclog" ) @@ -932,48 +933,21 @@ func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) { return conn, nil } -var stdErrBufferSize = 64 * 1024 - func (c *Client) logStderr(r io.Reader) { defer c.clientWaitGroup.Done() + + scanner := bufio.NewScanner(r) l := c.logger.Named(filepath.Base(c.config.Cmd.Path)) - reader := bufio.NewReaderSize(r, stdErrBufferSize) - // continuation indicates the previous line was a prefix - continuation := false - - for { - line, isPrefix, err := reader.ReadLine() - switch { - case err == io.EOF: - return - case err != nil: - l.Error("reading plugin stderr", "error", err) - return - } - - c.config.Stderr.Write(line) - - // The line was longer than our max token size, so it's likely - // incomplete and won't unmarshal. - if isPrefix || continuation { - l.Debug(string(line)) - - // if we're finishing a continued line, add the newline back in - if !isPrefix { - c.config.Stderr.Write([]byte{'\n'}) - } - - continuation = isPrefix - continue - } - - c.config.Stderr.Write([]byte{'\n'}) + for scanner.Scan() { + line := scanner.Text() + c.config.Stderr.Write([]byte(line + "\n")) + line = strings.TrimRightFunc(line, unicode.IsSpace) entry, err := parseJSON(line) // If output is not JSON format, print directly to Debug if err != nil { - l.Debug(string(line)) + l.Debug(line) } else { out := flattenKVPairs(entry.KVPairs) @@ -992,4 +966,8 @@ func (c *Client) logStderr(r io.Reader) { } } } + + if err := scanner.Err(); err != nil { + l.Error("reading plugin stderr", "error", err) + } } diff --git a/vendor/github.com/hashicorp/go-plugin/go.mod b/vendor/github.com/hashicorp/go-plugin/go.mod index f3ddf44e..20112852 100644 --- a/vendor/github.com/hashicorp/go-plugin/go.mod +++ b/vendor/github.com/hashicorp/go-plugin/go.mod @@ -1,16 +1,12 @@ module github.com/hashicorp/go-plugin require ( - github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect github.com/golang/protobuf v1.2.0 github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 github.com/oklog/run v1.0.0 - github.com/stretchr/testify v1.3.0 // indirect golang.org/x/net v0.0.0-20180826012351-8a410e7b638d - golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 // indirect - golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc // indirect golang.org/x/text v0.3.0 // indirect google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 // indirect google.golang.org/grpc v1.14.0 diff --git a/vendor/github.com/hashicorp/go-plugin/go.sum b/vendor/github.com/hashicorp/go-plugin/go.sum index 21b14e99..9ae0bec8 100644 --- a/vendor/github.com/hashicorp/go-plugin/go.sum +++ b/vendor/github.com/hashicorp/go-plugin/go.sum @@ -1,7 +1,3 @@ -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd h1:rNuUHR+CvK1IS89MMtcF0EpcVMZtjKfPRp4MEmt/aTs= @@ -12,17 +8,8 @@ github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 h1: github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc h1:WiYx1rIFmx8c0mXAFtv5D/mHyKe1+jmuP7PViuwqwuQ= -golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_broker.go b/vendor/github.com/hashicorp/go-plugin/grpc_broker.go index daf142d1..1a13780b 100644 --- a/vendor/github.com/hashicorp/go-plugin/grpc_broker.go +++ b/vendor/github.com/hashicorp/go-plugin/grpc_broker.go @@ -11,7 +11,7 @@ import ( "sync/atomic" "time" - "github.com/hashicorp/go-plugin/internal/plugin" + "github.com/hashicorp/go-plugin/internal/proto" "github.com/oklog/run" "google.golang.org/grpc" @@ -21,14 +21,14 @@ import ( // streamer interface is used in the broker to send/receive connection // information. type streamer interface { - Send(*plugin.ConnInfo) error - Recv() (*plugin.ConnInfo, error) + Send(*proto.ConnInfo) error + Recv() (*proto.ConnInfo, error) Close() } // sendErr is used to pass errors back during a send. type sendErr struct { - i *plugin.ConnInfo + i *proto.ConnInfo ch chan error } @@ -40,7 +40,7 @@ type gRPCBrokerServer struct { send chan *sendErr // recv is used to receive connection info from the gRPC stream. - recv chan *plugin.ConnInfo + recv chan *proto.ConnInfo // quit closes down the stream. quit chan struct{} @@ -52,7 +52,7 @@ type gRPCBrokerServer struct { func newGRPCBrokerServer() *gRPCBrokerServer { return &gRPCBrokerServer{ send: make(chan *sendErr), - recv: make(chan *plugin.ConnInfo), + recv: make(chan *proto.ConnInfo), quit: make(chan struct{}), } } @@ -60,7 +60,7 @@ func newGRPCBrokerServer() *gRPCBrokerServer { // StartStream implements the GRPCBrokerServer interface and will block until // the quit channel is closed or the context reports Done. The stream will pass // connection information to/from the client. -func (s *gRPCBrokerServer) StartStream(stream plugin.GRPCBroker_StartStreamServer) error { +func (s *gRPCBrokerServer) StartStream(stream proto.GRPCBroker_StartStreamServer) error { doneCh := stream.Context().Done() defer s.Close() @@ -99,7 +99,7 @@ func (s *gRPCBrokerServer) StartStream(stream plugin.GRPCBroker_StartStreamServe // Send is used by the GRPCBroker to pass connection information into the stream // to the client. -func (s *gRPCBrokerServer) Send(i *plugin.ConnInfo) error { +func (s *gRPCBrokerServer) Send(i *proto.ConnInfo) error { ch := make(chan error) defer close(ch) @@ -117,7 +117,7 @@ func (s *gRPCBrokerServer) Send(i *plugin.ConnInfo) error { // Recv is used by the GRPCBroker to pass connection information that has been // sent from the client from the stream to the broker. -func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) { +func (s *gRPCBrokerServer) Recv() (*proto.ConnInfo, error) { select { case <-s.quit: return nil, errors.New("broker closed") @@ -138,13 +138,13 @@ func (s *gRPCBrokerServer) Close() { // streamer interfaces. type gRPCBrokerClientImpl struct { // client is the underlying GRPC client used to make calls to the server. - client plugin.GRPCBrokerClient + client proto.GRPCBrokerClient // send is used to send connection info to the gRPC stream. send chan *sendErr // recv is used to receive connection info from the gRPC stream. - recv chan *plugin.ConnInfo + recv chan *proto.ConnInfo // quit closes down the stream. quit chan struct{} @@ -155,9 +155,9 @@ type gRPCBrokerClientImpl struct { func newGRPCBrokerClient(conn *grpc.ClientConn) *gRPCBrokerClientImpl { return &gRPCBrokerClientImpl{ - client: plugin.NewGRPCBrokerClient(conn), + client: proto.NewGRPCBrokerClient(conn), send: make(chan *sendErr), - recv: make(chan *plugin.ConnInfo), + recv: make(chan *proto.ConnInfo), quit: make(chan struct{}), } } @@ -209,7 +209,7 @@ func (s *gRPCBrokerClientImpl) StartStream() error { // Send is used by the GRPCBroker to pass connection information into the stream // to the plugin. -func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error { +func (s *gRPCBrokerClientImpl) Send(i *proto.ConnInfo) error { ch := make(chan error) defer close(ch) @@ -227,7 +227,7 @@ func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error { // Recv is used by the GRPCBroker to pass connection information that has been // sent from the plugin to the broker. -func (s *gRPCBrokerClientImpl) Recv() (*plugin.ConnInfo, error) { +func (s *gRPCBrokerClientImpl) Recv() (*proto.ConnInfo, error) { select { case <-s.quit: return nil, errors.New("broker closed") @@ -268,7 +268,7 @@ type GRPCBroker struct { } type gRPCBrokerPending struct { - ch chan *plugin.ConnInfo + ch chan *proto.ConnInfo doneCh chan struct{} } @@ -290,7 +290,7 @@ func (b *GRPCBroker) Accept(id uint32) (net.Listener, error) { return nil, err } - err = b.streamer.Send(&plugin.ConnInfo{ + err = b.streamer.Send(&proto.ConnInfo{ ServiceId: id, Network: listener.Addr().Network(), Address: listener.Addr().String(), @@ -365,7 +365,7 @@ func (b *GRPCBroker) Close() error { // Dial opens a connection by ID. func (b *GRPCBroker) Dial(id uint32) (conn *grpc.ClientConn, err error) { - var c *plugin.ConnInfo + var c *proto.ConnInfo // Open the stream p := b.getStream(id) @@ -435,7 +435,7 @@ func (m *GRPCBroker) getStream(id uint32) *gRPCBrokerPending { } m.streams[id] = &gRPCBrokerPending{ - ch: make(chan *plugin.ConnInfo, 1), + ch: make(chan *proto.ConnInfo, 1), doneCh: make(chan struct{}), } return m.streams[id] diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_client.go b/vendor/github.com/hashicorp/go-plugin/grpc_client.go index 294518ed..e81f6bd6 100644 --- a/vendor/github.com/hashicorp/go-plugin/grpc_client.go +++ b/vendor/github.com/hashicorp/go-plugin/grpc_client.go @@ -6,7 +6,7 @@ import ( "net" "time" - "github.com/hashicorp/go-plugin/internal/plugin" + "github.com/hashicorp/go-plugin/internal/proto" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/credentials" @@ -61,7 +61,7 @@ func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) { Plugins: c.config.Plugins, doneCtx: doneCtx, broker: broker, - controller: plugin.NewGRPCControllerClient(conn), + controller: proto.NewGRPCControllerClient(conn), } return cl, nil @@ -75,13 +75,13 @@ type GRPCClient struct { doneCtx context.Context broker *GRPCBroker - controller plugin.GRPCControllerClient + controller proto.GRPCControllerClient } // ClientProtocol impl. func (c *GRPCClient) Close() error { c.broker.Close() - c.controller.Shutdown(c.doneCtx, &plugin.Empty{}) + c.controller.Shutdown(c.doneCtx, &proto.Empty{}) return c.Conn.Close() } diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_controller.go b/vendor/github.com/hashicorp/go-plugin/grpc_controller.go index 1a8a8e70..aa4c3811 100644 --- a/vendor/github.com/hashicorp/go-plugin/grpc_controller.go +++ b/vendor/github.com/hashicorp/go-plugin/grpc_controller.go @@ -3,7 +3,7 @@ package plugin import ( "context" - "github.com/hashicorp/go-plugin/internal/plugin" + "github.com/hashicorp/go-plugin/internal/proto" ) // GRPCControllerServer handles shutdown calls to terminate the server when the @@ -14,8 +14,8 @@ type grpcControllerServer struct { // Shutdown stops the grpc server. It first will attempt a graceful stop, then a // full stop on the server. -func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) { - resp := &plugin.Empty{} +func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *proto.Empty) (*proto.Empty, error) { + resp := &proto.Empty{} // TODO: figure out why GracefullStop doesn't work. s.server.Stop() diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_server.go b/vendor/github.com/hashicorp/go-plugin/grpc_server.go index d3dbf1ce..60df4a43 100644 --- a/vendor/github.com/hashicorp/go-plugin/grpc_server.go +++ b/vendor/github.com/hashicorp/go-plugin/grpc_server.go @@ -9,7 +9,7 @@ import ( "net" hclog "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin/internal/plugin" + "github.com/hashicorp/go-plugin/internal/proto" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/health" @@ -75,7 +75,7 @@ func (s *GRPCServer) Init() error { // Register the broker service brokerServer := newGRPCBrokerServer() - plugin.RegisterGRPCBrokerServer(s.server, brokerServer) + proto.RegisterGRPCBrokerServer(s.server, brokerServer) s.broker = newGRPCBroker(brokerServer, s.TLS) go s.broker.Run() @@ -83,7 +83,7 @@ func (s *GRPCServer) Init() error { controllerServer := &grpcControllerServer{ server: s, } - plugin.RegisterGRPCControllerServer(s.server, controllerServer) + proto.RegisterGRPCControllerServer(s.server, controllerServer) // Register all our plugins onto the gRPC server. for k, raw := range s.Plugins { diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go b/vendor/github.com/hashicorp/go-plugin/internal/proto/gen.go similarity index 86% rename from vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go rename to vendor/github.com/hashicorp/go-plugin/internal/proto/gen.go index aa2fdc81..294ea431 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go +++ b/vendor/github.com/hashicorp/go-plugin/internal/proto/gen.go @@ -1,3 +1,3 @@ //go:generate protoc -I ./ ./grpc_broker.proto ./grpc_controller.proto --go_out=plugins=grpc:. -package plugin +package proto diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go b/vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_broker.pb.go similarity index 82% rename from vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go rename to vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_broker.pb.go index b6850aa5..39522f33 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go +++ b/vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_broker.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // source: grpc_broker.proto -package plugin +package proto import ( fmt "fmt" @@ -78,24 +78,24 @@ func (m *ConnInfo) GetAddress() string { } func init() { - proto.RegisterType((*ConnInfo)(nil), "plugin.ConnInfo") + proto.RegisterType((*ConnInfo)(nil), "proto.ConnInfo") } func init() { proto.RegisterFile("grpc_broker.proto", fileDescriptor_802e9beed3ec3b28) } var fileDescriptor_802e9beed3ec3b28 = []byte{ - // 175 bytes of a gzipped FileDescriptorProto + // 164 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4c, 0x2f, 0x2a, 0x48, - 0x8e, 0x4f, 0x2a, 0xca, 0xcf, 0x4e, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2b, - 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0x53, 0x8a, 0xe5, 0xe2, 0x70, 0xce, 0xcf, 0xcb, 0xf3, 0xcc, 0x4b, - 0xcb, 0x17, 0x92, 0xe5, 0xe2, 0x2a, 0x4e, 0x2d, 0x2a, 0xcb, 0x4c, 0x4e, 0x8d, 0xcf, 0x4c, 0x91, - 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0d, 0xe2, 0x84, 0x8a, 0x78, 0xa6, 0x08, 0x49, 0x70, 0xb1, 0xe7, - 0xa5, 0x96, 0x94, 0xe7, 0x17, 0x65, 0x4b, 0x30, 0x29, 0x30, 0x6a, 0x70, 0x06, 0xc1, 0xb8, 0x20, - 0x99, 0xc4, 0x94, 0x94, 0xa2, 0xd4, 0xe2, 0x62, 0x09, 0x66, 0x88, 0x0c, 0x94, 0x6b, 0xe4, 0xcc, - 0xc5, 0xe5, 0x1e, 0x14, 0xe0, 0xec, 0x04, 0xb6, 0x5a, 0xc8, 0x94, 0x8b, 0x3b, 0xb8, 0x24, 0xb1, - 0xa8, 0x24, 0xb8, 0xa4, 0x28, 0x35, 0x31, 0x57, 0x48, 0x40, 0x0f, 0xe2, 0x08, 0x3d, 0x98, 0x0b, - 0xa4, 0x30, 0x44, 0x34, 0x18, 0x0d, 0x18, 0x9d, 0x38, 0xa2, 0xa0, 0xae, 0x4d, 0x62, 0x03, 0x3b, - 0xde, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x10, 0x15, 0x39, 0x47, 0xd1, 0x00, 0x00, 0x00, + 0x8e, 0x4f, 0x2a, 0xca, 0xcf, 0x4e, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x05, + 0x53, 0x4a, 0xb1, 0x5c, 0x1c, 0xce, 0xf9, 0x79, 0x79, 0x9e, 0x79, 0x69, 0xf9, 0x42, 0xb2, 0x5c, + 0x5c, 0xc5, 0xa9, 0x45, 0x65, 0x99, 0xc9, 0xa9, 0xf1, 0x99, 0x29, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, + 0xbc, 0x41, 0x9c, 0x50, 0x11, 0xcf, 0x14, 0x21, 0x09, 0x2e, 0xf6, 0xbc, 0xd4, 0x92, 0xf2, 0xfc, + 0xa2, 0x6c, 0x09, 0x26, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x18, 0x17, 0x24, 0x93, 0x98, 0x92, 0x52, + 0x94, 0x5a, 0x5c, 0x2c, 0xc1, 0x0c, 0x91, 0x81, 0x72, 0x8d, 0x1c, 0xb9, 0xb8, 0xdc, 0x83, 0x02, + 0x9c, 0x9d, 0xc0, 0x36, 0x0b, 0x19, 0x73, 0x71, 0x07, 0x97, 0x24, 0x16, 0x95, 0x04, 0x97, 0x14, + 0xa5, 0x26, 0xe6, 0x0a, 0xf1, 0x43, 0x9c, 0xa2, 0x07, 0x73, 0x80, 0x14, 0xba, 0x80, 0x06, 0xa3, + 0x01, 0x63, 0x12, 0x1b, 0x58, 0xcc, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x7a, 0xda, 0xd5, 0x84, + 0xc4, 0x00, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -122,7 +122,7 @@ func NewGRPCBrokerClient(cc *grpc.ClientConn) GRPCBrokerClient { } func (c *gRPCBrokerClient) StartStream(ctx context.Context, opts ...grpc.CallOption) (GRPCBroker_StartStreamClient, error) { - stream, err := c.cc.NewStream(ctx, &_GRPCBroker_serviceDesc.Streams[0], "/plugin.GRPCBroker/StartStream", opts...) + stream, err := c.cc.NewStream(ctx, &_GRPCBroker_serviceDesc.Streams[0], "/proto.GRPCBroker/StartStream", opts...) if err != nil { return nil, err } @@ -188,7 +188,7 @@ func (x *gRPCBrokerStartStreamServer) Recv() (*ConnInfo, error) { } var _GRPCBroker_serviceDesc = grpc.ServiceDesc{ - ServiceName: "plugin.GRPCBroker", + ServiceName: "proto.GRPCBroker", HandlerType: (*GRPCBrokerServer)(nil), Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{ diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto b/vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_broker.proto similarity index 81% rename from vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto rename to vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_broker.proto index 3fa79e8a..7d978d27 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto +++ b/vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_broker.proto @@ -1,6 +1,5 @@ syntax = "proto3"; -package plugin; -option go_package = "plugin"; +package proto; message ConnInfo { uint32 service_id = 1; diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go b/vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_controller.pb.go similarity index 84% rename from vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go rename to vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_controller.pb.go index 38b42043..bb780d7f 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go +++ b/vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_controller.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // source: grpc_controller.proto -package plugin +package proto import ( fmt "fmt" @@ -54,20 +54,20 @@ func (m *Empty) XXX_DiscardUnknown() { var xxx_messageInfo_Empty proto.InternalMessageInfo func init() { - proto.RegisterType((*Empty)(nil), "plugin.Empty") + proto.RegisterType((*Empty)(nil), "proto.Empty") } func init() { proto.RegisterFile("grpc_controller.proto", fileDescriptor_23c2c7e42feab570) } var fileDescriptor_23c2c7e42feab570 = []byte{ - // 108 bytes of a gzipped FileDescriptorProto + // 97 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0x2f, 0x2a, 0x48, 0x8e, 0x4f, 0xce, 0xcf, 0x2b, 0x29, 0xca, 0xcf, 0xc9, 0x49, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, - 0xc9, 0x17, 0x62, 0x2b, 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0x53, 0x62, 0xe7, 0x62, 0x75, 0xcd, 0x2d, - 0x28, 0xa9, 0x34, 0xb2, 0xe2, 0xe2, 0x73, 0x0f, 0x0a, 0x70, 0x76, 0x86, 0x2b, 0x14, 0xd2, 0xe0, - 0xe2, 0x08, 0xce, 0x28, 0x2d, 0x49, 0xc9, 0x2f, 0xcf, 0x13, 0xe2, 0xd5, 0x83, 0xa8, 0xd7, 0x03, - 0x2b, 0x96, 0x42, 0xe5, 0x3a, 0x71, 0x44, 0x41, 0x8d, 0x4b, 0x62, 0x03, 0x9b, 0x6e, 0x0c, 0x08, - 0x00, 0x00, 0xff, 0xff, 0xab, 0x7c, 0x27, 0xe5, 0x76, 0x00, 0x00, 0x00, + 0xc9, 0x17, 0x62, 0x05, 0x53, 0x4a, 0xec, 0x5c, 0xac, 0xae, 0xb9, 0x05, 0x25, 0x95, 0x46, 0x16, + 0x5c, 0x7c, 0xee, 0x41, 0x01, 0xce, 0xce, 0x70, 0x75, 0x42, 0x6a, 0x5c, 0x1c, 0xc1, 0x19, 0xa5, + 0x25, 0x29, 0xf9, 0xe5, 0x79, 0x42, 0x3c, 0x10, 0x5d, 0x7a, 0x60, 0xb5, 0x52, 0x28, 0xbc, 0x24, + 0x36, 0x30, 0xc7, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x69, 0xa1, 0xad, 0x79, 0x69, 0x00, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -95,7 +95,7 @@ func NewGRPCControllerClient(cc *grpc.ClientConn) GRPCControllerClient { func (c *gRPCControllerClient) Shutdown(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { out := new(Empty) - err := c.cc.Invoke(ctx, "/plugin.GRPCController/Shutdown", in, out, opts...) + err := c.cc.Invoke(ctx, "/proto.GRPCController/Shutdown", in, out, opts...) if err != nil { return nil, err } @@ -121,7 +121,7 @@ func _GRPCController_Shutdown_Handler(srv interface{}, ctx context.Context, dec } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/plugin.GRPCController/Shutdown", + FullMethod: "/proto.GRPCController/Shutdown", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GRPCControllerServer).Shutdown(ctx, req.(*Empty)) @@ -130,7 +130,7 @@ func _GRPCController_Shutdown_Handler(srv interface{}, ctx context.Context, dec } var _GRPCController_serviceDesc = grpc.ServiceDesc{ - ServiceName: "plugin.GRPCController", + ServiceName: "proto.GRPCController", HandlerType: (*GRPCControllerServer)(nil), Methods: []grpc.MethodDesc{ { diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.proto b/vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_controller.proto similarity index 80% rename from vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.proto rename to vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_controller.proto index 345d0a1c..ecdf4e6e 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.proto +++ b/vendor/github.com/hashicorp/go-plugin/internal/proto/grpc_controller.proto @@ -1,6 +1,5 @@ syntax = "proto3"; -package plugin; -option go_package = "plugin"; +package proto; message Empty { } diff --git a/vendor/github.com/hashicorp/go-plugin/log_entry.go b/vendor/github.com/hashicorp/go-plugin/log_entry.go index fb2ef930..2996c14c 100644 --- a/vendor/github.com/hashicorp/go-plugin/log_entry.go +++ b/vendor/github.com/hashicorp/go-plugin/log_entry.go @@ -32,11 +32,11 @@ func flattenKVPairs(kvs []*logEntryKV) []interface{} { } // parseJSON handles parsing JSON output -func parseJSON(input []byte) (*logEntry, error) { +func parseJSON(input string) (*logEntry, error) { var raw map[string]interface{} entry := &logEntry{} - err := json.Unmarshal(input, &raw) + err := json.Unmarshal([]byte(input), &raw) if err != nil { return nil, err } diff --git a/vendor/github.com/hashicorp/go-plugin/testing.go b/vendor/github.com/hashicorp/go-plugin/testing.go index 2cf2c26c..8a8d1156 100644 --- a/vendor/github.com/hashicorp/go-plugin/testing.go +++ b/vendor/github.com/hashicorp/go-plugin/testing.go @@ -7,9 +7,9 @@ import ( "net" "net/rpc" - "github.com/mitchellh/go-testing-interface" hclog "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin/internal/plugin" + "github.com/hashicorp/go-plugin/internal/proto" + "github.com/mitchellh/go-testing-interface" "google.golang.org/grpc" ) @@ -173,7 +173,7 @@ func TestPluginGRPCConn(t testing.T, ps map[string]Plugin) (*GRPCClient, *GRPCSe Plugins: ps, broker: broker, doneCtx: context.Background(), - controller: plugin.NewGRPCControllerClient(conn), + controller: proto.NewGRPCControllerClient(conn), } return client, server diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/README.md b/vendor/github.com/hashicorp/hcl2/ext/dynblock/README.md deleted file mode 100644 index 2b24fdbe..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/README.md +++ /dev/null @@ -1,184 +0,0 @@ -# HCL Dynamic Blocks Extension - -This HCL extension implements a special block type named "dynamic" that can -be used to dynamically generate blocks of other types by iterating over -collection values. - -Normally the block structure in an HCL configuration file is rigid, even -though dynamic expressions can be used within attribute values. This is -convenient for most applications since it allows the overall structure of -the document to be decoded easily, but in some applications it is desirable -to allow dynamic block generation within certain portions of the configuration. - -Dynamic block generation is performed using the `dynamic` block type: - -```hcl -toplevel { - nested { - foo = "static block 1" - } - - dynamic "nested" { - for_each = ["a", "b", "c"] - iterator = nested - content { - foo = "dynamic block ${nested.value}" - } - } - - nested { - foo = "static block 2" - } -} -``` - -The above is interpreted as if it were written as follows: - -```hcl -toplevel { - nested { - foo = "static block 1" - } - - nested { - foo = "dynamic block a" - } - - nested { - foo = "dynamic block b" - } - - nested { - foo = "dynamic block c" - } - - nested { - foo = "static block 2" - } -} -``` - -Since HCL block syntax is not normally exposed to the possibility of unknown -values, this extension must make some compromises when asked to iterate over -an unknown collection. If the length of the collection cannot be statically -recognized (because it is an unknown value of list, map, or set type) then -the `dynamic` construct will generate a _single_ dynamic block whose iterator -key and value are both unknown values of the dynamic pseudo-type, thus causing -any attribute values derived from iteration to appear as unknown values. There -is no explicit representation of the fact that the length of the collection may -eventually be different than one. - -## Usage - -Pass a body to function `Expand` to obtain a new body that will, on access -to its content, evaluate and expand any nested `dynamic` blocks. -Dynamic block processing is also automatically propagated into any nested -blocks that are returned, allowing users to nest dynamic blocks inside -one another and to nest dynamic blocks inside other static blocks. - -HCL structural decoding does not normally have access to an `EvalContext`, so -any variables and functions that should be available to the `for_each` -and `labels` expressions must be passed in when calling `Expand`. Expressions -within the `content` block are evaluated separately and so can be passed a -separate `EvalContext` if desired, during normal attribute expression -evaluation. - -## Detecting Variables - -Some applications dynamically generate an `EvalContext` by analyzing which -variables are referenced by an expression before evaluating it. - -This unfortunately requires some extra effort when this analysis is required -for the context passed to `Expand`: the HCL API requires a schema to be -provided in order to do any analysis of the blocks in a body, but the low-level -schema model provides a description of only one level of nested blocks at -a time, and thus a new schema must be provided for each additional level of -nesting. - -To make this arduous process as convenient as possbile, this package provides -a helper function `WalkForEachVariables`, which returns a `WalkVariablesNode` -instance that can be used to find variables directly in a given body and also -determine which nested blocks require recursive calls. Using this mechanism -requires that the caller be able to look up a schema given a nested block type. -For _simple_ formats where a specific block type name always has the same schema -regardless of context, a walk can be implemented as follows: - -```go -func walkVariables(node dynblock.WalkVariablesNode, schema *hcl.BodySchema) []hcl.Traversal { - vars, children := node.Visit(schema) - - for _, child := range children { - var childSchema *hcl.BodySchema - switch child.BlockTypeName { - case "a": - childSchema = &hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "b", - LabelNames: []string{"key"}, - }, - }, - } - case "b": - childSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "val", - Required: true, - }, - }, - } - default: - // Should never happen, because the above cases should be exhaustive - // for the application's configuration format. - panic(fmt.Errorf("can't find schema for unknown block type %q", child.BlockTypeName)) - } - - vars = append(vars, testWalkAndAccumVars(child.Node, childSchema)...) - } -} -``` - -### Detecting Variables with `hcldec` Specifications - -For applications that use the higher-level `hcldec` package to decode nested -configuration structures into `cty` values, the same specification can be used -to automatically drive the recursive variable-detection walk described above. - -The helper function `ForEachVariablesHCLDec` allows an entire recursive -configuration structure to be analyzed in a single call given a `hcldec.Spec` -that describes the nested block structure. This means a `hcldec`-based -application can support dynamic blocks with only a little additional effort: - -```go -func decodeBody(body hcl.Body, spec hcldec.Spec) (cty.Value, hcl.Diagnostics) { - // Determine which variables are needed to expand dynamic blocks - neededForDynamic := dynblock.ForEachVariablesHCLDec(body, spec) - - // Build a suitable EvalContext and expand dynamic blocks - dynCtx := buildEvalContext(neededForDynamic) - dynBody := dynblock.Expand(body, dynCtx) - - // Determine which variables are needed to fully decode the expanded body - // This will analyze expressions that came both from static blocks in the - // original body and from blocks that were dynamically added by Expand. - neededForDecode := hcldec.Variables(dynBody, spec) - - // Build a suitable EvalContext and then fully decode the body as per the - // hcldec specification. - decCtx := buildEvalContext(neededForDecode) - return hcldec.Decode(dynBody, spec, decCtx) -} - -func buildEvalContext(needed []hcl.Traversal) *hcl.EvalContext { - // (to be implemented by your application) -} -``` - -# Performance - -This extension is going quite harshly against the grain of the HCL API, and -so it uses lots of wrapping objects and temporary data structures to get its -work done. HCL in general is not suitable for use in high-performance situations -or situations sensitive to memory pressure, but that is _especially_ true for -this extension. diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/expand_body.go b/vendor/github.com/hashicorp/hcl2/ext/dynblock/expand_body.go deleted file mode 100644 index 97d1e4dd..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/expand_body.go +++ /dev/null @@ -1,252 +0,0 @@ -package dynblock - -import ( - "fmt" - - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" -) - -// expandBody wraps another hcl.Body and expands any "dynamic" blocks found -// inside whenever Content or PartialContent is called. -type expandBody struct { - original hcl.Body - forEachCtx *hcl.EvalContext - iteration *iteration // non-nil if we're nested inside another "dynamic" block - - // These are used with PartialContent to produce a "remaining items" - // body to return. They are nil on all bodies fresh out of the transformer. - // - // Note that this is re-implemented here rather than delegating to the - // existing support required by the underlying body because we need to - // retain access to the entire original body on subsequent decode operations - // so we can retain any "dynamic" blocks for types we didn't take consume - // on the first pass. - hiddenAttrs map[string]struct{} - hiddenBlocks map[string]hcl.BlockHeaderSchema -} - -func (b *expandBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - extSchema := b.extendSchema(schema) - rawContent, diags := b.original.Content(extSchema) - - blocks, blockDiags := b.expandBlocks(schema, rawContent.Blocks, false) - diags = append(diags, blockDiags...) - attrs := b.prepareAttributes(rawContent.Attributes) - - content := &hcl.BodyContent{ - Attributes: attrs, - Blocks: blocks, - MissingItemRange: b.original.MissingItemRange(), - } - - return content, diags -} - -func (b *expandBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - extSchema := b.extendSchema(schema) - rawContent, _, diags := b.original.PartialContent(extSchema) - // We discard the "remain" argument above because we're going to construct - // our own remain that also takes into account remaining "dynamic" blocks. - - blocks, blockDiags := b.expandBlocks(schema, rawContent.Blocks, true) - diags = append(diags, blockDiags...) - attrs := b.prepareAttributes(rawContent.Attributes) - - content := &hcl.BodyContent{ - Attributes: attrs, - Blocks: blocks, - MissingItemRange: b.original.MissingItemRange(), - } - - remain := &expandBody{ - original: b.original, - forEachCtx: b.forEachCtx, - iteration: b.iteration, - hiddenAttrs: make(map[string]struct{}), - hiddenBlocks: make(map[string]hcl.BlockHeaderSchema), - } - for name := range b.hiddenAttrs { - remain.hiddenAttrs[name] = struct{}{} - } - for typeName, blockS := range b.hiddenBlocks { - remain.hiddenBlocks[typeName] = blockS - } - for _, attrS := range schema.Attributes { - remain.hiddenAttrs[attrS.Name] = struct{}{} - } - for _, blockS := range schema.Blocks { - remain.hiddenBlocks[blockS.Type] = blockS - } - - return content, remain, diags -} - -func (b *expandBody) extendSchema(schema *hcl.BodySchema) *hcl.BodySchema { - // We augment the requested schema to also include our special "dynamic" - // block type, since then we'll get instances of it interleaved with - // all of the literal child blocks we must also include. - extSchema := &hcl.BodySchema{ - Attributes: schema.Attributes, - Blocks: make([]hcl.BlockHeaderSchema, len(schema.Blocks), len(schema.Blocks)+len(b.hiddenBlocks)+1), - } - copy(extSchema.Blocks, schema.Blocks) - extSchema.Blocks = append(extSchema.Blocks, dynamicBlockHeaderSchema) - - // If we have any hiddenBlocks then we also need to register those here - // so that a call to "Content" on the underlying body won't fail. - // (We'll filter these out again once we process the result of either - // Content or PartialContent.) - for _, blockS := range b.hiddenBlocks { - extSchema.Blocks = append(extSchema.Blocks, blockS) - } - - // If we have any hiddenAttrs then we also need to register these, for - // the same reason as we deal with hiddenBlocks above. - if len(b.hiddenAttrs) != 0 { - newAttrs := make([]hcl.AttributeSchema, len(schema.Attributes), len(schema.Attributes)+len(b.hiddenAttrs)) - copy(newAttrs, extSchema.Attributes) - for name := range b.hiddenAttrs { - newAttrs = append(newAttrs, hcl.AttributeSchema{ - Name: name, - Required: false, - }) - } - extSchema.Attributes = newAttrs - } - - return extSchema -} - -func (b *expandBody) prepareAttributes(rawAttrs hcl.Attributes) hcl.Attributes { - if len(b.hiddenAttrs) == 0 && b.iteration == nil { - // Easy path: just pass through the attrs from the original body verbatim - return rawAttrs - } - - // Otherwise we have some work to do: we must filter out any attributes - // that are hidden (since a previous PartialContent call already saw these) - // and wrap the expressions of the inner attributes so that they will - // have access to our iteration variables. - attrs := make(hcl.Attributes, len(rawAttrs)) - for name, rawAttr := range rawAttrs { - if _, hidden := b.hiddenAttrs[name]; hidden { - continue - } - if b.iteration != nil { - attr := *rawAttr // shallow copy so we can mutate it - attr.Expr = exprWrap{ - Expression: attr.Expr, - i: b.iteration, - } - attrs[name] = &attr - } else { - // If we have no active iteration then no wrapping is required. - attrs[name] = rawAttr - } - } - return attrs -} - -func (b *expandBody) expandBlocks(schema *hcl.BodySchema, rawBlocks hcl.Blocks, partial bool) (hcl.Blocks, hcl.Diagnostics) { - var blocks hcl.Blocks - var diags hcl.Diagnostics - - for _, rawBlock := range rawBlocks { - switch rawBlock.Type { - case "dynamic": - realBlockType := rawBlock.Labels[0] - if _, hidden := b.hiddenBlocks[realBlockType]; hidden { - continue - } - - var blockS *hcl.BlockHeaderSchema - for _, candidate := range schema.Blocks { - if candidate.Type == realBlockType { - blockS = &candidate - break - } - } - if blockS == nil { - // Not a block type that the caller requested. - if !partial { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported block type", - Detail: fmt.Sprintf("Blocks of type %q are not expected here.", realBlockType), - Subject: &rawBlock.LabelRanges[0], - }) - } - continue - } - - spec, specDiags := b.decodeSpec(blockS, rawBlock) - diags = append(diags, specDiags...) - if specDiags.HasErrors() { - continue - } - - if spec.forEachVal.IsKnown() { - for it := spec.forEachVal.ElementIterator(); it.Next(); { - key, value := it.Element() - i := b.iteration.MakeChild(spec.iteratorName, key, value) - - block, blockDiags := spec.newBlock(i, b.forEachCtx) - diags = append(diags, blockDiags...) - if block != nil { - // Attach our new iteration context so that attributes - // and other nested blocks can refer to our iterator. - block.Body = b.expandChild(block.Body, i) - blocks = append(blocks, block) - } - } - } else { - // If our top-level iteration value isn't known then we're forced - // to compromise since HCL doesn't have any concept of an - // "unknown block". In this case then, we'll produce a single - // dynamic block with the iterator values set to DynamicVal, - // which at least makes the potential for a block visible - // in our result, even though it's not represented in a fully-accurate - // way. - i := b.iteration.MakeChild(spec.iteratorName, cty.DynamicVal, cty.DynamicVal) - block, blockDiags := spec.newBlock(i, b.forEachCtx) - diags = append(diags, blockDiags...) - if block != nil { - block.Body = b.expandChild(block.Body, i) - blocks = append(blocks, block) - } - } - - default: - if _, hidden := b.hiddenBlocks[rawBlock.Type]; !hidden { - // A static block doesn't create a new iteration context, but - // it does need to inherit _our own_ iteration context in - // case it contains expressions that refer to our inherited - // iterators, or nested "dynamic" blocks. - expandedBlock := *rawBlock // shallow copy - expandedBlock.Body = b.expandChild(rawBlock.Body, b.iteration) - blocks = append(blocks, &expandedBlock) - } - } - } - - return blocks, diags -} - -func (b *expandBody) expandChild(child hcl.Body, i *iteration) hcl.Body { - chiCtx := i.EvalContext(b.forEachCtx) - ret := Expand(child, chiCtx) - ret.(*expandBody).iteration = i - return ret -} - -func (b *expandBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - // blocks aren't allowed in JustAttributes mode and this body can - // only produce blocks, so we'll just pass straight through to our - // underlying body here. - return b.original.JustAttributes() -} - -func (b *expandBody) MissingItemRange() hcl.Range { - return b.original.MissingItemRange() -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/expand_spec.go b/vendor/github.com/hashicorp/hcl2/ext/dynblock/expand_spec.go deleted file mode 100644 index 41c0be26..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/expand_spec.go +++ /dev/null @@ -1,215 +0,0 @@ -package dynblock - -import ( - "fmt" - - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -type expandSpec struct { - blockType string - blockTypeRange hcl.Range - defRange hcl.Range - forEachVal cty.Value - iteratorName string - labelExprs []hcl.Expression - contentBody hcl.Body - inherited map[string]*iteration -} - -func (b *expandBody) decodeSpec(blockS *hcl.BlockHeaderSchema, rawSpec *hcl.Block) (*expandSpec, hcl.Diagnostics) { - var diags hcl.Diagnostics - - var schema *hcl.BodySchema - if len(blockS.LabelNames) != 0 { - schema = dynamicBlockBodySchemaLabels - } else { - schema = dynamicBlockBodySchemaNoLabels - } - - specContent, specDiags := rawSpec.Body.Content(schema) - diags = append(diags, specDiags...) - if specDiags.HasErrors() { - return nil, diags - } - - //// for_each attribute - - eachAttr := specContent.Attributes["for_each"] - eachVal, eachDiags := eachAttr.Expr.Value(b.forEachCtx) - diags = append(diags, eachDiags...) - - if !eachVal.CanIterateElements() && eachVal.Type() != cty.DynamicPseudoType { - // We skip this error for DynamicPseudoType because that means we either - // have a null (which is checked immediately below) or an unknown - // (which is handled in the expandBody Content methods). - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic for_each value", - Detail: fmt.Sprintf("Cannot use a %s value in for_each. An iterable collection is required.", eachVal.Type().FriendlyName()), - Subject: eachAttr.Expr.Range().Ptr(), - Expression: eachAttr.Expr, - EvalContext: b.forEachCtx, - }) - return nil, diags - } - if eachVal.IsNull() { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic for_each value", - Detail: "Cannot use a null value in for_each.", - Subject: eachAttr.Expr.Range().Ptr(), - Expression: eachAttr.Expr, - EvalContext: b.forEachCtx, - }) - return nil, diags - } - - //// iterator attribute - - iteratorName := blockS.Type - if iteratorAttr := specContent.Attributes["iterator"]; iteratorAttr != nil { - itTraversal, itDiags := hcl.AbsTraversalForExpr(iteratorAttr.Expr) - diags = append(diags, itDiags...) - if itDiags.HasErrors() { - return nil, diags - } - - if len(itTraversal) != 1 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic iterator name", - Detail: "Dynamic iterator must be a single variable name.", - Subject: itTraversal.SourceRange().Ptr(), - }) - return nil, diags - } - - iteratorName = itTraversal.RootName() - } - - var labelExprs []hcl.Expression - if labelsAttr := specContent.Attributes["labels"]; labelsAttr != nil { - var labelDiags hcl.Diagnostics - labelExprs, labelDiags = hcl.ExprList(labelsAttr.Expr) - diags = append(diags, labelDiags...) - if labelDiags.HasErrors() { - return nil, diags - } - - if len(labelExprs) > len(blockS.LabelNames) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Extraneous dynamic block label", - Detail: fmt.Sprintf("Blocks of type %q require %d label(s).", blockS.Type, len(blockS.LabelNames)), - Subject: labelExprs[len(blockS.LabelNames)].Range().Ptr(), - }) - return nil, diags - } else if len(labelExprs) < len(blockS.LabelNames) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Insufficient dynamic block labels", - Detail: fmt.Sprintf("Blocks of type %q require %d label(s).", blockS.Type, len(blockS.LabelNames)), - Subject: labelsAttr.Expr.Range().Ptr(), - }) - return nil, diags - } - } - - // Since our schema requests only blocks of type "content", we can assume - // that all entries in specContent.Blocks are content blocks. - if len(specContent.Blocks) == 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing dynamic content block", - Detail: "A dynamic block must have a nested block of type \"content\" to describe the body of each generated block.", - Subject: &specContent.MissingItemRange, - }) - return nil, diags - } - if len(specContent.Blocks) > 1 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Extraneous dynamic content block", - Detail: "Only one nested content block is allowed for each dynamic block.", - Subject: &specContent.Blocks[1].DefRange, - }) - return nil, diags - } - - return &expandSpec{ - blockType: blockS.Type, - blockTypeRange: rawSpec.LabelRanges[0], - defRange: rawSpec.DefRange, - forEachVal: eachVal, - iteratorName: iteratorName, - labelExprs: labelExprs, - contentBody: specContent.Blocks[0].Body, - }, diags -} - -func (s *expandSpec) newBlock(i *iteration, ctx *hcl.EvalContext) (*hcl.Block, hcl.Diagnostics) { - var diags hcl.Diagnostics - var labels []string - var labelRanges []hcl.Range - lCtx := i.EvalContext(ctx) - for _, labelExpr := range s.labelExprs { - labelVal, labelDiags := labelExpr.Value(lCtx) - diags = append(diags, labelDiags...) - if labelDiags.HasErrors() { - return nil, diags - } - - var convErr error - labelVal, convErr = convert.Convert(labelVal, cty.String) - if convErr != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic block label", - Detail: fmt.Sprintf("Cannot use this value as a dynamic block label: %s.", convErr), - Subject: labelExpr.Range().Ptr(), - Expression: labelExpr, - EvalContext: lCtx, - }) - return nil, diags - } - if labelVal.IsNull() { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic block label", - Detail: "Cannot use a null value as a dynamic block label.", - Subject: labelExpr.Range().Ptr(), - Expression: labelExpr, - EvalContext: lCtx, - }) - return nil, diags - } - if !labelVal.IsKnown() { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic block label", - Detail: "This value is not yet known. Dynamic block labels must be immediately-known values.", - Subject: labelExpr.Range().Ptr(), - Expression: labelExpr, - EvalContext: lCtx, - }) - return nil, diags - } - - labels = append(labels, labelVal.AsString()) - labelRanges = append(labelRanges, labelExpr.Range()) - } - - block := &hcl.Block{ - Type: s.blockType, - TypeRange: s.blockTypeRange, - Labels: labels, - LabelRanges: labelRanges, - DefRange: s.defRange, - Body: s.contentBody, - } - - return block, diags -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/expr_wrap.go b/vendor/github.com/hashicorp/hcl2/ext/dynblock/expr_wrap.go deleted file mode 100644 index 6916fc15..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/expr_wrap.go +++ /dev/null @@ -1,42 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" -) - -type exprWrap struct { - hcl.Expression - i *iteration -} - -func (e exprWrap) Variables() []hcl.Traversal { - raw := e.Expression.Variables() - ret := make([]hcl.Traversal, 0, len(raw)) - - // Filter out traversals that refer to our iterator name or any - // iterator we've inherited; we're going to provide those in - // our Value wrapper, so the caller doesn't need to know about them. - for _, traversal := range raw { - rootName := traversal.RootName() - if rootName == e.i.IteratorName { - continue - } - if _, inherited := e.i.Inherited[rootName]; inherited { - continue - } - ret = append(ret, traversal) - } - return ret -} - -func (e exprWrap) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - extCtx := e.i.EvalContext(ctx) - return e.Expression.Value(extCtx) -} - -// UnwrapExpression returns the expression being wrapped by this instance. -// This allows the original expression to be recovered by hcl.UnwrapExpression. -func (e exprWrap) UnwrapExpression() hcl.Expression { - return e.Expression -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/iteration.go b/vendor/github.com/hashicorp/hcl2/ext/dynblock/iteration.go deleted file mode 100644 index 7056d336..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/iteration.go +++ /dev/null @@ -1,66 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" -) - -type iteration struct { - IteratorName string - Key cty.Value - Value cty.Value - Inherited map[string]*iteration -} - -func (s *expandSpec) MakeIteration(key, value cty.Value) *iteration { - return &iteration{ - IteratorName: s.iteratorName, - Key: key, - Value: value, - Inherited: s.inherited, - } -} - -func (i *iteration) Object() cty.Value { - return cty.ObjectVal(map[string]cty.Value{ - "key": i.Key, - "value": i.Value, - }) -} - -func (i *iteration) EvalContext(base *hcl.EvalContext) *hcl.EvalContext { - new := base.NewChild() - - if i != nil { - new.Variables = map[string]cty.Value{} - for name, otherIt := range i.Inherited { - new.Variables[name] = otherIt.Object() - } - new.Variables[i.IteratorName] = i.Object() - } - - return new -} - -func (i *iteration) MakeChild(iteratorName string, key, value cty.Value) *iteration { - if i == nil { - // Create entirely new root iteration, then - return &iteration{ - IteratorName: iteratorName, - Key: key, - Value: value, - } - } - - inherited := map[string]*iteration{} - for name, otherIt := range i.Inherited { - inherited[name] = otherIt - } - inherited[i.IteratorName] = i - return &iteration{ - IteratorName: iteratorName, - Key: key, - Value: value, - Inherited: inherited, - } -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/public.go b/vendor/github.com/hashicorp/hcl2/ext/dynblock/public.go deleted file mode 100644 index b7e8ca95..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/public.go +++ /dev/null @@ -1,44 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl2/hcl" -) - -// Expand "dynamic" blocks in the given body, returning a new body that -// has those blocks expanded. -// -// The given EvalContext is used when evaluating "for_each" and "labels" -// attributes within dynamic blocks, allowing those expressions access to -// variables and functions beyond the iterator variable created by the -// iteration. -// -// Expand returns no diagnostics because no blocks are actually expanded -// until a call to Content or PartialContent on the returned body, which -// will then expand only the blocks selected by the schema. -// -// "dynamic" blocks are also expanded automatically within nested blocks -// in the given body, including within other dynamic blocks, thus allowing -// multi-dimensional iteration. However, it is not possible to -// dynamically-generate the "dynamic" blocks themselves except through nesting. -// -// parent { -// dynamic "child" { -// for_each = child_objs -// content { -// dynamic "grandchild" { -// for_each = child.value.children -// labels = [grandchild.key] -// content { -// parent_key = child.key -// value = grandchild.value -// } -// } -// } -// } -// } -func Expand(body hcl.Body, ctx *hcl.EvalContext) hcl.Body { - return &expandBody{ - original: body, - forEachCtx: ctx, - } -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/schema.go b/vendor/github.com/hashicorp/hcl2/ext/dynblock/schema.go deleted file mode 100644 index dc8ed5a2..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/schema.go +++ /dev/null @@ -1,50 +0,0 @@ -package dynblock - -import "github.com/hashicorp/hcl2/hcl" - -var dynamicBlockHeaderSchema = hcl.BlockHeaderSchema{ - Type: "dynamic", - LabelNames: []string{"type"}, -} - -var dynamicBlockBodySchemaLabels = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "for_each", - Required: true, - }, - { - Name: "iterator", - Required: false, - }, - { - Name: "labels", - Required: true, - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "content", - LabelNames: nil, - }, - }, -} - -var dynamicBlockBodySchemaNoLabels = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "for_each", - Required: true, - }, - { - Name: "iterator", - Required: false, - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "content", - LabelNames: nil, - }, - }, -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/variables.go b/vendor/github.com/hashicorp/hcl2/ext/dynblock/variables.go deleted file mode 100644 index 9cb67168..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/variables.go +++ /dev/null @@ -1,165 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" -) - -// WalkVariables begins the recursive process of walking the variables in the -// given body that are needed by any "for_each" or "labels" attributes in -// "dynamic" blocks. The result is a WalkVariablesNode, which can extract -// root-level variable traversals and produce a list of child nodes that -// also need to be processed by calling Visit. -// -// This function requires that the caller walk through the nested block -// structure in the given body level-by-level so that an appropriate schema -// can be provided at each level to inform further processing. This workflow -// is thus easiest to use for calling applications that have some higher-level -// schema representation available with which to drive this multi-step -// process. -func WalkForEachVariables(body hcl.Body) WalkVariablesNode { - return WalkVariablesNode{ - body: body, - } -} - -type WalkVariablesNode struct { - body hcl.Body - it *iteration -} - -type WalkVariablesChild struct { - BlockTypeName string - Node WalkVariablesNode -} - -// Visit returns the variable traversals required for any "dynamic" blocks -// directly in the body associated with this node, and also returns any child -// nodes that must be visited in order to continue the walk. -// -// Each child node has its associated block type name given in its BlockTypeName -// field, which the calling application should use to determine the appropriate -// schema for the content of each child node and pass it to the child node's -// own Visit method to continue the walk recursively. -func (n WalkVariablesNode) Visit(schema *hcl.BodySchema) (vars []hcl.Traversal, children []WalkVariablesChild) { - extSchema := n.extendSchema(schema) - container, _, _ := n.body.PartialContent(extSchema) - if container == nil { - return vars, children - } - - children = make([]WalkVariablesChild, 0, len(container.Blocks)) - - for _, block := range container.Blocks { - switch block.Type { - - case "dynamic": - blockTypeName := block.Labels[0] - inner, _, _ := block.Body.PartialContent(variableDetectionInnerSchema) - if inner == nil { - continue - } - - iteratorName := blockTypeName - if attr, exists := inner.Attributes["iterator"]; exists { - iterTraversal, _ := hcl.AbsTraversalForExpr(attr.Expr) - if len(iterTraversal) == 0 { - // Ignore this invalid dynamic block, since it'll produce - // an error if someone tries to extract content from it - // later anyway. - continue - } - iteratorName = iterTraversal.RootName() - } - blockIt := n.it.MakeChild(iteratorName, cty.DynamicVal, cty.DynamicVal) - - if attr, exists := inner.Attributes["for_each"]; exists { - // Filter out iterator names inherited from parent blocks - for _, traversal := range attr.Expr.Variables() { - if _, inherited := blockIt.Inherited[traversal.RootName()]; !inherited { - vars = append(vars, traversal) - } - } - } - if attr, exists := inner.Attributes["labels"]; exists { - // Filter out both our own iterator name _and_ those inherited - // from parent blocks, since we provide _both_ of these to the - // label expressions. - for _, traversal := range attr.Expr.Variables() { - ours := traversal.RootName() == iteratorName - _, inherited := blockIt.Inherited[traversal.RootName()] - - if !(ours || inherited) { - vars = append(vars, traversal) - } - } - } - - for _, contentBlock := range inner.Blocks { - // We only request "content" blocks in our schema, so we know - // any blocks we find here will be content blocks. We require - // exactly one content block for actual expansion, but we'll - // be more liberal here so that callers can still collect - // variables from erroneous "dynamic" blocks. - children = append(children, WalkVariablesChild{ - BlockTypeName: blockTypeName, - Node: WalkVariablesNode{ - body: contentBlock.Body, - it: blockIt, - }, - }) - } - - default: - children = append(children, WalkVariablesChild{ - BlockTypeName: block.Type, - Node: WalkVariablesNode{ - body: block.Body, - it: n.it, - }, - }) - - } - } - - return vars, children -} - -func (n WalkVariablesNode) extendSchema(schema *hcl.BodySchema) *hcl.BodySchema { - // We augment the requested schema to also include our special "dynamic" - // block type, since then we'll get instances of it interleaved with - // all of the literal child blocks we must also include. - extSchema := &hcl.BodySchema{ - Attributes: schema.Attributes, - Blocks: make([]hcl.BlockHeaderSchema, len(schema.Blocks), len(schema.Blocks)+1), - } - copy(extSchema.Blocks, schema.Blocks) - extSchema.Blocks = append(extSchema.Blocks, dynamicBlockHeaderSchema) - - return extSchema -} - -// This is a more relaxed schema than what's in schema.go, since we -// want to maximize the amount of variables we can find even if there -// are erroneous blocks. -var variableDetectionInnerSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "for_each", - Required: false, - }, - { - Name: "labels", - Required: false, - }, - { - Name: "iterator", - Required: false, - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "content", - }, - }, -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/dynblock/variables_hcldec.go b/vendor/github.com/hashicorp/hcl2/ext/dynblock/variables_hcldec.go deleted file mode 100644 index 480873a5..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/dynblock/variables_hcldec.go +++ /dev/null @@ -1,33 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcldec" -) - -// ForEachVariablesHCLDec is a wrapper around WalkForEachVariables that -// uses the given hcldec specification to automatically drive the recursive -// walk through nested blocks in the given body. -// -// This provides more convenient access to all of the "for_each" and "labels" -// dependencies in a body for applications that are already using hcldec -// as a more convenient way to recursively decode body contents. -func ForEachVariablesHCLDec(body hcl.Body, spec hcldec.Spec) []hcl.Traversal { - rootNode := WalkForEachVariables(body) - return walkVariablesWithHCLDec(rootNode, spec) -} - -func walkVariablesWithHCLDec(node WalkVariablesNode, spec hcldec.Spec) []hcl.Traversal { - vars, children := node.Visit(hcldec.ImpliedSchema(spec)) - - if len(children) > 0 { - childSpecs := hcldec.ChildBlockTypes(spec) - for _, child := range children { - if childSpec, exists := childSpecs[child.BlockTypeName]; exists { - vars = append(vars, walkVariablesWithHCLDec(child.Node, childSpec)...) - } - } - } - - return vars -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/typeexpr/README.md b/vendor/github.com/hashicorp/hcl2/ext/typeexpr/README.md deleted file mode 100644 index ff2b3f22..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/typeexpr/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# HCL Type Expressions Extension - -This HCL extension defines a convention for describing HCL types using function -call and variable reference syntax, allowing configuration formats to include -type information provided by users. - -The type syntax is processed statically from a hcl.Expression, so it cannot -use any of the usual language operators. This is similar to type expressions -in statically-typed programming languages. - -```hcl -variable "example" { - type = list(string) -} -``` - -The extension is built using the `hcl.ExprAsKeyword` and `hcl.ExprCall` -functions, and so it relies on the underlying syntax to define how "keyword" -and "call" are interpreted. The above shows how they are interpreted in -the HCL native syntax, while the following shows the same information -expressed in JSON: - -```json -{ - "variable": { - "example": { - "type": "list(string)" - } - } -} -``` - -Notice that since we have additional contextual information that we intend -to allow only calls and keywords the JSON syntax is able to parse the given -string directly as an expression, rather than as a template as would be -the case for normal expression evaluation. - -For more information, see [the godoc reference](http://godoc.org/github.com/hashicorp/hcl2/ext/typeexpr). - -## Type Expression Syntax - -When expressed in the native syntax, the following expressions are permitted -in a type expression: - -* `string` - string -* `bool` - boolean -* `number` - number -* `any` - `cty.DynamicPseudoType` (in function `TypeConstraint` only) -* `list()` - list of the type given as an argument -* `set()` - set of the type given as an argument -* `map()` - map of the type given as an argument -* `tuple([])` - tuple with the element types given in the single list argument -* `object({=, ...}` - object with the attributes and corresponding types given in the single map argument - -For example: - -* `list(string)` -* `object({name=string,age=number})` -* `map(object({name=string,age=number}))` - -Note that the object constructor syntax is not fully-general for all possible -object types because it requires the attribute names to be valid identifiers. -In practice it is expected that any time an object type is being fixed for -type checking it will be one that has identifiers as its attributes; object -types with weird attributes generally show up only from arbitrary object -constructors in configuration files, which are usually treated either as maps -or as the dynamic pseudo-type. diff --git a/vendor/github.com/hashicorp/hcl2/ext/typeexpr/doc.go b/vendor/github.com/hashicorp/hcl2/ext/typeexpr/doc.go deleted file mode 100644 index c4b37957..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/typeexpr/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package typeexpr extends HCL with a convention for describing HCL types -// within configuration files. -// -// The type syntax is processed statically from a hcl.Expression, so it cannot -// use any of the usual language operators. This is similar to type expressions -// in statically-typed programming languages. -// -// variable "example" { -// type = list(string) -// } -package typeexpr diff --git a/vendor/github.com/hashicorp/hcl2/ext/typeexpr/get_type.go b/vendor/github.com/hashicorp/hcl2/ext/typeexpr/get_type.go deleted file mode 100644 index a84338a8..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/typeexpr/get_type.go +++ /dev/null @@ -1,196 +0,0 @@ -package typeexpr - -import ( - "fmt" - - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" -) - -const invalidTypeSummary = "Invalid type specification" - -// getType is the internal implementation of both Type and TypeConstraint, -// using the passed flag to distinguish. When constraint is false, the "any" -// keyword will produce an error. -func getType(expr hcl.Expression, constraint bool) (cty.Type, hcl.Diagnostics) { - // First we'll try for one of our keywords - kw := hcl.ExprAsKeyword(expr) - switch kw { - case "bool": - return cty.Bool, nil - case "string": - return cty.String, nil - case "number": - return cty.Number, nil - case "any": - if constraint { - return cty.DynamicPseudoType, nil - } - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("The keyword %q cannot be used in this type specification: an exact type is required.", kw), - Subject: expr.Range().Ptr(), - }} - case "list", "map", "set": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("The %s type constructor requires one argument specifying the element type.", kw), - Subject: expr.Range().Ptr(), - }} - case "object": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "The object type constructor requires one argument specifying the attribute types and values as a map.", - Subject: expr.Range().Ptr(), - }} - case "tuple": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "The tuple type constructor requires one argument specifying the element types as a list.", - Subject: expr.Range().Ptr(), - }} - case "": - // okay! we'll fall through and try processing as a call, then. - default: - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("The keyword %q is not a valid type specification.", kw), - Subject: expr.Range().Ptr(), - }} - } - - // If we get down here then our expression isn't just a keyword, so we'll - // try to process it as a call instead. - call, diags := hcl.ExprCall(expr) - if diags.HasErrors() { - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "A type specification is either a primitive type keyword (bool, number, string) or a complex type constructor call, like list(string).", - Subject: expr.Range().Ptr(), - }} - } - - switch call.Name { - case "bool", "string", "number", "any": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("Primitive type keyword %q does not expect arguments.", call.Name), - Subject: &call.ArgsRange, - }} - } - - if len(call.Arguments) != 1 { - contextRange := call.ArgsRange - subjectRange := call.ArgsRange - if len(call.Arguments) > 1 { - // If we have too many arguments (as opposed to too _few_) then - // we'll highlight the extraneous arguments as the diagnostic - // subject. - subjectRange = hcl.RangeBetween(call.Arguments[1].Range(), call.Arguments[len(call.Arguments)-1].Range()) - } - - switch call.Name { - case "list", "set", "map": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("The %s type constructor requires one argument specifying the element type.", call.Name), - Subject: &subjectRange, - Context: &contextRange, - }} - case "object": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "The object type constructor requires one argument specifying the attribute types and values as a map.", - Subject: &subjectRange, - Context: &contextRange, - }} - case "tuple": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "The tuple type constructor requires one argument specifying the element types as a list.", - Subject: &subjectRange, - Context: &contextRange, - }} - } - } - - switch call.Name { - - case "list": - ety, diags := getType(call.Arguments[0], constraint) - return cty.List(ety), diags - case "set": - ety, diags := getType(call.Arguments[0], constraint) - return cty.Set(ety), diags - case "map": - ety, diags := getType(call.Arguments[0], constraint) - return cty.Map(ety), diags - case "object": - attrDefs, diags := hcl.ExprMap(call.Arguments[0]) - if diags.HasErrors() { - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "Object type constructor requires a map whose keys are attribute names and whose values are the corresponding attribute types.", - Subject: call.Arguments[0].Range().Ptr(), - Context: expr.Range().Ptr(), - }} - } - - atys := make(map[string]cty.Type) - for _, attrDef := range attrDefs { - attrName := hcl.ExprAsKeyword(attrDef.Key) - if attrName == "" { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "Object constructor map keys must be attribute names.", - Subject: attrDef.Key.Range().Ptr(), - Context: expr.Range().Ptr(), - }) - continue - } - aty, attrDiags := getType(attrDef.Value, constraint) - diags = append(diags, attrDiags...) - atys[attrName] = aty - } - return cty.Object(atys), diags - case "tuple": - elemDefs, diags := hcl.ExprList(call.Arguments[0]) - if diags.HasErrors() { - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "Tuple type constructor requires a list of element types.", - Subject: call.Arguments[0].Range().Ptr(), - Context: expr.Range().Ptr(), - }} - } - etys := make([]cty.Type, len(elemDefs)) - for i, defExpr := range elemDefs { - ety, elemDiags := getType(defExpr, constraint) - diags = append(diags, elemDiags...) - etys[i] = ety - } - return cty.Tuple(etys), diags - default: - // Can't access call.Arguments in this path because we've not validated - // that it contains exactly one expression here. - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("Keyword %q is not a valid type constructor.", call.Name), - Subject: expr.Range().Ptr(), - }} - } -} diff --git a/vendor/github.com/hashicorp/hcl2/ext/typeexpr/public.go b/vendor/github.com/hashicorp/hcl2/ext/typeexpr/public.go deleted file mode 100644 index e3f5eef5..00000000 --- a/vendor/github.com/hashicorp/hcl2/ext/typeexpr/public.go +++ /dev/null @@ -1,129 +0,0 @@ -package typeexpr - -import ( - "bytes" - "fmt" - "sort" - - "github.com/hashicorp/hcl2/hcl/hclsyntax" - - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" -) - -// Type attempts to process the given expression as a type expression and, if -// successful, returns the resulting type. If unsuccessful, error diagnostics -// are returned. -func Type(expr hcl.Expression) (cty.Type, hcl.Diagnostics) { - return getType(expr, false) -} - -// TypeConstraint attempts to parse the given expression as a type constraint -// and, if successful, returns the resulting type. If unsuccessful, error -// diagnostics are returned. -// -// A type constraint has the same structure as a type, but it additionally -// allows the keyword "any" to represent cty.DynamicPseudoType, which is often -// used as a wildcard in type checking and type conversion operations. -func TypeConstraint(expr hcl.Expression) (cty.Type, hcl.Diagnostics) { - return getType(expr, true) -} - -// TypeString returns a string rendering of the given type as it would be -// expected to appear in the HCL native syntax. -// -// This is primarily intended for showing types to the user in an application -// that uses typexpr, where the user can be assumed to be familiar with the -// type expression syntax. In applications that do not use typeexpr these -// results may be confusing to the user and so type.FriendlyName may be -// preferable, even though it's less precise. -// -// TypeString produces reasonable results only for types like what would be -// produced by the Type and TypeConstraint functions. In particular, it cannot -// support capsule types. -func TypeString(ty cty.Type) string { - // Easy cases first - switch ty { - case cty.String: - return "string" - case cty.Bool: - return "bool" - case cty.Number: - return "number" - case cty.DynamicPseudoType: - return "any" - } - - if ty.IsCapsuleType() { - panic("TypeString does not support capsule types") - } - - if ty.IsCollectionType() { - ety := ty.ElementType() - etyString := TypeString(ety) - switch { - case ty.IsListType(): - return fmt.Sprintf("list(%s)", etyString) - case ty.IsSetType(): - return fmt.Sprintf("set(%s)", etyString) - case ty.IsMapType(): - return fmt.Sprintf("map(%s)", etyString) - default: - // Should never happen because the above is exhaustive - panic("unsupported collection type") - } - } - - if ty.IsObjectType() { - var buf bytes.Buffer - buf.WriteString("object({") - atys := ty.AttributeTypes() - names := make([]string, 0, len(atys)) - for name := range atys { - names = append(names, name) - } - sort.Strings(names) - first := true - for _, name := range names { - aty := atys[name] - if !first { - buf.WriteByte(',') - } - if !hclsyntax.ValidIdentifier(name) { - // Should never happen for any type produced by this package, - // but we'll do something reasonable here just so we don't - // produce garbage if someone gives us a hand-assembled object - // type that has weird attribute names. - // Using Go-style quoting here isn't perfect, since it doesn't - // exactly match HCL syntax, but it's fine for an edge-case. - buf.WriteString(fmt.Sprintf("%q", name)) - } else { - buf.WriteString(name) - } - buf.WriteByte('=') - buf.WriteString(TypeString(aty)) - first = false - } - buf.WriteString("})") - return buf.String() - } - - if ty.IsTupleType() { - var buf bytes.Buffer - buf.WriteString("tuple([") - etys := ty.TupleElementTypes() - first := true - for _, ety := range etys { - if !first { - buf.WriteByte(',') - } - buf.WriteString(TypeString(ety)) - first = false - } - buf.WriteString("])") - return buf.String() - } - - // Should never happen because we covered all cases above. - panic(fmt.Errorf("unsupported type %#v", ty)) -} diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression.go b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression.go index 26819a2d..7f8d2b01 100644 --- a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression.go +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression.go @@ -1235,6 +1235,19 @@ func (e *SplatExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { return cty.DynamicVal, diags } + if sourceVal.IsNull() { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Splat of null value", + Detail: "Splat expressions (with the * symbol) cannot be applied to null values.", + Subject: e.Source.Range().Ptr(), + Context: hcl.RangeBetween(e.Source.Range(), e.MarkerRange).Ptr(), + Expression: e.Source, + EvalContext: ctx, + }) + return cty.DynamicVal, diags + } + sourceTy := sourceVal.Type() if sourceTy == cty.DynamicPseudoType { // If we don't even know the _type_ of our source value yet then @@ -1245,27 +1258,9 @@ func (e *SplatExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { // A "special power" of splat expressions is that they can be applied // both to tuples/lists and to other values, and in the latter case - // the value will be treated as an implicit single-item tuple, or as - // an empty tuple if the value is null. - autoUpgrade := !(sourceTy.IsTupleType() || sourceTy.IsListType() || sourceTy.IsSetType()) - - if sourceVal.IsNull() { - if autoUpgrade { - return cty.EmptyTupleVal, diags - } - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Splat of null value", - Detail: "Splat expressions (with the * symbol) cannot be applied to null sequences.", - Subject: e.Source.Range().Ptr(), - Context: hcl.RangeBetween(e.Source.Range(), e.MarkerRange).Ptr(), - Expression: e.Source, - EvalContext: ctx, - }) - return cty.DynamicVal, diags - } - - if autoUpgrade { + // the value will be treated as an implicit single-value tuple. We'll + // deal with that here first. + if !(sourceTy.IsTupleType() || sourceTy.IsListType() || sourceTy.IsSetType()) { sourceVal = cty.TupleVal([]cty.Value{sourceVal}) sourceTy = sourceVal.Type() } diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/parser.go b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/parser.go index 4a046f58..5fba724d 100644 --- a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/parser.go +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/parser.go @@ -9,6 +9,7 @@ import ( "github.com/apparentlymart/go-textseg/textseg" "github.com/hashicorp/hcl2/hcl" "github.com/zclconf/go-cty/cty" + "github.com/zclconf/go-cty/cty/convert" ) type parser struct { @@ -235,18 +236,10 @@ func (p *parser) finishParsingBodyAttribute(ident Token, singleLine bool) (Node, end := p.Peek() if end.Type != TokenNewline && end.Type != TokenEOF { if !p.recovery { - summary := "Missing newline after argument" - detail := "An argument definition must end with a newline." - - if end.Type == TokenComma { - summary = "Unexpected comma after argument" - detail = "Argument definitions must be separated by newlines, not commas. " + detail - } - diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, - Summary: summary, - Detail: detail, + Summary: "Missing newline after argument", + Detail: "An argument definition must end with a newline.", Subject: &end.Range, Context: hcl.RangeBetween(ident.Range, end.Range).Ptr(), }) @@ -293,9 +286,19 @@ Token: diags = append(diags, labelDiags...) labels = append(labels, label) labelRanges = append(labelRanges, labelRange) - // parseQuoteStringLiteral recovers up to the closing quote - // if it encounters problems, so we can continue looking for - // more labels and eventually the block body even. + if labelDiags.HasErrors() { + p.recoverAfterBodyItem() + return &Block{ + Type: blockType, + Labels: labels, + Body: nil, + + TypeRange: ident.Range, + LabelRanges: labelRanges, + OpenBraceRange: ident.Range, // placeholder + CloseBraceRange: ident.Range, // placeholder + }, diags + } case TokenIdent: tok = p.Read() // eat token @@ -1047,10 +1050,11 @@ func (p *parser) parseExpressionTerm() (Expression, hcl.Diagnostics) { } func (p *parser) numberLitValue(tok Token) (cty.Value, hcl.Diagnostics) { - // The cty.ParseNumberVal is always the same behavior as converting a - // string to a number, ensuring we always interpret decimal numbers in - // the same way. - numVal, err := cty.ParseNumberVal(string(tok.Bytes)) + // We'll lean on the cty converter to do the conversion, to ensure that + // the behavior is the same as what would happen if converting a + // non-literal string to a number. + numStrVal := cty.StringVal(string(tok.Bytes)) + numVal, err := convert.Convert(numStrVal, cty.Number) if err != nil { ret := cty.UnknownVal(cty.Number) return ret, hcl.Diagnostics{ @@ -1644,16 +1648,7 @@ Token: Subject: &tok.Range, Context: hcl.RangeBetween(oQuote.Range, tok.Range).Ptr(), }) - - // Now that we're returning an error callers won't attempt to use - // the result for any real operations, but they might try to use - // the partial AST for other analyses, so we'll leave a marker - // to indicate that there was something invalid in the string to - // help avoid misinterpretation of the partial result - ret.WriteString(which) - ret.WriteString("{ ... }") - - p.recover(TokenTemplateSeqEnd) // we'll try to keep parsing after the sequence ends + p.recover(TokenTemplateSeqEnd) case TokenEOF: diags = append(diags, &hcl.Diagnostic{ @@ -1674,7 +1669,7 @@ Token: Subject: &tok.Range, Context: hcl.RangeBetween(oQuote.Range, tok.Range).Ptr(), }) - p.recover(TokenCQuote) + p.recover(TokenOQuote) break Token } diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_string_lit.go b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_string_lit.go index 2895ade7..de1f524c 100644 --- a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_string_lit.go +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_string_lit.go @@ -1,10 +1,10 @@ -//line scan_string_lit.rl:1 +// line 1 "scan_string_lit.rl" package hclsyntax // This file is generated from scan_string_lit.rl. DO NOT EDIT. -//line scan_string_lit.go:9 +// line 9 "scan_string_lit.go" var _hclstrtok_actions []byte = []byte{ 0, 1, 0, 1, 1, 2, 1, 0, } @@ -114,12 +114,12 @@ const hclstrtok_error int = 0 const hclstrtok_en_quoted int = 10 const hclstrtok_en_unquoted int = 4 -//line scan_string_lit.rl:10 +// line 10 "scan_string_lit.rl" func scanStringLit(data []byte, quoted bool) [][]byte { var ret [][]byte -//line scan_string_lit.rl:61 + // line 61 "scan_string_lit.rl" // Ragel state p := 0 // "Pointer" into data @@ -144,11 +144,11 @@ func scanStringLit(data []byte, quoted bool) [][]byte { ret = append(ret, data[ts:te]) }*/ -//line scan_string_lit.go:154 + // line 154 "scan_string_lit.go" { } -//line scan_string_lit.go:158 + // line 158 "scan_string_lit.go" { var _klen int var _trans int @@ -229,7 +229,7 @@ func scanStringLit(data []byte, quoted bool) [][]byte { _acts++ switch _hclstrtok_actions[_acts-1] { case 0: -//line scan_string_lit.rl:40 + // line 40 "scan_string_lit.rl" // If te is behind p then we've skipped over some literal // characters which we must now return. @@ -239,12 +239,12 @@ func scanStringLit(data []byte, quoted bool) [][]byte { ts = p case 1: -//line scan_string_lit.rl:48 + // line 48 "scan_string_lit.rl" te = p ret = append(ret, data[ts:te]) -//line scan_string_lit.go:253 + // line 255 "scan_string_lit.go" } } @@ -267,12 +267,12 @@ func scanStringLit(data []byte, quoted bool) [][]byte { __acts++ switch _hclstrtok_actions[__acts-1] { case 1: -//line scan_string_lit.rl:48 + // line 48 "scan_string_lit.rl" te = p ret = append(ret, data[ts:te]) -//line scan_string_lit.go:278 + // line 281 "scan_string_lit.go" } } } @@ -282,7 +282,7 @@ func scanStringLit(data []byte, quoted bool) [][]byte { } } -//line scan_string_lit.rl:89 + // line 89 "scan_string_lit.rl" if te < p { // Collect any leftover literal characters at the end of the input diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_tokens.go b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_tokens.go index 30a08363..26451863 100644 --- a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_tokens.go +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_tokens.go @@ -1,4 +1,4 @@ -//line scan_tokens.rl:1 +// line 1 "scan_tokens.rl" package hclsyntax @@ -10,7 +10,7 @@ import ( // This file is generated from scan_tokens.rl. DO NOT EDIT. -//line scan_tokens.go:15 +// line 15 "scan_tokens.go" var _hcltok_actions []byte = []byte{ 0, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 6, 1, 7, 1, 8, @@ -225,23 +225,23 @@ var _hcltok_key_offsets []int16 = []int16{ 9172, 9173, 9182, 9190, 9192, 9195, 9197, 9199, 9201, 9206, 9219, 9223, 9238, 9267, 9278, 9280, 9284, 9288, 9293, 9297, 9299, 9306, 9310, 9318, - 9322, 9397, 9399, 9400, 9401, 9402, 9403, 9404, - 9406, 9411, 9413, 9415, 9416, 9460, 9461, 9462, - 9464, 9469, 9473, 9473, 9475, 9477, 9488, 9498, - 9506, 9507, 9509, 9510, 9514, 9518, 9528, 9532, - 9539, 9550, 9557, 9561, 9567, 9578, 9610, 9659, - 9674, 9689, 9694, 9696, 9701, 9733, 9741, 9743, - 9765, 9787, 9789, 9805, 9821, 9837, 9853, 9868, - 9878, 9895, 9912, 9929, 9945, 9955, 9972, 9988, - 10004, 10020, 10036, 10052, 10068, 10084, 10085, 10086, - 10087, 10088, 10090, 10092, 10094, 10108, 10122, 10136, - 10150, 10151, 10152, 10154, 10156, 10158, 10172, 10186, - 10187, 10188, 10190, 10192, 10194, 10243, 10287, 10289, - 10294, 10298, 10298, 10300, 10302, 10313, 10323, 10331, - 10332, 10334, 10335, 10339, 10343, 10353, 10357, 10364, - 10375, 10382, 10386, 10392, 10403, 10435, 10484, 10499, - 10514, 10519, 10521, 10526, 10558, 10566, 10568, 10590, - 10612, + 9322, 9398, 9400, 9401, 9402, 9403, 9404, 9405, + 9407, 9412, 9414, 9416, 9417, 9461, 9462, 9463, + 9465, 9470, 9474, 9474, 9476, 9478, 9489, 9499, + 9507, 9508, 9510, 9511, 9515, 9519, 9529, 9533, + 9540, 9551, 9558, 9562, 9568, 9579, 9611, 9660, + 9675, 9690, 9695, 9697, 9702, 9734, 9742, 9744, + 9766, 9788, 9790, 9806, 9822, 9838, 9854, 9869, + 9879, 9896, 9913, 9930, 9946, 9956, 9973, 9989, + 10005, 10021, 10037, 10053, 10069, 10085, 10086, 10087, + 10088, 10089, 10091, 10093, 10095, 10109, 10123, 10137, + 10151, 10152, 10153, 10155, 10157, 10159, 10173, 10187, + 10188, 10189, 10191, 10193, 10195, 10244, 10288, 10290, + 10295, 10299, 10299, 10301, 10303, 10314, 10324, 10332, + 10333, 10335, 10336, 10340, 10344, 10354, 10358, 10365, + 10376, 10383, 10387, 10393, 10404, 10436, 10485, 10500, + 10515, 10520, 10522, 10527, 10559, 10567, 10569, 10591, + 10613, } var _hcltok_trans_keys []byte = []byte{ @@ -847,7 +847,7 @@ var _hcltok_trans_keys []byte = []byte{ 140, 141, 143, 144, 153, 154, 189, 190, 191, 128, 136, 137, 191, 173, 128, 168, 169, 177, 178, 180, 181, 182, 183, 191, - 128, 255, 192, 255, 150, 151, 158, 159, + 0, 127, 192, 255, 150, 151, 158, 159, 152, 154, 156, 158, 134, 135, 142, 143, 190, 191, 192, 255, 181, 189, 191, 128, 190, 133, 181, 128, 129, 130, 140, 141, @@ -1268,7 +1268,7 @@ var _hcltok_trans_keys []byte = []byte{ 128, 140, 141, 143, 144, 153, 154, 189, 190, 191, 128, 136, 137, 191, 173, 128, 168, 169, 177, 178, 180, 181, 182, 183, - 191, 128, 255, 192, 255, 150, 151, 158, + 191, 0, 127, 192, 255, 150, 151, 158, 159, 152, 154, 156, 158, 134, 135, 142, 143, 190, 191, 192, 255, 181, 189, 191, 128, 190, 133, 181, 128, 129, 130, 140, @@ -1411,126 +1411,23 @@ var _hcltok_trans_keys []byte = []byte{ 192, 255, 162, 191, 192, 255, 160, 168, 128, 159, 161, 167, 169, 191, 158, 191, 192, 255, 9, 10, 13, 32, 33, 34, - 35, 38, 46, 47, 60, 61, 62, 64, - 92, 95, 123, 124, 125, 126, 127, 194, - 195, 198, 199, 203, 204, 205, 206, 207, - 210, 212, 213, 214, 215, 216, 217, 219, - 220, 221, 222, 223, 224, 225, 226, 227, - 228, 233, 234, 237, 238, 239, 240, 0, - 36, 37, 45, 48, 57, 58, 63, 65, - 90, 91, 96, 97, 122, 192, 193, 196, - 218, 229, 236, 241, 247, 9, 32, 10, - 61, 10, 38, 46, 42, 47, 46, 69, - 101, 48, 57, 60, 61, 61, 62, 61, - 45, 95, 194, 195, 198, 199, 203, 204, - 205, 206, 207, 210, 212, 213, 214, 215, - 216, 217, 219, 220, 221, 222, 223, 224, - 225, 226, 227, 228, 233, 234, 237, 239, - 240, 243, 48, 57, 65, 90, 97, 122, - 196, 218, 229, 236, 124, 125, 128, 191, - 170, 181, 186, 128, 191, 151, 183, 128, - 255, 192, 255, 0, 127, 173, 130, 133, - 146, 159, 165, 171, 175, 191, 192, 255, - 181, 190, 128, 175, 176, 183, 184, 185, - 186, 191, 134, 139, 141, 162, 128, 135, - 136, 255, 182, 130, 137, 176, 151, 152, - 154, 160, 136, 191, 192, 255, 128, 143, - 144, 170, 171, 175, 176, 178, 179, 191, - 128, 159, 160, 191, 176, 128, 138, 139, - 173, 174, 255, 148, 150, 164, 167, 173, - 176, 185, 189, 190, 192, 255, 144, 128, - 145, 146, 175, 176, 191, 128, 140, 141, - 255, 166, 176, 178, 191, 192, 255, 186, - 128, 137, 138, 170, 171, 179, 180, 181, - 182, 191, 160, 161, 162, 164, 165, 166, - 167, 168, 169, 170, 171, 172, 173, 174, - 175, 176, 177, 178, 179, 180, 181, 182, - 183, 184, 185, 186, 187, 188, 189, 190, - 128, 191, 128, 129, 130, 131, 137, 138, - 139, 140, 141, 142, 143, 144, 153, 154, - 155, 156, 157, 158, 159, 160, 161, 162, - 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, - 179, 180, 182, 183, 184, 188, 189, 190, - 191, 132, 187, 129, 130, 132, 133, 134, - 176, 177, 178, 179, 180, 181, 182, 183, - 128, 191, 128, 129, 130, 131, 132, 133, - 134, 135, 144, 136, 143, 145, 191, 192, - 255, 182, 183, 184, 128, 191, 128, 191, - 191, 128, 190, 192, 255, 128, 146, 147, - 148, 152, 153, 154, 155, 156, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, - 168, 169, 170, 171, 172, 173, 174, 175, - 176, 129, 191, 192, 255, 158, 159, 128, - 157, 160, 191, 192, 255, 128, 191, 164, - 169, 171, 172, 173, 174, 175, 180, 181, - 182, 183, 184, 185, 187, 188, 189, 190, - 191, 128, 163, 165, 186, 144, 145, 146, - 147, 148, 150, 151, 152, 155, 157, 158, - 160, 170, 171, 172, 175, 128, 159, 161, - 169, 173, 191, 128, 191, 10, 13, 34, - 36, 37, 92, 128, 191, 192, 223, 224, - 239, 240, 247, 248, 255, 10, 13, 34, - 36, 37, 92, 128, 191, 192, 223, 224, - 239, 240, 247, 248, 255, 10, 13, 34, - 36, 37, 92, 128, 191, 192, 223, 224, - 239, 240, 247, 248, 255, 10, 13, 34, - 36, 37, 92, 128, 191, 192, 223, 224, - 239, 240, 247, 248, 255, 10, 13, 36, - 37, 92, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 36, 37, 92, 123, - 192, 223, 224, 239, 240, 247, 10, 13, - 34, 36, 37, 92, 123, 128, 191, 192, - 223, 224, 239, 240, 247, 248, 255, 10, - 13, 34, 36, 37, 92, 123, 128, 191, - 192, 223, 224, 239, 240, 247, 248, 255, - 10, 13, 34, 36, 37, 92, 123, 128, - 191, 192, 223, 224, 239, 240, 247, 248, - 255, 10, 13, 34, 36, 37, 92, 128, - 191, 192, 223, 224, 239, 240, 247, 248, - 255, 36, 37, 92, 123, 192, 223, 224, - 239, 240, 247, 10, 13, 34, 36, 37, - 92, 123, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 34, 36, - 37, 92, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 34, 36, - 37, 92, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 34, 36, - 37, 92, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 34, 36, - 37, 92, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 34, 36, - 37, 92, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 34, 36, - 37, 92, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 34, 36, - 37, 92, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 123, 126, 123, 126, - 128, 191, 128, 191, 128, 191, 10, 13, - 36, 37, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 36, 37, - 128, 191, 192, 223, 224, 239, 240, 247, - 248, 255, 10, 13, 36, 37, 128, 191, - 192, 223, 224, 239, 240, 247, 248, 255, - 10, 13, 36, 37, 128, 191, 192, 223, - 224, 239, 240, 247, 248, 255, 126, 126, - 128, 191, 128, 191, 128, 191, 10, 13, - 36, 37, 128, 191, 192, 223, 224, 239, - 240, 247, 248, 255, 10, 13, 36, 37, - 128, 191, 192, 223, 224, 239, 240, 247, - 248, 255, 126, 126, 128, 191, 128, 191, - 128, 191, 95, 194, 195, 198, 199, 203, + 35, 37, 38, 46, 47, 60, 61, 62, + 64, 92, 95, 123, 124, 125, 126, 127, + 194, 195, 198, 199, 203, 204, 205, 206, + 207, 210, 212, 213, 214, 215, 216, 217, + 219, 220, 221, 222, 223, 224, 225, 226, + 227, 228, 233, 234, 237, 238, 239, 240, + 0, 39, 40, 45, 48, 57, 58, 63, + 65, 90, 91, 96, 97, 122, 192, 193, + 196, 218, 229, 236, 241, 247, 9, 32, + 10, 61, 10, 38, 46, 42, 47, 46, + 69, 101, 48, 57, 60, 61, 61, 62, + 61, 45, 95, 194, 195, 198, 199, 203, 204, 205, 206, 207, 210, 212, 213, 214, 215, 216, 217, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 233, 234, 237, - 238, 239, 240, 65, 90, 97, 122, 128, - 191, 192, 193, 196, 218, 229, 236, 241, - 247, 248, 255, 45, 95, 194, 195, 198, - 199, 203, 204, 205, 206, 207, 210, 212, - 213, 214, 215, 216, 217, 219, 220, 221, - 222, 223, 224, 225, 226, 227, 228, 233, - 234, 237, 239, 240, 243, 48, 57, 65, - 90, 97, 122, 196, 218, 229, 236, 128, + 239, 240, 243, 48, 57, 65, 90, 97, + 122, 196, 218, 229, 236, 124, 125, 128, 191, 170, 181, 186, 128, 191, 151, 183, 128, 255, 192, 255, 0, 127, 173, 130, 133, 146, 159, 165, 171, 175, 191, 192, @@ -1571,7 +1468,110 @@ var _hcltok_trans_keys []byte = []byte{ 190, 191, 128, 163, 165, 186, 144, 145, 146, 147, 148, 150, 151, 152, 155, 157, 158, 160, 170, 171, 172, 175, 128, 159, - 161, 169, 173, 191, 128, 191, + 161, 169, 173, 191, 128, 191, 10, 13, + 34, 36, 37, 92, 128, 191, 192, 223, + 224, 239, 240, 247, 248, 255, 10, 13, + 34, 36, 37, 92, 128, 191, 192, 223, + 224, 239, 240, 247, 248, 255, 10, 13, + 34, 36, 37, 92, 128, 191, 192, 223, + 224, 239, 240, 247, 248, 255, 10, 13, + 34, 36, 37, 92, 128, 191, 192, 223, + 224, 239, 240, 247, 248, 255, 10, 13, + 36, 37, 92, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 36, 37, 92, + 123, 192, 223, 224, 239, 240, 247, 10, + 13, 34, 36, 37, 92, 123, 128, 191, + 192, 223, 224, 239, 240, 247, 248, 255, + 10, 13, 34, 36, 37, 92, 123, 128, + 191, 192, 223, 224, 239, 240, 247, 248, + 255, 10, 13, 34, 36, 37, 92, 123, + 128, 191, 192, 223, 224, 239, 240, 247, + 248, 255, 10, 13, 34, 36, 37, 92, + 128, 191, 192, 223, 224, 239, 240, 247, + 248, 255, 36, 37, 92, 123, 192, 223, + 224, 239, 240, 247, 10, 13, 34, 36, + 37, 92, 123, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 34, + 36, 37, 92, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 34, + 36, 37, 92, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 34, + 36, 37, 92, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 34, + 36, 37, 92, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 34, + 36, 37, 92, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 34, + 36, 37, 92, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 34, + 36, 37, 92, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 123, 126, 123, + 126, 128, 191, 128, 191, 128, 191, 10, + 13, 36, 37, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 36, + 37, 128, 191, 192, 223, 224, 239, 240, + 247, 248, 255, 10, 13, 36, 37, 128, + 191, 192, 223, 224, 239, 240, 247, 248, + 255, 10, 13, 36, 37, 128, 191, 192, + 223, 224, 239, 240, 247, 248, 255, 126, + 126, 128, 191, 128, 191, 128, 191, 10, + 13, 36, 37, 128, 191, 192, 223, 224, + 239, 240, 247, 248, 255, 10, 13, 36, + 37, 128, 191, 192, 223, 224, 239, 240, + 247, 248, 255, 126, 126, 128, 191, 128, + 191, 128, 191, 95, 194, 195, 198, 199, + 203, 204, 205, 206, 207, 210, 212, 213, + 214, 215, 216, 217, 219, 220, 221, 222, + 223, 224, 225, 226, 227, 228, 233, 234, + 237, 238, 239, 240, 65, 90, 97, 122, + 128, 191, 192, 193, 196, 218, 229, 236, + 241, 247, 248, 255, 45, 95, 194, 195, + 198, 199, 203, 204, 205, 206, 207, 210, + 212, 213, 214, 215, 216, 217, 219, 220, + 221, 222, 223, 224, 225, 226, 227, 228, + 233, 234, 237, 239, 240, 243, 48, 57, + 65, 90, 97, 122, 196, 218, 229, 236, + 128, 191, 170, 181, 186, 128, 191, 151, + 183, 128, 255, 192, 255, 0, 127, 173, + 130, 133, 146, 159, 165, 171, 175, 191, + 192, 255, 181, 190, 128, 175, 176, 183, + 184, 185, 186, 191, 134, 139, 141, 162, + 128, 135, 136, 255, 182, 130, 137, 176, + 151, 152, 154, 160, 136, 191, 192, 255, + 128, 143, 144, 170, 171, 175, 176, 178, + 179, 191, 128, 159, 160, 191, 176, 128, + 138, 139, 173, 174, 255, 148, 150, 164, + 167, 173, 176, 185, 189, 190, 192, 255, + 144, 128, 145, 146, 175, 176, 191, 128, + 140, 141, 255, 166, 176, 178, 191, 192, + 255, 186, 128, 137, 138, 170, 171, 179, + 180, 181, 182, 191, 160, 161, 162, 164, + 165, 166, 167, 168, 169, 170, 171, 172, + 173, 174, 175, 176, 177, 178, 179, 180, + 181, 182, 183, 184, 185, 186, 187, 188, + 189, 190, 128, 191, 128, 129, 130, 131, + 137, 138, 139, 140, 141, 142, 143, 144, + 153, 154, 155, 156, 157, 158, 159, 160, + 161, 162, 163, 164, 165, 166, 167, 168, + 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 179, 180, 182, 183, 184, 188, + 189, 190, 191, 132, 187, 129, 130, 132, + 133, 134, 176, 177, 178, 179, 180, 181, + 182, 183, 128, 191, 128, 129, 130, 131, + 132, 133, 134, 135, 144, 136, 143, 145, + 191, 192, 255, 182, 183, 184, 128, 191, + 128, 191, 191, 128, 190, 192, 255, 128, + 146, 147, 148, 152, 153, 154, 155, 156, + 158, 159, 160, 161, 162, 163, 164, 165, + 166, 167, 168, 169, 170, 171, 172, 173, + 174, 175, 176, 129, 191, 192, 255, 158, + 159, 128, 157, 160, 191, 192, 255, 128, + 191, 164, 169, 171, 172, 173, 174, 175, + 180, 181, 182, 183, 184, 185, 187, 188, + 189, 190, 191, 128, 163, 165, 186, 144, + 145, 146, 147, 148, 150, 151, 152, 155, + 157, 158, 160, 170, 171, 172, 175, 128, + 159, 161, 169, 173, 191, 128, 191, } var _hcltok_single_lengths []byte = []byte{ @@ -1758,7 +1758,7 @@ var _hcltok_single_lengths []byte = []byte{ 1, 5, 2, 0, 3, 2, 2, 2, 1, 7, 0, 7, 17, 3, 0, 2, 0, 3, 0, 0, 1, 0, 2, 0, - 53, 2, 1, 1, 1, 1, 1, 2, + 54, 2, 1, 1, 1, 1, 1, 2, 3, 2, 2, 1, 34, 1, 1, 0, 3, 2, 0, 0, 0, 1, 2, 4, 1, 0, 1, 0, 0, 0, 0, 1, @@ -2164,23 +2164,23 @@ var _hcltok_index_offsets []int16 = []int16{ 7213, 7215, 7223, 7229, 7231, 7235, 7238, 7241, 7244, 7248, 7259, 7262, 7274, 7298, 7306, 7308, 7312, 7315, 7320, 7323, 7325, 7330, 7333, 7339, - 7342, 7407, 7410, 7412, 7414, 7416, 7418, 7420, - 7423, 7428, 7431, 7434, 7436, 7476, 7478, 7480, - 7482, 7487, 7491, 7492, 7494, 7496, 7503, 7510, - 7517, 7519, 7521, 7523, 7526, 7529, 7535, 7538, - 7543, 7550, 7555, 7558, 7562, 7569, 7601, 7650, - 7665, 7678, 7683, 7685, 7689, 7720, 7726, 7728, - 7749, 7769, 7771, 7783, 7795, 7807, 7819, 7830, - 7838, 7851, 7864, 7877, 7889, 7897, 7910, 7922, - 7934, 7946, 7958, 7970, 7982, 7994, 7996, 7998, - 8000, 8002, 8004, 8006, 8008, 8018, 8028, 8038, - 8048, 8050, 8052, 8054, 8056, 8058, 8068, 8077, - 8079, 8081, 8083, 8085, 8087, 8129, 8169, 8171, - 8176, 8180, 8181, 8183, 8185, 8192, 8199, 8206, - 8208, 8210, 8212, 8215, 8218, 8224, 8227, 8232, - 8239, 8244, 8247, 8251, 8258, 8290, 8339, 8354, - 8367, 8372, 8374, 8378, 8409, 8415, 8417, 8438, - 8458, + 7342, 7408, 7411, 7413, 7415, 7417, 7419, 7421, + 7424, 7429, 7432, 7435, 7437, 7477, 7479, 7481, + 7483, 7488, 7492, 7493, 7495, 7497, 7504, 7511, + 7518, 7520, 7522, 7524, 7527, 7530, 7536, 7539, + 7544, 7551, 7556, 7559, 7563, 7570, 7602, 7651, + 7666, 7679, 7684, 7686, 7690, 7721, 7727, 7729, + 7750, 7770, 7772, 7784, 7796, 7808, 7820, 7831, + 7839, 7852, 7865, 7878, 7890, 7898, 7911, 7923, + 7935, 7947, 7959, 7971, 7983, 7995, 7997, 7999, + 8001, 8003, 8005, 8007, 8009, 8019, 8029, 8039, + 8049, 8051, 8053, 8055, 8057, 8059, 8069, 8078, + 8080, 8082, 8084, 8086, 8088, 8130, 8170, 8172, + 8177, 8181, 8182, 8184, 8186, 8193, 8200, 8207, + 8209, 8211, 8213, 8216, 8219, 8225, 8228, 8233, + 8240, 8245, 8248, 8252, 8259, 8291, 8340, 8355, + 8368, 8373, 8375, 8379, 8410, 8416, 8418, 8439, + 8459, } var _hcltok_indicies []int16 = []int16{ @@ -2666,7 +2666,7 @@ var _hcltok_indicies []int16 = []int16{ 670, 671, 421, 671, 421, 671, 421, 670, 671, 670, 421, 421, 671, 670, 671, 421, 671, 421, 671, 670, 421, 671, 670, 671, - 671, 421, 671, 421, 671, 670, 421, 670, + 671, 421, 671, 421, 671, 670, 670, 421, 670, 421, 671, 671, 421, 671, 671, 671, 671, 671, 671, 671, 670, 421, 671, 671, 671, 421, 670, 671, 671, 671, 421, 671, @@ -2993,7 +2993,7 @@ var _hcltok_indicies []int16 = []int16{ 794, 1045, 794, 1045, 794, 1044, 1045, 1044, 794, 794, 1045, 1044, 1045, 794, 1045, 794, 1045, 1044, 794, 1045, 1044, 1045, 1045, 794, - 1045, 794, 1045, 1044, 794, 1044, 1044, 794, + 1045, 794, 1045, 1044, 1044, 794, 1044, 794, 1045, 1045, 794, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1044, 794, 1045, 1045, 1045, 794, 1044, 1045, 1045, 1045, 794, 1045, 794, 1045, @@ -3102,146 +3102,146 @@ var _hcltok_indicies []int16 = []int16{ 1045, 1044, 794, 1045, 794, 1139, 1058, 1046, 1044, 800, 1045, 1044, 794, 1049, 1140, 1046, 1058, 1046, 1044, 1045, 1044, 794, 1141, 1142, - 1143, 1141, 1144, 1145, 1146, 1148, 1149, 1150, - 1151, 1152, 1153, 671, 671, 421, 1154, 1155, - 1156, 1157, 671, 1160, 1161, 1163, 1164, 1165, - 1159, 1166, 1167, 1168, 1169, 1170, 1171, 1172, - 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, - 1181, 1182, 1183, 1184, 1185, 1187, 1188, 1189, - 1190, 1191, 1192, 671, 1147, 9, 1147, 421, - 1147, 421, 1159, 1162, 1186, 1193, 1158, 1141, - 1141, 1194, 1142, 1195, 1197, 1196, 2, 1, - 1198, 1196, 1199, 1196, 5, 1, 1196, 8, - 10, 10, 9, 1200, 1201, 1202, 1196, 1203, - 1204, 1196, 1205, 1196, 421, 421, 1207, 1208, - 490, 471, 1209, 471, 1210, 1211, 1212, 1213, - 1214, 1215, 1216, 1217, 1218, 1219, 1220, 545, - 1221, 521, 1222, 1223, 1224, 1225, 1226, 1227, - 1228, 1229, 1230, 1231, 1232, 1233, 421, 421, - 421, 426, 566, 1206, 1234, 1196, 1235, 1196, - 671, 1236, 421, 421, 421, 671, 1236, 671, - 671, 421, 1236, 421, 1236, 421, 1236, 421, - 671, 671, 671, 671, 671, 1236, 421, 671, - 671, 671, 421, 671, 421, 1236, 421, 671, - 671, 671, 671, 421, 1236, 671, 421, 671, - 421, 671, 421, 671, 671, 421, 671, 1236, - 421, 671, 421, 671, 421, 671, 1236, 671, - 421, 1236, 671, 421, 671, 421, 1236, 671, - 671, 671, 671, 671, 1236, 421, 421, 671, - 421, 671, 1236, 671, 421, 1236, 671, 671, - 1236, 421, 421, 671, 421, 671, 421, 671, - 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, - 1244, 1245, 1246, 1247, 716, 1248, 1249, 1250, - 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, - 1259, 1258, 1260, 1261, 1262, 1263, 1264, 672, - 1236, 1265, 1266, 1267, 1268, 1269, 1270, 1271, - 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, - 1280, 1281, 1282, 1283, 726, 1284, 1285, 1286, - 693, 1287, 1288, 1289, 1290, 1291, 1292, 672, - 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, - 675, 1301, 672, 675, 1302, 1303, 1304, 1305, - 684, 1236, 1306, 1307, 1308, 1309, 704, 1310, - 1311, 684, 1312, 1313, 1314, 1315, 1316, 672, - 1236, 1317, 1276, 1318, 1319, 1320, 684, 1321, - 1322, 675, 672, 684, 426, 1236, 1286, 672, - 675, 684, 426, 684, 426, 1323, 684, 1236, - 426, 675, 1324, 1325, 675, 1326, 1327, 682, - 1328, 1329, 1330, 1331, 1332, 1282, 1333, 1334, - 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, - 1343, 1344, 1301, 1345, 675, 684, 426, 1236, - 1346, 1347, 684, 672, 1236, 426, 672, 1236, - 675, 1348, 732, 1349, 1350, 1351, 1352, 1353, - 1354, 1355, 1356, 672, 1357, 1358, 1359, 1360, - 1361, 1362, 672, 684, 1236, 1364, 1365, 1366, - 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, - 1370, 1376, 1377, 1378, 1379, 1363, 1375, 1363, - 1236, 1363, 1236, 1380, 1380, 1381, 1382, 1383, - 1384, 1385, 1386, 1387, 1388, 1385, 770, 1389, - 1389, 1389, 1390, 1391, 1384, 1389, 771, 772, - 1392, 1389, 770, 1393, 1393, 1393, 1395, 1396, - 1397, 1393, 1398, 1399, 1400, 1393, 1394, 1401, - 1401, 1401, 1403, 1404, 1405, 1401, 1406, 1407, - 1408, 1401, 1402, 1389, 1389, 1409, 1410, 1384, - 1389, 771, 772, 1392, 1389, 770, 1411, 1412, - 1413, 770, 1414, 1415, 1416, 768, 768, 768, - 768, 1418, 1419, 1420, 1394, 768, 1421, 1422, - 1423, 768, 1417, 769, 769, 769, 1425, 1426, - 1427, 1394, 769, 1428, 1429, 1430, 769, 1424, - 768, 768, 768, 1432, 1433, 1434, 1402, 768, - 1435, 1436, 1437, 768, 1431, 1393, 1393, 770, - 1438, 1439, 1397, 1393, 1398, 1399, 1400, 1393, - 1394, 1440, 1441, 1442, 770, 1443, 1444, 1445, - 769, 769, 769, 769, 1447, 1448, 1449, 1402, - 769, 1450, 1451, 1452, 769, 1446, 1401, 1401, - 770, 1453, 1454, 1405, 1401, 1406, 1407, 1408, - 1401, 1402, 1401, 1401, 1401, 1403, 1404, 1405, - 770, 1406, 1407, 1408, 1401, 1402, 1401, 1401, - 1401, 1403, 1404, 1405, 771, 1406, 1407, 1408, - 1401, 1402, 1401, 1401, 1401, 1403, 1404, 1405, - 772, 1406, 1407, 1408, 1401, 1402, 1393, 1393, - 1393, 1395, 1396, 1397, 770, 1398, 1399, 1400, - 1393, 1394, 1393, 1393, 1393, 1395, 1396, 1397, - 771, 1398, 1399, 1400, 1393, 1394, 1393, 1393, - 1393, 1395, 1396, 1397, 772, 1398, 1399, 1400, - 1393, 1394, 1456, 768, 1458, 1457, 1459, 769, - 1461, 1460, 770, 1462, 774, 1462, 1463, 1462, - 776, 1464, 1465, 1466, 1467, 1468, 1469, 1470, - 1467, 780, 776, 1464, 1472, 1473, 1471, 781, - 782, 1474, 1471, 780, 1477, 1478, 1479, 1480, - 1475, 1481, 1482, 1483, 1475, 1476, 1486, 1487, - 1488, 1489, 1484, 1490, 1491, 1492, 1484, 1485, - 1494, 1493, 1496, 1495, 780, 1497, 781, 1497, - 782, 1497, 786, 1498, 1499, 1500, 1501, 1502, - 1503, 1504, 1501, 788, 786, 1498, 1506, 1505, - 789, 790, 1507, 1505, 788, 1509, 1508, 1511, - 1510, 788, 1512, 789, 1512, 790, 1512, 794, - 1515, 1516, 1518, 1519, 1520, 1514, 1521, 1522, - 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, - 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, - 1539, 1540, 1542, 1543, 1544, 1545, 1546, 1547, - 794, 794, 1513, 1514, 1517, 1541, 1548, 1513, - 1045, 794, 794, 1550, 1551, 864, 845, 1552, - 845, 1553, 1554, 1555, 1556, 1557, 1558, 1559, - 1560, 1561, 1562, 1563, 919, 1564, 895, 1565, - 1566, 1567, 1568, 1569, 1570, 1571, 1572, 1573, - 1574, 1575, 1576, 794, 794, 794, 800, 940, - 1549, 1045, 1577, 794, 794, 794, 1045, 1577, - 1045, 1045, 794, 1577, 794, 1577, 794, 1577, - 794, 1045, 1045, 1045, 1045, 1045, 1577, 794, - 1045, 1045, 1045, 794, 1045, 794, 1577, 794, - 1045, 1045, 1045, 1045, 794, 1577, 1045, 794, - 1045, 794, 1045, 794, 1045, 1045, 794, 1045, - 1577, 794, 1045, 794, 1045, 794, 1045, 1577, - 1045, 794, 1577, 1045, 794, 1045, 794, 1577, - 1045, 1045, 1045, 1045, 1045, 1577, 794, 794, - 1045, 794, 1045, 1577, 1045, 794, 1577, 1045, - 1045, 1577, 794, 794, 1045, 794, 1045, 794, - 1045, 1577, 1578, 1579, 1580, 1581, 1582, 1583, - 1584, 1585, 1586, 1587, 1588, 1090, 1589, 1590, - 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, - 1599, 1600, 1599, 1601, 1602, 1603, 1604, 1605, - 1046, 1577, 1606, 1607, 1608, 1609, 1610, 1611, - 1612, 1613, 1614, 1615, 1616, 1617, 1618, 1619, - 1620, 1621, 1622, 1623, 1624, 1100, 1625, 1626, - 1627, 1067, 1628, 1629, 1630, 1631, 1632, 1633, - 1046, 1634, 1635, 1636, 1637, 1638, 1639, 1640, - 1641, 1049, 1642, 1046, 1049, 1643, 1644, 1645, - 1646, 1058, 1577, 1647, 1648, 1649, 1650, 1078, - 1651, 1652, 1058, 1653, 1654, 1655, 1656, 1657, - 1046, 1577, 1658, 1617, 1659, 1660, 1661, 1058, - 1662, 1663, 1049, 1046, 1058, 800, 1577, 1627, - 1046, 1049, 1058, 800, 1058, 800, 1664, 1058, - 1577, 800, 1049, 1665, 1666, 1049, 1667, 1668, - 1056, 1669, 1670, 1671, 1672, 1673, 1623, 1674, - 1675, 1676, 1677, 1678, 1679, 1680, 1681, 1682, - 1683, 1684, 1685, 1642, 1686, 1049, 1058, 800, - 1577, 1687, 1688, 1058, 1046, 1577, 800, 1046, - 1577, 1049, 1689, 1106, 1690, 1691, 1692, 1693, - 1694, 1695, 1696, 1697, 1046, 1698, 1699, 1700, - 1701, 1702, 1703, 1046, 1058, 1577, 1705, 1706, - 1707, 1708, 1709, 1710, 1711, 1712, 1713, 1714, - 1715, 1711, 1717, 1718, 1719, 1720, 1704, 1716, - 1704, 1577, 1704, 1577, + 1143, 1141, 1144, 1145, 1146, 1147, 1148, 1149, + 1150, 1151, 1152, 1153, 671, 671, 421, 1154, + 1155, 1156, 1157, 671, 1160, 1161, 1163, 1164, + 1165, 1159, 1166, 1167, 1168, 1169, 1170, 1171, + 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, + 1180, 1181, 1182, 1183, 1184, 1185, 1187, 1188, + 1189, 1190, 1191, 1192, 671, 1147, 9, 1147, + 421, 1147, 421, 1159, 1162, 1186, 1193, 1158, + 1141, 1141, 1194, 1142, 1195, 1197, 1196, 2, + 1, 1198, 1196, 1199, 1196, 5, 1, 1196, + 8, 10, 10, 9, 1200, 1201, 1202, 1196, + 1203, 1204, 1196, 1205, 1196, 421, 421, 1207, + 1208, 490, 471, 1209, 471, 1210, 1211, 1212, + 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, + 545, 1221, 521, 1222, 1223, 1224, 1225, 1226, + 1227, 1228, 1229, 1230, 1231, 1232, 1233, 421, + 421, 421, 426, 566, 1206, 1234, 1196, 1235, + 1196, 671, 1236, 421, 421, 421, 671, 1236, + 671, 671, 421, 1236, 421, 1236, 421, 1236, + 421, 671, 671, 671, 671, 671, 1236, 421, + 671, 671, 671, 421, 671, 421, 1236, 421, + 671, 671, 671, 671, 421, 1236, 671, 421, + 671, 421, 671, 421, 671, 671, 421, 671, + 1236, 421, 671, 421, 671, 421, 671, 1236, + 671, 421, 1236, 671, 421, 671, 421, 1236, + 671, 671, 671, 671, 671, 1236, 421, 421, + 671, 421, 671, 1236, 671, 421, 1236, 671, + 671, 1236, 421, 421, 671, 421, 671, 421, + 671, 1236, 1237, 1238, 1239, 1240, 1241, 1242, + 1243, 1244, 1245, 1246, 1247, 716, 1248, 1249, + 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, + 1258, 1259, 1258, 1260, 1261, 1262, 1263, 1264, + 672, 1236, 1265, 1266, 1267, 1268, 1269, 1270, + 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, + 1279, 1280, 1281, 1282, 1283, 726, 1284, 1285, + 1286, 693, 1287, 1288, 1289, 1290, 1291, 1292, + 672, 1293, 1294, 1295, 1296, 1297, 1298, 1299, + 1300, 675, 1301, 672, 675, 1302, 1303, 1304, + 1305, 684, 1236, 1306, 1307, 1308, 1309, 704, + 1310, 1311, 684, 1312, 1313, 1314, 1315, 1316, + 672, 1236, 1317, 1276, 1318, 1319, 1320, 684, + 1321, 1322, 675, 672, 684, 426, 1236, 1286, + 672, 675, 684, 426, 684, 426, 1323, 684, + 1236, 426, 675, 1324, 1325, 675, 1326, 1327, + 682, 1328, 1329, 1330, 1331, 1332, 1282, 1333, + 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, + 1342, 1343, 1344, 1301, 1345, 675, 684, 426, + 1236, 1346, 1347, 684, 672, 1236, 426, 672, + 1236, 675, 1348, 732, 1349, 1350, 1351, 1352, + 1353, 1354, 1355, 1356, 672, 1357, 1358, 1359, + 1360, 1361, 1362, 672, 684, 1236, 1364, 1365, + 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, + 1374, 1370, 1376, 1377, 1378, 1379, 1363, 1375, + 1363, 1236, 1363, 1236, 1380, 1380, 1381, 1382, + 1383, 1384, 1385, 1386, 1387, 1388, 1385, 770, + 1389, 1389, 1389, 1390, 1391, 1384, 1389, 771, + 772, 1392, 1389, 770, 1393, 1393, 1393, 1395, + 1396, 1397, 1393, 1398, 1399, 1400, 1393, 1394, + 1401, 1401, 1401, 1403, 1404, 1405, 1401, 1406, + 1407, 1408, 1401, 1402, 1389, 1389, 1409, 1410, + 1384, 1389, 771, 772, 1392, 1389, 770, 1411, + 1412, 1413, 770, 1414, 1415, 1416, 768, 768, + 768, 768, 1418, 1419, 1420, 1394, 768, 1421, + 1422, 1423, 768, 1417, 769, 769, 769, 1425, + 1426, 1427, 1394, 769, 1428, 1429, 1430, 769, + 1424, 768, 768, 768, 1432, 1433, 1434, 1402, + 768, 1435, 1436, 1437, 768, 1431, 1393, 1393, + 770, 1438, 1439, 1397, 1393, 1398, 1399, 1400, + 1393, 1394, 1440, 1441, 1442, 770, 1443, 1444, + 1445, 769, 769, 769, 769, 1447, 1448, 1449, + 1402, 769, 1450, 1451, 1452, 769, 1446, 1401, + 1401, 770, 1453, 1454, 1405, 1401, 1406, 1407, + 1408, 1401, 1402, 1401, 1401, 1401, 1403, 1404, + 1405, 770, 1406, 1407, 1408, 1401, 1402, 1401, + 1401, 1401, 1403, 1404, 1405, 771, 1406, 1407, + 1408, 1401, 1402, 1401, 1401, 1401, 1403, 1404, + 1405, 772, 1406, 1407, 1408, 1401, 1402, 1393, + 1393, 1393, 1395, 1396, 1397, 770, 1398, 1399, + 1400, 1393, 1394, 1393, 1393, 1393, 1395, 1396, + 1397, 771, 1398, 1399, 1400, 1393, 1394, 1393, + 1393, 1393, 1395, 1396, 1397, 772, 1398, 1399, + 1400, 1393, 1394, 1456, 768, 1458, 1457, 1459, + 769, 1461, 1460, 770, 1462, 774, 1462, 1463, + 1462, 776, 1464, 1465, 1466, 1467, 1468, 1469, + 1470, 1467, 780, 776, 1464, 1472, 1473, 1471, + 781, 782, 1474, 1471, 780, 1477, 1478, 1479, + 1480, 1475, 1481, 1482, 1483, 1475, 1476, 1486, + 1487, 1488, 1489, 1484, 1490, 1491, 1492, 1484, + 1485, 1494, 1493, 1496, 1495, 780, 1497, 781, + 1497, 782, 1497, 786, 1498, 1499, 1500, 1501, + 1502, 1503, 1504, 1501, 788, 786, 1498, 1506, + 1505, 789, 790, 1507, 1505, 788, 1509, 1508, + 1511, 1510, 788, 1512, 789, 1512, 790, 1512, + 794, 1515, 1516, 1518, 1519, 1520, 1514, 1521, + 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, + 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, + 1538, 1539, 1540, 1542, 1543, 1544, 1545, 1546, + 1547, 794, 794, 1513, 1514, 1517, 1541, 1548, + 1513, 1045, 794, 794, 1550, 1551, 864, 845, + 1552, 845, 1553, 1554, 1555, 1556, 1557, 1558, + 1559, 1560, 1561, 1562, 1563, 919, 1564, 895, + 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1572, + 1573, 1574, 1575, 1576, 794, 794, 794, 800, + 940, 1549, 1045, 1577, 794, 794, 794, 1045, + 1577, 1045, 1045, 794, 1577, 794, 1577, 794, + 1577, 794, 1045, 1045, 1045, 1045, 1045, 1577, + 794, 1045, 1045, 1045, 794, 1045, 794, 1577, + 794, 1045, 1045, 1045, 1045, 794, 1577, 1045, + 794, 1045, 794, 1045, 794, 1045, 1045, 794, + 1045, 1577, 794, 1045, 794, 1045, 794, 1045, + 1577, 1045, 794, 1577, 1045, 794, 1045, 794, + 1577, 1045, 1045, 1045, 1045, 1045, 1577, 794, + 794, 1045, 794, 1045, 1577, 1045, 794, 1577, + 1045, 1045, 1577, 794, 794, 1045, 794, 1045, + 794, 1045, 1577, 1578, 1579, 1580, 1581, 1582, + 1583, 1584, 1585, 1586, 1587, 1588, 1090, 1589, + 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, + 1598, 1599, 1600, 1599, 1601, 1602, 1603, 1604, + 1605, 1046, 1577, 1606, 1607, 1608, 1609, 1610, + 1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, + 1619, 1620, 1621, 1622, 1623, 1624, 1100, 1625, + 1626, 1627, 1067, 1628, 1629, 1630, 1631, 1632, + 1633, 1046, 1634, 1635, 1636, 1637, 1638, 1639, + 1640, 1641, 1049, 1642, 1046, 1049, 1643, 1644, + 1645, 1646, 1058, 1577, 1647, 1648, 1649, 1650, + 1078, 1651, 1652, 1058, 1653, 1654, 1655, 1656, + 1657, 1046, 1577, 1658, 1617, 1659, 1660, 1661, + 1058, 1662, 1663, 1049, 1046, 1058, 800, 1577, + 1627, 1046, 1049, 1058, 800, 1058, 800, 1664, + 1058, 1577, 800, 1049, 1665, 1666, 1049, 1667, + 1668, 1056, 1669, 1670, 1671, 1672, 1673, 1623, + 1674, 1675, 1676, 1677, 1678, 1679, 1680, 1681, + 1682, 1683, 1684, 1685, 1642, 1686, 1049, 1058, + 800, 1577, 1687, 1688, 1058, 1046, 1577, 800, + 1046, 1577, 1049, 1689, 1106, 1690, 1691, 1692, + 1693, 1694, 1695, 1696, 1697, 1046, 1698, 1699, + 1700, 1701, 1702, 1703, 1046, 1058, 1577, 1705, + 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713, + 1714, 1715, 1711, 1717, 1718, 1719, 1720, 1704, + 1716, 1704, 1577, 1704, 1577, } var _hcltok_trans_targs []int16 = []int16{ @@ -4301,13 +4301,9 @@ const hcltok_en_bareTemplate int = 1549 const hcltok_en_identOnly int = 1556 const hcltok_en_main int = 1464 -//line scan_tokens.rl:16 +// line 16 "scan_tokens.rl" func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []Token { - stripData := stripUTF8BOM(data) - start.Byte += len(data) - len(stripData) - data = stripData - f := &tokenAccum{ Filename: filename, Bytes: data, @@ -4315,7 +4311,7 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To StartByte: start.Byte, } -//line scan_tokens.rl:299 + // line 295 "scan_tokens.rl" // Ragel state p := 0 // "Pointer" into data @@ -4343,7 +4339,7 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To var retBraces []int // stack of brace levels that cause us to use fret var heredocs []heredocInProgress // stack of heredocs we're currently processing -//line scan_tokens.rl:334 + // line 330 "scan_tokens.rl" // Make Go compiler happy _ = ts @@ -4363,7 +4359,7 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To f.emitToken(TokenType(b[0]), ts, te) } -//line scan_tokens.go:4375 + // line 4371 "scan_tokens.go" { top = 0 ts = 0 @@ -4371,7 +4367,7 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To act = 0 } -//line scan_tokens.go:4383 + // line 4379 "scan_tokens.go" { var _klen int var _trans int @@ -4392,10 +4388,11 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To _acts++ switch _hcltok_actions[_acts-1] { case 6: -//line NONE:1 + // line 1 "NONE" + ts = p -//line scan_tokens.go:4406 + // line 4403 "scan_tokens.go" } } @@ -4467,27 +4464,33 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To _acts++ switch _hcltok_actions[_acts-1] { case 0: -//line scan_tokens.rl:223 + // line 219 "scan_tokens.rl" + p-- case 1: -//line scan_tokens.rl:224 + // line 220 "scan_tokens.rl" + p-- case 2: -//line scan_tokens.rl:229 + // line 225 "scan_tokens.rl" + p-- case 3: -//line scan_tokens.rl:230 + // line 226 "scan_tokens.rl" + p-- case 7: -//line NONE:1 + // line 1 "NONE" + te = p + 1 case 8: -//line scan_tokens.rl:160 + // line 156 "scan_tokens.rl" + te = p + 1 { token(TokenTemplateInterp) @@ -4505,7 +4508,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 9: -//line scan_tokens.rl:170 + // line 166 "scan_tokens.rl" + te = p + 1 { token(TokenTemplateControl) @@ -4523,7 +4527,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 10: -//line scan_tokens.rl:84 + // line 80 "scan_tokens.rl" + te = p + 1 { token(TokenCQuote) @@ -4536,19 +4541,22 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } case 11: -//line scan_tokens.rl:244 + // line 240 "scan_tokens.rl" + te = p + 1 { token(TokenInvalid) } case 12: -//line scan_tokens.rl:245 + // line 241 "scan_tokens.rl" + te = p + 1 { token(TokenBadUTF8) } case 13: -//line scan_tokens.rl:160 + // line 156 "scan_tokens.rl" + te = p p-- { @@ -4567,7 +4575,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 14: -//line scan_tokens.rl:170 + // line 166 "scan_tokens.rl" + te = p p-- { @@ -4586,46 +4595,54 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 15: -//line scan_tokens.rl:243 + // line 239 "scan_tokens.rl" + te = p p-- { token(TokenQuotedLit) } case 16: -//line scan_tokens.rl:244 + // line 240 "scan_tokens.rl" + te = p p-- { token(TokenInvalid) } case 17: -//line scan_tokens.rl:245 + // line 241 "scan_tokens.rl" + te = p p-- { token(TokenBadUTF8) } case 18: -//line scan_tokens.rl:243 + // line 239 "scan_tokens.rl" + p = (te) - 1 { token(TokenQuotedLit) } case 19: -//line scan_tokens.rl:245 + // line 241 "scan_tokens.rl" + p = (te) - 1 { token(TokenBadUTF8) } case 20: -//line scan_tokens.rl:148 + // line 144 "scan_tokens.rl" + act = 10 case 21: -//line scan_tokens.rl:253 + // line 249 "scan_tokens.rl" + act = 11 case 22: -//line scan_tokens.rl:160 + // line 156 "scan_tokens.rl" + te = p + 1 { token(TokenTemplateInterp) @@ -4643,7 +4660,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 23: -//line scan_tokens.rl:170 + // line 166 "scan_tokens.rl" + te = p + 1 { token(TokenTemplateControl) @@ -4661,7 +4679,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 24: -//line scan_tokens.rl:111 + // line 107 "scan_tokens.rl" + te = p + 1 { // This action is called specificially when a heredoc literal @@ -4706,13 +4725,15 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To token(TokenStringLit) } case 25: -//line scan_tokens.rl:253 + // line 249 "scan_tokens.rl" + te = p + 1 { token(TokenBadUTF8) } case 26: -//line scan_tokens.rl:160 + // line 156 "scan_tokens.rl" + te = p p-- { @@ -4731,7 +4752,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 27: -//line scan_tokens.rl:170 + // line 166 "scan_tokens.rl" + te = p p-- { @@ -4750,7 +4772,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 28: -//line scan_tokens.rl:148 + // line 144 "scan_tokens.rl" + te = p p-- { @@ -4761,14 +4784,16 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To token(TokenStringLit) } case 29: -//line scan_tokens.rl:253 + // line 249 "scan_tokens.rl" + te = p p-- { token(TokenBadUTF8) } case 30: -//line scan_tokens.rl:148 + // line 144 "scan_tokens.rl" + p = (te) - 1 { // This action is called when a heredoc literal _doesn't_ end @@ -4778,7 +4803,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To token(TokenStringLit) } case 31: -//line NONE:1 + // line 1 "NONE" + switch act { case 0: { @@ -4803,13 +4829,16 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } case 32: -//line scan_tokens.rl:156 + // line 152 "scan_tokens.rl" + act = 14 case 33: -//line scan_tokens.rl:260 + // line 256 "scan_tokens.rl" + act = 15 case 34: -//line scan_tokens.rl:160 + // line 156 "scan_tokens.rl" + te = p + 1 { token(TokenTemplateInterp) @@ -4827,7 +4856,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 35: -//line scan_tokens.rl:170 + // line 166 "scan_tokens.rl" + te = p + 1 { token(TokenTemplateControl) @@ -4845,19 +4875,22 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 36: -//line scan_tokens.rl:156 + // line 152 "scan_tokens.rl" + te = p + 1 { token(TokenStringLit) } case 37: -//line scan_tokens.rl:260 + // line 256 "scan_tokens.rl" + te = p + 1 { token(TokenBadUTF8) } case 38: -//line scan_tokens.rl:160 + // line 156 "scan_tokens.rl" + te = p p-- { @@ -4876,7 +4909,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 39: -//line scan_tokens.rl:170 + // line 166 "scan_tokens.rl" + te = p p-- { @@ -4895,27 +4929,31 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 40: -//line scan_tokens.rl:156 + // line 152 "scan_tokens.rl" + te = p p-- { token(TokenStringLit) } case 41: -//line scan_tokens.rl:260 + // line 256 "scan_tokens.rl" + te = p p-- { token(TokenBadUTF8) } case 42: -//line scan_tokens.rl:156 + // line 152 "scan_tokens.rl" + p = (te) - 1 { token(TokenStringLit) } case 43: -//line NONE:1 + // line 1 "NONE" + switch act { case 0: { @@ -4936,51 +4974,60 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } case 44: -//line scan_tokens.rl:264 + // line 260 "scan_tokens.rl" + act = 16 case 45: -//line scan_tokens.rl:265 + // line 261 "scan_tokens.rl" + act = 17 case 46: -//line scan_tokens.rl:265 + // line 261 "scan_tokens.rl" + te = p + 1 { token(TokenBadUTF8) } case 47: -//line scan_tokens.rl:266 + // line 262 "scan_tokens.rl" + te = p + 1 { token(TokenInvalid) } case 48: -//line scan_tokens.rl:264 + // line 260 "scan_tokens.rl" + te = p p-- { token(TokenIdent) } case 49: -//line scan_tokens.rl:265 + // line 261 "scan_tokens.rl" + te = p p-- { token(TokenBadUTF8) } case 50: -//line scan_tokens.rl:264 + // line 260 "scan_tokens.rl" + p = (te) - 1 { token(TokenIdent) } case 51: -//line scan_tokens.rl:265 + // line 261 "scan_tokens.rl" + p = (te) - 1 { token(TokenBadUTF8) } case 52: -//line NONE:1 + // line 1 "NONE" + switch act { case 16: { @@ -4995,92 +5042,109 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } case 53: -//line scan_tokens.rl:272 + // line 268 "scan_tokens.rl" + act = 21 case 54: -//line scan_tokens.rl:285 + // line 281 "scan_tokens.rl" + act = 32 case 55: -//line scan_tokens.rl:295 + // line 291 "scan_tokens.rl" + act = 38 case 56: -//line scan_tokens.rl:296 + // line 292 "scan_tokens.rl" + act = 39 case 57: -//line scan_tokens.rl:274 + // line 270 "scan_tokens.rl" + te = p + 1 { token(TokenComment) } case 58: -//line scan_tokens.rl:275 + // line 271 "scan_tokens.rl" + te = p + 1 { token(TokenNewline) } case 59: -//line scan_tokens.rl:277 + // line 273 "scan_tokens.rl" + te = p + 1 { token(TokenEqualOp) } case 60: -//line scan_tokens.rl:278 + // line 274 "scan_tokens.rl" + te = p + 1 { token(TokenNotEqual) } case 61: -//line scan_tokens.rl:279 + // line 275 "scan_tokens.rl" + te = p + 1 { token(TokenGreaterThanEq) } case 62: -//line scan_tokens.rl:280 + // line 276 "scan_tokens.rl" + te = p + 1 { token(TokenLessThanEq) } case 63: -//line scan_tokens.rl:281 + // line 277 "scan_tokens.rl" + te = p + 1 { token(TokenAnd) } case 64: -//line scan_tokens.rl:282 + // line 278 "scan_tokens.rl" + te = p + 1 { token(TokenOr) } case 65: -//line scan_tokens.rl:283 + // line 279 "scan_tokens.rl" + te = p + 1 { token(TokenEllipsis) } case 66: -//line scan_tokens.rl:284 + // line 280 "scan_tokens.rl" + te = p + 1 { token(TokenFatArrow) } case 67: -//line scan_tokens.rl:285 + // line 281 "scan_tokens.rl" + te = p + 1 { selfToken() } case 68: -//line scan_tokens.rl:180 + // line 176 "scan_tokens.rl" + te = p + 1 { token(TokenOBrace) braces++ } case 69: -//line scan_tokens.rl:185 + // line 181 "scan_tokens.rl" + te = p + 1 { if len(retBraces) > 0 && retBraces[len(retBraces)-1] == braces { @@ -5100,7 +5164,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 70: -//line scan_tokens.rl:197 + // line 193 "scan_tokens.rl" + te = p + 1 { // Only consume from the retBraces stack and return if we are at @@ -5129,7 +5194,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 71: -//line scan_tokens.rl:79 + // line 75 "scan_tokens.rl" + te = p + 1 { token(TokenOQuote) @@ -5142,7 +5208,8 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 72: -//line scan_tokens.rl:89 + // line 85 "scan_tokens.rl" + te = p + 1 { token(TokenOHeredoc) @@ -5172,83 +5239,96 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } case 73: -//line scan_tokens.rl:295 + // line 291 "scan_tokens.rl" + te = p + 1 { token(TokenBadUTF8) } case 74: -//line scan_tokens.rl:296 + // line 292 "scan_tokens.rl" + te = p + 1 { token(TokenInvalid) } case 75: -//line scan_tokens.rl:270 + // line 266 "scan_tokens.rl" + te = p p-- case 76: -//line scan_tokens.rl:271 + // line 267 "scan_tokens.rl" + te = p p-- { token(TokenNumberLit) } case 77: -//line scan_tokens.rl:272 + // line 268 "scan_tokens.rl" + te = p p-- { token(TokenIdent) } case 78: -//line scan_tokens.rl:285 + // line 281 "scan_tokens.rl" + te = p p-- { selfToken() } case 79: -//line scan_tokens.rl:295 + // line 291 "scan_tokens.rl" + te = p p-- { token(TokenBadUTF8) } case 80: -//line scan_tokens.rl:296 + // line 292 "scan_tokens.rl" + te = p p-- { token(TokenInvalid) } case 81: -//line scan_tokens.rl:271 + // line 267 "scan_tokens.rl" + p = (te) - 1 { token(TokenNumberLit) } case 82: -//line scan_tokens.rl:272 + // line 268 "scan_tokens.rl" + p = (te) - 1 { token(TokenIdent) } case 83: -//line scan_tokens.rl:285 + // line 281 "scan_tokens.rl" + p = (te) - 1 { selfToken() } case 84: -//line scan_tokens.rl:295 + // line 291 "scan_tokens.rl" + p = (te) - 1 { token(TokenBadUTF8) } case 85: -//line NONE:1 + // line 1 "NONE" + switch act { case 21: { @@ -5272,7 +5352,7 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } -//line scan_tokens.go:5138 + // line 5218 "scan_tokens.go" } } @@ -5284,14 +5364,16 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To _acts++ switch _hcltok_actions[_acts-1] { case 4: -//line NONE:1 + // line 1 "NONE" + ts = 0 case 5: -//line NONE:1 + // line 1 "NONE" + act = 0 -//line scan_tokens.go:5156 + // line 5238 "scan_tokens.go" } } @@ -5317,7 +5399,7 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To } } -//line scan_tokens.rl:357 + // line 353 "scan_tokens.rl" // If we fall out here without being in a final state then we've // encountered something that the scanner can't match, which we'll diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_tokens.rl b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_tokens.rl index 1f37b88b..f9c3bf7e 100644 --- a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_tokens.rl +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/scan_tokens.rl @@ -9,17 +9,13 @@ import ( // This file is generated from scan_tokens.rl. DO NOT EDIT. %%{ - # (except when you are actually in scan_tokens.rl here, so edit away!) + # (except you are actually in scan_tokens.rl here, so edit away!) machine hcltok; write data; }%% func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []Token { - stripData := stripUTF8BOM(data) - start.Byte += len(data) - len(stripData) - data = stripData - f := &tokenAccum{ Filename: filename, Bytes: data, @@ -44,7 +40,7 @@ func scanTokens(data []byte, filename string, start hcl.Pos, mode scanMode) []To Ident = (ID_Start | '_') (ID_Continue | '-')*; # Symbols that just represent themselves are handled as a single rule. - SelfToken = "[" | "]" | "(" | ")" | "." | "," | "*" | "/" | "%" | "+" | "-" | "=" | "<" | ">" | "!" | "?" | ":" | "\n" | "&" | "|" | "~" | "^" | ";" | "`" | "'"; + SelfToken = "[" | "]" | "(" | ")" | "." | "," | "*" | "/" | "%" | "+" | "-" | "=" | "<" | ">" | "!" | "?" | ":" | "\n" | "&" | "|" | "~" | "^" | ";" | "`"; EqualOp = "=="; NotEqual = "!="; diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/spec.md b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/spec.md index 091c1c23..4bd35fae 100644 --- a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/spec.md +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/spec.md @@ -9,13 +9,13 @@ generation of configuration. The language consists of three integrated sub-languages: -- The _structural_ language defines the overall hierarchical configuration +* The _structural_ language defines the overall hierarchical configuration structure, and is a serialization of HCL bodies, blocks and attributes. -- The _expression_ language is used to express attribute values, either as +* The _expression_ language is used to express attribute values, either as literals or as derivations of other values. -- The _template_ language is used to compose values together into strings, +* The _template_ language is used to compose values together into strings, as one of several types of expression in the expression language. In normal use these three sub-languages are used together within configuration @@ -30,19 +30,19 @@ Within this specification a semi-formal notation is used to illustrate the details of syntax. This notation is intended for human consumption rather than machine consumption, with the following conventions: -- A naked name starting with an uppercase letter is a global production, +* A naked name starting with an uppercase letter is a global production, common to all of the syntax specifications in this document. -- A naked name starting with a lowercase letter is a local production, +* A naked name starting with a lowercase letter is a local production, meaningful only within the specification where it is defined. -- Double and single quotes (`"` and `'`) are used to mark literal character +* Double and single quotes (`"` and `'`) are used to mark literal character sequences, which may be either punctuation markers or keywords. -- The default operator for combining items, which has no punctuation, +* The default operator for combining items, which has no punctuation, is concatenation. -- The symbol `|` indicates that any one of its left and right operands may +* The symbol `|` indicates that any one of its left and right operands may be present. -- The `*` symbol indicates zero or more repetitions of the item to its left. -- The `?` symbol indicates zero or one of the item to its left. -- Parentheses (`(` and `)`) are used to group items together to apply +* The `*` symbol indicates zero or more repetitions of the item to its left. +* The `?` symbol indicates zero or one of the item to its left. +* Parentheses (`(` and `)`) are used to group items together to apply the `|`, `*` and `?` operators to them collectively. The grammar notation does not fully describe the language. The prose may @@ -77,11 +77,11 @@ are not valid within HCL native syntax. Comments serve as program documentation and come in two forms: -- _Line comments_ start with either the `//` or `#` sequences and end with +* _Line comments_ start with either the `//` or `#` sequences and end with the next newline sequence. A line comments is considered equivalent to a newline sequence. -- _Inline comments_ start with the `/*` sequence and end with the `*/` +* _Inline comments_ start with the `/*` sequence and end with the `*/` sequence, and may have any characters within except the ending sequence. An inline comments is considered equivalent to a whitespace sequence. @@ -91,7 +91,7 @@ template literals except inside an interpolation sequence or template directive. ### Identifiers Identifiers name entities such as blocks, attributes and expression variables. -Identifiers are interpreted as per [UAX #31][uax31] Section 2. Specifically, +Identifiers are interpreted as per [UAX #31][UAX31] Section 2. Specifically, their syntax is defined in terms of the `ID_Start` and `ID_Continue` character properties as follows: @@ -109,7 +109,7 @@ that is not part of the unicode `ID_Continue` definition. This is to allow attribute names and block type names to contain dashes, although underscores as word separators are considered the idiomatic usage. -[uax31]: http://unicode.org/reports/tr31/ "Unicode Identifier and Pattern Syntax" +[UAX31]: http://unicode.org/reports/tr31/ "Unicode Identifier and Pattern Syntax" ### Keywords @@ -150,9 +150,9 @@ expmark = ('e' | 'E') ("+" | "-")?; The structural language consists of syntax representing the following constructs: -- _Attributes_, which assign a value to a specified name. -- _Blocks_, which create a child body annotated by a type and optional labels. -- _Body Content_, which consists of a collection of attributes and blocks. +* _Attributes_, which assign a value to a specified name. +* _Blocks_, which create a child body annotated by a type and optional labels. +* _Body Content_, which consists of a collection of attributes and blocks. These constructs correspond to the similarly-named concepts in the language-agnostic HCL information model. @@ -253,9 +253,9 @@ LiteralValue = ( ); ``` -- Numeric literals represent values of type _number_. -- The `true` and `false` keywords represent values of type _bool_. -- The `null` keyword represents a null value of the dynamic pseudo-type. +* Numeric literals represent values of type _number_. +* The `true` and `false` keywords represent values of type _bool_. +* The `null` keyword represents a null value of the dynamic pseudo-type. String literals are not directly available in the expression sub-language, but are available via the template sub-language, which can in turn be incorporated @@ -286,8 +286,8 @@ When specifying an object element, an identifier is interpreted as a literal attribute name as opposed to a variable reference. To populate an item key from a variable, use parentheses to disambiguate: -- `{foo = "baz"}` is interpreted as an attribute literally named `foo`. -- `{(foo) = "baz"}` is interpreted as an attribute whose name is taken +* `{foo = "baz"}` is interpreted as an attribute literally named `foo`. +* `{(foo) = "baz"}` is interpreted as an attribute whose name is taken from the variable named `foo`. Between the open and closing delimiters of these sequences, newline sequences @@ -299,12 +299,12 @@ _for expression_ interpretation has priority, so to produce a tuple whose first element is the value of a variable named `for`, or an object with a key named `for`, use parentheses to disambiguate: -- `[for, foo, baz]` is a syntax error. -- `[(for), foo, baz]` is a tuple whose first element is the value of variable +* `[for, foo, baz]` is a syntax error. +* `[(for), foo, baz]` is a tuple whose first element is the value of variable `for`. -- `{for: 1, baz: 2}` is a syntax error. -- `{(for): 1, baz: 2}` is an object with an attribute literally named `for`. -- `{baz: 2, for: 1}` is equivalent to the previous example, and resolves the +* `{for: 1, baz: 2}` is a syntax error. +* `{(for): 1, baz: 2}` is an object with an attribute literally named `for`. +* `{baz: 2, for: 1}` is equivalent to the previous example, and resolves the ambiguity by reordering. ### Template Expressions @@ -312,9 +312,9 @@ key named `for`, use parentheses to disambiguate: A _template expression_ embeds a program written in the template sub-language as an expression. Template expressions come in two forms: -- A _quoted_ template expression is delimited by quote characters (`"`) and +* A _quoted_ template expression is delimited by quote characters (`"`) and defines a template as a single-line expression with escape characters. -- A _heredoc_ template expression is introduced by a `<<` sequence and +* A _heredoc_ template expression is introduced by a `<<` sequence and defines a template via a multi-line sequence terminated by a user-chosen delimiter. @@ -322,7 +322,7 @@ In both cases the template interpolation and directive syntax is available for use within the delimiters, and any text outside of these special sequences is interpreted as a literal string. -In _quoted_ template expressions any literal string sequences within the +In _quoted_ template expressions any literal string sequences within the template behave in a special way: literal newline sequences are not permitted and instead _escape sequences_ can be included, starting with the backslash `\`: @@ -458,14 +458,14 @@ are provided, the first is the key and the second is the value. Tuple, object, list, map, and set types are iterable. The type of collection used defines how the key and value variables are populated: -- For tuple and list types, the _key_ is the zero-based index into the +* For tuple and list types, the _key_ is the zero-based index into the sequence for each element, and the _value_ is the element value. The elements are visited in index order. -- For object and map types, the _key_ is the string attribute name or element +* For object and map types, the _key_ is the string attribute name or element key, and the _value_ is the attribute or element value. The elements are visited in the order defined by a lexicographic sort of the attribute names or keys. -- For set types, the _key_ and _value_ are both the element value. The elements +* For set types, the _key_ and _value_ are both the element value. The elements are visited in an undefined but consistent order. The expression after the colon and (in the case of object `for`) the expression @@ -487,12 +487,12 @@ immediately after the value expression, this activates the grouping mode in which each value in the resulting object is a _tuple_ of all of the values that were produced against each distinct key. -- `[for v in ["a", "b"]: v]` returns `["a", "b"]`. -- `[for i, v in ["a", "b"]: i]` returns `[0, 1]`. -- `{for i, v in ["a", "b"]: v => i}` returns `{a = 0, b = 1}`. -- `{for i, v in ["a", "a", "b"]: k => v}` produces an error, because attribute +* `[for v in ["a", "b"]: v]` returns `["a", "b"]`. +* `[for i, v in ["a", "b"]: i]` returns `[0, 1]`. +* `{for i, v in ["a", "b"]: v => i}` returns `{a = 0, b = 1}`. +* `{for i, v in ["a", "a", "b"]: k => v}` produces an error, because attribute `a` is defined twice. -- `{for i, v in ["a", "a", "b"]: v => i...}` returns `{a = [0, 1], b = [2]}`. +* `{for i, v in ["a", "a", "b"]: v => i...}` returns `{a = [0, 1], b = [2]}`. If the `if` keyword is used after the element expression(s), it applies an additional predicate that can be used to conditionally filter elements from @@ -502,7 +502,7 @@ element expression(s). It must evaluate to a boolean value; if `true`, the element will be evaluated as normal, while if `false` the element will be skipped. -- `[for i, v in ["a", "b", "c"]: v if i < 2]` returns `["a", "b"]`. +* `[for i, v in ["a", "b", "c"]: v if i < 2]` returns `["a", "b"]`. If the collection value, element expression(s) or condition expression return unknown values that are otherwise type-valid, the result is a value of the @@ -567,10 +567,10 @@ elements in a tuple, list, or set value. There are two kinds of "splat" operator: -- The _attribute-only_ splat operator supports only attribute lookups into +* The _attribute-only_ splat operator supports only attribute lookups into the elements from a list, but supports an arbitrary number of them. -- The _full_ splat operator additionally supports indexing into the elements +* The _full_ splat operator additionally supports indexing into the elements from a list, and allows any combination of attribute access and index operations. @@ -583,9 +583,9 @@ fullSplat = "[" "*" "]" (GetAttr | Index)*; The splat operators can be thought of as shorthands for common operations that could otherwise be performed using _for expressions_: -- `tuple.*.foo.bar[0]` is approximately equivalent to +* `tuple.*.foo.bar[0]` is approximately equivalent to `[for v in tuple: v.foo.bar][0]`. -- `tuple[*].foo.bar[0]` is approximately equivalent to +* `tuple[*].foo.bar[0]` is approximately equivalent to `[for v in tuple: v.foo.bar[0]]` Note the difference in how the trailing index operator is interpreted in @@ -597,15 +597,13 @@ _for expressions_ shown above: if a splat operator is applied to a value that is _not_ of tuple, list, or set type, the value is coerced automatically into a single-value list of the value type: -- `any_object.*.id` is equivalent to `[any_object.id]`, assuming that `any_object` +* `any_object.*.id` is equivalent to `[any_object.id]`, assuming that `any_object` is a single object. -- `any_number.*` is equivalent to `[any_number]`, assuming that `any_number` +* `any_number.*` is equivalent to `[any_number]`, assuming that `any_number` is a single number. -If applied to a null value that is not tuple, list, or set, the result is always -an empty tuple, which allows conveniently converting a possibly-null scalar -value into a tuple of zero or one elements. It is illegal to apply a splat -operator to a null value of tuple, list, or set type. +If the left operand of a splat operator is an unknown value of any type, the +result is a value of the dynamic pseudo-type. ### Operations @@ -686,7 +684,7 @@ Arithmetic operations are considered to be performed in an arbitrary-precision number space. If either operand of an arithmetic operator is an unknown number or a value -of the dynamic pseudo-type, the result is an unknown number. +of the dynamic pseudo-type, the result is an unknown number. ### Logic Operators @@ -711,7 +709,7 @@ the outcome of a boolean expression. Conditional = Expression "?" Expression ":" Expression; ``` -The first expression is the _predicate_, which is evaluated and must produce +The first expression is the _predicate_, which is evaluated and must produce a boolean result. If the predicate value is `true`, the result of the second expression is the result of the conditional. If the predicate value is `false`, the result of the third expression is the result of the conditional. @@ -779,8 +777,8 @@ interpolations or directives that are adjacent to it. A strip marker is a tilde (`~`) placed immediately after the opening `{` or before the closing `}` of a template sequence: -- `hello ${~ "world" }` produces `"helloworld"`. -- `%{ if true ~} hello %{~ endif }` produces `"hello"`. +* `hello ${~ "world" }` produces `"helloworld"`. +* `%{ if true ~} hello %{~ endif }` produces `"hello"`. When a strip marker is present, any spaces adjacent to it in the corresponding string literal (if any) are removed before producing the final value. Space @@ -789,7 +787,7 @@ characters are interpreted as per Unicode's definition. Stripping is done at syntax level rather than value level. Values returned by interpolations or directives are not subject to stripping: -- `${"hello" ~}${" world"}` produces `"hello world"`, and not `"helloworld"`, +* `${"hello" ~}${" world"}` produces `"hello world"`, and not `"helloworld"`, because the space is not in a template literal directly adjacent to the strip marker. @@ -827,9 +825,9 @@ TemplateIf = ( The evaluation of the `if` directive is equivalent to the conditional expression, with the following exceptions: -- The two sub-templates always produce strings, and thus the result value is +* The two sub-templates always produce strings, and thus the result value is also always a string. -- The `else` clause may be omitted, in which case the conditional's third +* The `else` clause may be omitted, in which case the conditional's third expression result is implied to be the empty string. ### Template For Directive @@ -849,9 +847,9 @@ TemplateFor = ( The evaluation of the `for` directive is equivalent to the _for expression_ when producing a tuple, with the following exceptions: -- The sub-template always produces a string. -- There is no equivalent of the "if" clause on the for expression. -- The elements of the resulting tuple are all converted to strings and +* The sub-template always produces a string. +* There is no equivalent of the "if" clause on the for expression. +* The elements of the resulting tuple are all converted to strings and concatenated to produce a flat string result. ### Template Interpolation Unwrapping @@ -867,13 +865,13 @@ template or expression syntax. Unwrapping allows arbitrary expressions to be used to populate attributes when strings in such languages are interpreted as templates. -- `${true}` produces the boolean value `true` -- `${"${true}"}` produces the boolean value `true`, because both the inner +* `${true}` produces the boolean value `true` +* `${"${true}"}` produces the boolean value `true`, because both the inner and outer interpolations are subject to unwrapping. -- `hello ${true}` produces the string `"hello true"` -- `${""}${true}` produces the string `"true"` because there are two +* `hello ${true}` produces the string `"hello true"` +* `${""}${true}` produces the string `"true"` because there are two interpolation sequences, even though one produces an empty result. -- `%{ for v in [true] }${v}%{ endif }` produces the string `true` because +* `%{ for v in [true] }${v}%{ endif }` produces the string `true` because the presence of the `for` directive circumvents the unwrapping even though the final result is a single value. diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/structure.go b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/structure.go index 22e389c8..ebafcb49 100644 --- a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/structure.go +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/structure.go @@ -255,9 +255,9 @@ func (b *Body) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { example := b.Blocks[0] diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, - Summary: fmt.Sprintf("Unexpected %q block", example.Type), + Summary: fmt.Sprintf("Unexpected %s block", example.Type), Detail: "Blocks are not allowed here.", - Subject: &example.TypeRange, + Context: &example.TypeRange, }) // we will continue processing anyway, and return the attributes // we are able to find so that certain analyses can still be done diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/token.go b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/token.go index 67be099c..7b53bd3a 100644 --- a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/token.go +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/token.go @@ -90,7 +90,6 @@ const ( TokenBitwiseNot TokenType = '~' TokenBitwiseXor TokenType = '^' TokenStarStar TokenType = '➚' - TokenApostrophe TokenType = '\'' TokenBacktick TokenType = '`' TokenSemicolon TokenType = ';' TokenTabs TokenType = '␉' @@ -184,15 +183,11 @@ func checkInvalidTokens(tokens Tokens) hcl.Diagnostics { toldBitwise := 0 toldExponent := 0 toldBacktick := 0 - toldApostrophe := 0 toldSemicolon := 0 toldTabs := 0 toldBadUTF8 := 0 for _, tok := range tokens { - // copy token so it's safe to point to it - tok := tok - switch tok.Type { case TokenBitwiseAnd, TokenBitwiseOr, TokenBitwiseXor, TokenBitwiseNot: if toldBitwise < 4 { @@ -228,30 +223,16 @@ func checkInvalidTokens(tokens Tokens) hcl.Diagnostics { case TokenBacktick: // Only report for alternating (even) backticks, so we won't report both start and ends of the same // backtick-quoted string. - if (toldBacktick % 2) == 0 { + if toldExponent < 4 && (toldExponent%2) == 0 { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Invalid character", Detail: "The \"`\" character is not valid. To create a multi-line string, use the \"heredoc\" syntax, like \"< 0: // No spaces after open brackets return false diff --git a/vendor/github.com/hashicorp/hil/convert.go b/vendor/github.com/hashicorp/hil/convert.go index 184e029b..f2024d01 100644 --- a/vendor/github.com/hashicorp/hil/convert.go +++ b/vendor/github.com/hashicorp/hil/convert.go @@ -47,23 +47,8 @@ func hilMapstructureWeakDecode(m interface{}, rawVal interface{}) error { } func InterfaceToVariable(input interface{}) (ast.Variable, error) { - if iv, ok := input.(ast.Variable); ok { - return iv, nil - } - - // This is just to maintain backward compatibility - // after https://github.com/mitchellh/mapstructure/pull/98 - if v, ok := input.([]ast.Variable); ok { - return ast.Variable{ - Type: ast.TypeList, - Value: v, - }, nil - } - if v, ok := input.(map[string]ast.Variable); ok { - return ast.Variable{ - Type: ast.TypeMap, - Value: v, - }, nil + if inputVariable, ok := input.(ast.Variable); ok { + return inputVariable, nil } var stringVal string diff --git a/vendor/github.com/hashicorp/hil/go.mod b/vendor/github.com/hashicorp/hil/go.mod deleted file mode 100644 index 45719a69..00000000 --- a/vendor/github.com/hashicorp/hil/go.mod +++ /dev/null @@ -1,6 +0,0 @@ -module github.com/hashicorp/hil - -require ( - github.com/mitchellh/mapstructure v1.1.2 - github.com/mitchellh/reflectwalk v1.0.0 -) diff --git a/vendor/github.com/hashicorp/hil/go.sum b/vendor/github.com/hashicorp/hil/go.sum deleted file mode 100644 index 83639b69..00000000 --- a/vendor/github.com/hashicorp/hil/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/LICENSE b/vendor/github.com/hashicorp/terraform-config-inspect/LICENSE deleted file mode 100644 index 82b4de97..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/LICENSE +++ /dev/null @@ -1,353 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/diagnostic.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/diagnostic.go deleted file mode 100644 index 8d04ad4d..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/diagnostic.go +++ /dev/null @@ -1,138 +0,0 @@ -package tfconfig - -import ( - "fmt" - - legacyhclparser "github.com/hashicorp/hcl/hcl/parser" - "github.com/hashicorp/hcl2/hcl" -) - -// Diagnostic describes a problem (error or warning) encountered during -// configuration loading. -type Diagnostic struct { - Severity DiagSeverity `json:"severity"` - Summary string `json:"summary"` - Detail string `json:"detail,omitempty"` - - // Pos is not populated for all diagnostics, but when populated should - // indicate a particular line that the described problem relates to. - Pos *SourcePos `json:"pos,omitempty"` -} - -// Diagnostics represents a sequence of diagnostics. This is the type that -// should be returned from a function that might generate diagnostics. -type Diagnostics []Diagnostic - -// HasErrors returns true if there is at least one Diagnostic of severity -// DiagError in the receiever. -// -// If a function returns a Diagnostics without errors then the result can -// be assumed to be complete within the "best effort" constraints of this -// library. If errors are present then the caller may wish to employ more -// caution in relying on the result. -func (diags Diagnostics) HasErrors() bool { - for _, diag := range diags { - if diag.Severity == DiagError { - return true - } - } - return false -} - -func (diags Diagnostics) Error() string { - switch len(diags) { - case 0: - return "no problems" - case 1: - return fmt.Sprintf("%s: %s", diags[0].Summary, diags[0].Detail) - default: - return fmt.Sprintf("%s: %s (and %d other messages)", diags[0].Summary, diags[0].Detail, len(diags)-1) - } -} - -// Err returns an error representing the receiver if the receiver HasErrors, or -// nil otherwise. -// -// The returned error can be type-asserted back to a Diagnostics if needed. -func (diags Diagnostics) Err() error { - if diags.HasErrors() { - return diags - } - return nil -} - -// DiagSeverity describes the severity of a Diagnostic. -type DiagSeverity rune - -// DiagError indicates a problem that prevented proper processing of the -// configuration. In the precense of DiagError diagnostics the result is -// likely to be incomplete. -const DiagError DiagSeverity = 'E' - -// DiagWarning indicates a problem that the user may wish to consider but -// that did not prevent proper processing of the configuration. -const DiagWarning DiagSeverity = 'W' - -// MarshalJSON is an implementation of encoding/json.Marshaler -func (s DiagSeverity) MarshalJSON() ([]byte, error) { - switch s { - case DiagError: - return []byte(`"error"`), nil - case DiagWarning: - return []byte(`"warning"`), nil - default: - return []byte(`"invalid"`), nil - } -} - -func diagnosticsHCL(diags hcl.Diagnostics) Diagnostics { - if len(diags) == 0 { - return nil - } - ret := make(Diagnostics, len(diags)) - for i, diag := range diags { - ret[i] = Diagnostic{ - Summary: diag.Summary, - Detail: diag.Detail, - } - switch diag.Severity { - case hcl.DiagError: - ret[i].Severity = DiagError - case hcl.DiagWarning: - ret[i].Severity = DiagWarning - } - if diag.Subject != nil { - pos := sourcePosHCL(*diag.Subject) - ret[i].Pos = &pos - } - } - return ret -} - -func diagnosticsError(err error) Diagnostics { - if err == nil { - return nil - } - - if posErr, ok := err.(*legacyhclparser.PosError); ok { - pos := sourcePosLegacyHCL(posErr.Pos, "") - return Diagnostics{ - Diagnostic{ - Severity: DiagError, - Summary: posErr.Err.Error(), - Pos: &pos, - }, - } - } - - return Diagnostics{ - Diagnostic{ - Severity: DiagError, - Summary: err.Error(), - }, - } -} - -func diagnosticsErrorf(format string, args ...interface{}) Diagnostics { - return diagnosticsError(fmt.Errorf(format, args...)) -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/doc.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/doc.go deleted file mode 100644 index 1604a6e0..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/doc.go +++ /dev/null @@ -1,21 +0,0 @@ -// Package tfconfig is a helper library that does careful, shallow parsing of -// Terraform modules to provide access to high-level metadata while -// remaining broadly compatible with configurations targeting various -// different Terraform versions. -// -// This packge focuses on describing top-level objects only, and in particular -// does not attempt any sort of processing that would require access to plugins. -// Currently it allows callers to extract high-level information about -// variables, outputs, resource blocks, provider dependencies, and Terraform -// Core dependencies. -// -// This package only works at the level of single modules. A full configuration -// is a tree of potentially several modules, some of which may be references -// to remote packages. There are some basic helpers for traversing calls to -// modules at relative local paths, however. -// -// This package employs a "best effort" parsing strategy, producing as complete -// a result as possible even though the input may not be entirely valid. The -// intended use-case is high-level analysis and indexing of externally-facing -// module characteristics, as opposed to validating or even applying the module. -package tfconfig diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go deleted file mode 100644 index 2d13fe12..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go +++ /dev/null @@ -1,130 +0,0 @@ -package tfconfig - -import ( - "fmt" - "io/ioutil" - "path/filepath" - "strings" - - "github.com/hashicorp/hcl2/hcl" -) - -// LoadModule reads the directory at the given path and attempts to interpret -// it as a Terraform module. -func LoadModule(dir string) (*Module, Diagnostics) { - - // For broad compatibility here we actually have two separate loader - // codepaths. The main one uses the new HCL parser and API and is intended - // for configurations from Terraform 0.12 onwards (though will work for - // many older configurations too), but we'll also fall back on one that - // uses the _old_ HCL implementation so we can deal with some edge-cases - // that are not valid in new HCL. - - module, diags := loadModule(dir) - if diags.HasErrors() { - // Try using the legacy HCL parser and see if we fare better. - legacyModule, legacyDiags := loadModuleLegacyHCL(dir) - if !legacyDiags.HasErrors() { - legacyModule.init(legacyDiags) - return legacyModule, legacyDiags - } - } - - module.init(diags) - return module, diags -} - -// IsModuleDir checks if the given path contains terraform configuration files. -// This allows the caller to decide how to handle directories that do not have tf files. -func IsModuleDir(dir string) bool { - primaryPaths, _ := dirFiles(dir) - if len(primaryPaths) == 0 { - return false - } - return true -} - -func (m *Module) init(diags Diagnostics) { - // Fill in any additional provider requirements that are implied by - // resource configurations, to avoid the caller from needing to apply - // this logic itself. Implied requirements don't have version constraints, - // but we'll make sure the requirement value is still non-nil in this - // case so callers can easily recognize it. - for _, r := range m.ManagedResources { - if _, exists := m.RequiredProviders[r.Provider.Name]; !exists { - m.RequiredProviders[r.Provider.Name] = []string{} - } - } - for _, r := range m.DataResources { - if _, exists := m.RequiredProviders[r.Provider.Name]; !exists { - m.RequiredProviders[r.Provider.Name] = []string{} - } - } - - // We redundantly also reference the diagnostics from inside the module - // object, primarily so that we can easily included in JSON-serialized - // versions of the module object. - m.Diagnostics = diags -} - -func dirFiles(dir string) (primary []string, diags hcl.Diagnostics) { - infos, err := ioutil.ReadDir(dir) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Failed to read module directory", - Detail: fmt.Sprintf("Module directory %s does not exist or cannot be read.", dir), - }) - return - } - - var override []string - for _, info := range infos { - if info.IsDir() { - // We only care about files - continue - } - - name := info.Name() - ext := fileExt(name) - if ext == "" || isIgnoredFile(name) { - continue - } - - baseName := name[:len(name)-len(ext)] // strip extension - isOverride := baseName == "override" || strings.HasSuffix(baseName, "_override") - - fullPath := filepath.Join(dir, name) - if isOverride { - override = append(override, fullPath) - } else { - primary = append(primary, fullPath) - } - } - - // We are assuming that any _override files will be logically named, - // and processing the files in alphabetical order. Primaries first, then overrides. - primary = append(primary, override...) - - return -} - -// fileExt returns the Terraform configuration extension of the given -// path, or a blank string if it is not a recognized extension. -func fileExt(path string) string { - if strings.HasSuffix(path, ".tf") { - return ".tf" - } else if strings.HasSuffix(path, ".tf.json") { - return ".tf.json" - } else { - return "" - } -} - -// isIgnoredFile returns true if the given filename (which must not have a -// directory path ahead of it) should be ignored as e.g. an editor swap file. -func isIgnoredFile(name string) bool { - return strings.HasPrefix(name, ".") || // Unix-like hidden files - strings.HasSuffix(name, "~") || // vim - strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#") // emacs -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_hcl.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_hcl.go deleted file mode 100644 index 8fa8e035..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_hcl.go +++ /dev/null @@ -1,312 +0,0 @@ -package tfconfig - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/hashicorp/hcl2/hcl/hclsyntax" - - "github.com/hashicorp/hcl2/gohcl" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hclparse" - ctyjson "github.com/zclconf/go-cty/cty/json" -) - -func loadModule(dir string) (*Module, Diagnostics) { - mod := newModule(dir) - primaryPaths, diags := dirFiles(dir) - - parser := hclparse.NewParser() - - for _, filename := range primaryPaths { - var file *hcl.File - var fileDiags hcl.Diagnostics - if strings.HasSuffix(filename, ".json") { - file, fileDiags = parser.ParseJSONFile(filename) - } else { - file, fileDiags = parser.ParseHCLFile(filename) - } - diags = append(diags, fileDiags...) - if file == nil { - continue - } - - content, _, contentDiags := file.Body.PartialContent(rootSchema) - diags = append(diags, contentDiags...) - - for _, block := range content.Blocks { - switch block.Type { - - case "terraform": - content, _, contentDiags := block.Body.PartialContent(terraformBlockSchema) - diags = append(diags, contentDiags...) - - if attr, defined := content.Attributes["required_version"]; defined { - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - if !valDiags.HasErrors() { - mod.RequiredCore = append(mod.RequiredCore, version) - } - } - - for _, block := range content.Blocks { - // Our schema only allows required_providers here, so we - // assume that we'll only get that block type. - attrs, attrDiags := block.Body.JustAttributes() - diags = append(diags, attrDiags...) - - for name, attr := range attrs { - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - if !valDiags.HasErrors() { - mod.RequiredProviders[name] = append(mod.RequiredProviders[name], version) - } - } - } - - case "variable": - content, _, contentDiags := block.Body.PartialContent(variableSchema) - diags = append(diags, contentDiags...) - - name := block.Labels[0] - v := &Variable{ - Name: name, - Pos: sourcePosHCL(block.DefRange), - } - - mod.Variables[name] = v - - if attr, defined := content.Attributes["type"]; defined { - // We handle this particular attribute in a somewhat-tricky way: - // since Terraform may evolve its type expression syntax in - // future versions, we don't want to be overly-strict in how - // we handle it here, and so we'll instead just take the raw - // source provided by the user, using the source location - // information in the expression object. - // - // However, older versions of Terraform expected the type - // to be a string containing a keyword, so we'll need to - // handle that as a special case first for backward compatibility. - - var typeExpr string - - var typeExprAsStr string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &typeExprAsStr) - if !valDiags.HasErrors() { - typeExpr = typeExprAsStr - } else { - - rng := attr.Expr.Range() - sourceFilename := rng.Filename - source, exists := parser.Sources()[sourceFilename] - if exists { - typeExpr = string(rng.SliceBytes(source)) - } else { - // This should never happen, so we'll just warn about it and leave the type unspecified. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Source code not available", - Detail: fmt.Sprintf("Source code is not available for the file %q, which declares the variable %q.", sourceFilename, name), - Subject: &block.DefRange, - }) - typeExpr = "" - } - - } - - v.Type = typeExpr - } - - if attr, defined := content.Attributes["description"]; defined { - var description string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &description) - diags = append(diags, valDiags...) - v.Description = description - } - - if attr, defined := content.Attributes["default"]; defined { - // To avoid the caller needing to deal with cty here, we'll - // use its JSON encoding to convert into an - // approximately-equivalent plain Go interface{} value - // to return. - val, valDiags := attr.Expr.Value(nil) - diags = append(diags, valDiags...) - if val.IsWhollyKnown() { // should only be false if there are errors in the input - valJSON, err := ctyjson.Marshal(val, val.Type()) - if err != nil { - // Should never happen, since all possible known - // values have a JSON mapping. - panic(fmt.Errorf("failed to serialize default value as JSON: %s", err)) - } - var def interface{} - err = json.Unmarshal(valJSON, &def) - if err != nil { - // Again should never happen, because valJSON is - // guaranteed valid by ctyjson.Marshal. - panic(fmt.Errorf("failed to re-parse default value from JSON: %s", err)) - } - v.Default = def - } - } - - case "output": - - content, _, contentDiags := block.Body.PartialContent(outputSchema) - diags = append(diags, contentDiags...) - - name := block.Labels[0] - o := &Output{ - Name: name, - Pos: sourcePosHCL(block.DefRange), - } - - mod.Outputs[name] = o - - if attr, defined := content.Attributes["description"]; defined { - var description string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &description) - diags = append(diags, valDiags...) - o.Description = description - } - - case "provider": - - content, _, contentDiags := block.Body.PartialContent(providerConfigSchema) - diags = append(diags, contentDiags...) - - name := block.Labels[0] - - if attr, defined := content.Attributes["version"]; defined { - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - if !valDiags.HasErrors() { - mod.RequiredProviders[name] = append(mod.RequiredProviders[name], version) - } - } - - // Even if there wasn't an explicit version required, we still - // need an entry in our map to signal the unversioned dependency. - if _, exists := mod.RequiredProviders[name]; !exists { - mod.RequiredProviders[name] = []string{} - } - - case "resource", "data": - - content, _, contentDiags := block.Body.PartialContent(resourceSchema) - diags = append(diags, contentDiags...) - - typeName := block.Labels[0] - name := block.Labels[1] - - r := &Resource{ - Type: typeName, - Name: name, - Pos: sourcePosHCL(block.DefRange), - } - - var resourcesMap map[string]*Resource - - switch block.Type { - case "resource": - r.Mode = ManagedResourceMode - resourcesMap = mod.ManagedResources - case "data": - r.Mode = DataResourceMode - resourcesMap = mod.DataResources - } - - key := r.MapKey() - - resourcesMap[key] = r - - if attr, defined := content.Attributes["provider"]; defined { - // New style here is to provide this as a naked traversal - // expression, but we also support quoted references for - // older configurations that predated this convention. - traversal, travDiags := hcl.AbsTraversalForExpr(attr.Expr) - if travDiags.HasErrors() { - traversal = nil // in case we got any partial results - - // Fall back on trying to parse as a string - var travStr string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &travStr) - if !valDiags.HasErrors() { - var strDiags hcl.Diagnostics - traversal, strDiags = hclsyntax.ParseTraversalAbs([]byte(travStr), "", hcl.Pos{}) - if strDiags.HasErrors() { - traversal = nil - } - } - } - - // If we get out here with a nil traversal then we didn't - // succeed in processing the input. - if len(traversal) > 0 { - providerName := traversal.RootName() - alias := "" - if len(traversal) > 1 { - if getAttr, ok := traversal[1].(hcl.TraverseAttr); ok { - alias = getAttr.Name - } - } - r.Provider = ProviderRef{ - Name: providerName, - Alias: alias, - } - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider reference", - Detail: "Provider argument requires a provider name followed by an optional alias, like \"aws.foo\".", - Subject: attr.Expr.Range().Ptr(), - }) - } - } else { - // If provider _isn't_ set then we'll infer it from the - // resource type. - r.Provider = ProviderRef{ - Name: resourceTypeDefaultProviderName(r.Type), - } - } - - case "module": - - content, _, contentDiags := block.Body.PartialContent(moduleCallSchema) - diags = append(diags, contentDiags...) - - name := block.Labels[0] - mc := &ModuleCall{ - Name: block.Labels[0], - Pos: sourcePosHCL(block.DefRange), - } - - mod.ModuleCalls[name] = mc - - if attr, defined := content.Attributes["source"]; defined { - var source string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &source) - diags = append(diags, valDiags...) - mc.Source = source - } - - if attr, defined := content.Attributes["version"]; defined { - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - mc.Version = version - } - - default: - // Should never happen because our cases above should be - // exhaustive for our schema. - panic(fmt.Errorf("unhandled block type %q", block.Type)) - } - } - } - - return mod, diagnosticsHCL(diags) -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go deleted file mode 100644 index 3ed0c6a8..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go +++ /dev/null @@ -1,322 +0,0 @@ -package tfconfig - -import ( - "io/ioutil" - "strings" - - legacyhcl "github.com/hashicorp/hcl" - legacyast "github.com/hashicorp/hcl/hcl/ast" -) - -func loadModuleLegacyHCL(dir string) (*Module, Diagnostics) { - // This implementation is intentionally more quick-and-dirty than the - // main loader. In particular, it doesn't bother to keep careful track - // of multiple error messages because we always fall back on returning - // the main parser's error message if our fallback parsing produces - // an error, and thus the errors here are not seen by the end-caller. - mod := newModule(dir) - - primaryPaths, diags := dirFiles(dir) - if diags.HasErrors() { - return mod, diagnosticsHCL(diags) - } - - for _, filename := range primaryPaths { - src, err := ioutil.ReadFile(filename) - if err != nil { - return mod, diagnosticsErrorf("Error reading %s: %s", filename, err) - } - - hclRoot, err := legacyhcl.Parse(string(src)) - if err != nil { - return mod, diagnosticsErrorf("Error parsing %s: %s", filename, err) - } - - list, ok := hclRoot.Node.(*legacyast.ObjectList) - if !ok { - return mod, diagnosticsErrorf("Error parsing %s: no root object", filename) - } - - for _, item := range list.Filter("terraform").Items { - if len(item.Keys) > 0 { - item = &legacyast.ObjectItem{ - Val: &legacyast.ObjectType{ - List: &legacyast.ObjectList{ - Items: []*legacyast.ObjectItem{item}, - }, - }, - } - } - - type TerraformBlock struct { - RequiredVersion string `hcl:"required_version"` - } - var block TerraformBlock - err = legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("terraform block: %s", err) - } - - if block.RequiredVersion != "" { - mod.RequiredCore = append(mod.RequiredCore, block.RequiredVersion) - } - } - - if vars := list.Filter("variable"); len(vars.Items) > 0 { - vars = vars.Children() - type VariableBlock struct { - Type string `hcl:"type"` - Default interface{} - Description string - Fields []string `hcl:",decodedFields"` - } - - for _, item := range vars.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 1) - - if len(item.Keys) != 1 { - return nil, diagnosticsErrorf("variable block at %s has no label", item.Pos()) - } - - name := item.Keys[0].Token.Value().(string) - - var block VariableBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("invalid variable block at %s: %s", item.Pos(), err) - } - - // Clean up legacy HCL decoding ambiguity by unwrapping list of maps - if ms, ok := block.Default.([]map[string]interface{}); ok { - def := make(map[string]interface{}) - for _, m := range ms { - for k, v := range m { - def[k] = v - } - } - block.Default = def - } - - v := &Variable{ - Name: name, - Type: block.Type, - Description: block.Description, - Default: block.Default, - Pos: sourcePosLegacyHCL(item.Pos(), filename), - } - if _, exists := mod.Variables[name]; exists { - return nil, diagnosticsErrorf("duplicate variable block for %q", name) - } - mod.Variables[name] = v - - } - } - - if outputs := list.Filter("output"); len(outputs.Items) > 0 { - outputs = outputs.Children() - type OutputBlock struct { - Description string - } - - for _, item := range outputs.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 1) - - if len(item.Keys) != 1 { - return nil, diagnosticsErrorf("output block at %s has no label", item.Pos()) - } - - name := item.Keys[0].Token.Value().(string) - - var block OutputBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("invalid output block at %s: %s", item.Pos(), err) - } - - o := &Output{ - Name: name, - Description: block.Description, - Pos: sourcePosLegacyHCL(item.Pos(), filename), - } - if _, exists := mod.Outputs[name]; exists { - return nil, diagnosticsErrorf("duplicate output block for %q", name) - } - mod.Outputs[name] = o - } - } - - for _, blockType := range []string{"resource", "data"} { - if resources := list.Filter(blockType); len(resources.Items) > 0 { - resources = resources.Children() - type ResourceBlock struct { - Provider string - } - - for _, item := range resources.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 2) - - if len(item.Keys) != 2 { - return nil, diagnosticsErrorf("resource block at %s has wrong label count", item.Pos()) - } - - typeName := item.Keys[0].Token.Value().(string) - name := item.Keys[1].Token.Value().(string) - var mode ResourceMode - var rMap map[string]*Resource - switch blockType { - case "resource": - mode = ManagedResourceMode - rMap = mod.ManagedResources - case "data": - mode = DataResourceMode - rMap = mod.DataResources - } - - var block ResourceBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("invalid resource block at %s: %s", item.Pos(), err) - } - - var providerName, providerAlias string - if dotPos := strings.IndexByte(block.Provider, '.'); dotPos != -1 { - providerName = block.Provider[:dotPos] - providerAlias = block.Provider[dotPos+1:] - } else { - providerName = block.Provider - } - if providerName == "" { - providerName = resourceTypeDefaultProviderName(typeName) - } - - r := &Resource{ - Mode: mode, - Type: typeName, - Name: name, - Provider: ProviderRef{ - Name: providerName, - Alias: providerAlias, - }, - Pos: sourcePosLegacyHCL(item.Pos(), filename), - } - key := r.MapKey() - if _, exists := rMap[key]; exists { - return nil, diagnosticsErrorf("duplicate resource block for %q", key) - } - rMap[key] = r - } - } - - } - - if moduleCalls := list.Filter("module"); len(moduleCalls.Items) > 0 { - moduleCalls = moduleCalls.Children() - type ModuleBlock struct { - Source string - Version string - } - - for _, item := range moduleCalls.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 1) - - if len(item.Keys) != 1 { - return nil, diagnosticsErrorf("module block at %s has no label", item.Pos()) - } - - name := item.Keys[0].Token.Value().(string) - - var block ModuleBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("module block at %s: %s", item.Pos(), err) - } - - mc := &ModuleCall{ - Name: name, - Source: block.Source, - Version: block.Version, - Pos: sourcePosLegacyHCL(item.Pos(), filename), - } - if _, exists := mod.ModuleCalls[name]; exists { - return nil, diagnosticsErrorf("duplicate module block for %q", name) - } - mod.ModuleCalls[name] = mc - } - } - - if providerConfigs := list.Filter("provider"); len(providerConfigs.Items) > 0 { - providerConfigs = providerConfigs.Children() - type ProviderBlock struct { - Version string - } - - for _, item := range providerConfigs.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 1) - - if len(item.Keys) != 1 { - return nil, diagnosticsErrorf("provider block at %s has no label", item.Pos()) - } - - name := item.Keys[0].Token.Value().(string) - - var block ProviderBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("invalid provider block at %s: %s", item.Pos(), err) - } - - if block.Version != "" { - mod.RequiredProviders[name] = append(mod.RequiredProviders[name], block.Version) - } - - // Even if there wasn't an explicit version required, we still - // need an entry in our map to signal the unversioned dependency. - if _, exists := mod.RequiredProviders[name]; !exists { - mod.RequiredProviders[name] = []string{} - } - - } - } - } - - return mod, nil -} - -// unwrapLegacyHCLObjectKeysFromJSON cleans up an edge case that can occur when -// parsing JSON as input: if we're parsing JSON then directly nested -// items will show up as additional "keys". -// -// For objects that expect a fixed number of keys, this breaks the -// decoding process. This function unwraps the object into what it would've -// looked like if it came directly from HCL by specifying the number of keys -// you expect. -// -// Example: -// -// { "foo": { "baz": {} } } -// -// Will show up with Keys being: []string{"foo", "baz"} -// when we really just want the first two. This function will fix this. -func unwrapLegacyHCLObjectKeysFromJSON(item *legacyast.ObjectItem, depth int) { - if len(item.Keys) > depth && item.Keys[0].Token.JSON { - for len(item.Keys) > depth { - // Pop off the last key - n := len(item.Keys) - key := item.Keys[n-1] - item.Keys[n-1] = nil - item.Keys = item.Keys[:n-1] - - // Wrap our value in a list - item.Val = &legacyast.ObjectType{ - List: &legacyast.ObjectList{ - Items: []*legacyast.ObjectItem{ - &legacyast.ObjectItem{ - Keys: []*legacyast.ObjectKey{key}, - Val: item.Val, - }, - }, - }, - } - } - } -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go deleted file mode 100644 index 65ddb230..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go +++ /dev/null @@ -1,35 +0,0 @@ -package tfconfig - -// Module is the top-level type representing a parsed and processed Terraform -// module. -type Module struct { - // Path is the local filesystem directory where the module was loaded from. - Path string `json:"path"` - - Variables map[string]*Variable `json:"variables"` - Outputs map[string]*Output `json:"outputs"` - - RequiredCore []string `json:"required_core,omitempty"` - RequiredProviders map[string][]string `json:"required_providers"` - - ManagedResources map[string]*Resource `json:"managed_resources"` - DataResources map[string]*Resource `json:"data_resources"` - ModuleCalls map[string]*ModuleCall `json:"module_calls"` - - // Diagnostics records any errors and warnings that were detected during - // loading, primarily for inclusion in serialized forms of the module - // since this slice is also returned as a second argument from LoadModule. - Diagnostics Diagnostics `json:"diagnostics,omitempty"` -} - -func newModule(path string) *Module { - return &Module{ - Path: path, - Variables: make(map[string]*Variable), - Outputs: make(map[string]*Output), - RequiredProviders: make(map[string][]string), - ManagedResources: make(map[string]*Resource), - DataResources: make(map[string]*Resource), - ModuleCalls: make(map[string]*ModuleCall), - } -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module_call.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module_call.go deleted file mode 100644 index 5e1e05a7..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module_call.go +++ /dev/null @@ -1,11 +0,0 @@ -package tfconfig - -// ModuleCall represents a "module" block within a module. That is, a -// declaration of a child module from inside its parent. -type ModuleCall struct { - Name string `json:"name"` - Source string `json:"source"` - Version string `json:"version,omitempty"` - - Pos SourcePos `json:"pos"` -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/output.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/output.go deleted file mode 100644 index 890b25e6..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/output.go +++ /dev/null @@ -1,9 +0,0 @@ -package tfconfig - -// Output represents a single output from a Terraform module. -type Output struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - - Pos SourcePos `json:"pos"` -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go deleted file mode 100644 index d9248377..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go +++ /dev/null @@ -1,9 +0,0 @@ -package tfconfig - -// ProviderRef is a reference to a provider configuration within a module. -// It represents the contents of a "provider" argument in a resource, or -// a value in the "providers" map for a module call. -type ProviderRef struct { - Name string `json:"name"` - Alias string `json:"alias,omitempty"` // Empty if the default provider configuration is referenced -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/resource.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/resource.go deleted file mode 100644 index 401c8fce..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/resource.go +++ /dev/null @@ -1,64 +0,0 @@ -package tfconfig - -import ( - "fmt" - "strconv" - "strings" -) - -// Resource represents a single "resource" or "data" block within a module. -type Resource struct { - Mode ResourceMode `json:"mode"` - Type string `json:"type"` - Name string `json:"name"` - - Provider ProviderRef `json:"provider"` - - Pos SourcePos `json:"pos"` -} - -// MapKey returns a string that can be used to uniquely identify the receiver -// in a map[string]*Resource. -func (r *Resource) MapKey() string { - switch r.Mode { - case ManagedResourceMode: - return fmt.Sprintf("%s.%s", r.Type, r.Name) - case DataResourceMode: - return fmt.Sprintf("data.%s.%s", r.Type, r.Name) - default: - // should never happen - return fmt.Sprintf("[invalid_mode!].%s.%s", r.Type, r.Name) - } -} - -// ResourceMode represents the "mode" of a resource, which is used to -// distinguish between managed resources ("resource" blocks in config) and -// data resources ("data" blocks in config). -type ResourceMode rune - -const InvalidResourceMode ResourceMode = 0 -const ManagedResourceMode ResourceMode = 'M' -const DataResourceMode ResourceMode = 'D' - -func (m ResourceMode) String() string { - switch m { - case ManagedResourceMode: - return "managed" - case DataResourceMode: - return "data" - default: - return "" - } -} - -// MarshalJSON implements encoding/json.Marshaler. -func (m ResourceMode) MarshalJSON() ([]byte, error) { - return []byte(strconv.Quote(m.String())), nil -} - -func resourceTypeDefaultProviderName(typeName string) string { - if underPos := strings.IndexByte(typeName, '_'); underPos != -1 { - return typeName[:underPos] - } - return typeName -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/schema.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/schema.go deleted file mode 100644 index 3af742ff..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/schema.go +++ /dev/null @@ -1,106 +0,0 @@ -package tfconfig - -import ( - "github.com/hashicorp/hcl2/hcl" -) - -var rootSchema = &hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "terraform", - LabelNames: nil, - }, - { - Type: "variable", - LabelNames: []string{"name"}, - }, - { - Type: "output", - LabelNames: []string{"name"}, - }, - { - Type: "provider", - LabelNames: []string{"name"}, - }, - { - Type: "resource", - LabelNames: []string{"type", "name"}, - }, - { - Type: "data", - LabelNames: []string{"type", "name"}, - }, - { - Type: "module", - LabelNames: []string{"name"}, - }, - }, -} - -var terraformBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "required_version", - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "required_providers", - }, - }, -} - -var providerConfigSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "version", - }, - { - Name: "alias", - }, - }, -} - -var variableSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "type", - }, - { - Name: "description", - }, - { - Name: "default", - }, - }, -} - -var outputSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "description", - }, - }, -} - -var moduleCallSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "source", - }, - { - Name: "version", - }, - { - Name: "providers", - }, - }, -} - -var resourceSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "provider", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/source_pos.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/source_pos.go deleted file mode 100644 index 883914eb..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/source_pos.go +++ /dev/null @@ -1,50 +0,0 @@ -package tfconfig - -import ( - legacyhcltoken "github.com/hashicorp/hcl/hcl/token" - "github.com/hashicorp/hcl2/hcl" -) - -// SourcePos is a pointer to a particular location in a source file. -// -// This type is embedded into other structs to allow callers to locate the -// definition of each described module element. The SourcePos of an element -// is usually the first line of its definition, although the definition can -// be a little "fuzzy" with JSON-based config files. -type SourcePos struct { - Filename string `json:"filename"` - Line int `json:"line"` -} - -func sourcePos(filename string, line int) SourcePos { - return SourcePos{ - Filename: filename, - Line: line, - } -} - -func sourcePosHCL(rng hcl.Range) SourcePos { - // We intentionally throw away the column information here because - // current and legacy HCL both disagree on the definition of a column - // and so a line-only reference is the best granularity we can do - // such that the result is consistent between both parsers. - return SourcePos{ - Filename: rng.Filename, - Line: rng.Start.Line, - } -} - -func sourcePosLegacyHCL(pos legacyhcltoken.Pos, filename string) SourcePos { - useFilename := pos.Filename - // We'll try to use the filename given in legacy HCL position, but - // in practice there's no way to actually get this populated via - // the HCL API so it's usually empty except in some specialized - // situations, such as positions in error objects. - if useFilename == "" { - useFilename = filename - } - return SourcePos{ - Filename: useFilename, - Line: pos.Line, - } -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/variable.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/variable.go deleted file mode 100644 index 0f73fc99..00000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/variable.go +++ /dev/null @@ -1,16 +0,0 @@ -package tfconfig - -// Variable represents a single variable from a Terraform module. -type Variable struct { - Name string `json:"name"` - Type string `json:"type,omitempty"` - Description string `json:"description,omitempty"` - - // Default is an approximate representation of the default value in - // the native Go type system. The conversion from the value given in - // configuration may be slightly lossy. Only values that can be - // serialized by json.Marshal will be included here. - Default interface{} `json:"default,omitempty"` - - Pos SourcePos `json:"pos"` -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/count_attr.go b/vendor/github.com/hashicorp/terraform/addrs/count_attr.go deleted file mode 100644 index 90a5faf0..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/count_attr.go +++ /dev/null @@ -1,12 +0,0 @@ -package addrs - -// CountAttr is the address of an attribute of the "count" object in -// the interpolation scope, like "count.index". -type CountAttr struct { - referenceable - Name string -} - -func (ca CountAttr) String() string { - return "count." + ca.Name -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/doc.go b/vendor/github.com/hashicorp/terraform/addrs/doc.go deleted file mode 100644 index 46093314..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -// Package addrs contains types that represent "addresses", which are -// references to specific objects within a Terraform configuration or -// state. -// -// All addresses have string representations based on HCL traversal syntax -// which should be used in the user-interface, and also in-memory -// representations that can be used internally. -// -// For object types that exist within Terraform modules a pair of types is -// used. The "local" part of the address is represented by a type, and then -// an absolute path to that object in the context of its module is represented -// by a type of the same name with an "Abs" prefix added, for "absolute". -// -// All types within this package should be treated as immutable, even if this -// is not enforced by the Go compiler. It is always an implementation error -// to modify an address object in-place after it is initially constructed. -package addrs diff --git a/vendor/github.com/hashicorp/terraform/addrs/input_variable.go b/vendor/github.com/hashicorp/terraform/addrs/input_variable.go deleted file mode 100644 index d2c046c1..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/input_variable.go +++ /dev/null @@ -1,41 +0,0 @@ -package addrs - -import ( - "fmt" -) - -// InputVariable is the address of an input variable. -type InputVariable struct { - referenceable - Name string -} - -func (v InputVariable) String() string { - return "var." + v.Name -} - -// AbsInputVariableInstance is the address of an input variable within a -// particular module instance. -type AbsInputVariableInstance struct { - Module ModuleInstance - Variable InputVariable -} - -// InputVariable returns the absolute address of the input variable of the -// given name inside the receiving module instance. -func (m ModuleInstance) InputVariable(name string) AbsInputVariableInstance { - return AbsInputVariableInstance{ - Module: m, - Variable: InputVariable{ - Name: name, - }, - } -} - -func (v AbsInputVariableInstance) String() string { - if len(v.Module) == 0 { - return v.String() - } - - return fmt.Sprintf("%s.%s", v.Module.String(), v.Variable.String()) -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/instance_key.go b/vendor/github.com/hashicorp/terraform/addrs/instance_key.go deleted file mode 100644 index cef8b279..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/instance_key.go +++ /dev/null @@ -1,123 +0,0 @@ -package addrs - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" -) - -// InstanceKey represents the key of an instance within an object that -// contains multiple instances due to using "count" or "for_each" arguments -// in configuration. -// -// IntKey and StringKey are the two implementations of this type. No other -// implementations are allowed. The single instance of an object that _isn't_ -// using "count" or "for_each" is represented by NoKey, which is a nil -// InstanceKey. -type InstanceKey interface { - instanceKeySigil() - String() string -} - -// ParseInstanceKey returns the instance key corresponding to the given value, -// which must be known and non-null. -// -// If an unknown or null value is provided then this function will panic. This -// function is intended to deal with the values that would naturally be found -// in a hcl.TraverseIndex, which (when parsed from source, at least) can never -// contain unknown or null values. -func ParseInstanceKey(key cty.Value) (InstanceKey, error) { - switch key.Type() { - case cty.String: - return StringKey(key.AsString()), nil - case cty.Number: - var idx int - err := gocty.FromCtyValue(key, &idx) - return IntKey(idx), err - default: - return NoKey, fmt.Errorf("either a string or an integer is required") - } -} - -// NoKey represents the absense of an InstanceKey, for the single instance -// of a configuration object that does not use "count" or "for_each" at all. -var NoKey InstanceKey - -// IntKey is the InstanceKey representation representing integer indices, as -// used when the "count" argument is specified or if for_each is used with -// a sequence type. -type IntKey int - -func (k IntKey) instanceKeySigil() { -} - -func (k IntKey) String() string { - return fmt.Sprintf("[%d]", int(k)) -} - -// StringKey is the InstanceKey representation representing string indices, as -// used when the "for_each" argument is specified with a map or object type. -type StringKey string - -func (k StringKey) instanceKeySigil() { -} - -func (k StringKey) String() string { - // FIXME: This isn't _quite_ right because Go's quoted string syntax is - // slightly different than HCL's, but we'll accept it for now. - return fmt.Sprintf("[%q]", string(k)) -} - -// InstanceKeyLess returns true if the first given instance key i should sort -// before the second key j, and false otherwise. -func InstanceKeyLess(i, j InstanceKey) bool { - iTy := instanceKeyType(i) - jTy := instanceKeyType(j) - - switch { - case i == j: - return false - case i == NoKey: - return true - case j == NoKey: - return false - case iTy != jTy: - // The ordering here is arbitrary except that we want NoKeyType - // to sort before the others, so we'll just use the enum values - // of InstanceKeyType here (where NoKey is zero, sorting before - // any other). - return uint32(iTy) < uint32(jTy) - case iTy == IntKeyType: - return int(i.(IntKey)) < int(j.(IntKey)) - case iTy == StringKeyType: - return string(i.(StringKey)) < string(j.(StringKey)) - default: - // Shouldn't be possible to get down here in practice, since the - // above is exhaustive. - return false - } -} - -func instanceKeyType(k InstanceKey) InstanceKeyType { - if _, ok := k.(StringKey); ok { - return StringKeyType - } - if _, ok := k.(IntKey); ok { - return IntKeyType - } - return NoKeyType -} - -// InstanceKeyType represents the different types of instance key that are -// supported. Usually it is sufficient to simply type-assert an InstanceKey -// value to either IntKey or StringKey, but this type and its values can be -// used to represent the types themselves, rather than specific values -// of those types. -type InstanceKeyType rune - -const ( - NoKeyType InstanceKeyType = 0 - IntKeyType InstanceKeyType = 'I' - StringKeyType InstanceKeyType = 'S' -) diff --git a/vendor/github.com/hashicorp/terraform/addrs/local_value.go b/vendor/github.com/hashicorp/terraform/addrs/local_value.go deleted file mode 100644 index 61a07b9c..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/local_value.go +++ /dev/null @@ -1,48 +0,0 @@ -package addrs - -import ( - "fmt" -) - -// LocalValue is the address of a local value. -type LocalValue struct { - referenceable - Name string -} - -func (v LocalValue) String() string { - return "local." + v.Name -} - -// Absolute converts the receiver into an absolute address within the given -// module instance. -func (v LocalValue) Absolute(m ModuleInstance) AbsLocalValue { - return AbsLocalValue{ - Module: m, - LocalValue: v, - } -} - -// AbsLocalValue is the absolute address of a local value within a module instance. -type AbsLocalValue struct { - Module ModuleInstance - LocalValue LocalValue -} - -// LocalValue returns the absolute address of a local value of the given -// name within the receiving module instance. -func (m ModuleInstance) LocalValue(name string) AbsLocalValue { - return AbsLocalValue{ - Module: m, - LocalValue: LocalValue{ - Name: name, - }, - } -} - -func (v AbsLocalValue) String() string { - if len(v.Module) == 0 { - return v.LocalValue.String() - } - return fmt.Sprintf("%s.%s", v.Module.String(), v.LocalValue.String()) -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/module.go b/vendor/github.com/hashicorp/terraform/addrs/module.go deleted file mode 100644 index 6420c630..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/module.go +++ /dev/null @@ -1,75 +0,0 @@ -package addrs - -import ( - "strings" -) - -// Module is an address for a module call within configuration. This is -// the static counterpart of ModuleInstance, representing a traversal through -// the static module call tree in configuration and does not take into account -// the potentially-multiple instances of a module that might be created by -// "count" and "for_each" arguments within those calls. -// -// This type should be used only in very specialized cases when working with -// the static module call tree. Type ModuleInstance is appropriate in more cases. -// -// Although Module is a slice, it should be treated as immutable after creation. -type Module []string - -// RootModule is the module address representing the root of the static module -// call tree, which is also the zero value of Module. -// -// Note that this is not the root of the dynamic module tree, which is instead -// represented by RootModuleInstance. -var RootModule Module - -// IsRoot returns true if the receiver is the address of the root module, -// or false otherwise. -func (m Module) IsRoot() bool { - return len(m) == 0 -} - -func (m Module) String() string { - if len(m) == 0 { - return "" - } - return strings.Join([]string(m), ".") -} - -// Child returns the address of a child call in the receiver, identified by the -// given name. -func (m Module) Child(name string) Module { - ret := make(Module, 0, len(m)+1) - ret = append(ret, m...) - return append(ret, name) -} - -// Parent returns the address of the parent module of the receiver, or the -// receiver itself if there is no parent (if it's the root module address). -func (m Module) Parent() Module { - if len(m) == 0 { - return m - } - return m[:len(m)-1] -} - -// Call returns the module call address that corresponds to the given module -// instance, along with the address of the module that contains it. -// -// There is no call for the root module, so this method will panic if called -// on the root module address. -// -// In practice, this just turns the last element of the receiver into a -// ModuleCall and then returns a slice of the receiever that excludes that -// last part. This is just a convenience for situations where a call address -// is required, such as when dealing with *Reference and Referencable values. -func (m Module) Call() (Module, ModuleCall) { - if len(m) == 0 { - panic("cannot produce ModuleCall for root module") - } - - caller, callName := m[:len(m)-1], m[len(m)-1] - return caller, ModuleCall{ - Name: callName, - } -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/module_call.go b/vendor/github.com/hashicorp/terraform/addrs/module_call.go deleted file mode 100644 index 09596cc8..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/module_call.go +++ /dev/null @@ -1,81 +0,0 @@ -package addrs - -import ( - "fmt" -) - -// ModuleCall is the address of a call from the current module to a child -// module. -// -// There is no "Abs" version of ModuleCall because an absolute module path -// is represented by ModuleInstance. -type ModuleCall struct { - referenceable - Name string -} - -func (c ModuleCall) String() string { - return "module." + c.Name -} - -// Instance returns the address of an instance of the receiver identified by -// the given key. -func (c ModuleCall) Instance(key InstanceKey) ModuleCallInstance { - return ModuleCallInstance{ - Call: c, - Key: key, - } -} - -// ModuleCallInstance is the address of one instance of a module created from -// a module call, which might create multiple instances using "count" or -// "for_each" arguments. -type ModuleCallInstance struct { - referenceable - Call ModuleCall - Key InstanceKey -} - -func (c ModuleCallInstance) String() string { - if c.Key == NoKey { - return c.Call.String() - } - return fmt.Sprintf("module.%s%s", c.Call.Name, c.Key) -} - -// ModuleInstance returns the address of the module instance that corresponds -// to the receiving call instance when resolved in the given calling module. -// In other words, it returns the child module instance that the receving -// call instance creates. -func (c ModuleCallInstance) ModuleInstance(caller ModuleInstance) ModuleInstance { - return caller.Child(c.Call.Name, c.Key) -} - -// Output returns the address of an output of the receiver identified by its -// name. -func (c ModuleCallInstance) Output(name string) ModuleCallOutput { - return ModuleCallOutput{ - Call: c, - Name: name, - } -} - -// ModuleCallOutput is the address of a particular named output produced by -// an instance of a module call. -type ModuleCallOutput struct { - referenceable - Call ModuleCallInstance - Name string -} - -func (co ModuleCallOutput) String() string { - return fmt.Sprintf("%s.%s", co.Call.String(), co.Name) -} - -// AbsOutputValue returns the absolute output value address that corresponds -// to the receving module call output address, once resolved in the given -// calling module. -func (co ModuleCallOutput) AbsOutputValue(caller ModuleInstance) AbsOutputValue { - moduleAddr := co.Call.ModuleInstance(caller) - return moduleAddr.OutputValue(co.Name) -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/module_instance.go b/vendor/github.com/hashicorp/terraform/addrs/module_instance.go deleted file mode 100644 index 67e73e52..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/module_instance.go +++ /dev/null @@ -1,415 +0,0 @@ -package addrs - -import ( - "bytes" - "fmt" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" - - "github.com/hashicorp/terraform/tfdiags" -) - -// ModuleInstance is an address for a particular module instance within the -// dynamic module tree. This is an extension of the static traversals -// represented by type Module that deals with the possibility of a single -// module call producing multiple instances via the "count" and "for_each" -// arguments. -// -// Although ModuleInstance is a slice, it should be treated as immutable after -// creation. -type ModuleInstance []ModuleInstanceStep - -var ( - _ Targetable = ModuleInstance(nil) -) - -func ParseModuleInstance(traversal hcl.Traversal) (ModuleInstance, tfdiags.Diagnostics) { - mi, remain, diags := parseModuleInstancePrefix(traversal) - if len(remain) != 0 { - if len(remain) == len(traversal) { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid module instance address", - Detail: "A module instance address must begin with \"module.\".", - Subject: remain.SourceRange().Ptr(), - }) - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid module instance address", - Detail: "The module instance address is followed by additional invalid content.", - Subject: remain.SourceRange().Ptr(), - }) - } - } - return mi, diags -} - -// ParseModuleInstanceStr is a helper wrapper around ParseModuleInstance -// that takes a string and parses it with the HCL native syntax traversal parser -// before interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a reference string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseProviderConfigCompact. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// then the returned address is invalid. -func ParseModuleInstanceStr(str string) (ModuleInstance, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return nil, diags - } - - addr, addrDiags := ParseModuleInstance(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} - -func parseModuleInstancePrefix(traversal hcl.Traversal) (ModuleInstance, hcl.Traversal, tfdiags.Diagnostics) { - remain := traversal - var mi ModuleInstance - var diags tfdiags.Diagnostics - - for len(remain) > 0 { - var next string - switch tt := remain[0].(type) { - case hcl.TraverseRoot: - next = tt.Name - case hcl.TraverseAttr: - next = tt.Name - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: "Module address prefix must be followed by dot and then a name.", - Subject: remain[0].SourceRange().Ptr(), - }) - break - } - - if next != "module" { - break - } - - kwRange := remain[0].SourceRange() - remain = remain[1:] - // If we have the prefix "module" then we should be followed by an - // module call name, as an attribute, and then optionally an index step - // giving the instance key. - if len(remain) == 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: "Prefix \"module.\" must be followed by a module name.", - Subject: &kwRange, - }) - break - } - - var moduleName string - switch tt := remain[0].(type) { - case hcl.TraverseAttr: - moduleName = tt.Name - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: "Prefix \"module.\" must be followed by a module name.", - Subject: remain[0].SourceRange().Ptr(), - }) - break - } - remain = remain[1:] - step := ModuleInstanceStep{ - Name: moduleName, - } - - if len(remain) > 0 { - if idx, ok := remain[0].(hcl.TraverseIndex); ok { - remain = remain[1:] - - switch idx.Key.Type() { - case cty.String: - step.InstanceKey = StringKey(idx.Key.AsString()) - case cty.Number: - var idxInt int - err := gocty.FromCtyValue(idx.Key, &idxInt) - if err == nil { - step.InstanceKey = IntKey(idxInt) - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: fmt.Sprintf("Invalid module index: %s.", err), - Subject: idx.SourceRange().Ptr(), - }) - } - default: - // Should never happen, because no other types are allowed in traversal indices. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: "Invalid module key: must be either a string or an integer.", - Subject: idx.SourceRange().Ptr(), - }) - } - } - } - - mi = append(mi, step) - } - - var retRemain hcl.Traversal - if len(remain) > 0 { - retRemain = make(hcl.Traversal, len(remain)) - copy(retRemain, remain) - // The first element here might be either a TraverseRoot or a - // TraverseAttr, depending on whether we had a module address on the - // front. To make life easier for callers, we'll normalize to always - // start with a TraverseRoot. - if tt, ok := retRemain[0].(hcl.TraverseAttr); ok { - retRemain[0] = hcl.TraverseRoot{ - Name: tt.Name, - SrcRange: tt.SrcRange, - } - } - } - - return mi, retRemain, diags -} - -// UnkeyedInstanceShim is a shim method for converting a Module address to the -// equivalent ModuleInstance address that assumes that no modules have -// keyed instances. -// -// This is a temporary allowance for the fact that Terraform does not presently -// support "count" and "for_each" on modules, and thus graph building code that -// derives graph nodes from configuration must just assume unkeyed modules -// in order to construct the graph. At a later time when "count" and "for_each" -// support is added for modules, all callers of this method will need to be -// reworked to allow for keyed module instances. -func (m Module) UnkeyedInstanceShim() ModuleInstance { - path := make(ModuleInstance, len(m)) - for i, name := range m { - path[i] = ModuleInstanceStep{Name: name} - } - return path -} - -// ModuleInstanceStep is a single traversal step through the dynamic module -// tree. It is used only as part of ModuleInstance. -type ModuleInstanceStep struct { - Name string - InstanceKey InstanceKey -} - -// RootModuleInstance is the module instance address representing the root -// module, which is also the zero value of ModuleInstance. -var RootModuleInstance ModuleInstance - -// IsRoot returns true if the receiver is the address of the root module instance, -// or false otherwise. -func (m ModuleInstance) IsRoot() bool { - return len(m) == 0 -} - -// Child returns the address of a child module instance of the receiver, -// identified by the given name and key. -func (m ModuleInstance) Child(name string, key InstanceKey) ModuleInstance { - ret := make(ModuleInstance, 0, len(m)+1) - ret = append(ret, m...) - return append(ret, ModuleInstanceStep{ - Name: name, - InstanceKey: key, - }) -} - -// Parent returns the address of the parent module instance of the receiver, or -// the receiver itself if there is no parent (if it's the root module address). -func (m ModuleInstance) Parent() ModuleInstance { - if len(m) == 0 { - return m - } - return m[:len(m)-1] -} - -// String returns a string representation of the receiver, in the format used -// within e.g. user-provided resource addresses. -// -// The address of the root module has the empty string as its representation. -func (m ModuleInstance) String() string { - var buf bytes.Buffer - sep := "" - for _, step := range m { - buf.WriteString(sep) - buf.WriteString("module.") - buf.WriteString(step.Name) - if step.InstanceKey != NoKey { - buf.WriteString(step.InstanceKey.String()) - } - sep = "." - } - return buf.String() -} - -// Equal returns true if the receiver and the given other value -// contains the exact same parts. -func (m ModuleInstance) Equal(o ModuleInstance) bool { - return m.String() == o.String() -} - -// Less returns true if the receiver should sort before the given other value -// in a sorted list of addresses. -func (m ModuleInstance) Less(o ModuleInstance) bool { - if len(m) != len(o) { - // Shorter path sorts first. - return len(m) < len(o) - } - - for i := range m { - mS, oS := m[i], o[i] - switch { - case mS.Name != oS.Name: - return mS.Name < oS.Name - case mS.InstanceKey != oS.InstanceKey: - return InstanceKeyLess(mS.InstanceKey, oS.InstanceKey) - } - } - - return false -} - -// Ancestors returns a slice containing the receiver and all of its ancestor -// module instances, all the way up to (and including) the root module. -// The result is ordered by depth, with the root module always first. -// -// Since the result always includes the root module, a caller may choose to -// ignore it by slicing the result with [1:]. -func (m ModuleInstance) Ancestors() []ModuleInstance { - ret := make([]ModuleInstance, 0, len(m)+1) - for i := 0; i <= len(m); i++ { - ret = append(ret, m[:i]) - } - return ret -} - -// IsAncestor returns true if the receiver is an ancestor of the given -// other value. -func (m ModuleInstance) IsAncestor(o ModuleInstance) bool { - // Longer or equal sized paths means the receiver cannot - // be an ancestor of the given module insatnce. - if len(m) >= len(o) { - return false - } - - for i, ms := range m { - if ms.Name != o[i].Name { - return false - } - if ms.InstanceKey != NoKey && ms.InstanceKey != o[i].InstanceKey { - return false - } - } - - return true -} - -// Call returns the module call address that corresponds to the given module -// instance, along with the address of the module instance that contains it. -// -// There is no call for the root module, so this method will panic if called -// on the root module address. -// -// A single module call can produce potentially many module instances, so the -// result discards any instance key that might be present on the last step -// of the instance. To retain this, use CallInstance instead. -// -// In practice, this just turns the last element of the receiver into a -// ModuleCall and then returns a slice of the receiever that excludes that -// last part. This is just a convenience for situations where a call address -// is required, such as when dealing with *Reference and Referencable values. -func (m ModuleInstance) Call() (ModuleInstance, ModuleCall) { - if len(m) == 0 { - panic("cannot produce ModuleCall for root module") - } - - inst, lastStep := m[:len(m)-1], m[len(m)-1] - return inst, ModuleCall{ - Name: lastStep.Name, - } -} - -// CallInstance returns the module call instance address that corresponds to -// the given module instance, along with the address of the module instance -// that contains it. -// -// There is no call for the root module, so this method will panic if called -// on the root module address. -// -// In practice, this just turns the last element of the receiver into a -// ModuleCallInstance and then returns a slice of the receiever that excludes -// that last part. This is just a convenience for situations where a call\ -// address is required, such as when dealing with *Reference and Referencable -// values. -func (m ModuleInstance) CallInstance() (ModuleInstance, ModuleCallInstance) { - if len(m) == 0 { - panic("cannot produce ModuleCallInstance for root module") - } - - inst, lastStep := m[:len(m)-1], m[len(m)-1] - return inst, ModuleCallInstance{ - Call: ModuleCall{ - Name: lastStep.Name, - }, - Key: lastStep.InstanceKey, - } -} - -// TargetContains implements Targetable by returning true if the given other -// address either matches the receiver, is a sub-module-instance of the -// receiver, or is a targetable absolute address within a module that -// is contained within the reciever. -func (m ModuleInstance) TargetContains(other Targetable) bool { - switch to := other.(type) { - - case ModuleInstance: - if len(to) < len(m) { - // Can't be contained if the path is shorter - return false - } - // Other is contained if its steps match for the length of our own path. - for i, ourStep := range m { - otherStep := to[i] - if ourStep != otherStep { - return false - } - } - // If we fall out here then the prefixed matched, so it's contained. - return true - - case AbsResource: - return m.TargetContains(to.Module) - - case AbsResourceInstance: - return m.TargetContains(to.Module) - - default: - return false - } -} - -func (m ModuleInstance) targetableSigil() { - // ModuleInstance is targetable -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/output_value.go b/vendor/github.com/hashicorp/terraform/addrs/output_value.go deleted file mode 100644 index bcd923ac..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/output_value.go +++ /dev/null @@ -1,75 +0,0 @@ -package addrs - -import ( - "fmt" -) - -// OutputValue is the address of an output value, in the context of the module -// that is defining it. -// -// This is related to but separate from ModuleCallOutput, which represents -// a module output from the perspective of its parent module. Since output -// values cannot be represented from the module where they are defined, -// OutputValue is not Referenceable, while ModuleCallOutput is. -type OutputValue struct { - Name string -} - -func (v OutputValue) String() string { - return "output." + v.Name -} - -// Absolute converts the receiver into an absolute address within the given -// module instance. -func (v OutputValue) Absolute(m ModuleInstance) AbsOutputValue { - return AbsOutputValue{ - Module: m, - OutputValue: v, - } -} - -// AbsOutputValue is the absolute address of an output value within a module instance. -// -// This represents an output globally within the namespace of a particular -// configuration. It is related to but separate from ModuleCallOutput, which -// represents a module output from the perspective of its parent module. -type AbsOutputValue struct { - Module ModuleInstance - OutputValue OutputValue -} - -// OutputValue returns the absolute address of an output value of the given -// name within the receiving module instance. -func (m ModuleInstance) OutputValue(name string) AbsOutputValue { - return AbsOutputValue{ - Module: m, - OutputValue: OutputValue{ - Name: name, - }, - } -} - -func (v AbsOutputValue) String() string { - if v.Module.IsRoot() { - return v.OutputValue.String() - } - return fmt.Sprintf("%s.%s", v.Module.String(), v.OutputValue.String()) -} - -// ModuleCallOutput converts an AbsModuleOutput into a ModuleCallOutput, -// returning also the module instance that the ModuleCallOutput is relative -// to. -// -// The root module does not have a call, and so this method cannot be used -// with outputs in the root module, and will panic in that case. -func (v AbsOutputValue) ModuleCallOutput() (ModuleInstance, ModuleCallOutput) { - if v.Module.IsRoot() { - panic("ReferenceFromCall used with root module output") - } - - caller, call := v.Module.CallInstance() - return caller, ModuleCallOutput{ - Call: call, - Name: v.OutputValue.Name, - } -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/parse_ref.go b/vendor/github.com/hashicorp/terraform/addrs/parse_ref.go deleted file mode 100644 index 84fe8a0d..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/parse_ref.go +++ /dev/null @@ -1,338 +0,0 @@ -package addrs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - "github.com/hashicorp/terraform/tfdiags" -) - -// Reference describes a reference to an address with source location -// information. -type Reference struct { - Subject Referenceable - SourceRange tfdiags.SourceRange - Remaining hcl.Traversal -} - -// ParseRef attempts to extract a referencable address from the prefix of the -// given traversal, which must be an absolute traversal or this function -// will panic. -// -// If no error diagnostics are returned, the returned reference includes the -// address that was extracted, the source range it was extracted from, and any -// remaining relative traversal that was not consumed as part of the -// reference. -// -// If error diagnostics are returned then the Reference value is invalid and -// must not be used. -func ParseRef(traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) { - ref, diags := parseRef(traversal) - - // Normalize a little to make life easier for callers. - if ref != nil { - if len(ref.Remaining) == 0 { - ref.Remaining = nil - } - } - - return ref, diags -} - -// ParseRefStr is a helper wrapper around ParseRef that takes a string -// and parses it with the HCL native syntax traversal parser before -// interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a reference string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseRef. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned reference may be nil or incomplete. -func ParseRefStr(str string) (*Reference, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return nil, diags - } - - ref, targetDiags := ParseRef(traversal) - diags = diags.Append(targetDiags) - return ref, diags -} - -func parseRef(traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - root := traversal.RootName() - rootRange := traversal[0].SourceRange() - - switch root { - - case "count": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: CountAttr{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "data": - if len(traversal) < 3 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: `The "data" object must be followed by two attribute names: the data source type and the resource name.`, - Subject: traversal.SourceRange().Ptr(), - }) - return nil, diags - } - remain := traversal[1:] // trim off "data" so we can use our shared resource reference parser - return parseResourceRef(DataResourceMode, rootRange, remain) - - case "local": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: LocalValue{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "module": - callName, callRange, remain, diags := parseSingleAttrRef(traversal) - if diags.HasErrors() { - return nil, diags - } - - // A traversal starting with "module" can either be a reference to - // an entire module instance or to a single output from a module - // instance, depending on what we find after this introducer. - - callInstance := ModuleCallInstance{ - Call: ModuleCall{ - Name: callName, - }, - Key: NoKey, - } - - if len(remain) == 0 { - // Reference to an entire module instance. Might alternatively - // be a reference to a collection of instances of a particular - // module, but the caller will need to deal with that ambiguity - // since we don't have enough context here. - return &Reference{ - Subject: callInstance, - SourceRange: tfdiags.SourceRangeFromHCL(callRange), - Remaining: remain, - }, diags - } - - if idxTrav, ok := remain[0].(hcl.TraverseIndex); ok { - var err error - callInstance.Key, err = ParseInstanceKey(idxTrav.Key) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid index key", - Detail: fmt.Sprintf("Invalid index for module instance: %s.", err), - Subject: &idxTrav.SrcRange, - }) - return nil, diags - } - remain = remain[1:] - - if len(remain) == 0 { - // Also a reference to an entire module instance, but we have a key - // now. - return &Reference{ - Subject: callInstance, - SourceRange: tfdiags.SourceRangeFromHCL(hcl.RangeBetween(callRange, idxTrav.SrcRange)), - Remaining: remain, - }, diags - } - } - - if attrTrav, ok := remain[0].(hcl.TraverseAttr); ok { - remain = remain[1:] - return &Reference{ - Subject: ModuleCallOutput{ - Name: attrTrav.Name, - Call: callInstance, - }, - SourceRange: tfdiags.SourceRangeFromHCL(hcl.RangeBetween(callRange, attrTrav.SrcRange)), - Remaining: remain, - }, diags - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: "Module instance objects do not support this operation.", - Subject: remain[0].SourceRange().Ptr(), - }) - return nil, diags - - case "path": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: PathAttr{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "self": - return &Reference{ - Subject: Self, - SourceRange: tfdiags.SourceRangeFromHCL(rootRange), - Remaining: traversal[1:], - }, diags - - case "terraform": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: TerraformAttr{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "var": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: InputVariable{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - default: - return parseResourceRef(ManagedResourceMode, rootRange, traversal) - } -} - -func parseResourceRef(mode ResourceMode, startRange hcl.Range, traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - if len(traversal) < 2 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: `A reference to a resource type must be followed by at least one attribute access, specifying the resource name.`, - Subject: hcl.RangeBetween(traversal[0].SourceRange(), traversal[len(traversal)-1].SourceRange()).Ptr(), - }) - return nil, diags - } - - var typeName, name string - switch tt := traversal[0].(type) { // Could be either root or attr, depending on our resource mode - case hcl.TraverseRoot: - typeName = tt.Name - case hcl.TraverseAttr: - typeName = tt.Name - default: - // If it isn't a TraverseRoot then it must be a "data" reference. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: `The "data" object does not support this operation.`, - Subject: traversal[0].SourceRange().Ptr(), - }) - return nil, diags - } - - attrTrav, ok := traversal[1].(hcl.TraverseAttr) - if !ok { - var what string - switch mode { - case DataResourceMode: - what = "data source" - default: - what = "resource type" - } - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: fmt.Sprintf(`A reference to a %s must be followed by at least one attribute access, specifying the resource name.`, what), - Subject: traversal[1].SourceRange().Ptr(), - }) - return nil, diags - } - name = attrTrav.Name - rng := hcl.RangeBetween(startRange, attrTrav.SrcRange) - remain := traversal[2:] - - resourceAddr := Resource{ - Mode: mode, - Type: typeName, - Name: name, - } - resourceInstAddr := ResourceInstance{ - Resource: resourceAddr, - Key: NoKey, - } - - if len(remain) == 0 { - // This might actually be a reference to the collection of all instances - // of the resource, but we don't have enough context here to decide - // so we'll let the caller resolve that ambiguity. - return &Reference{ - Subject: resourceInstAddr, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - }, diags - } - - if idxTrav, ok := remain[0].(hcl.TraverseIndex); ok { - var err error - resourceInstAddr.Key, err = ParseInstanceKey(idxTrav.Key) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid index key", - Detail: fmt.Sprintf("Invalid index for resource instance: %s.", err), - Subject: &idxTrav.SrcRange, - }) - return nil, diags - } - remain = remain[1:] - rng = hcl.RangeBetween(rng, idxTrav.SrcRange) - } - - return &Reference{ - Subject: resourceInstAddr, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags -} - -func parseSingleAttrRef(traversal hcl.Traversal) (string, hcl.Range, hcl.Traversal, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - root := traversal.RootName() - rootRange := traversal[0].SourceRange() - - if len(traversal) < 2 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: fmt.Sprintf("The %q object cannot be accessed directly. Instead, access one of its attributes.", root), - Subject: &rootRange, - }) - return "", hcl.Range{}, nil, diags - } - if attrTrav, ok := traversal[1].(hcl.TraverseAttr); ok { - return attrTrav.Name, hcl.RangeBetween(rootRange, attrTrav.SrcRange), traversal[2:], diags - } - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: fmt.Sprintf("The %q object does not support this operation.", root), - Subject: traversal[1].SourceRange().Ptr(), - }) - return "", hcl.Range{}, nil, diags -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/parse_target.go b/vendor/github.com/hashicorp/terraform/addrs/parse_target.go deleted file mode 100644 index 057443af..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/parse_target.go +++ /dev/null @@ -1,318 +0,0 @@ -package addrs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/hcl/hclsyntax" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/tfdiags" -) - -// Target describes a targeted address with source location information. -type Target struct { - Subject Targetable - SourceRange tfdiags.SourceRange -} - -// ParseTarget attempts to interpret the given traversal as a targetable -// address. The given traversal must be absolute, or this function will -// panic. -// -// If no error diagnostics are returned, the returned target includes the -// address that was extracted and the source range it was extracted from. -// -// If error diagnostics are returned then the Target value is invalid and -// must not be used. -func ParseTarget(traversal hcl.Traversal) (*Target, tfdiags.Diagnostics) { - path, remain, diags := parseModuleInstancePrefix(traversal) - if diags.HasErrors() { - return nil, diags - } - - rng := tfdiags.SourceRangeFromHCL(traversal.SourceRange()) - - if len(remain) == 0 { - return &Target{ - Subject: path, - SourceRange: rng, - }, diags - } - - mode := ManagedResourceMode - if remain.RootName() == "data" { - mode = DataResourceMode - remain = remain[1:] - } - - if len(remain) < 2 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "Resource specification must include a resource type and name.", - Subject: remain.SourceRange().Ptr(), - }) - return nil, diags - } - - var typeName, name string - switch tt := remain[0].(type) { - case hcl.TraverseRoot: - typeName = tt.Name - case hcl.TraverseAttr: - typeName = tt.Name - default: - switch mode { - case ManagedResourceMode: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource type name is required.", - Subject: remain[0].SourceRange().Ptr(), - }) - case DataResourceMode: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A data source name is required.", - Subject: remain[0].SourceRange().Ptr(), - }) - default: - panic("unknown mode") - } - return nil, diags - } - - switch tt := remain[1].(type) { - case hcl.TraverseAttr: - name = tt.Name - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource name is required.", - Subject: remain[1].SourceRange().Ptr(), - }) - return nil, diags - } - - var subject Targetable - remain = remain[2:] - switch len(remain) { - case 0: - subject = path.Resource(mode, typeName, name) - case 1: - if tt, ok := remain[0].(hcl.TraverseIndex); ok { - key, err := ParseInstanceKey(tt.Key) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: fmt.Sprintf("Invalid resource instance key: %s.", err), - Subject: remain[0].SourceRange().Ptr(), - }) - return nil, diags - } - - subject = path.ResourceInstance(mode, typeName, name, key) - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "Resource instance key must be given in square brackets.", - Subject: remain[0].SourceRange().Ptr(), - }) - return nil, diags - } - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "Unexpected extra operators after address.", - Subject: remain[1].SourceRange().Ptr(), - }) - return nil, diags - } - - return &Target{ - Subject: subject, - SourceRange: rng, - }, diags -} - -// ParseTargetStr is a helper wrapper around ParseTarget that takes a string -// and parses it with the HCL native syntax traversal parser before -// interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a target string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseTarget. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned target may be nil or incomplete. -func ParseTargetStr(str string) (*Target, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return nil, diags - } - - target, targetDiags := ParseTarget(traversal) - diags = diags.Append(targetDiags) - return target, diags -} - -// ParseAbsResource attempts to interpret the given traversal as an absolute -// resource address, using the same syntax as expected by ParseTarget. -// -// If no error diagnostics are returned, the returned target includes the -// address that was extracted and the source range it was extracted from. -// -// If error diagnostics are returned then the AbsResource value is invalid and -// must not be used. -func ParseAbsResource(traversal hcl.Traversal) (AbsResource, tfdiags.Diagnostics) { - addr, diags := ParseTarget(traversal) - if diags.HasErrors() { - return AbsResource{}, diags - } - - switch tt := addr.Subject.(type) { - - case AbsResource: - return tt, diags - - case AbsResourceInstance: // Catch likely user error with specialized message - // Assume that the last element of the traversal must be the index, - // since that's required for a valid resource instance address. - indexStep := traversal[len(traversal)-1] - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource address is required. This instance key identifies a specific resource instance, which is not expected here.", - Subject: indexStep.SourceRange().Ptr(), - }) - return AbsResource{}, diags - - case ModuleInstance: // Catch likely user error with specialized message - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource address is required here. The module path must be followed by a resource specification.", - Subject: traversal.SourceRange().Ptr(), - }) - return AbsResource{}, diags - - default: // Generic message for other address types - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource address is required here.", - Subject: traversal.SourceRange().Ptr(), - }) - return AbsResource{}, diags - - } -} - -// ParseAbsResourceStr is a helper wrapper around ParseAbsResource that takes a -// string and parses it with the HCL native syntax traversal parser before -// interpreting it. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned address may be incomplete. -// -// Since this function has no context about the source of the given string, -// any returned diagnostics will not have meaningful source location -// information. -func ParseAbsResourceStr(str string) (AbsResource, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return AbsResource{}, diags - } - - addr, addrDiags := ParseAbsResource(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} - -// ParseAbsResourceInstance attempts to interpret the given traversal as an -// absolute resource instance address, using the same syntax as expected by -// ParseTarget. -// -// If no error diagnostics are returned, the returned target includes the -// address that was extracted and the source range it was extracted from. -// -// If error diagnostics are returned then the AbsResource value is invalid and -// must not be used. -func ParseAbsResourceInstance(traversal hcl.Traversal) (AbsResourceInstance, tfdiags.Diagnostics) { - addr, diags := ParseTarget(traversal) - if diags.HasErrors() { - return AbsResourceInstance{}, diags - } - - switch tt := addr.Subject.(type) { - - case AbsResource: - return tt.Instance(NoKey), diags - - case AbsResourceInstance: - return tt, diags - - case ModuleInstance: // Catch likely user error with specialized message - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource instance address is required here. The module path must be followed by a resource instance specification.", - Subject: traversal.SourceRange().Ptr(), - }) - return AbsResourceInstance{}, diags - - default: // Generic message for other address types - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource address is required here.", - Subject: traversal.SourceRange().Ptr(), - }) - return AbsResourceInstance{}, diags - - } -} - -// ParseAbsResourceInstanceStr is a helper wrapper around -// ParseAbsResourceInstance that takes a string and parses it with the HCL -// native syntax traversal parser before interpreting it. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned address may be incomplete. -// -// Since this function has no context about the source of the given string, -// any returned diagnostics will not have meaningful source location -// information. -func ParseAbsResourceInstanceStr(str string) (AbsResourceInstance, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return AbsResourceInstance{}, diags - } - - addr, addrDiags := ParseAbsResourceInstance(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/path_attr.go b/vendor/github.com/hashicorp/terraform/addrs/path_attr.go deleted file mode 100644 index cfc13f4b..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/path_attr.go +++ /dev/null @@ -1,12 +0,0 @@ -package addrs - -// PathAttr is the address of an attribute of the "path" object in -// the interpolation scope, like "path.module". -type PathAttr struct { - referenceable - Name string -} - -func (pa PathAttr) String() string { - return "path." + pa.Name -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/provider_config.go b/vendor/github.com/hashicorp/terraform/addrs/provider_config.go deleted file mode 100644 index 340dd19e..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/provider_config.go +++ /dev/null @@ -1,297 +0,0 @@ -package addrs - -import ( - "fmt" - - "github.com/hashicorp/terraform/tfdiags" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" -) - -// ProviderConfig is the address of a provider configuration. -type ProviderConfig struct { - Type string - - // If not empty, Alias identifies which non-default (aliased) provider - // configuration this address refers to. - Alias string -} - -// NewDefaultProviderConfig returns the address of the default (un-aliased) -// configuration for the provider with the given type name. -func NewDefaultProviderConfig(typeName string) ProviderConfig { - return ProviderConfig{ - Type: typeName, - } -} - -// ParseProviderConfigCompact parses the given absolute traversal as a relative -// provider address in compact form. The following are examples of traversals -// that can be successfully parsed as compact relative provider configuration -// addresses: -// -// aws -// aws.foo -// -// This function will panic if given a relative traversal. -// -// If the returned diagnostics contains errors then the result value is invalid -// and must not be used. -func ParseProviderConfigCompact(traversal hcl.Traversal) (ProviderConfig, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - ret := ProviderConfig{ - Type: traversal.RootName(), - } - - if len(traversal) < 2 { - // Just a type name, then. - return ret, diags - } - - aliasStep := traversal[1] - switch ts := aliasStep.(type) { - case hcl.TraverseAttr: - ret.Alias = ts.Name - return ret, diags - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "The provider type name must either stand alone or be followed by an alias name separated with a dot.", - Subject: aliasStep.SourceRange().Ptr(), - }) - } - - if len(traversal) > 2 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "Extraneous extra operators after provider configuration address.", - Subject: traversal[2:].SourceRange().Ptr(), - }) - } - - return ret, diags -} - -// ParseProviderConfigCompactStr is a helper wrapper around ParseProviderConfigCompact -// that takes a string and parses it with the HCL native syntax traversal parser -// before interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a reference string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseProviderConfigCompact. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// then the returned address is invalid. -func ParseProviderConfigCompactStr(str string) (ProviderConfig, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return ProviderConfig{}, diags - } - - addr, addrDiags := ParseProviderConfigCompact(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} - -// Absolute returns an AbsProviderConfig from the receiver and the given module -// instance address. -func (pc ProviderConfig) Absolute(module ModuleInstance) AbsProviderConfig { - return AbsProviderConfig{ - Module: module, - ProviderConfig: pc, - } -} - -func (pc ProviderConfig) String() string { - if pc.Type == "" { - // Should never happen; always indicates a bug - return "provider." - } - - if pc.Alias != "" { - return fmt.Sprintf("provider.%s.%s", pc.Type, pc.Alias) - } - - return "provider." + pc.Type -} - -// StringCompact is an alternative to String that returns the form that can -// be parsed by ParseProviderConfigCompact, without the "provider." prefix. -func (pc ProviderConfig) StringCompact() string { - if pc.Alias != "" { - return fmt.Sprintf("%s.%s", pc.Type, pc.Alias) - } - return pc.Type -} - -// AbsProviderConfig is the absolute address of a provider configuration -// within a particular module instance. -type AbsProviderConfig struct { - Module ModuleInstance - ProviderConfig ProviderConfig -} - -// ParseAbsProviderConfig parses the given traversal as an absolute provider -// address. The following are examples of traversals that can be successfully -// parsed as absolute provider configuration addresses: -// -// provider.aws -// provider.aws.foo -// module.bar.provider.aws -// module.bar.module.baz.provider.aws.foo -// module.foo[1].provider.aws.foo -// -// This type of address is used, for example, to record the relationships -// between resources and provider configurations in the state structure. -// This type of address is not generally used in the UI, except in error -// messages that refer to provider configurations. -func ParseAbsProviderConfig(traversal hcl.Traversal) (AbsProviderConfig, tfdiags.Diagnostics) { - modInst, remain, diags := parseModuleInstancePrefix(traversal) - ret := AbsProviderConfig{ - Module: modInst, - } - if len(remain) < 2 || remain.RootName() != "provider" { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "Provider address must begin with \"provider.\", followed by a provider type name.", - Subject: remain.SourceRange().Ptr(), - }) - return ret, diags - } - if len(remain) > 3 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "Extraneous operators after provider configuration alias.", - Subject: hcl.Traversal(remain[3:]).SourceRange().Ptr(), - }) - return ret, diags - } - - if tt, ok := remain[1].(hcl.TraverseAttr); ok { - ret.ProviderConfig.Type = tt.Name - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "The prefix \"provider.\" must be followed by a provider type name.", - Subject: remain[1].SourceRange().Ptr(), - }) - return ret, diags - } - - if len(remain) == 3 { - if tt, ok := remain[2].(hcl.TraverseAttr); ok { - ret.ProviderConfig.Alias = tt.Name - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "Provider type name must be followed by a configuration alias name.", - Subject: remain[2].SourceRange().Ptr(), - }) - return ret, diags - } - } - - return ret, diags -} - -// ParseAbsProviderConfigStr is a helper wrapper around ParseAbsProviderConfig -// that takes a string and parses it with the HCL native syntax traversal parser -// before interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a reference string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseAbsProviderConfig. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned address is invalid. -func ParseAbsProviderConfigStr(str string) (AbsProviderConfig, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return AbsProviderConfig{}, diags - } - - addr, addrDiags := ParseAbsProviderConfig(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} - -// ProviderConfigDefault returns the address of the default provider config -// of the given type inside the recieving module instance. -func (m ModuleInstance) ProviderConfigDefault(name string) AbsProviderConfig { - return AbsProviderConfig{ - Module: m, - ProviderConfig: ProviderConfig{ - Type: name, - }, - } -} - -// ProviderConfigAliased returns the address of an aliased provider config -// of with given type and alias inside the recieving module instance. -func (m ModuleInstance) ProviderConfigAliased(name, alias string) AbsProviderConfig { - return AbsProviderConfig{ - Module: m, - ProviderConfig: ProviderConfig{ - Type: name, - Alias: alias, - }, - } -} - -// Inherited returns an address that the receiving configuration address might -// inherit from in a parent module. The second bool return value indicates if -// such inheritance is possible, and thus whether the returned address is valid. -// -// Inheritance is possible only for default (un-aliased) providers in modules -// other than the root module. Even if a valid address is returned, inheritence -// may not be performed for other reasons, such as if the calling module -// provided explicit provider configurations within the call for this module. -// The ProviderTransformer graph transform in the main terraform module has -// the authoritative logic for provider inheritance, and this method is here -// mainly just for its benefit. -func (pc AbsProviderConfig) Inherited() (AbsProviderConfig, bool) { - // Can't inherit if we're already in the root. - if len(pc.Module) == 0 { - return AbsProviderConfig{}, false - } - - // Can't inherit if we have an alias. - if pc.ProviderConfig.Alias != "" { - return AbsProviderConfig{}, false - } - - // Otherwise, we might inherit from a configuration with the same - // provider name in the parent module instance. - parentMod := pc.Module.Parent() - return pc.ProviderConfig.Absolute(parentMod), true -} - -func (pc AbsProviderConfig) String() string { - if len(pc.Module) == 0 { - return pc.ProviderConfig.String() - } - return fmt.Sprintf("%s.%s", pc.Module.String(), pc.ProviderConfig.String()) -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/referenceable.go b/vendor/github.com/hashicorp/terraform/addrs/referenceable.go deleted file mode 100644 index 211083a5..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/referenceable.go +++ /dev/null @@ -1,20 +0,0 @@ -package addrs - -// Referenceable is an interface implemented by all address types that can -// appear as references in configuration language expressions. -type Referenceable interface { - // All implementations of this interface must be covered by the type switch - // in lang.Scope.buildEvalContext. - referenceableSigil() - - // String produces a string representation of the address that could be - // parsed as a HCL traversal and passed to ParseRef to produce an identical - // result. - String() string -} - -type referenceable struct { -} - -func (r referenceable) referenceableSigil() { -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/resource.go b/vendor/github.com/hashicorp/terraform/addrs/resource.go deleted file mode 100644 index 28667708..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/resource.go +++ /dev/null @@ -1,270 +0,0 @@ -package addrs - -import ( - "fmt" - "strings" -) - -// Resource is an address for a resource block within configuration, which -// contains potentially-multiple resource instances if that configuration -// block uses "count" or "for_each". -type Resource struct { - referenceable - Mode ResourceMode - Type string - Name string -} - -func (r Resource) String() string { - switch r.Mode { - case ManagedResourceMode: - return fmt.Sprintf("%s.%s", r.Type, r.Name) - case DataResourceMode: - return fmt.Sprintf("data.%s.%s", r.Type, r.Name) - default: - // Should never happen, but we'll return a string here rather than - // crashing just in case it does. - return fmt.Sprintf(".%s.%s", r.Type, r.Name) - } -} - -func (r Resource) Equal(o Resource) bool { - return r.String() == o.String() -} - -// Instance produces the address for a specific instance of the receiver -// that is idenfied by the given key. -func (r Resource) Instance(key InstanceKey) ResourceInstance { - return ResourceInstance{ - Resource: r, - Key: key, - } -} - -// Absolute returns an AbsResource from the receiver and the given module -// instance address. -func (r Resource) Absolute(module ModuleInstance) AbsResource { - return AbsResource{ - Module: module, - Resource: r, - } -} - -// DefaultProviderConfig returns the address of the provider configuration -// that should be used for the resource identified by the reciever if it -// does not have a provider configuration address explicitly set in -// configuration. -// -// This method is not able to verify that such a configuration exists, nor -// represent the behavior of automatically inheriting certain provider -// configurations from parent modules. It just does a static analysis of the -// receiving address and returns an address to start from, relative to the -// same module that contains the resource. -func (r Resource) DefaultProviderConfig() ProviderConfig { - typeName := r.Type - if under := strings.Index(typeName, "_"); under != -1 { - typeName = typeName[:under] - } - return ProviderConfig{ - Type: typeName, - } -} - -// ResourceInstance is an address for a specific instance of a resource. -// When a resource is defined in configuration with "count" or "for_each" it -// produces zero or more instances, which can be addressed using this type. -type ResourceInstance struct { - referenceable - Resource Resource - Key InstanceKey -} - -func (r ResourceInstance) ContainingResource() Resource { - return r.Resource -} - -func (r ResourceInstance) String() string { - if r.Key == NoKey { - return r.Resource.String() - } - return r.Resource.String() + r.Key.String() -} - -func (r ResourceInstance) Equal(o ResourceInstance) bool { - return r.String() == o.String() -} - -// Absolute returns an AbsResourceInstance from the receiver and the given module -// instance address. -func (r ResourceInstance) Absolute(module ModuleInstance) AbsResourceInstance { - return AbsResourceInstance{ - Module: module, - Resource: r, - } -} - -// AbsResource is an absolute address for a resource under a given module path. -type AbsResource struct { - targetable - Module ModuleInstance - Resource Resource -} - -// Resource returns the address of a particular resource within the receiver. -func (m ModuleInstance) Resource(mode ResourceMode, typeName string, name string) AbsResource { - return AbsResource{ - Module: m, - Resource: Resource{ - Mode: mode, - Type: typeName, - Name: name, - }, - } -} - -// Instance produces the address for a specific instance of the receiver -// that is idenfied by the given key. -func (r AbsResource) Instance(key InstanceKey) AbsResourceInstance { - return AbsResourceInstance{ - Module: r.Module, - Resource: r.Resource.Instance(key), - } -} - -// TargetContains implements Targetable by returning true if the given other -// address is either equal to the receiver or is an instance of the -// receiver. -func (r AbsResource) TargetContains(other Targetable) bool { - switch to := other.(type) { - - case AbsResource: - // We'll use our stringification as a cheat-ish way to test for equality. - return to.String() == r.String() - - case AbsResourceInstance: - return r.TargetContains(to.ContainingResource()) - - default: - return false - - } -} - -func (r AbsResource) String() string { - if len(r.Module) == 0 { - return r.Resource.String() - } - return fmt.Sprintf("%s.%s", r.Module.String(), r.Resource.String()) -} - -func (r AbsResource) Equal(o AbsResource) bool { - return r.String() == o.String() -} - -// AbsResourceInstance is an absolute address for a resource instance under a -// given module path. -type AbsResourceInstance struct { - targetable - Module ModuleInstance - Resource ResourceInstance -} - -// ResourceInstance returns the address of a particular resource instance within the receiver. -func (m ModuleInstance) ResourceInstance(mode ResourceMode, typeName string, name string, key InstanceKey) AbsResourceInstance { - return AbsResourceInstance{ - Module: m, - Resource: ResourceInstance{ - Resource: Resource{ - Mode: mode, - Type: typeName, - Name: name, - }, - Key: key, - }, - } -} - -// ContainingResource returns the address of the resource that contains the -// receving resource instance. In other words, it discards the key portion -// of the address to produce an AbsResource value. -func (r AbsResourceInstance) ContainingResource() AbsResource { - return AbsResource{ - Module: r.Module, - Resource: r.Resource.ContainingResource(), - } -} - -// TargetContains implements Targetable by returning true if the given other -// address is equal to the receiver. -func (r AbsResourceInstance) TargetContains(other Targetable) bool { - switch to := other.(type) { - - case AbsResourceInstance: - // We'll use our stringification as a cheat-ish way to test for equality. - return to.String() == r.String() - - default: - return false - - } -} - -func (r AbsResourceInstance) String() string { - if len(r.Module) == 0 { - return r.Resource.String() - } - return fmt.Sprintf("%s.%s", r.Module.String(), r.Resource.String()) -} - -func (r AbsResourceInstance) Equal(o AbsResourceInstance) bool { - return r.String() == o.String() -} - -// Less returns true if the receiver should sort before the given other value -// in a sorted list of addresses. -func (r AbsResourceInstance) Less(o AbsResourceInstance) bool { - switch { - - case len(r.Module) != len(o.Module): - return len(r.Module) < len(o.Module) - - case r.Module.String() != o.Module.String(): - return r.Module.Less(o.Module) - - case r.Resource.Resource.Mode != o.Resource.Resource.Mode: - return r.Resource.Resource.Mode == DataResourceMode - - case r.Resource.Resource.Type != o.Resource.Resource.Type: - return r.Resource.Resource.Type < o.Resource.Resource.Type - - case r.Resource.Resource.Name != o.Resource.Resource.Name: - return r.Resource.Resource.Name < o.Resource.Resource.Name - - case r.Resource.Key != o.Resource.Key: - return InstanceKeyLess(r.Resource.Key, o.Resource.Key) - - default: - return false - - } -} - -// ResourceMode defines which lifecycle applies to a given resource. Each -// resource lifecycle has a slightly different address format. -type ResourceMode rune - -//go:generate stringer -type ResourceMode - -const ( - // InvalidResourceMode is the zero value of ResourceMode and is not - // a valid resource mode. - InvalidResourceMode ResourceMode = 0 - - // ManagedResourceMode indicates a managed resource, as defined by - // "resource" blocks in configuration. - ManagedResourceMode ResourceMode = 'M' - - // DataResourceMode indicates a data resource, as defined by - // "data" blocks in configuration. - DataResourceMode ResourceMode = 'D' -) diff --git a/vendor/github.com/hashicorp/terraform/addrs/resource_phase.go b/vendor/github.com/hashicorp/terraform/addrs/resource_phase.go deleted file mode 100644 index 9bdbdc42..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/resource_phase.go +++ /dev/null @@ -1,105 +0,0 @@ -package addrs - -import "fmt" - -// ResourceInstancePhase is a special kind of reference used only internally -// during graph building to represent resource instances that are in a -// non-primary state. -// -// Graph nodes can declare themselves referenceable via an instance phase -// or can declare that they reference an instance phase in order to accomodate -// secondary graph nodes dealing with, for example, destroy actions. -// -// This special reference type cannot be accessed directly by end-users, and -// should never be shown in the UI. -type ResourceInstancePhase struct { - referenceable - ResourceInstance ResourceInstance - Phase ResourceInstancePhaseType -} - -var _ Referenceable = ResourceInstancePhase{} - -// Phase returns a special "phase address" for the receving instance. See the -// documentation of ResourceInstancePhase for the limited situations where this -// is intended to be used. -func (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase { - return ResourceInstancePhase{ - ResourceInstance: r, - Phase: rpt, - } -} - -// ContainingResource returns an address for the same phase of the resource -// that this instance belongs to. -func (rp ResourceInstancePhase) ContainingResource() ResourcePhase { - return rp.ResourceInstance.Resource.Phase(rp.Phase) -} - -func (rp ResourceInstancePhase) String() string { - // We use a different separator here than usual to ensure that we'll - // never conflict with any non-phased resource instance string. This - // is intentionally something that would fail parsing with ParseRef, - // because this special address type should never be exposed in the UI. - return fmt.Sprintf("%s#%s", rp.ResourceInstance, rp.Phase) -} - -// ResourceInstancePhaseType is an enumeration used with ResourceInstancePhase. -type ResourceInstancePhaseType string - -const ( - // ResourceInstancePhaseDestroy represents the "destroy" phase of a - // resource instance. - ResourceInstancePhaseDestroy ResourceInstancePhaseType = "destroy" - - // ResourceInstancePhaseDestroyCBD is similar to ResourceInstancePhaseDestroy - // but is used for resources that have "create_before_destroy" set, thus - // requiring a different dependency ordering. - ResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = "destroy-cbd" -) - -func (rpt ResourceInstancePhaseType) String() string { - return string(rpt) -} - -// ResourcePhase is a special kind of reference used only internally -// during graph building to represent resources that are in a -// non-primary state. -// -// Graph nodes can declare themselves referenceable via a resource phase -// or can declare that they reference a resource phase in order to accomodate -// secondary graph nodes dealing with, for example, destroy actions. -// -// Since resources (as opposed to instances) aren't actually phased, this -// address type is used only as an approximation during initial construction -// of the resource-oriented plan graph, under the assumption that resource -// instances with ResourceInstancePhase addresses will be created in dynamic -// subgraphs during the graph walk. -// -// This special reference type cannot be accessed directly by end-users, and -// should never be shown in the UI. -type ResourcePhase struct { - referenceable - Resource Resource - Phase ResourceInstancePhaseType -} - -var _ Referenceable = ResourcePhase{} - -// Phase returns a special "phase address" for the receving instance. See the -// documentation of ResourceInstancePhase for the limited situations where this -// is intended to be used. -func (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase { - return ResourcePhase{ - Resource: r, - Phase: rpt, - } -} - -func (rp ResourcePhase) String() string { - // We use a different separator here than usual to ensure that we'll - // never conflict with any non-phased resource instance string. This - // is intentionally something that would fail parsing with ParseRef, - // because this special address type should never be exposed in the UI. - return fmt.Sprintf("%s#%s", rp.Resource, rp.Phase) -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/resourcemode_string.go b/vendor/github.com/hashicorp/terraform/addrs/resourcemode_string.go deleted file mode 100644 index 56e99adf..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/resourcemode_string.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by "stringer -type ResourceMode"; DO NOT EDIT. - -package addrs - -import "strconv" - -const ( - _ResourceMode_name_0 = "InvalidResourceMode" - _ResourceMode_name_1 = "DataResourceMode" - _ResourceMode_name_2 = "ManagedResourceMode" -) - -func (i ResourceMode) String() string { - switch { - case i == 0: - return _ResourceMode_name_0 - case i == 68: - return _ResourceMode_name_1 - case i == 77: - return _ResourceMode_name_2 - default: - return "ResourceMode(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/self.go b/vendor/github.com/hashicorp/terraform/addrs/self.go deleted file mode 100644 index 7f24eaf0..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/self.go +++ /dev/null @@ -1,14 +0,0 @@ -package addrs - -// Self is the address of the special object "self" that behaves as an alias -// for a containing object currently in scope. -const Self selfT = 0 - -type selfT int - -func (s selfT) referenceableSigil() { -} - -func (s selfT) String() string { - return "self" -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/targetable.go b/vendor/github.com/hashicorp/terraform/addrs/targetable.go deleted file mode 100644 index 16819a5a..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/targetable.go +++ /dev/null @@ -1,26 +0,0 @@ -package addrs - -// Targetable is an interface implemented by all address types that can be -// used as "targets" for selecting sub-graphs of a graph. -type Targetable interface { - targetableSigil() - - // TargetContains returns true if the receiver is considered to contain - // the given other address. Containment, for the purpose of targeting, - // means that if a container address is targeted then all of the - // addresses within it are also implicitly targeted. - // - // A targetable address always contains at least itself. - TargetContains(other Targetable) bool - - // String produces a string representation of the address that could be - // parsed as a HCL traversal and passed to ParseTarget to produce an - // identical result. - String() string -} - -type targetable struct { -} - -func (r targetable) targetableSigil() { -} diff --git a/vendor/github.com/hashicorp/terraform/addrs/terraform_attr.go b/vendor/github.com/hashicorp/terraform/addrs/terraform_attr.go deleted file mode 100644 index a880182a..00000000 --- a/vendor/github.com/hashicorp/terraform/addrs/terraform_attr.go +++ /dev/null @@ -1,12 +0,0 @@ -package addrs - -// TerraformAttr is the address of an attribute of the "terraform" object in -// the interpolation scope, like "terraform.workspace". -type TerraformAttr struct { - referenceable - Name string -} - -func (ta TerraformAttr) String() string { - return "terraform." + ta.Name -} diff --git a/vendor/github.com/hashicorp/terraform/command/format/diagnostic.go b/vendor/github.com/hashicorp/terraform/command/format/diagnostic.go deleted file mode 100644 index 46935121..00000000 --- a/vendor/github.com/hashicorp/terraform/command/format/diagnostic.go +++ /dev/null @@ -1,304 +0,0 @@ -package format - -import ( - "bufio" - "bytes" - "fmt" - "sort" - "strings" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcled" - "github.com/hashicorp/hcl2/hclparse" - "github.com/hashicorp/terraform/tfdiags" - "github.com/mitchellh/colorstring" - wordwrap "github.com/mitchellh/go-wordwrap" - "github.com/zclconf/go-cty/cty" -) - -// Diagnostic formats a single diagnostic message. -// -// The width argument specifies at what column the diagnostic messages will -// be wrapped. If set to zero, messages will not be wrapped by this function -// at all. Although the long-form text parts of the message are wrapped, -// not all aspects of the message are guaranteed to fit within the specified -// terminal width. -func Diagnostic(diag tfdiags.Diagnostic, sources map[string][]byte, color *colorstring.Colorize, width int) string { - if diag == nil { - // No good reason to pass a nil diagnostic in here... - return "" - } - - var buf bytes.Buffer - - switch diag.Severity() { - case tfdiags.Error: - buf.WriteString(color.Color("\n[bold][red]Error: [reset]")) - case tfdiags.Warning: - buf.WriteString(color.Color("\n[bold][yellow]Warning: [reset]")) - default: - // Clear out any coloring that might be applied by Terraform's UI helper, - // so our result is not context-sensitive. - buf.WriteString(color.Color("\n[reset]")) - } - - desc := diag.Description() - sourceRefs := diag.Source() - - // We don't wrap the summary, since we expect it to be terse, and since - // this is where we put the text of a native Go error it may not always - // be pure text that lends itself well to word-wrapping. - fmt.Fprintf(&buf, color.Color("[bold]%s[reset]\n\n"), desc.Summary) - - if sourceRefs.Subject != nil { - // We'll borrow HCL's range implementation here, because it has some - // handy features to help us produce a nice source code snippet. - highlightRange := sourceRefs.Subject.ToHCL() - snippetRange := highlightRange - if sourceRefs.Context != nil { - snippetRange = sourceRefs.Context.ToHCL() - } - - // Make sure the snippet includes the highlight. This should be true - // for any reasonable diagnostic, but we'll make sure. - snippetRange = hcl.RangeOver(snippetRange, highlightRange) - - var src []byte - if sources != nil { - src = sources[snippetRange.Filename] - } - if src == nil { - // This should generally not happen, as long as sources are always - // loaded through the main loader. We may load things in other - // ways in weird cases, so we'll tolerate it at the expense of - // a not-so-helpful error message. - fmt.Fprintf(&buf, " on %s line %d:\n (source code not available)\n", highlightRange.Filename, highlightRange.Start.Line) - } else { - file, offset := parseRange(src, highlightRange) - - headerRange := highlightRange - if snippetRange.Empty() { - // We assume that empty range signals diagnostic - // related to the whole body, so we lookup the definition - // instead of attempting to render empty range - snippetRange = hcled.ContextDefRange(file, offset-1) - headerRange = snippetRange - } - - contextStr := hcled.ContextString(file, offset-1) - if contextStr != "" { - contextStr = ", in " + contextStr - } - - fmt.Fprintf(&buf, " on %s line %d%s:\n", headerRange.Filename, headerRange.Start.Line, contextStr) - - // Config snippet rendering - sc := hcl.NewRangeScanner(src, highlightRange.Filename, bufio.ScanLines) - for sc.Scan() { - lineRange := sc.Range() - if !lineRange.Overlaps(snippetRange) { - continue - } - beforeRange, highlightedRange, afterRange := lineRange.PartitionAround(highlightRange) - if highlightedRange.Empty() { - fmt.Fprintf(&buf, "%4d: %s\n", lineRange.Start.Line, sc.Bytes()) - } else { - before := beforeRange.SliceBytes(src) - highlighted := highlightedRange.SliceBytes(src) - after := afterRange.SliceBytes(src) - fmt.Fprintf( - &buf, color.Color("%4d: %s[underline]%s[reset]%s\n"), - lineRange.Start.Line, - before, highlighted, after, - ) - } - } - - } - - if fromExpr := diag.FromExpr(); fromExpr != nil { - // We may also be able to generate information about the dynamic - // values of relevant variables at the point of evaluation, then. - // This is particularly useful for expressions that get evaluated - // multiple times with different values, such as blocks using - // "count" and "for_each", or within "for" expressions. - expr := fromExpr.Expression - ctx := fromExpr.EvalContext - vars := expr.Variables() - stmts := make([]string, 0, len(vars)) - seen := make(map[string]struct{}, len(vars)) - Traversals: - for _, traversal := range vars { - for len(traversal) > 1 { - val, diags := traversal.TraverseAbs(ctx) - if diags.HasErrors() { - // Skip anything that generates errors, since we probably - // already have the same error in our diagnostics set - // already. - traversal = traversal[:len(traversal)-1] - continue - } - - traversalStr := traversalStr(traversal) - if _, exists := seen[traversalStr]; exists { - continue Traversals // don't show duplicates when the same variable is referenced multiple times - } - switch { - case !val.IsKnown(): - // Can't say anything about this yet, then. - continue Traversals - case val.IsNull(): - stmts = append(stmts, fmt.Sprintf(color.Color("[bold]%s[reset] is null"), traversalStr)) - default: - stmts = append(stmts, fmt.Sprintf(color.Color("[bold]%s[reset] is %s"), traversalStr, compactValueStr(val))) - } - seen[traversalStr] = struct{}{} - } - } - - sort.Strings(stmts) // FIXME: Should maybe use a traversal-aware sort that can sort numeric indexes properly? - - if len(stmts) > 0 { - fmt.Fprint(&buf, color.Color(" [dark_gray]|----------------[reset]\n")) - } - for _, stmt := range stmts { - fmt.Fprintf(&buf, color.Color(" [dark_gray]|[reset] %s\n"), stmt) - } - } - - buf.WriteByte('\n') - } - - if desc.Detail != "" { - detail := desc.Detail - if width != 0 { - detail = wordwrap.WrapString(detail, uint(width)) - } - fmt.Fprintf(&buf, "%s\n", detail) - } - - return buf.String() -} - -// sourceCodeContextStr attempts to find a user-friendly description of -// the location of the given range in the given source code. -// -// An empty string is returned if no suitable description is available, e.g. -// because the source is invalid, or because the offset is not inside any sort -// of identifiable container. -func parseRange(src []byte, rng hcl.Range) (*hcl.File, int) { - filename := rng.Filename - offset := rng.Start.Byte - - // We need to re-parse here to get a *hcl.File we can interrogate. This - // is not awesome since we presumably already parsed the file earlier too, - // but this re-parsing is architecturally simpler than retaining all of - // the hcl.File objects and we only do this in the case of an error anyway - // so the overhead here is not a big problem. - parser := hclparse.NewParser() - var file *hcl.File - var diags hcl.Diagnostics - if strings.HasSuffix(filename, ".json") { - file, diags = parser.ParseJSON(src, filename) - } else { - file, diags = parser.ParseHCL(src, filename) - } - if diags.HasErrors() { - return file, offset - } - - return file, offset -} - -// traversalStr produces a representation of an HCL traversal that is compact, -// resembles HCL native syntax, and is suitable for display in the UI. -func traversalStr(traversal hcl.Traversal) string { - // This is a specialized subset of traversal rendering tailored to - // producing helpful contextual messages in diagnostics. It is not - // comprehensive nor intended to be used for other purposes. - - var buf bytes.Buffer - for _, step := range traversal { - switch tStep := step.(type) { - case hcl.TraverseRoot: - buf.WriteString(tStep.Name) - case hcl.TraverseAttr: - buf.WriteByte('.') - buf.WriteString(tStep.Name) - case hcl.TraverseIndex: - buf.WriteByte('[') - if keyTy := tStep.Key.Type(); keyTy.IsPrimitiveType() { - buf.WriteString(compactValueStr(tStep.Key)) - } else { - // We'll just use a placeholder for more complex values, - // since otherwise our result could grow ridiculously long. - buf.WriteString("...") - } - buf.WriteByte(']') - } - } - return buf.String() -} - -// compactValueStr produces a compact, single-line summary of a given value -// that is suitable for display in the UI. -// -// For primitives it returns a full representation, while for more complex -// types it instead summarizes the type, size, etc to produce something -// that is hopefully still somewhat useful but not as verbose as a rendering -// of the entire data structure. -func compactValueStr(val cty.Value) string { - // This is a specialized subset of value rendering tailored to producing - // helpful but concise messages in diagnostics. It is not comprehensive - // nor intended to be used for other purposes. - - ty := val.Type() - switch { - case val.IsNull(): - return "null" - case !val.IsKnown(): - // Should never happen here because we should filter before we get - // in here, but we'll do something reasonable rather than panic. - return "(not yet known)" - case ty == cty.Bool: - if val.True() { - return "true" - } - return "false" - case ty == cty.Number: - bf := val.AsBigFloat() - return bf.Text('g', 10) - case ty == cty.String: - // Go string syntax is not exactly the same as HCL native string syntax, - // but we'll accept the minor edge-cases where this is different here - // for now, just to get something reasonable here. - return fmt.Sprintf("%q", val.AsString()) - case ty.IsCollectionType() || ty.IsTupleType(): - l := val.LengthInt() - switch l { - case 0: - return "empty " + ty.FriendlyName() - case 1: - return ty.FriendlyName() + " with 1 element" - default: - return fmt.Sprintf("%s with %d elements", ty.FriendlyName(), l) - } - case ty.IsObjectType(): - atys := ty.AttributeTypes() - l := len(atys) - switch l { - case 0: - return "object with no attributes" - case 1: - var name string - for k := range atys { - name = k - } - return fmt.Sprintf("object with 1 attribute %q", name) - default: - return fmt.Sprintf("object with %d attributes", l) - } - default: - return ty.FriendlyName() - } -} diff --git a/vendor/github.com/hashicorp/terraform/command/format/diff.go b/vendor/github.com/hashicorp/terraform/command/format/diff.go deleted file mode 100644 index 049f6254..00000000 --- a/vendor/github.com/hashicorp/terraform/command/format/diff.go +++ /dev/null @@ -1,1088 +0,0 @@ -package format - -import ( - "bufio" - "bytes" - "fmt" - "sort" - "strings" - - "github.com/mitchellh/colorstring" - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/plans/objchange" - "github.com/hashicorp/terraform/states" -) - -// ResourceChange returns a string representation of a change to a particular -// resource, for inclusion in user-facing plan output. -// -// The resource schema must be provided along with the change so that the -// formatted change can reflect the configuration structure for the associated -// resource. -// -// If "color" is non-nil, it will be used to color the result. Otherwise, -// no color codes will be included. -func ResourceChange( - change *plans.ResourceInstanceChangeSrc, - schema *configschema.Block, - color *colorstring.Colorize, -) string { - addr := change.Addr - var buf bytes.Buffer - - if color == nil { - color = &colorstring.Colorize{ - Colors: colorstring.DefaultColors, - Disable: true, - Reset: false, - } - } - - dispAddr := addr.String() - if change.DeposedKey != states.NotDeposed { - dispAddr = fmt.Sprintf("%s (deposed object %s)", dispAddr, change.DeposedKey) - } - - switch change.Action { - case plans.Create: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be created", dispAddr))) - case plans.Read: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be read during apply\n # (config refers to values not yet known)", dispAddr))) - case plans.Update: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be updated in-place", dispAddr))) - case plans.CreateThenDelete, plans.DeleteThenCreate: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] must be [bold][red]replaced", dispAddr))) - case plans.Delete: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be [bold][red]destroyed", dispAddr))) - default: - // should never happen, since the above is exhaustive - buf.WriteString(fmt.Sprintf("%s has an action the plan renderer doesn't support (this is a bug)", dispAddr)) - } - buf.WriteString(color.Color("[reset]\n")) - - switch change.Action { - case plans.Create: - buf.WriteString(color.Color("[green] +[reset] ")) - case plans.Read: - buf.WriteString(color.Color("[cyan] <=[reset] ")) - case plans.Update: - buf.WriteString(color.Color("[yellow] ~[reset] ")) - case plans.DeleteThenCreate: - buf.WriteString(color.Color("[red]-[reset]/[green]+[reset] ")) - case plans.CreateThenDelete: - buf.WriteString(color.Color("[green]+[reset]/[red]-[reset] ")) - case plans.Delete: - buf.WriteString(color.Color("[red] -[reset] ")) - default: - buf.WriteString(color.Color("??? ")) - } - - switch addr.Resource.Resource.Mode { - case addrs.ManagedResourceMode: - buf.WriteString(fmt.Sprintf( - "resource %q %q", - addr.Resource.Resource.Type, - addr.Resource.Resource.Name, - )) - case addrs.DataResourceMode: - buf.WriteString(fmt.Sprintf( - "data %q %q ", - addr.Resource.Resource.Type, - addr.Resource.Resource.Name, - )) - default: - // should never happen, since the above is exhaustive - buf.WriteString(addr.String()) - } - - buf.WriteString(" {") - - p := blockBodyDiffPrinter{ - buf: &buf, - color: color, - action: change.Action, - requiredReplace: change.RequiredReplace, - } - - // Most commonly-used resources have nested blocks that result in us - // going at least three traversals deep while we recurse here, so we'll - // start with that much capacity and then grow as needed for deeper - // structures. - path := make(cty.Path, 0, 3) - - changeV, err := change.Decode(schema.ImpliedType()) - if err != nil { - // Should never happen in here, since we've already been through - // loads of layers of encode/decode of the planned changes before now. - panic(fmt.Sprintf("failed to decode plan for %s while rendering diff: %s", addr, err)) - } - - bodyWritten := p.writeBlockBodyDiff(schema, changeV.Before, changeV.After, 6, path) - if bodyWritten { - buf.WriteString("\n") - buf.WriteString(strings.Repeat(" ", 4)) - } - buf.WriteString("}\n") - - return buf.String() -} - -type blockBodyDiffPrinter struct { - buf *bytes.Buffer - color *colorstring.Colorize - action plans.Action - requiredReplace cty.PathSet -} - -const forcesNewResourceCaption = " [red]# forces replacement[reset]" - -// writeBlockBodyDiff writes attribute or block differences -// and returns true if any differences were found and written -func (p *blockBodyDiffPrinter) writeBlockBodyDiff(schema *configschema.Block, old, new cty.Value, indent int, path cty.Path) bool { - path = ctyEnsurePathCapacity(path, 1) - - bodyWritten := false - blankBeforeBlocks := false - { - attrNames := make([]string, 0, len(schema.Attributes)) - attrNameLen := 0 - for name := range schema.Attributes { - oldVal := ctyGetAttrMaybeNull(old, name) - newVal := ctyGetAttrMaybeNull(new, name) - if oldVal.IsNull() && newVal.IsNull() { - // Skip attributes where both old and new values are null - // (we do this early here so that we'll do our value alignment - // based on the longest attribute name that has a change, rather - // than the longest attribute name in the full set.) - continue - } - - attrNames = append(attrNames, name) - if len(name) > attrNameLen { - attrNameLen = len(name) - } - } - sort.Strings(attrNames) - if len(attrNames) > 0 { - blankBeforeBlocks = true - } - - for _, name := range attrNames { - attrS := schema.Attributes[name] - oldVal := ctyGetAttrMaybeNull(old, name) - newVal := ctyGetAttrMaybeNull(new, name) - - bodyWritten = true - p.writeAttrDiff(name, attrS, oldVal, newVal, attrNameLen, indent, path) - } - } - - { - blockTypeNames := make([]string, 0, len(schema.BlockTypes)) - for name := range schema.BlockTypes { - blockTypeNames = append(blockTypeNames, name) - } - sort.Strings(blockTypeNames) - - for _, name := range blockTypeNames { - blockS := schema.BlockTypes[name] - oldVal := ctyGetAttrMaybeNull(old, name) - newVal := ctyGetAttrMaybeNull(new, name) - - bodyWritten = true - p.writeNestedBlockDiffs(name, blockS, oldVal, newVal, blankBeforeBlocks, indent, path) - - // Always include a blank for any subsequent block types. - blankBeforeBlocks = true - } - } - - return bodyWritten -} - -func (p *blockBodyDiffPrinter) writeAttrDiff(name string, attrS *configschema.Attribute, old, new cty.Value, nameLen, indent int, path cty.Path) { - path = append(path, cty.GetAttrStep{Name: name}) - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - showJustNew := false - var action plans.Action - switch { - case old.IsNull(): - action = plans.Create - showJustNew = true - case new.IsNull(): - action = plans.Delete - case ctyEqualWithUnknown(old, new): - action = plans.NoOp - showJustNew = true - default: - action = plans.Update - } - - p.writeActionSymbol(action) - - p.buf.WriteString(p.color.Color("[bold]")) - p.buf.WriteString(name) - p.buf.WriteString(p.color.Color("[reset]")) - p.buf.WriteString(strings.Repeat(" ", nameLen-len(name))) - p.buf.WriteString(" = ") - - if attrS.Sensitive { - p.buf.WriteString("(sensitive value)") - } else { - switch { - case showJustNew: - p.writeValue(new, action, indent+2) - default: - // We show new even if it is null to emphasize the fact - // that it is being unset, since otherwise it is easy to - // misunderstand that the value is still set to the old value. - p.writeValueDiff(old, new, indent+2, path) - } - } -} - -func (p *blockBodyDiffPrinter) writeNestedBlockDiffs(name string, blockS *configschema.NestedBlock, old, new cty.Value, blankBefore bool, indent int, path cty.Path) { - path = append(path, cty.GetAttrStep{Name: name}) - if old.IsNull() && new.IsNull() { - // Nothing to do if both old and new is null - return - } - - // Where old/new are collections representing a nesting mode other than - // NestingSingle, we assume the collection value can never be unknown - // since we always produce the container for the nested objects, even if - // the objects within are computed. - - switch blockS.Nesting { - case configschema.NestingSingle: - var action plans.Action - switch { - case old.IsNull(): - action = plans.Create - case new.IsNull(): - action = plans.Delete - case !new.IsKnown() || !old.IsKnown(): - // "old" should actually always be known due to our contract - // that old values must never be unknown, but we'll allow it - // anyway to be robust. - action = plans.Update - case !(new.Equals(old).True()): - action = plans.Update - } - - if blankBefore { - p.buf.WriteRune('\n') - } - p.writeNestedBlockDiff(name, nil, &blockS.Block, action, old, new, indent, path) - case configschema.NestingList: - // For the sake of handling nested blocks, we'll treat a null list - // the same as an empty list since the config language doesn't - // distinguish these anyway. - if old.IsNull() { - old = cty.ListValEmpty(old.Type().ElementType()) - } - if new.IsNull() { - new = cty.ListValEmpty(new.Type().ElementType()) - } - - oldItems := ctyCollectionValues(old) - newItems := ctyCollectionValues(new) - - // Here we intentionally preserve the index-based correspondance - // between old and new, rather than trying to detect insertions - // and removals in the list, because this more accurately reflects - // how Terraform Core and providers will understand the change, - // particularly when the nested block contains computed attributes - // that will themselves maintain correspondance by index. - - // commonLen is number of elements that exist in both lists, which - // will be presented as updates (~). Any additional items in one - // of the lists will be presented as either creates (+) or deletes (-) - // depending on which list they belong to. - var commonLen int - switch { - case len(oldItems) < len(newItems): - commonLen = len(oldItems) - default: - commonLen = len(newItems) - } - - if blankBefore && (len(oldItems) > 0 || len(newItems) > 0) { - p.buf.WriteRune('\n') - } - - for i := 0; i < commonLen; i++ { - path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) - oldItem := oldItems[i] - newItem := newItems[i] - action := plans.Update - if oldItem.RawEquals(newItem) { - action = plans.NoOp - } - p.writeNestedBlockDiff(name, nil, &blockS.Block, action, oldItem, newItem, indent, path) - } - for i := commonLen; i < len(oldItems); i++ { - path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) - oldItem := oldItems[i] - newItem := cty.NullVal(oldItem.Type()) - p.writeNestedBlockDiff(name, nil, &blockS.Block, plans.Delete, oldItem, newItem, indent, path) - } - for i := commonLen; i < len(newItems); i++ { - path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) - newItem := newItems[i] - oldItem := cty.NullVal(newItem.Type()) - p.writeNestedBlockDiff(name, nil, &blockS.Block, plans.Create, oldItem, newItem, indent, path) - } - case configschema.NestingSet: - // For the sake of handling nested blocks, we'll treat a null set - // the same as an empty set since the config language doesn't - // distinguish these anyway. - if old.IsNull() { - old = cty.SetValEmpty(old.Type().ElementType()) - } - if new.IsNull() { - new = cty.SetValEmpty(new.Type().ElementType()) - } - - oldItems := ctyCollectionValues(old) - newItems := ctyCollectionValues(new) - - if (len(oldItems) + len(newItems)) == 0 { - // Nothing to do if both sets are empty - return - } - - allItems := make([]cty.Value, 0, len(oldItems)+len(newItems)) - allItems = append(allItems, oldItems...) - allItems = append(allItems, newItems...) - all := cty.SetVal(allItems) - - if blankBefore { - p.buf.WriteRune('\n') - } - - for it := all.ElementIterator(); it.Next(); { - _, val := it.Element() - var action plans.Action - var oldValue, newValue cty.Value - switch { - case !val.IsKnown(): - action = plans.Update - newValue = val - case !old.HasElement(val).True(): - action = plans.Create - oldValue = cty.NullVal(val.Type()) - newValue = val - case !new.HasElement(val).True(): - action = plans.Delete - oldValue = val - newValue = cty.NullVal(val.Type()) - default: - action = plans.NoOp - oldValue = val - newValue = val - } - path := append(path, cty.IndexStep{Key: val}) - p.writeNestedBlockDiff(name, nil, &blockS.Block, action, oldValue, newValue, indent, path) - } - - case configschema.NestingMap: - // TODO: Implement this, once helper/schema is actually able to - // produce schemas containing nested map block types. - } -} - -func (p *blockBodyDiffPrinter) writeNestedBlockDiff(name string, label *string, blockS *configschema.Block, action plans.Action, old, new cty.Value, indent int, path cty.Path) { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - p.writeActionSymbol(action) - - if label != nil { - fmt.Fprintf(p.buf, "%s %q {", name, *label) - } else { - fmt.Fprintf(p.buf, "%s {", name) - } - - if action != plans.NoOp && (p.pathForcesNewResource(path) || p.pathForcesNewResource(path[:len(path)-1])) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - - bodyWritten := p.writeBlockBodyDiff(blockS, old, new, indent+4, path) - if bodyWritten { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent+2)) - } - p.buf.WriteString("}") -} - -func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, indent int) { - if !val.IsKnown() { - p.buf.WriteString("(known after apply)") - return - } - if val.IsNull() { - p.buf.WriteString(p.color.Color("[dark_gray]null[reset]")) - return - } - - ty := val.Type() - - switch { - case ty.IsPrimitiveType(): - switch ty { - case cty.String: - { - // Special behavior for JSON strings containing array or object - src := []byte(val.AsString()) - ty, err := ctyjson.ImpliedType(src) - if err == nil && !ty.IsPrimitiveType() { - jv, err := ctyjson.Unmarshal(src, ty) - if err == nil { - p.buf.WriteString("jsonencode(") - if jv.LengthInt() == 0 { - p.writeValue(jv, action, 0) - } else { - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent+4)) - p.writeValue(jv, action, indent+4) - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent)) - } - p.buf.WriteByte(')') - break // don't *also* do the normal behavior below - } - } - } - fmt.Fprintf(p.buf, "%q", val.AsString()) - case cty.Bool: - if val.True() { - p.buf.WriteString("true") - } else { - p.buf.WriteString("false") - } - case cty.Number: - bf := val.AsBigFloat() - p.buf.WriteString(bf.Text('f', -1)) - default: - // should never happen, since the above is exhaustive - fmt.Fprintf(p.buf, "%#v", val) - } - case ty.IsListType() || ty.IsSetType() || ty.IsTupleType(): - p.buf.WriteString("[") - - it := val.ElementIterator() - for it.Next() { - _, val := it.Element() - - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(action) - p.writeValue(val, action, indent+4) - p.buf.WriteString(",") - } - - if val.LengthInt() > 0 { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - } - p.buf.WriteString("]") - case ty.IsMapType(): - p.buf.WriteString("{") - - keyLen := 0 - for it := val.ElementIterator(); it.Next(); { - key, _ := it.Element() - if keyStr := key.AsString(); len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - - for it := val.ElementIterator(); it.Next(); { - key, val := it.Element() - - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(action) - p.writeValue(key, action, indent+4) - p.buf.WriteString(strings.Repeat(" ", keyLen-len(key.AsString()))) - p.buf.WriteString(" = ") - p.writeValue(val, action, indent+4) - } - - if val.LengthInt() > 0 { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - } - p.buf.WriteString("}") - case ty.IsObjectType(): - p.buf.WriteString("{") - - atys := ty.AttributeTypes() - attrNames := make([]string, 0, len(atys)) - nameLen := 0 - for attrName := range atys { - attrNames = append(attrNames, attrName) - if len(attrName) > nameLen { - nameLen = len(attrName) - } - } - sort.Strings(attrNames) - - for _, attrName := range attrNames { - val := val.GetAttr(attrName) - - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(action) - p.buf.WriteString(attrName) - p.buf.WriteString(strings.Repeat(" ", nameLen-len(attrName))) - p.buf.WriteString(" = ") - p.writeValue(val, action, indent+4) - } - - if len(attrNames) > 0 { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - } - p.buf.WriteString("}") - } -} - -func (p *blockBodyDiffPrinter) writeValueDiff(old, new cty.Value, indent int, path cty.Path) { - ty := old.Type() - typesEqual := ctyTypesEqual(ty, new.Type()) - - // We have some specialized diff implementations for certain complex - // values where it's useful to see a visualization of the diff of - // the nested elements rather than just showing the entire old and - // new values verbatim. - // However, these specialized implementations can apply only if both - // values are known and non-null. - if old.IsKnown() && new.IsKnown() && !old.IsNull() && !new.IsNull() && typesEqual { - switch { - case ty == cty.String: - // We have special behavior for both multi-line strings in general - // and for strings that can parse as JSON. For the JSON handling - // to apply, both old and new must be valid JSON. - // For single-line strings that don't parse as JSON we just fall - // out of this switch block and do the default old -> new rendering. - oldS := old.AsString() - newS := new.AsString() - - { - // Special behavior for JSON strings containing object or - // list values. - oldBytes := []byte(oldS) - newBytes := []byte(newS) - oldType, oldErr := ctyjson.ImpliedType(oldBytes) - newType, newErr := ctyjson.ImpliedType(newBytes) - if oldErr == nil && newErr == nil && !(oldType.IsPrimitiveType() && newType.IsPrimitiveType()) { - oldJV, oldErr := ctyjson.Unmarshal(oldBytes, oldType) - newJV, newErr := ctyjson.Unmarshal(newBytes, newType) - if oldErr == nil && newErr == nil { - if !oldJV.RawEquals(newJV) { // two JSON values may differ only in insignificant whitespace - p.buf.WriteString("jsonencode(") - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(plans.Update) - p.writeValueDiff(oldJV, newJV, indent+4, path) - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteByte(')') - } else { - // if they differ only in insigificant whitespace - // then we'll note that but still expand out the - // effective value. - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color("jsonencode( [red]# whitespace changes force replacement[reset]")) - } else { - p.buf.WriteString(p.color.Color("jsonencode( [dim]# whitespace changes[reset]")) - } - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent+4)) - p.writeValue(oldJV, plans.NoOp, indent+4) - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteByte(')') - } - return - } - } - } - - if strings.Index(oldS, "\n") < 0 && strings.Index(newS, "\n") < 0 { - break - } - - p.buf.WriteString("<<~EOT") - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - p.buf.WriteString("\n") - - var oldLines, newLines []cty.Value - { - r := strings.NewReader(oldS) - sc := bufio.NewScanner(r) - for sc.Scan() { - oldLines = append(oldLines, cty.StringVal(sc.Text())) - } - } - { - r := strings.NewReader(newS) - sc := bufio.NewScanner(r) - for sc.Scan() { - newLines = append(newLines, cty.StringVal(sc.Text())) - } - } - - diffLines := ctySequenceDiff(oldLines, newLines) - for _, diffLine := range diffLines { - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(diffLine.Action) - - switch diffLine.Action { - case plans.NoOp, plans.Delete: - p.buf.WriteString(diffLine.Before.AsString()) - case plans.Create: - p.buf.WriteString(diffLine.After.AsString()) - default: - // Should never happen since the above covers all - // actions that ctySequenceDiff can return for strings - p.buf.WriteString(diffLine.After.AsString()) - - } - p.buf.WriteString("\n") - } - - p.buf.WriteString(strings.Repeat(" ", indent)) // +4 here because there's no symbol - p.buf.WriteString("EOT") - - return - - case ty.IsSetType(): - p.buf.WriteString("[") - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - p.buf.WriteString("\n") - - var addedVals, removedVals, allVals []cty.Value - for it := old.ElementIterator(); it.Next(); { - _, val := it.Element() - allVals = append(allVals, val) - if new.HasElement(val).False() { - removedVals = append(removedVals, val) - } - } - for it := new.ElementIterator(); it.Next(); { - _, val := it.Element() - allVals = append(allVals, val) - if val.IsKnown() && old.HasElement(val).False() { - addedVals = append(addedVals, val) - } - } - - var all, added, removed cty.Value - if len(allVals) > 0 { - all = cty.SetVal(allVals) - } else { - all = cty.SetValEmpty(ty.ElementType()) - } - if len(addedVals) > 0 { - added = cty.SetVal(addedVals) - } else { - added = cty.SetValEmpty(ty.ElementType()) - } - if len(removedVals) > 0 { - removed = cty.SetVal(removedVals) - } else { - removed = cty.SetValEmpty(ty.ElementType()) - } - - for it := all.ElementIterator(); it.Next(); { - _, val := it.Element() - - p.buf.WriteString(strings.Repeat(" ", indent+2)) - - var action plans.Action - switch { - case !val.IsKnown(): - action = plans.Update - case added.HasElement(val).True(): - action = plans.Create - case removed.HasElement(val).True(): - action = plans.Delete - default: - action = plans.NoOp - } - - p.writeActionSymbol(action) - p.writeValue(val, action, indent+4) - p.buf.WriteString(",\n") - } - - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteString("]") - return - case ty.IsListType() || ty.IsTupleType(): - p.buf.WriteString("[") - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - p.buf.WriteString("\n") - - elemDiffs := ctySequenceDiff(old.AsValueSlice(), new.AsValueSlice()) - for _, elemDiff := range elemDiffs { - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(elemDiff.Action) - switch elemDiff.Action { - case plans.NoOp, plans.Delete: - p.writeValue(elemDiff.Before, elemDiff.Action, indent+4) - case plans.Update: - p.writeValueDiff(elemDiff.Before, elemDiff.After, indent+4, path) - case plans.Create: - p.writeValue(elemDiff.After, elemDiff.Action, indent+4) - default: - // Should never happen since the above covers all - // actions that ctySequenceDiff can return. - p.writeValue(elemDiff.After, elemDiff.Action, indent+4) - } - - p.buf.WriteString(",\n") - } - - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteString("]") - return - - case ty.IsMapType(): - p.buf.WriteString("{") - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - p.buf.WriteString("\n") - - var allKeys []string - keyLen := 0 - for it := old.ElementIterator(); it.Next(); { - k, _ := it.Element() - keyStr := k.AsString() - allKeys = append(allKeys, keyStr) - if len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - for it := new.ElementIterator(); it.Next(); { - k, _ := it.Element() - keyStr := k.AsString() - allKeys = append(allKeys, keyStr) - if len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - - sort.Strings(allKeys) - - lastK := "" - for i, k := range allKeys { - if i > 0 && lastK == k { - continue // skip duplicates (list is sorted) - } - lastK = k - - p.buf.WriteString(strings.Repeat(" ", indent+2)) - kV := cty.StringVal(k) - var action plans.Action - if old.HasIndex(kV).False() { - action = plans.Create - } else if new.HasIndex(kV).False() { - action = plans.Delete - } else if eqV := old.Index(kV).Equals(new.Index(kV)); eqV.IsKnown() && eqV.True() { - action = plans.NoOp - } else { - action = plans.Update - } - - path := append(path, cty.IndexStep{Key: kV}) - - p.writeActionSymbol(action) - p.writeValue(kV, action, indent+4) - p.buf.WriteString(strings.Repeat(" ", keyLen-len(k))) - p.buf.WriteString(" = ") - switch action { - case plans.Create, plans.NoOp: - v := new.Index(kV) - p.writeValue(v, action, indent+4) - case plans.Delete: - oldV := old.Index(kV) - newV := cty.NullVal(oldV.Type()) - p.writeValueDiff(oldV, newV, indent+4, path) - default: - oldV := old.Index(kV) - newV := new.Index(kV) - p.writeValueDiff(oldV, newV, indent+4, path) - } - - p.buf.WriteByte('\n') - } - - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteString("}") - return - case ty.IsObjectType(): - p.buf.WriteString("{") - p.buf.WriteString("\n") - - forcesNewResource := p.pathForcesNewResource(path) - - var allKeys []string - keyLen := 0 - for it := old.ElementIterator(); it.Next(); { - k, _ := it.Element() - keyStr := k.AsString() - allKeys = append(allKeys, keyStr) - if len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - for it := new.ElementIterator(); it.Next(); { - k, _ := it.Element() - keyStr := k.AsString() - allKeys = append(allKeys, keyStr) - if len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - - sort.Strings(allKeys) - - lastK := "" - for i, k := range allKeys { - if i > 0 && lastK == k { - continue // skip duplicates (list is sorted) - } - lastK = k - - p.buf.WriteString(strings.Repeat(" ", indent+2)) - kV := k - var action plans.Action - if !old.Type().HasAttribute(kV) { - action = plans.Create - } else if !new.Type().HasAttribute(kV) { - action = plans.Delete - } else if eqV := old.GetAttr(kV).Equals(new.GetAttr(kV)); eqV.IsKnown() && eqV.True() { - action = plans.NoOp - } else { - action = plans.Update - } - - path := append(path, cty.GetAttrStep{Name: kV}) - - p.writeActionSymbol(action) - p.buf.WriteString(k) - p.buf.WriteString(strings.Repeat(" ", keyLen-len(k))) - p.buf.WriteString(" = ") - - switch action { - case plans.Create, plans.NoOp: - v := new.GetAttr(kV) - p.writeValue(v, action, indent+4) - case plans.Delete: - oldV := old.GetAttr(kV) - newV := cty.NullVal(oldV.Type()) - p.writeValueDiff(oldV, newV, indent+4, path) - default: - oldV := old.GetAttr(kV) - newV := new.GetAttr(kV) - p.writeValueDiff(oldV, newV, indent+4, path) - } - - p.buf.WriteString("\n") - } - - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteString("}") - - if forcesNewResource { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - return - } - } - - // In all other cases, we just show the new and old values as-is - p.writeValue(old, plans.Delete, indent) - if new.IsNull() { - p.buf.WriteString(p.color.Color(" [dark_gray]->[reset] ")) - } else { - p.buf.WriteString(p.color.Color(" [yellow]->[reset] ")) - } - - p.writeValue(new, plans.Create, indent) - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } -} - -// writeActionSymbol writes a symbol to represent the given action, followed -// by a space. -// -// It only supports the actions that can be represented with a single character: -// Create, Delete, Update and NoAction. -func (p *blockBodyDiffPrinter) writeActionSymbol(action plans.Action) { - switch action { - case plans.Create: - p.buf.WriteString(p.color.Color("[green]+[reset] ")) - case plans.Delete: - p.buf.WriteString(p.color.Color("[red]-[reset] ")) - case plans.Update: - p.buf.WriteString(p.color.Color("[yellow]~[reset] ")) - case plans.NoOp: - p.buf.WriteString(" ") - default: - // Should never happen - p.buf.WriteString(p.color.Color("? ")) - } -} - -func (p *blockBodyDiffPrinter) pathForcesNewResource(path cty.Path) bool { - if !p.action.IsReplace() { - // "requiredReplace" only applies when the instance is being replaced - return false - } - return p.requiredReplace.Has(path) -} - -func ctyEmptyString(value cty.Value) bool { - if !value.IsNull() && value.IsKnown() { - valueType := value.Type() - if valueType == cty.String && value.AsString() == "" { - return true - } - } - return false -} - -func ctyGetAttrMaybeNull(val cty.Value, name string) cty.Value { - attrType := val.Type().AttributeType(name) - - if val.IsNull() { - return cty.NullVal(attrType) - } - - // We treat "" as null here - // as existing SDK doesn't support null yet. - // This allows us to avoid spurious diffs - // until we introduce null to the SDK. - attrValue := val.GetAttr(name) - if ctyEmptyString(attrValue) { - return cty.NullVal(attrType) - } - - return attrValue -} - -func ctyCollectionValues(val cty.Value) []cty.Value { - if !val.IsKnown() || val.IsNull() { - return nil - } - - ret := make([]cty.Value, 0, val.LengthInt()) - for it := val.ElementIterator(); it.Next(); { - _, value := it.Element() - ret = append(ret, value) - } - return ret -} - -// ctySequenceDiff returns differences between given sequences of cty.Value(s) -// in the form of Create, Delete, or Update actions (for objects). -func ctySequenceDiff(old, new []cty.Value) []*plans.Change { - var ret []*plans.Change - lcs := objchange.LongestCommonSubsequence(old, new) - var oldI, newI, lcsI int - for oldI < len(old) || newI < len(new) || lcsI < len(lcs) { - for oldI < len(old) && (lcsI >= len(lcs) || !old[oldI].RawEquals(lcs[lcsI])) { - isObjectDiff := old[oldI].Type().IsObjectType() && new[newI].Type().IsObjectType() - if isObjectDiff && newI < len(new) { - ret = append(ret, &plans.Change{ - Action: plans.Update, - Before: old[oldI], - After: new[newI], - }) - oldI++ - newI++ // we also consume the next "new" in this case - continue - } - - ret = append(ret, &plans.Change{ - Action: plans.Delete, - Before: old[oldI], - After: cty.NullVal(old[oldI].Type()), - }) - oldI++ - } - for newI < len(new) && (lcsI >= len(lcs) || !new[newI].RawEquals(lcs[lcsI])) { - ret = append(ret, &plans.Change{ - Action: plans.Create, - Before: cty.NullVal(new[newI].Type()), - After: new[newI], - }) - newI++ - } - if lcsI < len(lcs) { - ret = append(ret, &plans.Change{ - Action: plans.NoOp, - Before: new[newI], - After: new[newI], - }) - - // All of our indexes advance together now, since the line - // is common to all three sequences. - lcsI++ - oldI++ - newI++ - } - } - return ret -} - -func ctyEqualWithUnknown(old, new cty.Value) bool { - if !old.IsWhollyKnown() || !new.IsWhollyKnown() { - return false - } - return old.Equals(new).True() -} - -// ctyTypesEqual checks equality of two types more loosely -// by avoiding checks of object/tuple elements -// as we render differences on element-by-element basis anyway -func ctyTypesEqual(oldT, newT cty.Type) bool { - if oldT.IsObjectType() && newT.IsObjectType() { - return true - } - if oldT.IsTupleType() && newT.IsTupleType() { - return true - } - return oldT.Equals(newT) -} - -func ctyEnsurePathCapacity(path cty.Path, minExtra int) cty.Path { - if cap(path)-len(path) >= minExtra { - return path - } - newCap := cap(path) * 2 - if newCap < (len(path) + minExtra) { - newCap = len(path) + minExtra - } - newPath := make(cty.Path, len(path), newCap) - copy(newPath, path) - return newPath -} diff --git a/vendor/github.com/hashicorp/terraform/command/format/format.go b/vendor/github.com/hashicorp/terraform/command/format/format.go deleted file mode 100644 index aa8d7deb..00000000 --- a/vendor/github.com/hashicorp/terraform/command/format/format.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package format contains helpers for formatting various Terraform -// structures for human-readabout output. -// -// This package is used by the official Terraform CLI in formatting any -// output and is exported to encourage non-official frontends to mimic the -// output formatting as much as possible so that text formats of Terraform -// structures have a consistent look and feel. -package format diff --git a/vendor/github.com/hashicorp/terraform/command/format/object_id.go b/vendor/github.com/hashicorp/terraform/command/format/object_id.go deleted file mode 100644 index 85ebbfec..00000000 --- a/vendor/github.com/hashicorp/terraform/command/format/object_id.go +++ /dev/null @@ -1,123 +0,0 @@ -package format - -import ( - "github.com/zclconf/go-cty/cty" -) - -// ObjectValueID takes a value that is assumed to be an object representation -// of some resource instance object and attempts to heuristically find an -// attribute of it that is likely to be a unique identifier in the remote -// system that it belongs to which will be useful to the user. -// -// If such an attribute is found, its name and string value intended for -// display are returned. Both returned strings are empty if no such attribute -// exists, in which case the caller should assume that the resource instance -// address within the Terraform configuration is the best available identifier. -// -// This is only a best-effort sort of thing, relying on naming conventions in -// our resource type schemas. The result is not guaranteed to be unique, but -// should generally be suitable for display to an end-user anyway. -// -// This function will panic if the given value is not of an object type. -func ObjectValueID(obj cty.Value) (k, v string) { - if obj.IsNull() || !obj.IsKnown() { - return "", "" - } - - atys := obj.Type().AttributeTypes() - - switch { - - case atys["id"] == cty.String: - v := obj.GetAttr("id") - if v.IsKnown() && !v.IsNull() { - return "id", v.AsString() - } - - case atys["name"] == cty.String: - // "name" isn't always globally unique, but if there isn't also an - // "id" then it _often_ is, in practice. - v := obj.GetAttr("name") - if v.IsKnown() && !v.IsNull() { - return "name", v.AsString() - } - } - - return "", "" -} - -// ObjectValueName takes a value that is assumed to be an object representation -// of some resource instance object and attempts to heuristically find an -// attribute of it that is likely to be a human-friendly name in the remote -// system that it belongs to which will be useful to the user. -// -// If such an attribute is found, its name and string value intended for -// display are returned. Both returned strings are empty if no such attribute -// exists, in which case the caller should assume that the resource instance -// address within the Terraform configuration is the best available identifier. -// -// This is only a best-effort sort of thing, relying on naming conventions in -// our resource type schemas. The result is not guaranteed to be unique, but -// should generally be suitable for display to an end-user anyway. -// -// Callers that use both ObjectValueName and ObjectValueID at the same time -// should be prepared to get the same attribute key and value from both in -// some cases, since there is overlap betweek the id-extraction and -// name-extraction heuristics. -// -// This function will panic if the given value is not of an object type. -func ObjectValueName(obj cty.Value) (k, v string) { - if obj.IsNull() || !obj.IsKnown() { - return "", "" - } - - atys := obj.Type().AttributeTypes() - - switch { - - case atys["name"] == cty.String: - v := obj.GetAttr("name") - if v.IsKnown() && !v.IsNull() { - return "name", v.AsString() - } - - case atys["tags"].IsMapType() && atys["tags"].ElementType() == cty.String: - tags := obj.GetAttr("tags") - if tags.IsNull() || !tags.IsWhollyKnown() { - break - } - - switch { - case tags.HasIndex(cty.StringVal("name")).RawEquals(cty.True): - v := tags.Index(cty.StringVal("name")) - if v.IsKnown() && !v.IsNull() { - return "tags.name", v.AsString() - } - case tags.HasIndex(cty.StringVal("Name")).RawEquals(cty.True): - // AWS-style naming convention - v := tags.Index(cty.StringVal("Name")) - if v.IsKnown() && !v.IsNull() { - return "tags.Name", v.AsString() - } - } - } - - return "", "" -} - -// ObjectValueIDOrName is a convenience wrapper around both ObjectValueID -// and ObjectValueName (in that preference order) to try to extract some sort -// of human-friendly descriptive string value for an object as additional -// context about an object when it is being displayed in a compact way (where -// not all of the attributes are visible.) -// -// Just as with the two functions it wraps, it is a best-effort and may return -// two empty strings if no suitable attribute can be found for a given object. -func ObjectValueIDOrName(obj cty.Value) (k, v string) { - k, v = ObjectValueID(obj) - if k != "" { - return - } - k, v = ObjectValueName(obj) - return -} diff --git a/vendor/github.com/hashicorp/terraform/command/format/plan.go b/vendor/github.com/hashicorp/terraform/command/format/plan.go deleted file mode 100644 index 098653fc..00000000 --- a/vendor/github.com/hashicorp/terraform/command/format/plan.go +++ /dev/null @@ -1,302 +0,0 @@ -package format - -import ( - "bytes" - "fmt" - "log" - "sort" - "strings" - - "github.com/mitchellh/colorstring" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/terraform" -) - -// Plan is a representation of a plan optimized for display to -// an end-user, as opposed to terraform.Plan which is for internal use. -// -// DisplayPlan excludes implementation details that may otherwise appear -// in the main plan, such as destroy actions on data sources (which are -// there only to clean up the state). -type Plan struct { - Resources []*InstanceDiff -} - -// InstanceDiff is a representation of an instance diff optimized -// for display, in conjunction with DisplayPlan. -type InstanceDiff struct { - Addr *terraform.ResourceAddress - Action plans.Action - - // Attributes describes changes to the attributes of the instance. - // - // For destroy diffs this is always nil. - Attributes []*AttributeDiff - - Tainted bool - Deposed bool -} - -// AttributeDiff is a representation of an attribute diff optimized -// for display, in conjunction with DisplayInstanceDiff. -type AttributeDiff struct { - // Path is a dot-delimited traversal through possibly many levels of list and map structure, - // intended for display purposes only. - Path string - - Action plans.Action - - OldValue string - NewValue string - - NewComputed bool - Sensitive bool - ForcesNew bool -} - -// PlanStats gives summary counts for a Plan. -type PlanStats struct { - ToAdd, ToChange, ToDestroy int -} - -// NewPlan produces a display-oriented Plan from a terraform.Plan. -func NewPlan(changes *plans.Changes) *Plan { - log.Printf("[TRACE] NewPlan for %#v", changes) - ret := &Plan{} - if changes == nil { - // Nothing to do! - return ret - } - - for _, rc := range changes.Resources { - addr := rc.Addr - log.Printf("[TRACE] NewPlan found %s (%s)", addr, rc.Action) - dataSource := addr.Resource.Resource.Mode == addrs.DataResourceMode - - // We create "delete" actions for data resources so we can clean - // up their entries in state, but this is an implementation detail - // that users shouldn't see. - if dataSource && rc.Action == plans.Delete { - continue - } - - // For now we'll shim this to work with our old types. - // TODO: Update for the new plan types, ideally also switching over to - // a structural diff renderer instead of a flat renderer. - did := &InstanceDiff{ - Addr: terraform.NewLegacyResourceInstanceAddress(addr), - Action: rc.Action, - } - - if rc.DeposedKey != states.NotDeposed { - did.Deposed = true - } - - // Since this is just a temporary stub implementation on the way - // to us replacing this with the structural diff renderer, we currently - // don't include any attributes here. - // FIXME: Implement the structural diff renderer to replace this - // codepath altogether. - - ret.Resources = append(ret.Resources, did) - } - - // Sort the instance diffs by their addresses for display. - sort.Slice(ret.Resources, func(i, j int) bool { - iAddr := ret.Resources[i].Addr - jAddr := ret.Resources[j].Addr - return iAddr.Less(jAddr) - }) - - return ret -} - -// Format produces and returns a text representation of the receiving plan -// intended for display in a terminal. -// -// If color is not nil, it is used to colorize the output. -func (p *Plan) Format(color *colorstring.Colorize) string { - if p.Empty() { - return "This plan does nothing." - } - - if color == nil { - color = &colorstring.Colorize{ - Colors: colorstring.DefaultColors, - Reset: false, - } - } - - // Find the longest path length of all the paths that are changing, - // so we can align them all. - keyLen := 0 - for _, r := range p.Resources { - for _, attr := range r.Attributes { - key := attr.Path - - if len(key) > keyLen { - keyLen = len(key) - } - } - } - - buf := new(bytes.Buffer) - for _, r := range p.Resources { - formatPlanInstanceDiff(buf, r, keyLen, color) - } - - return strings.TrimSpace(buf.String()) -} - -// Stats returns statistics about the plan -func (p *Plan) Stats() PlanStats { - var ret PlanStats - for _, r := range p.Resources { - switch r.Action { - case plans.Create: - ret.ToAdd++ - case plans.Update: - ret.ToChange++ - case plans.DeleteThenCreate, plans.CreateThenDelete: - ret.ToAdd++ - ret.ToDestroy++ - case plans.Delete: - ret.ToDestroy++ - } - } - return ret -} - -// ActionCounts returns the number of diffs for each action type -func (p *Plan) ActionCounts() map[plans.Action]int { - ret := map[plans.Action]int{} - for _, r := range p.Resources { - ret[r.Action]++ - } - return ret -} - -// Empty returns true if there is at least one resource diff in the receiving plan. -func (p *Plan) Empty() bool { - return len(p.Resources) == 0 -} - -// DiffActionSymbol returns a string that, once passed through a -// colorstring.Colorize, will produce a result that can be written -// to a terminal to produce a symbol made of three printable -// characters, possibly interspersed with VT100 color codes. -func DiffActionSymbol(action plans.Action) string { - switch action { - case plans.DeleteThenCreate: - return "[red]-[reset]/[green]+[reset]" - case plans.CreateThenDelete: - return "[green]+[reset]/[red]-[reset]" - case plans.Create: - return " [green]+[reset]" - case plans.Delete: - return " [red]-[reset]" - case plans.Read: - return " [cyan]<=[reset]" - case plans.Update: - return " [yellow]~[reset]" - default: - return " ?" - } -} - -// formatPlanInstanceDiff writes the text representation of the given instance diff -// to the given buffer, using the given colorizer. -func formatPlanInstanceDiff(buf *bytes.Buffer, r *InstanceDiff, keyLen int, colorizer *colorstring.Colorize) { - addrStr := r.Addr.String() - - // Determine the color for the text (green for adding, yellow - // for change, red for delete), and symbol, and output the - // resource header. - color := "yellow" - symbol := DiffActionSymbol(r.Action) - oldValues := true - switch r.Action { - case plans.DeleteThenCreate, plans.CreateThenDelete: - color = "yellow" - case plans.Create: - color = "green" - oldValues = false - case plans.Delete: - color = "red" - case plans.Read: - color = "cyan" - oldValues = false - } - - var extraStr string - if r.Tainted { - extraStr = extraStr + " (tainted)" - } - if r.Deposed { - extraStr = extraStr + " (deposed)" - } - if r.Action.IsReplace() { - extraStr = extraStr + colorizer.Color(" [red][bold](new resource required)") - } - - buf.WriteString( - colorizer.Color(fmt.Sprintf( - "[%s]%s [%s]%s%s\n", - color, symbol, color, addrStr, extraStr, - )), - ) - - for _, attr := range r.Attributes { - - v := attr.NewValue - var dispV string - switch { - case v == "" && attr.NewComputed: - dispV = "" - case attr.Sensitive: - dispV = "" - default: - dispV = fmt.Sprintf("%q", v) - } - - updateMsg := "" - switch { - case attr.ForcesNew && r.Action.IsReplace(): - updateMsg = colorizer.Color(" [red](forces new resource)") - case attr.Sensitive && oldValues: - updateMsg = colorizer.Color(" [yellow](attribute changed)") - } - - if oldValues { - u := attr.OldValue - var dispU string - switch { - case attr.Sensitive: - dispU = "" - default: - dispU = fmt.Sprintf("%q", u) - } - buf.WriteString(fmt.Sprintf( - " %s:%s %s => %s%s\n", - attr.Path, - strings.Repeat(" ", keyLen-len(attr.Path)), - dispU, dispV, - updateMsg, - )) - } else { - buf.WriteString(fmt.Sprintf( - " %s:%s %s%s\n", - attr.Path, - strings.Repeat(" ", keyLen-len(attr.Path)), - dispV, - updateMsg, - )) - } - } - - // Write the reset color so we don't bleed color into later text - buf.WriteString(colorizer.Color("[reset]\n")) -} diff --git a/vendor/github.com/hashicorp/terraform/command/format/state.go b/vendor/github.com/hashicorp/terraform/command/format/state.go deleted file mode 100644 index f411ef9c..00000000 --- a/vendor/github.com/hashicorp/terraform/command/format/state.go +++ /dev/null @@ -1,286 +0,0 @@ -package format - -import ( - "bytes" - "fmt" - "sort" - "strings" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/terraform" - "github.com/mitchellh/colorstring" -) - -// StateOpts are the options for formatting a state. -type StateOpts struct { - // State is the state to format. This is required. - State *states.State - - // Schemas are used to decode attributes. This is required. - Schemas *terraform.Schemas - - // Color is the colorizer. This is optional. - Color *colorstring.Colorize -} - -// State takes a state and returns a string -func State(opts *StateOpts) string { - if opts.Color == nil { - panic("colorize not given") - } - - if opts.Schemas == nil { - panic("schemas not given") - } - - s := opts.State - if len(s.Modules) == 0 { - return "The state file is empty. No resources are represented." - } - - buf := bytes.NewBufferString("[reset]") - p := blockBodyDiffPrinter{ - buf: buf, - color: opts.Color, - action: plans.NoOp, - } - - // Format all the modules - for _, m := range s.Modules { - formatStateModule(p, m, opts.Schemas) - } - - // Write the outputs for the root module - m := s.RootModule() - - if m.OutputValues != nil { - if len(m.OutputValues) > 0 { - p.buf.WriteString("Outputs:\n\n") - } - - // Sort the outputs - ks := make([]string, 0, len(m.OutputValues)) - for k := range m.OutputValues { - ks = append(ks, k) - } - sort.Strings(ks) - - // Output each output k/v pair - for _, k := range ks { - v := m.OutputValues[k] - p.buf.WriteString(fmt.Sprintf("%s = ", k)) - p.writeValue(v.Value, plans.NoOp, 0) - p.buf.WriteString("\n\n") - } - } - - return opts.Color.Color(strings.TrimSpace(p.buf.String())) - -} - -func formatStateModule(p blockBodyDiffPrinter, m *states.Module, schemas *terraform.Schemas) { - // First get the names of all the resources so we can show them - // in alphabetical order. - names := make([]string, 0, len(m.Resources)) - for name := range m.Resources { - names = append(names, name) - } - sort.Strings(names) - - // Go through each resource and begin building up the output. - for _, key := range names { - for k, v := range m.Resources[key].Instances { - addr := m.Resources[key].Addr - - taintStr := "" - if v.Current.Status == 'T' { - taintStr = "(tainted)" - } - p.buf.WriteString(fmt.Sprintf("# %s: %s\n", addr.Absolute(m.Addr).Instance(k), taintStr)) - - var schema *configschema.Block - provider := m.Resources[key].ProviderConfig.ProviderConfig.StringCompact() - if _, exists := schemas.Providers[provider]; !exists { - // This should never happen in normal use because we should've - // loaded all of the schemas and checked things prior to this - // point. We can't return errors here, but since this is UI code - // we will try to do _something_ reasonable. - p.buf.WriteString(fmt.Sprintf("# missing schema for provider %q\n\n", provider)) - continue - } - - switch addr.Mode { - case addrs.ManagedResourceMode: - schema, _ = schemas.ResourceTypeConfig( - provider, - addr.Mode, - addr.Type, - ) - if schema == nil { - p.buf.WriteString(fmt.Sprintf( - "# missing schema for provider %q resource type %s\n\n", provider, addr.Type)) - continue - } - - p.buf.WriteString(fmt.Sprintf( - "resource %q %q {", - addr.Type, - addr.Name, - )) - case addrs.DataResourceMode: - schema, _ = schemas.ResourceTypeConfig( - provider, - addr.Mode, - addr.Type, - ) - if schema == nil { - p.buf.WriteString(fmt.Sprintf( - "# missing schema for provider %q data source %s\n\n", provider, addr.Type)) - continue - } - - p.buf.WriteString(fmt.Sprintf( - "data %q %q {", - addr.Type, - addr.Name, - )) - default: - // should never happen, since the above is exhaustive - p.buf.WriteString(addr.String()) - } - - val, err := v.Current.Decode(schema.ImpliedType()) - if err != nil { - fmt.Println(err.Error()) - break - } - - path := make(cty.Path, 0, 3) - bodyWritten := p.writeBlockBodyDiff(schema, val.Value, val.Value, 2, path) - if bodyWritten { - p.buf.WriteString("\n") - } - - p.buf.WriteString("}\n\n") - } - } - p.buf.WriteString("[reset]\n") -} - -func formatNestedList(indent string, outputList []interface{}) string { - outputBuf := new(bytes.Buffer) - outputBuf.WriteString(fmt.Sprintf("%s[", indent)) - - lastIdx := len(outputList) - 1 - - for i, value := range outputList { - outputBuf.WriteString(fmt.Sprintf("\n%s%s%s", indent, " ", value)) - if i != lastIdx { - outputBuf.WriteString(",") - } - } - - outputBuf.WriteString(fmt.Sprintf("\n%s]", indent)) - return strings.TrimPrefix(outputBuf.String(), "\n") -} - -func formatListOutput(indent, outputName string, outputList []interface{}) string { - keyIndent := "" - - outputBuf := new(bytes.Buffer) - - if outputName != "" { - outputBuf.WriteString(fmt.Sprintf("%s%s = [", indent, outputName)) - keyIndent = " " - } - - lastIdx := len(outputList) - 1 - - for i, value := range outputList { - switch typedValue := value.(type) { - case string: - outputBuf.WriteString(fmt.Sprintf("\n%s%s%s", indent, keyIndent, value)) - case []interface{}: - outputBuf.WriteString(fmt.Sprintf("\n%s%s", indent, - formatNestedList(indent+keyIndent, typedValue))) - case map[string]interface{}: - outputBuf.WriteString(fmt.Sprintf("\n%s%s", indent, - formatNestedMap(indent+keyIndent, typedValue))) - } - - if lastIdx != i { - outputBuf.WriteString(",") - } - } - - if outputName != "" { - if len(outputList) > 0 { - outputBuf.WriteString(fmt.Sprintf("\n%s]", indent)) - } else { - outputBuf.WriteString("]") - } - } - - return strings.TrimPrefix(outputBuf.String(), "\n") -} - -func formatNestedMap(indent string, outputMap map[string]interface{}) string { - ks := make([]string, 0, len(outputMap)) - for k, _ := range outputMap { - ks = append(ks, k) - } - sort.Strings(ks) - - outputBuf := new(bytes.Buffer) - outputBuf.WriteString(fmt.Sprintf("%s{", indent)) - - lastIdx := len(outputMap) - 1 - for i, k := range ks { - v := outputMap[k] - outputBuf.WriteString(fmt.Sprintf("\n%s%s = %v", indent+" ", k, v)) - - if lastIdx != i { - outputBuf.WriteString(",") - } - } - - outputBuf.WriteString(fmt.Sprintf("\n%s}", indent)) - - return strings.TrimPrefix(outputBuf.String(), "\n") -} - -func formatMapOutput(indent, outputName string, outputMap map[string]interface{}) string { - ks := make([]string, 0, len(outputMap)) - for k, _ := range outputMap { - ks = append(ks, k) - } - sort.Strings(ks) - - keyIndent := "" - - outputBuf := new(bytes.Buffer) - if outputName != "" { - outputBuf.WriteString(fmt.Sprintf("%s%s = {", indent, outputName)) - keyIndent = " " - } - - for _, k := range ks { - v := outputMap[k] - outputBuf.WriteString(fmt.Sprintf("\n%s%s%s = %v", indent, keyIndent, k, v)) - } - - if outputName != "" { - if len(outputMap) > 0 { - outputBuf.WriteString(fmt.Sprintf("\n%s}", indent)) - } else { - outputBuf.WriteString("}") - } - } - - return strings.TrimPrefix(outputBuf.String(), "\n") -} diff --git a/vendor/github.com/hashicorp/terraform/config/configschema/decoder_spec.go b/vendor/github.com/hashicorp/terraform/config/configschema/decoder_spec.go new file mode 100644 index 00000000..2b1b0cac --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/config/configschema/decoder_spec.go @@ -0,0 +1,97 @@ +package configschema + +import ( + "github.com/hashicorp/hcl2/hcldec" + "github.com/zclconf/go-cty/cty" +) + +var mapLabelNames = []string{"key"} + +// DecoderSpec returns a hcldec.Spec that can be used to decode a HCL Body +// using the facilities in the hcldec package. +// +// The returned specification is guaranteed to return a value of the same type +// returned by method ImpliedType, but it may contain null or unknown values if +// any of the block attributes are defined as optional and/or computed +// respectively. +func (b *Block) DecoderSpec() hcldec.Spec { + ret := hcldec.ObjectSpec{} + if b == nil { + return ret + } + + for name, attrS := range b.Attributes { + switch { + case attrS.Computed && attrS.Optional: + // In this special case we use an unknown value as a default + // to get the intended behavior that the result is computed + // unless it has been explicitly set in config. + ret[name] = &hcldec.DefaultSpec{ + Primary: &hcldec.AttrSpec{ + Name: name, + Type: attrS.Type, + }, + Default: &hcldec.LiteralSpec{ + Value: cty.UnknownVal(attrS.Type), + }, + } + case attrS.Computed: + ret[name] = &hcldec.LiteralSpec{ + Value: cty.UnknownVal(attrS.Type), + } + default: + ret[name] = &hcldec.AttrSpec{ + Name: name, + Type: attrS.Type, + Required: attrS.Required, + } + } + } + + for name, blockS := range b.BlockTypes { + if _, exists := ret[name]; exists { + // This indicates an invalid schema, since it's not valid to + // define both an attribute and a block type of the same name. + // However, we don't raise this here since it's checked by + // InternalValidate. + continue + } + + childSpec := blockS.Block.DecoderSpec() + + switch blockS.Nesting { + case NestingSingle: + ret[name] = &hcldec.BlockSpec{ + TypeName: name, + Nested: childSpec, + Required: blockS.MinItems == 1 && blockS.MaxItems >= 1, + } + case NestingList: + ret[name] = &hcldec.BlockListSpec{ + TypeName: name, + Nested: childSpec, + MinItems: blockS.MinItems, + MaxItems: blockS.MaxItems, + } + case NestingSet: + ret[name] = &hcldec.BlockSetSpec{ + TypeName: name, + Nested: childSpec, + MinItems: blockS.MinItems, + MaxItems: blockS.MaxItems, + } + case NestingMap: + ret[name] = &hcldec.BlockMapSpec{ + TypeName: name, + Nested: childSpec, + LabelNames: mapLabelNames, + } + default: + // Invalid nesting type is just ignored. It's checked by + // InternalValidate. + continue + } + } + + return ret +} diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/doc.go b/vendor/github.com/hashicorp/terraform/config/configschema/doc.go similarity index 100% rename from vendor/github.com/hashicorp/terraform/configs/configschema/doc.go rename to vendor/github.com/hashicorp/terraform/config/configschema/doc.go diff --git a/vendor/github.com/hashicorp/terraform/config/configschema/implied_type.go b/vendor/github.com/hashicorp/terraform/config/configschema/implied_type.go new file mode 100644 index 00000000..67324ebc --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/config/configschema/implied_type.go @@ -0,0 +1,21 @@ +package configschema + +import ( + "github.com/hashicorp/hcl2/hcldec" + "github.com/zclconf/go-cty/cty" +) + +// ImpliedType returns the cty.Type that would result from decoding a +// configuration block using the receiving block schema. +// +// ImpliedType always returns a result, even if the given schema is +// inconsistent. Code that creates configschema.Block objects should be +// tested using the InternalValidate method to detect any inconsistencies +// that would cause this method to fall back on defaults and assumptions. +func (b *Block) ImpliedType() cty.Type { + if b == nil { + return cty.EmptyObject + } + + return hcldec.ImpliedType(b.DecoderSpec()) +} diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/internal_validate.go b/vendor/github.com/hashicorp/terraform/config/configschema/internal_validate.go similarity index 88% rename from vendor/github.com/hashicorp/terraform/configs/configschema/internal_validate.go rename to vendor/github.com/hashicorp/terraform/config/configschema/internal_validate.go index eb8c6bf1..33cbe884 100644 --- a/vendor/github.com/hashicorp/terraform/configs/configschema/internal_validate.go +++ b/vendor/github.com/hashicorp/terraform/config/configschema/internal_validate.go @@ -76,15 +76,6 @@ func (b *Block) internalValidate(prefix string, err error) error { if blockS.MinItems > blockS.MaxItems && blockS.MaxItems != 0 { err = multierror.Append(err, fmt.Errorf("%s%s: MinItems must be less than or equal to MaxItems in %s mode", prefix, name, blockS.Nesting)) } - if blockS.Nesting == NestingSet { - ety := blockS.Block.ImpliedType() - if ety.HasDynamicTypes() { - // This is not permitted because the HCL (cty) set implementation - // needs to know the exact type of set elements in order to - // properly hash them, and so can't support mixed types. - err = multierror.Append(err, fmt.Errorf("%s%s: NestingSet blocks may not contain attributes of cty.DynamicPseudoType", prefix, name)) - } - } case NestingMap: if blockS.MinItems != 0 || blockS.MaxItems != 0 { err = multierror.Append(err, fmt.Errorf("%s%s: MinItems and MaxItems must both be 0 in NestingMap mode", prefix, name)) diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/nestingmode_string.go b/vendor/github.com/hashicorp/terraform/config/configschema/nestingmode_string.go similarity index 100% rename from vendor/github.com/hashicorp/terraform/configs/configschema/nestingmode_string.go rename to vendor/github.com/hashicorp/terraform/config/configschema/nestingmode_string.go diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/schema.go b/vendor/github.com/hashicorp/terraform/config/configschema/schema.go similarity index 93% rename from vendor/github.com/hashicorp/terraform/configs/configschema/schema.go rename to vendor/github.com/hashicorp/terraform/config/configschema/schema.go index 0c23741f..9a8ee550 100644 --- a/vendor/github.com/hashicorp/terraform/configs/configschema/schema.go +++ b/vendor/github.com/hashicorp/terraform/config/configschema/schema.go @@ -28,12 +28,6 @@ type Attribute struct { // Type is a type specification that the attribute's value must conform to. Type cty.Type - // Description is an English-language description of the purpose and - // usage of the attribute. A description should be concise and use only - // one or two sentences, leaving full definition to longer-form - // documentation defined elsewhere. - Description string - // Required, if set to true, specifies that an omitted or null value is // not permitted. Required bool diff --git a/vendor/github.com/hashicorp/terraform/config/hcl2shim/flatmap.go b/vendor/github.com/hashicorp/terraform/config/hcl2shim/flatmap.go deleted file mode 100644 index bb4228d9..00000000 --- a/vendor/github.com/hashicorp/terraform/config/hcl2shim/flatmap.go +++ /dev/null @@ -1,424 +0,0 @@ -package hcl2shim - -import ( - "fmt" - "strconv" - "strings" - - "github.com/zclconf/go-cty/cty/convert" - - "github.com/zclconf/go-cty/cty" -) - -// FlatmapValueFromHCL2 converts a value from HCL2 (really, from the cty dynamic -// types library that HCL2 uses) to a map compatible with what would be -// produced by the "flatmap" package. -// -// The type of the given value informs the structure of the resulting map. -// The value must be of an object type or this function will panic. -// -// Flatmap values can only represent maps when they are of primitive types, -// so the given value must not have any maps of complex types or the result -// is undefined. -func FlatmapValueFromHCL2(v cty.Value) map[string]string { - if v.IsNull() { - return nil - } - - if !v.Type().IsObjectType() { - panic(fmt.Sprintf("HCL2ValueFromFlatmap called on %#v", v.Type())) - } - - m := make(map[string]string) - flatmapValueFromHCL2Map(m, "", v) - return m -} - -func flatmapValueFromHCL2Value(m map[string]string, key string, val cty.Value) { - ty := val.Type() - switch { - case ty.IsPrimitiveType() || ty == cty.DynamicPseudoType: - flatmapValueFromHCL2Primitive(m, key, val) - case ty.IsObjectType() || ty.IsMapType(): - flatmapValueFromHCL2Map(m, key+".", val) - case ty.IsTupleType() || ty.IsListType() || ty.IsSetType(): - flatmapValueFromHCL2Seq(m, key+".", val) - default: - panic(fmt.Sprintf("cannot encode %s to flatmap", ty.FriendlyName())) - } -} - -func flatmapValueFromHCL2Primitive(m map[string]string, key string, val cty.Value) { - if !val.IsKnown() { - m[key] = UnknownVariableValue - return - } - if val.IsNull() { - // Omit entirely - return - } - - var err error - val, err = convert.Convert(val, cty.String) - if err != nil { - // Should not be possible, since all primitive types can convert to string. - panic(fmt.Sprintf("invalid primitive encoding to flatmap: %s", err)) - } - m[key] = val.AsString() -} - -func flatmapValueFromHCL2Map(m map[string]string, prefix string, val cty.Value) { - if val.IsNull() { - // Omit entirely - return - } - if !val.IsKnown() { - switch { - case val.Type().IsObjectType(): - // Whole objects can't be unknown in flatmap, so instead we'll - // just write all of the attribute values out as unknown. - for name, aty := range val.Type().AttributeTypes() { - flatmapValueFromHCL2Value(m, prefix+name, cty.UnknownVal(aty)) - } - default: - m[prefix+"%"] = UnknownVariableValue - } - return - } - - len := 0 - for it := val.ElementIterator(); it.Next(); { - ak, av := it.Element() - name := ak.AsString() - flatmapValueFromHCL2Value(m, prefix+name, av) - len++ - } - if !val.Type().IsObjectType() { // objects don't have an explicit count included, since their attribute count is fixed - m[prefix+"%"] = strconv.Itoa(len) - } -} - -func flatmapValueFromHCL2Seq(m map[string]string, prefix string, val cty.Value) { - if val.IsNull() { - // Omit entirely - return - } - if !val.IsKnown() { - m[prefix+"#"] = UnknownVariableValue - return - } - - // For sets this won't actually generate exactly what helper/schema would've - // generated, because we don't have access to the set key function it - // would've used. However, in practice it doesn't actually matter what the - // keys are as long as they are unique, so we'll just generate sequential - // indexes for them as if it were a list. - // - // An important implication of this, however, is that the set ordering will - // not be consistent across mutations and so different keys may be assigned - // to the same value when round-tripping. Since this shim is intended to - // be short-lived and not used for round-tripping, we accept this. - i := 0 - for it := val.ElementIterator(); it.Next(); { - _, av := it.Element() - key := prefix + strconv.Itoa(i) - flatmapValueFromHCL2Value(m, key, av) - i++ - } - m[prefix+"#"] = strconv.Itoa(i) -} - -// HCL2ValueFromFlatmap converts a map compatible with what would be produced -// by the "flatmap" package to a HCL2 (really, the cty dynamic types library -// that HCL2 uses) object type. -// -// The intended result type must be provided in order to guide how the -// map contents are decoded. This must be an object type or this function -// will panic. -// -// Flatmap values can only represent maps when they are of primitive types, -// so the given type must not have any maps of complex types or the result -// is undefined. -// -// The result may contain null values if the given map does not contain keys -// for all of the different key paths implied by the given type. -func HCL2ValueFromFlatmap(m map[string]string, ty cty.Type) (cty.Value, error) { - if m == nil { - return cty.NullVal(ty), nil - } - if !ty.IsObjectType() { - panic(fmt.Sprintf("HCL2ValueFromFlatmap called on %#v", ty)) - } - - return hcl2ValueFromFlatmapObject(m, "", ty.AttributeTypes()) -} - -func hcl2ValueFromFlatmapValue(m map[string]string, key string, ty cty.Type) (cty.Value, error) { - var val cty.Value - var err error - switch { - case ty.IsPrimitiveType(): - val, err = hcl2ValueFromFlatmapPrimitive(m, key, ty) - case ty.IsObjectType(): - val, err = hcl2ValueFromFlatmapObject(m, key+".", ty.AttributeTypes()) - case ty.IsTupleType(): - val, err = hcl2ValueFromFlatmapTuple(m, key+".", ty.TupleElementTypes()) - case ty.IsMapType(): - val, err = hcl2ValueFromFlatmapMap(m, key+".", ty) - case ty.IsListType(): - val, err = hcl2ValueFromFlatmapList(m, key+".", ty) - case ty.IsSetType(): - val, err = hcl2ValueFromFlatmapSet(m, key+".", ty) - default: - err = fmt.Errorf("cannot decode %s from flatmap", ty.FriendlyName()) - } - - if err != nil { - return cty.DynamicVal, err - } - return val, nil -} - -func hcl2ValueFromFlatmapPrimitive(m map[string]string, key string, ty cty.Type) (cty.Value, error) { - rawVal, exists := m[key] - if !exists { - return cty.NullVal(ty), nil - } - if rawVal == UnknownVariableValue { - return cty.UnknownVal(ty), nil - } - - var err error - val := cty.StringVal(rawVal) - val, err = convert.Convert(val, ty) - if err != nil { - // This should never happen for _valid_ input, but flatmap data might - // be tampered with by the user and become invalid. - return cty.DynamicVal, fmt.Errorf("invalid value for %q in state: %s", key, err) - } - - return val, nil -} - -func hcl2ValueFromFlatmapObject(m map[string]string, prefix string, atys map[string]cty.Type) (cty.Value, error) { - vals := make(map[string]cty.Value) - for name, aty := range atys { - val, err := hcl2ValueFromFlatmapValue(m, prefix+name, aty) - if err != nil { - return cty.DynamicVal, err - } - vals[name] = val - } - return cty.ObjectVal(vals), nil -} - -func hcl2ValueFromFlatmapTuple(m map[string]string, prefix string, etys []cty.Type) (cty.Value, error) { - var vals []cty.Value - - // if the container is unknown, there is no count string - listName := strings.TrimRight(prefix, ".") - if m[listName] == UnknownVariableValue { - return cty.UnknownVal(cty.Tuple(etys)), nil - } - - countStr, exists := m[prefix+"#"] - if !exists { - return cty.NullVal(cty.Tuple(etys)), nil - } - if countStr == UnknownVariableValue { - return cty.UnknownVal(cty.Tuple(etys)), nil - } - - count, err := strconv.Atoi(countStr) - if err != nil { - return cty.DynamicVal, fmt.Errorf("invalid count value for %q in state: %s", prefix, err) - } - if count != len(etys) { - return cty.DynamicVal, fmt.Errorf("wrong number of values for %q in state: got %d, but need %d", prefix, count, len(etys)) - } - - vals = make([]cty.Value, len(etys)) - for i, ety := range etys { - key := prefix + strconv.Itoa(i) - val, err := hcl2ValueFromFlatmapValue(m, key, ety) - if err != nil { - return cty.DynamicVal, err - } - vals[i] = val - } - return cty.TupleVal(vals), nil -} - -func hcl2ValueFromFlatmapMap(m map[string]string, prefix string, ty cty.Type) (cty.Value, error) { - vals := make(map[string]cty.Value) - ety := ty.ElementType() - - // if the container is unknown, there is no count string - listName := strings.TrimRight(prefix, ".") - if m[listName] == UnknownVariableValue { - return cty.UnknownVal(ty), nil - } - - // We actually don't really care about the "count" of a map for our - // purposes here, but we do need to check if it _exists_ in order to - // recognize the difference between null (not set at all) and empty. - if strCount, exists := m[prefix+"%"]; !exists { - return cty.NullVal(ty), nil - } else if strCount == UnknownVariableValue { - return cty.UnknownVal(ty), nil - } - - for fullKey := range m { - if !strings.HasPrefix(fullKey, prefix) { - continue - } - - // The flatmap format doesn't allow us to distinguish between keys - // that contain periods and nested objects, so by convention a - // map is only ever of primitive type in flatmap, and we just assume - // that the remainder of the raw key (dots and all) is the key we - // want in the result value. - key := fullKey[len(prefix):] - if key == "%" { - // Ignore the "count" key - continue - } - - val, err := hcl2ValueFromFlatmapValue(m, fullKey, ety) - if err != nil { - return cty.DynamicVal, err - } - vals[key] = val - } - - if len(vals) == 0 { - return cty.MapValEmpty(ety), nil - } - return cty.MapVal(vals), nil -} - -func hcl2ValueFromFlatmapList(m map[string]string, prefix string, ty cty.Type) (cty.Value, error) { - var vals []cty.Value - - // if the container is unknown, there is no count string - listName := strings.TrimRight(prefix, ".") - if m[listName] == UnknownVariableValue { - return cty.UnknownVal(ty), nil - } - - countStr, exists := m[prefix+"#"] - if !exists { - return cty.NullVal(ty), nil - } - if countStr == UnknownVariableValue { - return cty.UnknownVal(ty), nil - } - - count, err := strconv.Atoi(countStr) - if err != nil { - return cty.DynamicVal, fmt.Errorf("invalid count value for %q in state: %s", prefix, err) - } - - ety := ty.ElementType() - if count == 0 { - return cty.ListValEmpty(ety), nil - } - - vals = make([]cty.Value, count) - for i := 0; i < count; i++ { - key := prefix + strconv.Itoa(i) - val, err := hcl2ValueFromFlatmapValue(m, key, ety) - if err != nil { - return cty.DynamicVal, err - } - vals[i] = val - } - - return cty.ListVal(vals), nil -} - -func hcl2ValueFromFlatmapSet(m map[string]string, prefix string, ty cty.Type) (cty.Value, error) { - var vals []cty.Value - ety := ty.ElementType() - - // if the container is unknown, there is no count string - listName := strings.TrimRight(prefix, ".") - if m[listName] == UnknownVariableValue { - return cty.UnknownVal(ty), nil - } - - strCount, exists := m[prefix+"#"] - if !exists { - return cty.NullVal(ty), nil - } else if strCount == UnknownVariableValue { - return cty.UnknownVal(ty), nil - } - - // Keep track of keys we've seen, se we don't add the same set value - // multiple times. The cty.Set will normally de-duplicate values, but we may - // have unknown values that would not show as equivalent. - seen := map[string]bool{} - - for fullKey := range m { - if !strings.HasPrefix(fullKey, prefix) { - continue - } - subKey := fullKey[len(prefix):] - if subKey == "#" { - // Ignore the "count" key - continue - } - key := fullKey - if dot := strings.IndexByte(subKey, '.'); dot != -1 { - key = fullKey[:dot+len(prefix)] - } - - if seen[key] { - continue - } - - seen[key] = true - - // The flatmap format doesn't allow us to distinguish between keys - // that contain periods and nested objects, so by convention a - // map is only ever of primitive type in flatmap, and we just assume - // that the remainder of the raw key (dots and all) is the key we - // want in the result value. - - val, err := hcl2ValueFromFlatmapValue(m, key, ety) - if err != nil { - return cty.DynamicVal, err - } - vals = append(vals, val) - } - - if len(vals) == 0 && strCount == "1" { - // An empty set wouldn't be represented in the flatmap, so this must be - // a single empty object since the count is actually 1. - // Add an appropriately typed null value to the set. - var val cty.Value - switch { - case ety.IsMapType(): - val = cty.MapValEmpty(ety) - case ety.IsListType(): - val = cty.ListValEmpty(ety) - case ety.IsSetType(): - val = cty.SetValEmpty(ety) - case ety.IsObjectType(): - // TODO: cty.ObjectValEmpty - objectMap := map[string]cty.Value{} - for attr, ty := range ety.AttributeTypes() { - objectMap[attr] = cty.NullVal(ty) - } - val = cty.ObjectVal(objectMap) - default: - val = cty.NullVal(ety) - } - vals = append(vals, val) - - } else if len(vals) == 0 { - return cty.SetValEmpty(ety), nil - } - - return cty.SetVal(vals), nil -} diff --git a/vendor/github.com/hashicorp/terraform/config/hcl2shim/paths.go b/vendor/github.com/hashicorp/terraform/config/hcl2shim/paths.go deleted file mode 100644 index 99437cbb..00000000 --- a/vendor/github.com/hashicorp/terraform/config/hcl2shim/paths.go +++ /dev/null @@ -1,253 +0,0 @@ -package hcl2shim - -import ( - "fmt" - "reflect" - "strconv" - "strings" - - "github.com/zclconf/go-cty/cty" -) - -// RequiresReplace takes a list of flatmapped paths from a -// InstanceDiff.Attributes along with the corresponding cty.Type, and returns -// the list of the cty.Paths that are flagged as causing the resource -// replacement (RequiresNew). -// This will filter out redundant paths, paths that refer to flatmapped indexes -// (e.g. "#", "%"), and will return any changes within a set as the path to the -// set itself. -func RequiresReplace(attrs []string, ty cty.Type) ([]cty.Path, error) { - var paths []cty.Path - - for _, attr := range attrs { - p, err := requiresReplacePath(attr, ty) - if err != nil { - return nil, err - } - - paths = append(paths, p) - } - - // now trim off any trailing paths that aren't GetAttrSteps, since only an - // attribute itself can require replacement - paths = trimPaths(paths) - - // There may be redundant paths due to set elements or index attributes - // Do some ugly n^2 filtering, but these are always fairly small sets. - for i := 0; i < len(paths)-1; i++ { - for j := i + 1; j < len(paths); j++ { - if reflect.DeepEqual(paths[i], paths[j]) { - // swap the tail and slice it off - paths[j], paths[len(paths)-1] = paths[len(paths)-1], paths[j] - paths = paths[:len(paths)-1] - j-- - } - } - } - - return paths, nil -} - -// trimPaths removes any trailing steps that aren't of type GetAttrSet, since -// only an attribute itself can require replacement -func trimPaths(paths []cty.Path) []cty.Path { - var trimmed []cty.Path - for _, path := range paths { - path = trimPath(path) - if len(path) > 0 { - trimmed = append(trimmed, path) - } - } - return trimmed -} - -func trimPath(path cty.Path) cty.Path { - for len(path) > 0 { - _, isGetAttr := path[len(path)-1].(cty.GetAttrStep) - if isGetAttr { - break - } - path = path[:len(path)-1] - } - return path -} - -// requiresReplacePath takes a key from a flatmap along with the cty.Type -// describing the structure, and returns the cty.Path that would be used to -// reference the nested value in the data structure. -// This is used specifically to record the RequiresReplace attributes from a -// ResourceInstanceDiff. -func requiresReplacePath(k string, ty cty.Type) (cty.Path, error) { - if k == "" { - return nil, nil - } - if !ty.IsObjectType() { - panic(fmt.Sprintf("requires replace path on non-object type: %#v", ty)) - } - - path, err := pathFromFlatmapKeyObject(k, ty.AttributeTypes()) - if err != nil { - return path, fmt.Errorf("[%s] %s", k, err) - } - return path, nil -} - -func pathSplit(p string) (string, string) { - parts := strings.SplitN(p, ".", 2) - head := parts[0] - rest := "" - if len(parts) > 1 { - rest = parts[1] - } - return head, rest -} - -func pathFromFlatmapKeyObject(key string, atys map[string]cty.Type) (cty.Path, error) { - k, rest := pathSplit(key) - - path := cty.Path{cty.GetAttrStep{Name: k}} - - ty, ok := atys[k] - if !ok { - return path, fmt.Errorf("attribute %q not found", k) - } - - if rest == "" { - return path, nil - } - - p, err := pathFromFlatmapKeyValue(rest, ty) - if err != nil { - return path, err - } - - return append(path, p...), nil -} - -func pathFromFlatmapKeyValue(key string, ty cty.Type) (cty.Path, error) { - var path cty.Path - var err error - - switch { - case ty.IsPrimitiveType(): - err = fmt.Errorf("invalid step %q with type %#v", key, ty) - case ty.IsObjectType(): - path, err = pathFromFlatmapKeyObject(key, ty.AttributeTypes()) - case ty.IsTupleType(): - path, err = pathFromFlatmapKeyTuple(key, ty.TupleElementTypes()) - case ty.IsMapType(): - path, err = pathFromFlatmapKeyMap(key, ty) - case ty.IsListType(): - path, err = pathFromFlatmapKeyList(key, ty) - case ty.IsSetType(): - path, err = pathFromFlatmapKeySet(key, ty) - default: - err = fmt.Errorf("unrecognized type: %s", ty.FriendlyName()) - } - - if err != nil { - return path, err - } - - return path, nil -} - -func pathFromFlatmapKeyTuple(key string, etys []cty.Type) (cty.Path, error) { - var path cty.Path - var err error - - k, rest := pathSplit(key) - - // we don't need to convert the index keys to paths - if k == "#" { - return path, nil - } - - idx, err := strconv.Atoi(k) - if err != nil { - return path, err - } - - path = cty.Path{cty.IndexStep{Key: cty.NumberIntVal(int64(idx))}} - - if idx >= len(etys) { - return path, fmt.Errorf("index %s out of range in %#v", key, etys) - } - - if rest == "" { - return path, nil - } - - ty := etys[idx] - - p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) - if err != nil { - return path, err - } - - return append(path, p...), nil -} - -func pathFromFlatmapKeyMap(key string, ty cty.Type) (cty.Path, error) { - var path cty.Path - var err error - - k, rest := key, "" - if !ty.ElementType().IsPrimitiveType() { - k, rest = pathSplit(key) - } - - // we don't need to convert the index keys to paths - if k == "%" { - return path, nil - } - - path = cty.Path{cty.IndexStep{Key: cty.StringVal(k)}} - - if rest == "" { - return path, nil - } - - p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) - if err != nil { - return path, err - } - - return append(path, p...), nil -} - -func pathFromFlatmapKeyList(key string, ty cty.Type) (cty.Path, error) { - var path cty.Path - var err error - - k, rest := pathSplit(key) - - // we don't need to convert the index keys to paths - if key == "#" { - return path, nil - } - - idx, err := strconv.Atoi(k) - if err != nil { - return path, err - } - - path = cty.Path{cty.IndexStep{Key: cty.NumberIntVal(int64(idx))}} - - if rest == "" { - return path, nil - } - - p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) - if err != nil { - return path, err - } - - return append(path, p...), nil -} - -func pathFromFlatmapKeySet(key string, ty cty.Type) (cty.Path, error) { - // once we hit a set, we can't return consistent paths, so just mark the - // set as a whole changed. - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform/config/hcl2shim/values.go b/vendor/github.com/hashicorp/terraform/config/hcl2shim/values.go index 2c5b2907..0b697a5f 100644 --- a/vendor/github.com/hashicorp/terraform/config/hcl2shim/values.go +++ b/vendor/github.com/hashicorp/terraform/config/hcl2shim/values.go @@ -6,8 +6,6 @@ import ( "github.com/hashicorp/hil/ast" "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/configs/configschema" ) // UnknownVariableValue is a sentinel value that can be used @@ -16,108 +14,6 @@ import ( // unknown keys. const UnknownVariableValue = "74D93920-ED26-11E3-AC10-0800200C9A66" -// ConfigValueFromHCL2Block is like ConfigValueFromHCL2 but it works only for -// known object values and uses the provided block schema to perform some -// additional normalization to better mimic the shape of value that the old -// HCL1/HIL-based codepaths would've produced. -// -// In particular, it discards the collections that we use to represent nested -// blocks (other than NestingSingle) if they are empty, which better mimics -// the HCL1 behavior because HCL1 had no knowledge of the schema and so didn't -// know that an unspecified block _could_ exist. -// -// The given object value must conform to the schema's implied type or this -// function will panic or produce incorrect results. -// -// This is primarily useful for the final transition from new-style values to -// terraform.ResourceConfig before calling to a legacy provider, since -// helper/schema (the old provider SDK) is particularly sensitive to these -// subtle differences within its validation code. -func ConfigValueFromHCL2Block(v cty.Value, schema *configschema.Block) map[string]interface{} { - if v.IsNull() { - return nil - } - if !v.IsKnown() { - panic("ConfigValueFromHCL2Block used with unknown value") - } - if !v.Type().IsObjectType() { - panic(fmt.Sprintf("ConfigValueFromHCL2Block used with non-object value %#v", v)) - } - - atys := v.Type().AttributeTypes() - ret := make(map[string]interface{}) - - for name := range schema.Attributes { - if _, exists := atys[name]; !exists { - continue - } - - av := v.GetAttr(name) - if av.IsNull() { - // Skip nulls altogether, to better mimic how HCL1 would behave - continue - } - ret[name] = ConfigValueFromHCL2(av) - } - - for name, blockS := range schema.BlockTypes { - if _, exists := atys[name]; !exists { - continue - } - bv := v.GetAttr(name) - if !bv.IsKnown() { - ret[name] = UnknownVariableValue - continue - } - if bv.IsNull() { - continue - } - - switch blockS.Nesting { - - case configschema.NestingSingle: - ret[name] = ConfigValueFromHCL2Block(bv, &blockS.Block) - - case configschema.NestingList, configschema.NestingSet: - l := bv.LengthInt() - if l == 0 { - // skip empty collections to better mimic how HCL1 would behave - continue - } - - elems := make([]interface{}, 0, l) - for it := bv.ElementIterator(); it.Next(); { - _, ev := it.Element() - if !ev.IsKnown() { - elems = append(elems, UnknownVariableValue) - continue - } - elems = append(elems, ConfigValueFromHCL2Block(ev, &blockS.Block)) - } - ret[name] = elems - - case configschema.NestingMap: - if bv.LengthInt() == 0 { - // skip empty collections to better mimic how HCL1 would behave - continue - } - - elems := make(map[string]interface{}) - for it := bv.ElementIterator(); it.Next(); { - ek, ev := it.Element() - if !ev.IsKnown() { - elems[ek.AsString()] = UnknownVariableValue - continue - } - elems[ek.AsString()] = ConfigValueFromHCL2Block(ev, &blockS.Block) - } - ret[name] = elems - } - } - - return ret -} - // ConfigValueFromHCL2 converts a value from HCL2 (really, from the cty dynamic // types library that HCL2 uses) to a value type that matches what would've // been produced from the HCL-based interpolator for an equivalent structure. @@ -177,10 +73,7 @@ func ConfigValueFromHCL2(v cty.Value) interface{} { it := v.ElementIterator() for it.Next() { ek, ev := it.Element() - cv := ConfigValueFromHCL2(ev) - if cv != nil { - l[ek.AsString()] = cv - } + l[ek.AsString()] = ConfigValueFromHCL2(ev) } return l } diff --git a/vendor/github.com/hashicorp/terraform/config/hcl2shim/values_equiv.go b/vendor/github.com/hashicorp/terraform/config/hcl2shim/values_equiv.go deleted file mode 100644 index 92f0213d..00000000 --- a/vendor/github.com/hashicorp/terraform/config/hcl2shim/values_equiv.go +++ /dev/null @@ -1,214 +0,0 @@ -package hcl2shim - -import ( - "github.com/zclconf/go-cty/cty" -) - -// ValuesSDKEquivalent returns true if both of the given values seem equivalent -// as far as the legacy SDK diffing code would be concerned. -// -// Since SDK diffing is a fuzzy, inexact operation, this function is also -// fuzzy and inexact. It will err on the side of returning false if it -// encounters an ambiguous situation. Ambiguity is most common in the presence -// of sets because in practice it is impossible to exactly correlate -// nonequal-but-equivalent set elements because they have no identity separate -// from their value. -// -// This must be used _only_ for comparing values for equivalence within the -// SDK planning code. It is only meaningful to compare the "prior state" -// provided by Terraform Core with the "planned new state" produced by the -// legacy SDK code via shims. In particular it is not valid to use this -// function with their the config value or the "proposed new state" value -// because they contain only the subset of data that Terraform Core itself is -// able to determine. -func ValuesSDKEquivalent(a, b cty.Value) bool { - if a == cty.NilVal || b == cty.NilVal { - // We don't generally expect nils to appear, but we'll allow them - // for robustness since the data structures produced by legacy SDK code - // can sometimes be non-ideal. - return a == b // equivalent if they are _both_ nil - } - if a.RawEquals(b) { - // Easy case. We use RawEquals because we want two unknowns to be - // considered equal here, whereas "Equals" would return unknown. - return true - } - if !a.IsKnown() || !b.IsKnown() { - // Two unknown values are equivalent regardless of type. A known is - // never equivalent to an unknown. - return a.IsKnown() == b.IsKnown() - } - if aZero, bZero := valuesSDKEquivalentIsNullOrZero(a), valuesSDKEquivalentIsNullOrZero(b); aZero || bZero { - // Two null/zero values are equivalent regardless of type. A non-zero is - // never equivalent to a zero. - return aZero == bZero - } - - // If we get down here then we are guaranteed that both a and b are known, - // non-null values. - - aTy := a.Type() - bTy := b.Type() - switch { - case aTy.IsSetType() && bTy.IsSetType(): - return valuesSDKEquivalentSets(a, b) - case aTy.IsListType() && bTy.IsListType(): - return valuesSDKEquivalentSequences(a, b) - case aTy.IsTupleType() && bTy.IsTupleType(): - return valuesSDKEquivalentSequences(a, b) - case aTy.IsMapType() && bTy.IsMapType(): - return valuesSDKEquivalentMappings(a, b) - case aTy.IsObjectType() && bTy.IsObjectType(): - return valuesSDKEquivalentMappings(a, b) - case aTy == cty.Number && bTy == cty.Number: - return valuesSDKEquivalentNumbers(a, b) - default: - // We've now covered all the interesting cases, so anything that falls - // down here cannot be equivalent. - return false - } -} - -// valuesSDKEquivalentIsNullOrZero returns true if the given value is either -// null or is the "zero value" (in the SDK/Go sense) for its type. -func valuesSDKEquivalentIsNullOrZero(v cty.Value) bool { - if v == cty.NilVal { - return true - } - - ty := v.Type() - switch { - case !v.IsKnown(): - return false - case v.IsNull(): - return true - - // After this point, v is always known and non-null - case ty.IsListType() || ty.IsSetType() || ty.IsMapType() || ty.IsObjectType() || ty.IsTupleType(): - return v.LengthInt() == 0 - case ty == cty.String: - return v.RawEquals(cty.StringVal("")) - case ty == cty.Number: - return v.RawEquals(cty.Zero) - case ty == cty.Bool: - return v.RawEquals(cty.False) - default: - // The above is exhaustive, but for robustness we'll consider anything - // else to _not_ be zero unless it is null. - return false - } -} - -// valuesSDKEquivalentSets returns true only if each of the elements in a can -// be correlated with at least one equivalent element in b and vice-versa. -// This is a fuzzy operation that prefers to signal non-equivalence if it cannot -// be certain that all elements are accounted for. -func valuesSDKEquivalentSets(a, b cty.Value) bool { - if aLen, bLen := a.LengthInt(), b.LengthInt(); aLen != bLen { - return false - } - - // Our methodology here is a little tricky, to deal with the fact that - // it's impossible to directly correlate two non-equal set elements because - // they don't have identities separate from their values. - // The approach is to count the number of equivalent elements each element - // of a has in b and vice-versa, and then return true only if each element - // in both sets has at least one equivalent. - as := a.AsValueSlice() - bs := b.AsValueSlice() - aeqs := make([]bool, len(as)) - beqs := make([]bool, len(bs)) - for ai, av := range as { - for bi, bv := range bs { - if ValuesSDKEquivalent(av, bv) { - aeqs[ai] = true - beqs[bi] = true - } - } - } - - for _, eq := range aeqs { - if !eq { - return false - } - } - for _, eq := range beqs { - if !eq { - return false - } - } - return true -} - -// valuesSDKEquivalentSequences decides equivalence for two sequence values -// (lists or tuples). -func valuesSDKEquivalentSequences(a, b cty.Value) bool { - as := a.AsValueSlice() - bs := b.AsValueSlice() - if len(as) != len(bs) { - return false - } - - for i := range as { - if !ValuesSDKEquivalent(as[i], bs[i]) { - return false - } - } - return true -} - -// valuesSDKEquivalentMappings decides equivalence for two mapping values -// (maps or objects). -func valuesSDKEquivalentMappings(a, b cty.Value) bool { - as := a.AsValueMap() - bs := b.AsValueMap() - if len(as) != len(bs) { - return false - } - - for k, av := range as { - bv, ok := bs[k] - if !ok { - return false - } - if !ValuesSDKEquivalent(av, bv) { - return false - } - } - return true -} - -// valuesSDKEquivalentNumbers decides equivalence for two number values based -// on the fact that the SDK uses int and float64 representations while -// cty (and thus Terraform Core) uses big.Float, and so we expect to lose -// precision in the round-trip. -// -// This does _not_ attempt to allow for an epsilon difference that may be -// caused by accumulated innacuracy in a float calculation, under the -// expectation that providers generally do not actually do compuations on -// floats and instead just pass string representations of them on verbatim -// to remote APIs. A remote API _itself_ may introduce inaccuracy, but that's -// a problem for the provider itself to deal with, based on its knowledge of -// the remote system, e.g. using DiffSuppressFunc. -func valuesSDKEquivalentNumbers(a, b cty.Value) bool { - if a.RawEquals(b) { - return true // easy - } - - af := a.AsBigFloat() - bf := b.AsBigFloat() - - if af.IsInt() != bf.IsInt() { - return false - } - if af.IsInt() && bf.IsInt() { - return false // a.RawEquals(b) test above is good enough for integers - } - - // The SDK supports only int and float64, so if it's not an integer - // we know that only a float64-level of precision can possibly be - // significant. - af64, _ := af.Float64() - bf64, _ := bf.Float64() - return af64 == bf64 -} diff --git a/vendor/github.com/hashicorp/terraform/config/interpolate_funcs.go b/vendor/github.com/hashicorp/terraform/config/interpolate_funcs.go index faa077ee..b94fca88 100644 --- a/vendor/github.com/hashicorp/terraform/config/interpolate_funcs.go +++ b/vendor/github.com/hashicorp/terraform/config/interpolate_funcs.go @@ -47,20 +47,6 @@ func stringSliceToVariableValue(values []string) []ast.Variable { return output } -// listVariableSliceToVariableValue converts a list of lists into the value -// required to be returned from interpolation functions which return TypeList. -func listVariableSliceToVariableValue(values [][]ast.Variable) []ast.Variable { - output := make([]ast.Variable, len(values)) - - for index, value := range values { - output[index] = ast.Variable{ - Type: ast.TypeList, - Value: value, - } - } - return output -} - func listVariableValueToStringSlice(values []ast.Variable) ([]string, error) { output := make([]string, len(values)) for index, value := range values { diff --git a/vendor/github.com/hashicorp/terraform/config/module/storage.go b/vendor/github.com/hashicorp/terraform/config/module/storage.go index 7734cbc0..4b828dcb 100644 --- a/vendor/github.com/hashicorp/terraform/config/module/storage.go +++ b/vendor/github.com/hashicorp/terraform/config/module/storage.go @@ -312,7 +312,7 @@ func (s Storage) findRegistryModule(mSource, constraint string) (moduleRecord, e // we need to lookup available versions // Only on Get if it's not found, on unconditionally on Update if (s.Mode == GetModeGet && !found) || (s.Mode == GetModeUpdate) { - resp, err := s.registry.ModuleVersions(mod) + resp, err := s.registry.Versions(mod) if err != nil { return rec, err } @@ -332,7 +332,7 @@ func (s Storage) findRegistryModule(mSource, constraint string) (moduleRecord, e rec.Version = match.Version - rec.url, err = s.registry.ModuleLocation(mod, rec.Version) + rec.url, err = s.registry.Location(mod, rec.Version) if err != nil { return rec, err } diff --git a/vendor/github.com/hashicorp/terraform/configs/backend.go b/vendor/github.com/hashicorp/terraform/configs/backend.go deleted file mode 100644 index 6df7ddd0..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/backend.go +++ /dev/null @@ -1,55 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcldec" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// Backend represents a "backend" block inside a "terraform" block in a module -// or file. -type Backend struct { - Type string - Config hcl.Body - - TypeRange hcl.Range - DeclRange hcl.Range -} - -func decodeBackendBlock(block *hcl.Block) (*Backend, hcl.Diagnostics) { - return &Backend{ - Type: block.Labels[0], - TypeRange: block.LabelRanges[0], - Config: block.Body, - DeclRange: block.DefRange, - }, nil -} - -// Hash produces a hash value for the reciever that covers the type and the -// portions of the config that conform to the given schema. -// -// If the config does not conform to the schema then the result is not -// meaningful for comparison since it will be based on an incomplete result. -// -// As an exception, required attributes in the schema are treated as optional -// for the purpose of hashing, so that an incomplete configuration can still -// be hashed. Other errors, such as extraneous attributes, have no such special -// case. -func (b *Backend) Hash(schema *configschema.Block) int { - // Don't fail if required attributes are not set. Instead, we'll just - // hash them as nulls. - schema = schema.NoneRequired() - spec := schema.DecoderSpec() - val, _ := hcldec.Decode(b.Config, spec, nil) - if val == cty.NilVal { - val = cty.UnknownVal(schema.ImpliedType()) - } - - toHash := cty.TupleVal([]cty.Value{ - cty.StringVal(b.Type), - val, - }) - - return toHash.Hash() -} diff --git a/vendor/github.com/hashicorp/terraform/configs/compat_shim.go b/vendor/github.com/hashicorp/terraform/configs/compat_shim.go deleted file mode 100644 index 66037fcd..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/compat_shim.go +++ /dev/null @@ -1,116 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - "github.com/zclconf/go-cty/cty" -) - -// ------------------------------------------------------------------------- -// Functions in this file are compatibility shims intended to ease conversion -// from the old configuration loader. Any use of these functions that makes -// a change should generate a deprecation warning explaining to the user how -// to update their code for new patterns. -// -// Shims are particularly important for any patterns that have been widely -// documented in books, tutorials, etc. Users will still be starting from -// these examples and we want to help them adopt the latest patterns rather -// than leave them stranded. -// ------------------------------------------------------------------------- - -// shimTraversalInString takes any arbitrary expression and checks if it is -// a quoted string in the native syntax. If it _is_, then it is parsed as a -// traversal and re-wrapped into a synthetic traversal expression and a -// warning is generated. Otherwise, the given expression is just returned -// verbatim. -// -// This function has no effect on expressions from the JSON syntax, since -// traversals in strings are the required pattern in that syntax. -// -// If wantKeyword is set, the generated warning diagnostic will talk about -// keywords rather than references. The behavior is otherwise unchanged, and -// the caller remains responsible for checking that the result is indeed -// a keyword, e.g. using hcl.ExprAsKeyword. -func shimTraversalInString(expr hcl.Expression, wantKeyword bool) (hcl.Expression, hcl.Diagnostics) { - // ObjectConsKeyExpr is a special wrapper type used for keys on object - // constructors to deal with the fact that naked identifiers are normally - // handled as "bareword" strings rather than as variable references. Since - // we know we're interpreting as a traversal anyway (and thus it won't - // matter whether it's a string or an identifier) we can safely just unwrap - // here and then process whatever we find inside as normal. - if ocke, ok := expr.(*hclsyntax.ObjectConsKeyExpr); ok { - expr = ocke.Wrapped - } - - if !exprIsNativeQuotedString(expr) { - return expr, nil - } - - strVal, diags := expr.Value(nil) - if diags.HasErrors() || strVal.IsNull() || !strVal.IsKnown() { - // Since we're not even able to attempt a shim here, we'll discard - // the diagnostics we saw so far and let the caller's own error - // handling take care of reporting the invalid expression. - return expr, nil - } - - // The position handling here isn't _quite_ right because it won't - // take into account any escape sequences in the literal string, but - // it should be close enough for any error reporting to make sense. - srcRange := expr.Range() - startPos := srcRange.Start // copy - startPos.Column++ // skip initial quote - startPos.Byte++ // skip initial quote - - traversal, tDiags := hclsyntax.ParseTraversalAbs( - []byte(strVal.AsString()), - srcRange.Filename, - startPos, - ) - diags = append(diags, tDiags...) - - // For initial release our deprecation warnings are disabled to allow - // a period where modules can be compatible with both old and new - // conventions. - // FIXME: Re-enable these deprecation warnings in a release prior to - // Terraform 0.13 and then remove the shims altogether for 0.13. - /* - if wantKeyword { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted keywords are deprecated", - Detail: "In this context, keywords are expected literally rather than in quotes. Previous versions of Terraform required quotes, but that usage is now deprecated. Remove the quotes surrounding this keyword to silence this warning.", - Subject: &srcRange, - }) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted references are deprecated", - Detail: "In this context, references are expected literally rather than in quotes. Previous versions of Terraform required quotes, but that usage is now deprecated. Remove the quotes surrounding this reference to silence this warning.", - Subject: &srcRange, - }) - } - */ - - return &hclsyntax.ScopeTraversalExpr{ - Traversal: traversal, - SrcRange: srcRange, - }, diags -} - -// shimIsIgnoreChangesStar returns true if the given expression seems to be -// a string literal whose value is "*". This is used to support a legacy -// form of ignore_changes = all . -// -// This function does not itself emit any diagnostics, so it's the caller's -// responsibility to emit a warning diagnostic when this function returns true. -func shimIsIgnoreChangesStar(expr hcl.Expression) bool { - val, valDiags := expr.Value(nil) - if valDiags.HasErrors() { - return false - } - if val.Type() != cty.String || val.IsNull() || !val.IsKnown() { - return false - } - return val.AsString() == "*" -} diff --git a/vendor/github.com/hashicorp/terraform/configs/config.go b/vendor/github.com/hashicorp/terraform/configs/config.go deleted file mode 100644 index e068cbc3..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/config.go +++ /dev/null @@ -1,205 +0,0 @@ -package configs - -import ( - "sort" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/addrs" -) - -// A Config is a node in the tree of modules within a configuration. -// -// The module tree is constructed by following ModuleCall instances recursively -// through the root module transitively into descendent modules. -// -// A module tree described in *this* package represents the static tree -// represented by configuration. During evaluation a static ModuleNode may -// expand into zero or more module instances depending on the use of count and -// for_each configuration attributes within each call. -type Config struct { - // RootModule points to the Config for the root module within the same - // module tree as this module. If this module _is_ the root module then - // this is self-referential. - Root *Config - - // ParentModule points to the Config for the module that directly calls - // this module. If this is the root module then this field is nil. - Parent *Config - - // Path is a sequence of module logical names that traverse from the root - // module to this config. Path is empty for the root module. - // - // This should only be used to display paths to the end-user in rare cases - // where we are talking about the static module tree, before module calls - // have been resolved. In most cases, a addrs.ModuleInstance describing - // a node in the dynamic module tree is better, since it will then include - // any keys resulting from evaluating "count" and "for_each" arguments. - Path addrs.Module - - // ChildModules points to the Config for each of the direct child modules - // called from this module. The keys in this map match the keys in - // Module.ModuleCalls. - Children map[string]*Config - - // Module points to the object describing the configuration for the - // various elements (variables, resources, etc) defined by this module. - Module *Module - - // CallRange is the source range for the header of the module block that - // requested this module. - // - // This field is meaningless for the root module, where its contents are undefined. - CallRange hcl.Range - - // SourceAddr is the source address that the referenced module was requested - // from, as specified in configuration. - // - // This field is meaningless for the root module, where its contents are undefined. - SourceAddr string - - // SourceAddrRange is the location in the configuration source where the - // SourceAddr value was set, for use in diagnostic messages. - // - // This field is meaningless for the root module, where its contents are undefined. - SourceAddrRange hcl.Range - - // Version is the specific version that was selected for this module, - // based on version constraints given in configuration. - // - // This field is nil if the module was loaded from a non-registry source, - // since versions are not supported for other sources. - // - // This field is meaningless for the root module, where it will always - // be nil. - Version *version.Version -} - -// NewEmptyConfig constructs a single-node configuration tree with an empty -// root module. This is generally a pretty useless thing to do, so most callers -// should instead use BuildConfig. -func NewEmptyConfig() *Config { - ret := &Config{} - ret.Root = ret - ret.Children = make(map[string]*Config) - ret.Module = &Module{} - return ret -} - -// Depth returns the number of "hops" the receiver is from the root of its -// module tree, with the root module having a depth of zero. -func (c *Config) Depth() int { - ret := 0 - this := c - for this.Parent != nil { - ret++ - this = this.Parent - } - return ret -} - -// DeepEach calls the given function once for each module in the tree, starting -// with the receiver. -// -// A parent is always called before its children and children of a particular -// node are visited in lexicographic order by their names. -func (c *Config) DeepEach(cb func(c *Config)) { - cb(c) - - names := make([]string, 0, len(c.Children)) - for name := range c.Children { - names = append(names, name) - } - - for _, name := range names { - c.Children[name].DeepEach(cb) - } -} - -// AllModules returns a slice of all the receiver and all of its descendent -// nodes in the module tree, in the same order they would be visited by -// DeepEach. -func (c *Config) AllModules() []*Config { - var ret []*Config - c.DeepEach(func(c *Config) { - ret = append(ret, c) - }) - return ret -} - -// Descendent returns the descendent config that has the given path beneath -// the receiver, or nil if there is no such module. -// -// The path traverses the static module tree, prior to any expansion to handle -// count and for_each arguments. -// -// An empty path will just return the receiver, and is therefore pointless. -func (c *Config) Descendent(path addrs.Module) *Config { - current := c - for _, name := range path { - current = current.Children[name] - if current == nil { - return nil - } - } - return current -} - -// DescendentForInstance is like Descendent except that it accepts a path -// to a particular module instance in the dynamic module graph, returning -// the node from the static module graph that corresponds to it. -// -// All instances created by a particular module call share the same -// configuration, so the keys within the given path are disregarded. -func (c *Config) DescendentForInstance(path addrs.ModuleInstance) *Config { - current := c - for _, step := range path { - current = current.Children[step.Name] - if current == nil { - return nil - } - } - return current -} - -// ProviderTypes returns the names of each distinct provider type referenced -// in the receiving configuration. -// -// This is a helper for easily determining which provider types are required -// to fully interpret the configuration, though it does not include version -// information and so callers are expected to have already dealt with -// provider version selection in an earlier step and have identified suitable -// versions for each provider. -func (c *Config) ProviderTypes() []string { - m := make(map[string]struct{}) - c.gatherProviderTypes(m) - - ret := make([]string, 0, len(m)) - for k := range m { - ret = append(ret, k) - } - sort.Strings(ret) - return ret -} -func (c *Config) gatherProviderTypes(m map[string]struct{}) { - if c == nil { - return - } - - for _, pc := range c.Module.ProviderConfigs { - m[pc.Name] = struct{}{} - } - for _, rc := range c.Module.ManagedResources { - providerAddr := rc.ProviderConfigAddr() - m[providerAddr.Type] = struct{}{} - } - for _, rc := range c.Module.DataResources { - providerAddr := rc.ProviderConfigAddr() - m[providerAddr.Type] = struct{}{} - } - - // Must also visit our child modules, recursively. - for _, cc := range c.Children { - cc.gatherProviderTypes(m) - } -} diff --git a/vendor/github.com/hashicorp/terraform/configs/config_build.go b/vendor/github.com/hashicorp/terraform/configs/config_build.go deleted file mode 100644 index 948b2c8f..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/config_build.go +++ /dev/null @@ -1,179 +0,0 @@ -package configs - -import ( - "sort" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/addrs" -) - -// BuildConfig constructs a Config from a root module by loading all of its -// descendent modules via the given ModuleWalker. -// -// The result is a module tree that has so far only had basic module- and -// file-level invariants validated. If the returned diagnostics contains errors, -// the returned module tree may be incomplete but can still be used carefully -// for static analysis. -func BuildConfig(root *Module, walker ModuleWalker) (*Config, hcl.Diagnostics) { - var diags hcl.Diagnostics - cfg := &Config{ - Module: root, - } - cfg.Root = cfg // Root module is self-referential. - cfg.Children, diags = buildChildModules(cfg, walker) - return cfg, diags -} - -func buildChildModules(parent *Config, walker ModuleWalker) (map[string]*Config, hcl.Diagnostics) { - var diags hcl.Diagnostics - ret := map[string]*Config{} - - calls := parent.Module.ModuleCalls - - // We'll sort the calls by their local names so that they'll appear in a - // predictable order in any logging that's produced during the walk. - callNames := make([]string, 0, len(calls)) - for k := range calls { - callNames = append(callNames, k) - } - sort.Strings(callNames) - - for _, callName := range callNames { - call := calls[callName] - path := make([]string, len(parent.Path)+1) - copy(path, parent.Path) - path[len(path)-1] = call.Name - - req := ModuleRequest{ - Name: call.Name, - Path: path, - SourceAddr: call.SourceAddr, - SourceAddrRange: call.SourceAddrRange, - VersionConstraint: call.Version, - Parent: parent, - CallRange: call.DeclRange, - } - - mod, ver, modDiags := walker.LoadModule(&req) - diags = append(diags, modDiags...) - if mod == nil { - // nil can be returned if the source address was invalid and so - // nothing could be loaded whatsoever. LoadModule should've - // returned at least one error diagnostic in that case. - continue - } - - child := &Config{ - Parent: parent, - Root: parent.Root, - Path: path, - Module: mod, - CallRange: call.DeclRange, - SourceAddr: call.SourceAddr, - SourceAddrRange: call.SourceAddrRange, - Version: ver, - } - - child.Children, modDiags = buildChildModules(child, walker) - - ret[call.Name] = child - } - - return ret, diags -} - -// A ModuleWalker knows how to find and load a child module given details about -// the module to be loaded and a reference to its partially-loaded parent -// Config. -type ModuleWalker interface { - // LoadModule finds and loads a requested child module. - // - // If errors are detected during loading, implementations should return them - // in the diagnostics object. If the diagnostics object contains any errors - // then the caller will tolerate the returned module being nil or incomplete. - // If no errors are returned, it should be non-nil and complete. - // - // Full validation need not have been performed but an implementation should - // ensure that the basic file- and module-validations performed by the - // LoadConfigDir function (valid syntax, no namespace collisions, etc) have - // been performed before returning a module. - LoadModule(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) -} - -// ModuleWalkerFunc is an implementation of ModuleWalker that directly wraps -// a callback function, for more convenient use of that interface. -type ModuleWalkerFunc func(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) - -// LoadModule implements ModuleWalker. -func (f ModuleWalkerFunc) LoadModule(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) { - return f(req) -} - -// ModuleRequest is used with the ModuleWalker interface to describe a child -// module that must be loaded. -type ModuleRequest struct { - // Name is the "logical name" of the module call within configuration. - // This is provided in case the name is used as part of a storage key - // for the module, but implementations must otherwise treat it as an - // opaque string. It is guaranteed to have already been validated as an - // HCL identifier and UTF-8 encoded. - Name string - - // Path is a list of logical names that traverse from the root module to - // this module. This can be used, for example, to form a lookup key for - // each distinct module call in a configuration, allowing for multiple - // calls with the same name at different points in the tree. - Path addrs.Module - - // SourceAddr is the source address string provided by the user in - // configuration. - SourceAddr string - - // SourceAddrRange is the source range for the SourceAddr value as it - // was provided in configuration. This can and should be used to generate - // diagnostics about the source address having invalid syntax, referring - // to a non-existent object, etc. - SourceAddrRange hcl.Range - - // VersionConstraint is the version constraint applied to the module in - // configuration. This data structure includes the source range for - // the constraint, which can and should be used to generate diagnostics - // about constraint-related issues, such as constraints that eliminate all - // available versions of a module whose source is otherwise valid. - VersionConstraint VersionConstraint - - // Parent is the partially-constructed module tree node that the loaded - // module will be added to. Callers may refer to any field of this - // structure except Children, which is still under construction when - // ModuleRequest objects are created and thus has undefined content. - // The main reason this is provided is so that full module paths can - // be constructed for uniqueness. - Parent *Config - - // CallRange is the source range for the header of the "module" block - // in configuration that prompted this request. This can be used as the - // subject of an error diagnostic that relates to the module call itself, - // rather than to either its source address or its version number. - CallRange hcl.Range -} - -// DisabledModuleWalker is a ModuleWalker that doesn't support -// child modules at all, and so will return an error if asked to load one. -// -// This is provided primarily for testing. There is no good reason to use this -// in the main application. -var DisabledModuleWalker ModuleWalker - -func init() { - DisabledModuleWalker = ModuleWalkerFunc(func(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) { - return nil, nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Child modules are not supported", - Detail: "Child module calls are not allowed in this context.", - Subject: &req.CallRange, - }, - } - }) -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/copy_dir.go b/vendor/github.com/hashicorp/terraform/configs/configload/copy_dir.go deleted file mode 100644 index ad34a320..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/copy_dir.go +++ /dev/null @@ -1,114 +0,0 @@ -package configload - -import ( - "io" - "os" - "path/filepath" - "strings" -) - -// copyDir copies the src directory contents into dst. Both directories -// should already exist. -func copyDir(dst, src string) error { - src, err := filepath.EvalSymlinks(src) - if err != nil { - return err - } - - walkFn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if path == src { - return nil - } - - if strings.HasPrefix(filepath.Base(path), ".") { - // Skip any dot files - if info.IsDir() { - return filepath.SkipDir - } else { - return nil - } - } - - // The "path" has the src prefixed to it. We need to join our - // destination with the path without the src on it. - dstPath := filepath.Join(dst, path[len(src):]) - - // we don't want to try and copy the same file over itself. - if eq, err := sameFile(path, dstPath); eq { - return nil - } else if err != nil { - return err - } - - // If we have a directory, make that subdirectory, then continue - // the walk. - if info.IsDir() { - if path == filepath.Join(src, dst) { - // dst is in src; don't walk it. - return nil - } - - if err := os.MkdirAll(dstPath, 0755); err != nil { - return err - } - - return nil - } - - // If we have a file, copy the contents. - srcF, err := os.Open(path) - if err != nil { - return err - } - defer srcF.Close() - - dstF, err := os.Create(dstPath) - if err != nil { - return err - } - defer dstF.Close() - - if _, err := io.Copy(dstF, srcF); err != nil { - return err - } - - // Chmod it - return os.Chmod(dstPath, info.Mode()) - } - - return filepath.Walk(src, walkFn) -} - -// sameFile tried to determine if to paths are the same file. -// If the paths don't match, we lookup the inode on supported systems. -func sameFile(a, b string) (bool, error) { - if a == b { - return true, nil - } - - aIno, err := inode(a) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - bIno, err := inode(b) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - if aIno > 0 && aIno == bIno { - return true, nil - } - - return false, nil -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/doc.go b/vendor/github.com/hashicorp/terraform/configs/configload/doc.go deleted file mode 100644 index 8b615f90..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package configload knows how to install modules into the .terraform/modules -// directory and to load modules from those installed locations. It is used -// in conjunction with the LoadConfig function in the parent package. -package configload diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/getter.go b/vendor/github.com/hashicorp/terraform/configs/configload/getter.go deleted file mode 100644 index 4a3dacee..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/getter.go +++ /dev/null @@ -1,150 +0,0 @@ -package configload - -import ( - "fmt" - "log" - "os" - "path/filepath" - - cleanhttp "github.com/hashicorp/go-cleanhttp" - getter "github.com/hashicorp/go-getter" -) - -// We configure our own go-getter detector and getter sets here, because -// the set of sources we support is part of Terraform's documentation and -// so we don't want any new sources introduced in go-getter to sneak in here -// and work even though they aren't documented. This also insulates us from -// any meddling that might be done by other go-getter callers linked into our -// executable. - -var goGetterDetectors = []getter.Detector{ - new(getter.GitHubDetector), - new(getter.BitBucketDetector), - new(getter.S3Detector), - new(getter.FileDetector), -} - -var goGetterNoDetectors = []getter.Detector{} - -var goGetterDecompressors = map[string]getter.Decompressor{ - "bz2": new(getter.Bzip2Decompressor), - "gz": new(getter.GzipDecompressor), - "xz": new(getter.XzDecompressor), - "zip": new(getter.ZipDecompressor), - - "tar.bz2": new(getter.TarBzip2Decompressor), - "tar.tbz2": new(getter.TarBzip2Decompressor), - - "tar.gz": new(getter.TarGzipDecompressor), - "tgz": new(getter.TarGzipDecompressor), - - "tar.xz": new(getter.TarXzDecompressor), - "txz": new(getter.TarXzDecompressor), -} - -var goGetterGetters = map[string]getter.Getter{ - "file": new(getter.FileGetter), - "git": new(getter.GitGetter), - "hg": new(getter.HgGetter), - "s3": new(getter.S3Getter), - "http": getterHTTPGetter, - "https": getterHTTPGetter, -} - -var getterHTTPClient = cleanhttp.DefaultClient() - -var getterHTTPGetter = &getter.HttpGetter{ - Client: getterHTTPClient, - Netrc: true, -} - -// A reusingGetter is a helper for the module installer that remembers -// the final resolved addresses of all of the sources it has already been -// asked to install, and will copy from a prior installation directory if -// it has the same resolved source address. -// -// The keys in a reusingGetter are resolved and trimmed source addresses -// (with a scheme always present, and without any "subdir" component), -// and the values are the paths where each source was previously installed. -type reusingGetter map[string]string - -// getWithGoGetter retrieves the package referenced in the given address -// into the installation path and then returns the full path to any subdir -// indicated in the address. -// -// The errors returned by this function are those surfaced by the underlying -// go-getter library, which have very inconsistent quality as -// end-user-actionable error messages. At this time we do not have any -// reasonable way to improve these error messages at this layer because -// the underlying errors are not separatelyr recognizable. -func (g reusingGetter) getWithGoGetter(instPath, addr string) (string, error) { - packageAddr, subDir := splitAddrSubdir(addr) - - log.Printf("[DEBUG] will download %q to %s", packageAddr, instPath) - - realAddr, err := getter.Detect(packageAddr, instPath, getter.Detectors) - if err != nil { - return "", err - } - - var realSubDir string - realAddr, realSubDir = splitAddrSubdir(realAddr) - if realSubDir != "" { - subDir = filepath.Join(realSubDir, subDir) - } - - if realAddr != packageAddr { - log.Printf("[TRACE] go-getter detectors rewrote %q to %q", packageAddr, realAddr) - } - - if prevDir, exists := g[realAddr]; exists { - log.Printf("[TRACE] copying previous install %s to %s", prevDir, instPath) - err := os.Mkdir(instPath, os.ModePerm) - if err != nil { - return "", fmt.Errorf("failed to create directory %s: %s", instPath, err) - } - err = copyDir(instPath, prevDir) - if err != nil { - return "", fmt.Errorf("failed to copy from %s to %s: %s", prevDir, instPath, err) - } - } else { - log.Printf("[TRACE] fetching %q to %q", realAddr, instPath) - client := getter.Client{ - Src: realAddr, - Dst: instPath, - Pwd: instPath, - - Mode: getter.ClientModeDir, - - Detectors: goGetterNoDetectors, // we already did detection above - Decompressors: goGetterDecompressors, - Getters: goGetterGetters, - } - err = client.Get() - if err != nil { - return "", err - } - // Remember where we installed this so we might reuse this directory - // on subsequent calls to avoid re-downloading. - g[realAddr] = instPath - } - - // Our subDir string can contain wildcards until this point, so that - // e.g. a subDir of * can expand to one top-level directory in a .tar.gz - // archive. Now that we've expanded the archive successfully we must - // resolve that into a concrete path. - var finalDir string - if subDir != "" { - finalDir, err = getter.SubdirGlob(instPath, subDir) - log.Printf("[TRACE] expanded %q to %q", subDir, finalDir) - if err != nil { - return "", err - } - } else { - finalDir = instPath - } - - // If we got this far then we have apparently succeeded in downloading - // the requested object! - return filepath.Clean(finalDir), nil -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/inode.go b/vendor/github.com/hashicorp/terraform/configs/configload/inode.go deleted file mode 100644 index 57df0414..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/inode.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build linux darwin openbsd netbsd solaris dragonfly - -package configload - -import ( - "fmt" - "os" - "syscall" -) - -// lookup the inode of a file on posix systems -func inode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - if st, ok := stat.Sys().(*syscall.Stat_t); ok { - return st.Ino, nil - } - return 0, fmt.Errorf("could not determine file inode") -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/inode_freebsd.go b/vendor/github.com/hashicorp/terraform/configs/configload/inode_freebsd.go deleted file mode 100644 index 4dc28eaa..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/inode_freebsd.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build freebsd - -package configload - -import ( - "fmt" - "os" - "syscall" -) - -// lookup the inode of a file on posix systems -func inode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - if st, ok := stat.Sys().(*syscall.Stat_t); ok { - return uint64(st.Ino), nil - } - return 0, fmt.Errorf("could not determine file inode") -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/inode_windows.go b/vendor/github.com/hashicorp/terraform/configs/configload/inode_windows.go deleted file mode 100644 index 0d22e672..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/inode_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build windows - -package configload - -// no syscall.Stat_t on windows, return 0 for inodes -func inode(path string) (uint64, error) { - return 0, nil -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/loader.go b/vendor/github.com/hashicorp/terraform/configs/configload/loader.go deleted file mode 100644 index 416b48fc..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/loader.go +++ /dev/null @@ -1,150 +0,0 @@ -package configload - -import ( - "fmt" - "path/filepath" - - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/registry" - "github.com/hashicorp/terraform/svchost/disco" - "github.com/spf13/afero" -) - -// A Loader instance is the main entry-point for loading configurations via -// this package. -// -// It extends the general config-loading functionality in the parent package -// "configs" to support installation of modules from remote sources and -// loading full configurations using modules that were previously installed. -type Loader struct { - // parser is used to read configuration - parser *configs.Parser - - // modules is used to install and locate descendent modules that are - // referenced (directly or indirectly) from the root module. - modules moduleMgr -} - -// Config is used with NewLoader to specify configuration arguments for the -// loader. -type Config struct { - // ModulesDir is a path to a directory where descendent modules are - // (or should be) installed. (This is usually the - // .terraform/modules directory, in the common case where this package - // is being loaded from the main Terraform CLI package.) - ModulesDir string - - // Services is the service discovery client to use when locating remote - // module registry endpoints. If this is nil then registry sources are - // not supported, which should be true only in specialized circumstances - // such as in tests. - Services *disco.Disco -} - -// NewLoader creates and returns a loader that reads configuration from the -// real OS filesystem. -// -// The loader has some internal state about the modules that are currently -// installed, which is read from disk as part of this function. If that -// manifest cannot be read then an error will be returned. -func NewLoader(config *Config) (*Loader, error) { - fs := afero.NewOsFs() - parser := configs.NewParser(fs) - reg := registry.NewClient(config.Services, nil) - - ret := &Loader{ - parser: parser, - modules: moduleMgr{ - FS: afero.Afero{Fs: fs}, - CanInstall: true, - Dir: config.ModulesDir, - Services: config.Services, - Registry: reg, - }, - } - - err := ret.modules.readModuleManifestSnapshot() - if err != nil { - return nil, fmt.Errorf("failed to read module manifest: %s", err) - } - - return ret, nil -} - -// ModulesDir returns the path to the directory where the loader will look for -// the local cache of remote module packages. -func (l *Loader) ModulesDir() string { - return l.modules.Dir -} - -// RefreshModules updates the in-memory cache of the module manifest from the -// module manifest file on disk. This is not necessary in normal use because -// module installation and configuration loading are separate steps, but it -// can be useful in tests where module installation is done as a part of -// configuration loading by a helper function. -// -// Call this function after any module installation where an existing loader -// is already alive and may be used again later. -// -// An error is returned if the manifest file cannot be read. -func (l *Loader) RefreshModules() error { - if l == nil { - // Nothing to do, then. - return nil - } - return l.modules.readModuleManifestSnapshot() -} - -// Parser returns the underlying parser for this loader. -// -// This is useful for loading other sorts of files than the module directories -// that a loader deals with, since then they will share the source code cache -// for this loader and can thus be shown as snippets in diagnostic messages. -func (l *Loader) Parser() *configs.Parser { - return l.parser -} - -// Sources returns the source code cache for the underlying parser of this -// loader. This is a shorthand for l.Parser().Sources(). -func (l *Loader) Sources() map[string][]byte { - return l.parser.Sources() -} - -// IsConfigDir returns true if and only if the given directory contains at -// least one Terraform configuration file. This is a wrapper around calling -// the same method name on the loader's parser. -func (l *Loader) IsConfigDir(path string) bool { - return l.parser.IsConfigDir(path) -} - -// ImportSources writes into the receiver's source code the given source -// code buffers. -// -// This is useful in the situation where an ancillary loader is created for -// some reason (e.g. loading config from a plan file) but the cached source -// code from that loader must be imported into the "main" loader in order -// to return source code snapshots in diagnostic messages. -// -// loader.ImportSources(otherLoader.Sources()) -func (l *Loader) ImportSources(sources map[string][]byte) { - p := l.Parser() - for name, src := range sources { - p.ForceFileSource(name, src) - } -} - -// ImportSourcesFromSnapshot writes into the receiver's source code the -// source files from the given snapshot. -// -// This is similar to ImportSources but knows how to unpack and flatten a -// snapshot data structure to get the corresponding flat source file map. -func (l *Loader) ImportSourcesFromSnapshot(snap *Snapshot) { - p := l.Parser() - for _, m := range snap.Modules { - baseDir := m.Dir - for fn, src := range m.Files { - fullPath := filepath.Join(baseDir, fn) - p.ForceFileSource(fullPath, src) - } - } -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/loader_load.go b/vendor/github.com/hashicorp/terraform/configs/configload/loader_load.go deleted file mode 100644 index 93a94204..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/loader_load.go +++ /dev/null @@ -1,97 +0,0 @@ -package configload - -import ( - "fmt" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/configs" -) - -// LoadConfig reads the Terraform module in the given directory and uses it as the -// root module to build the static module tree that represents a configuration, -// assuming that all required descendent modules have already been installed. -// -// If error diagnostics are returned, the returned configuration may be either -// nil or incomplete. In the latter case, cautious static analysis is possible -// in spite of the errors. -// -// LoadConfig performs the basic syntax and uniqueness validations that are -// required to process the individual modules, and also detects -func (l *Loader) LoadConfig(rootDir string) (*configs.Config, hcl.Diagnostics) { - rootMod, diags := l.parser.LoadConfigDir(rootDir) - if rootMod == nil { - return nil, diags - } - - cfg, cDiags := configs.BuildConfig(rootMod, configs.ModuleWalkerFunc(l.moduleWalkerLoad)) - diags = append(diags, cDiags...) - - return cfg, diags -} - -// moduleWalkerLoad is a configs.ModuleWalkerFunc for loading modules that -// are presumed to have already been installed. A different function -// (moduleWalkerInstall) is used for installation. -func (l *Loader) moduleWalkerLoad(req *configs.ModuleRequest) (*configs.Module, *version.Version, hcl.Diagnostics) { - // Since we're just loading here, we expect that all referenced modules - // will be already installed and described in our manifest. However, we - // do verify that the manifest and the configuration are in agreement - // so that we can prompt the user to run "terraform init" if not. - - key := l.modules.manifest.ModuleKey(req.Path) - record, exists := l.modules.manifest[key] - - if !exists { - return nil, nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Module not installed", - Detail: "This module is not yet installed. Run \"terraform init\" to install all modules required by this configuration.", - Subject: &req.CallRange, - }, - } - } - - var diags hcl.Diagnostics - - // Check for inconsistencies between manifest and config - if req.SourceAddr != record.SourceAddr { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Module source has changed", - Detail: "The source address was changed since this module was installed. Run \"terraform init\" to install all modules required by this configuration.", - Subject: &req.SourceAddrRange, - }) - } - if !req.VersionConstraint.Required.Check(record.Version) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Module version requirements have changed", - Detail: fmt.Sprintf( - "The version requirements have changed since this module was installed and the installed version (%s) is no longer acceptable. Run \"terraform init\" to install all modules required by this configuration.", - record.Version, - ), - Subject: &req.SourceAddrRange, - }) - } - - mod, mDiags := l.parser.LoadConfigDir(record.Dir) - diags = append(diags, mDiags...) - if mod == nil { - // nil specifically indicates that the directory does not exist or - // cannot be read, so in this case we'll discard any generic diagnostics - // returned from LoadConfigDir and produce our own context-sensitive - // error message. - return nil, nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Module not installed", - Detail: fmt.Sprintf("This module's local cache directory %s could not be read. Run \"terraform init\" to install all modules required by this configuration.", record.Dir), - Subject: &req.CallRange, - }, - } - } - - return mod, record.Version, diags -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/loader_snapshot.go b/vendor/github.com/hashicorp/terraform/configs/configload/loader_snapshot.go deleted file mode 100644 index 44c64397..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/loader_snapshot.go +++ /dev/null @@ -1,504 +0,0 @@ -package configload - -import ( - "fmt" - "io" - "os" - "path/filepath" - "sort" - "time" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/internal/modsdir" - "github.com/spf13/afero" -) - -// LoadConfigWithSnapshot is a variant of LoadConfig that also simultaneously -// creates an in-memory snapshot of the configuration files used, which can -// be later used to create a loader that may read only from this snapshot. -func (l *Loader) LoadConfigWithSnapshot(rootDir string) (*configs.Config, *Snapshot, hcl.Diagnostics) { - rootMod, diags := l.parser.LoadConfigDir(rootDir) - if rootMod == nil { - return nil, nil, diags - } - - snap := &Snapshot{ - Modules: map[string]*SnapshotModule{}, - } - walker := l.makeModuleWalkerSnapshot(snap) - cfg, cDiags := configs.BuildConfig(rootMod, walker) - diags = append(diags, cDiags...) - - addDiags := l.addModuleToSnapshot(snap, "", rootDir, "", nil) - diags = append(diags, addDiags...) - - return cfg, snap, diags -} - -// NewLoaderFromSnapshot creates a Loader that reads files only from the -// given snapshot. -// -// A snapshot-based loader cannot install modules, so calling InstallModules -// on the return value will cause a panic. -// -// A snapshot-based loader also has access only to configuration files. Its -// underlying parser does not have access to other files in the native -// filesystem, such as values files. For those, either use a normal loader -// (created by NewLoader) or use the configs.Parser API directly. -func NewLoaderFromSnapshot(snap *Snapshot) *Loader { - fs := snapshotFS{snap} - parser := configs.NewParser(fs) - - ret := &Loader{ - parser: parser, - modules: moduleMgr{ - FS: afero.Afero{Fs: fs}, - CanInstall: false, - manifest: snap.moduleManifest(), - }, - } - - return ret -} - -// Snapshot is an in-memory representation of the source files from a -// configuration, which can be used as an alternative configurations source -// for a loader with NewLoaderFromSnapshot. -// -// The primary purpose of a Snapshot is to build the configuration portion -// of a plan file (see ../../plans/planfile) so that it can later be reloaded -// and used to recover the exact configuration that the plan was built from. -type Snapshot struct { - // Modules is a map from opaque module keys (suitable for use as directory - // names on all supported operating systems) to the snapshot information - // about each module. - Modules map[string]*SnapshotModule -} - -// NewEmptySnapshot constructs and returns a snapshot containing only an empty -// root module. This is not useful for anything except placeholders in tests. -func NewEmptySnapshot() *Snapshot { - return &Snapshot{ - Modules: map[string]*SnapshotModule{ - "": &SnapshotModule{ - Files: map[string][]byte{}, - }, - }, - } -} - -// SnapshotModule represents a single module within a Snapshot. -type SnapshotModule struct { - // Dir is the path, relative to the root directory given when the - // snapshot was created, where the module appears in the snapshot's - // virtual filesystem. - Dir string - - // Files is a map from each configuration file filename for the - // module to a raw byte representation of the source file contents. - Files map[string][]byte - - // SourceAddr is the source address given for this module in configuration. - SourceAddr string `json:"Source"` - - // Version is the version of the module that is installed, or nil if - // the module is installed from a source that does not support versions. - Version *version.Version `json:"-"` -} - -// moduleManifest constructs a module manifest based on the contents of -// the receiving snapshot. -func (s *Snapshot) moduleManifest() modsdir.Manifest { - ret := make(modsdir.Manifest) - - for k, modSnap := range s.Modules { - ret[k] = modsdir.Record{ - Key: k, - Dir: modSnap.Dir, - SourceAddr: modSnap.SourceAddr, - Version: modSnap.Version, - } - } - - return ret -} - -// makeModuleWalkerSnapshot creates a configs.ModuleWalker that will exhibit -// the same lookup behaviors as l.moduleWalkerLoad but will additionally write -// source files from the referenced modules into the given snapshot. -func (l *Loader) makeModuleWalkerSnapshot(snap *Snapshot) configs.ModuleWalker { - return configs.ModuleWalkerFunc( - func(req *configs.ModuleRequest) (*configs.Module, *version.Version, hcl.Diagnostics) { - mod, v, diags := l.moduleWalkerLoad(req) - if diags.HasErrors() { - return mod, v, diags - } - - key := l.modules.manifest.ModuleKey(req.Path) - record, exists := l.modules.manifest[key] - - if !exists { - // Should never happen, since otherwise moduleWalkerLoader would've - // returned an error and we would've returned already. - panic(fmt.Sprintf("module %s is not present in manifest", key)) - } - - addDiags := l.addModuleToSnapshot(snap, key, record.Dir, record.SourceAddr, record.Version) - diags = append(diags, addDiags...) - - return mod, v, diags - }, - ) -} - -func (l *Loader) addModuleToSnapshot(snap *Snapshot, key string, dir string, sourceAddr string, v *version.Version) hcl.Diagnostics { - var diags hcl.Diagnostics - - primaryFiles, overrideFiles, moreDiags := l.parser.ConfigDirFiles(dir) - if moreDiags.HasErrors() { - // Any diagnostics we get here should be already present - // in diags, so it's weird if we get here but we'll allow it - // and return a general error message in that case. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Failed to read directory for module", - Detail: fmt.Sprintf("The source directory %s could not be read", dir), - }) - return diags - } - - snapMod := &SnapshotModule{ - Dir: dir, - Files: map[string][]byte{}, - SourceAddr: sourceAddr, - Version: v, - } - - files := make([]string, 0, len(primaryFiles)+len(overrideFiles)) - files = append(files, primaryFiles...) - files = append(files, overrideFiles...) - sources := l.Sources() // should be populated with all the files we need by now - for _, filePath := range files { - filename := filepath.Base(filePath) - src, exists := sources[filePath] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing source file for snapshot", - Detail: fmt.Sprintf("The source code for file %s could not be found to produce a configuration snapshot.", filePath), - }) - continue - } - snapMod.Files[filepath.Clean(filename)] = src - } - - snap.Modules[key] = snapMod - - return diags -} - -// snapshotFS is an implementation of afero.Fs that reads from a snapshot. -// -// This is not intended as a general-purpose filesystem implementation. Instead, -// it just supports the minimal functionality required to support the -// configuration loader and parser as an implementation detail of creating -// a loader from a snapshot. -type snapshotFS struct { - snap *Snapshot -} - -var _ afero.Fs = snapshotFS{} - -func (fs snapshotFS) Create(name string) (afero.File, error) { - return nil, fmt.Errorf("cannot create file inside configuration snapshot") -} - -func (fs snapshotFS) Mkdir(name string, perm os.FileMode) error { - return fmt.Errorf("cannot create directory inside configuration snapshot") -} - -func (fs snapshotFS) MkdirAll(name string, perm os.FileMode) error { - return fmt.Errorf("cannot create directories inside configuration snapshot") -} - -func (fs snapshotFS) Open(name string) (afero.File, error) { - - // Our "filesystem" is sparsely populated only with the directories - // mentioned by modules in our snapshot, so the high-level process - // for opening a file is: - // - Find the module snapshot corresponding to the containing directory - // - Find the file within that snapshot - // - Wrap the resulting byte slice in a snapshotFile to return - // - // The other possibility handled here is if the given name is for the - // module directory itself, in which case we'll return a snapshotDir - // instead. - // - // This function doesn't try to be incredibly robust in supporting - // different permutations of paths, etc because in practice we only - // need to support the path forms that our own loader and parser will - // generate. - - dir := filepath.Dir(name) - fn := filepath.Base(name) - directDir := filepath.Clean(name) - - // First we'll check to see if this is an exact path for a module directory. - // We need to do this first (rather than as part of the next loop below) - // because a module in a child directory of another module can otherwise - // appear to be a file in that parent directory. - for _, candidate := range fs.snap.Modules { - modDir := filepath.Clean(candidate.Dir) - if modDir == directDir { - // We've matched the module directory itself - filenames := make([]string, 0, len(candidate.Files)) - for n := range candidate.Files { - filenames = append(filenames, n) - } - sort.Strings(filenames) - return snapshotDir{ - filenames: filenames, - }, nil - } - } - - // If we get here then the given path isn't a module directory exactly, so - // we'll treat it as a file path and try to find a module directory it - // could be located in. - var modSnap *SnapshotModule - for _, candidate := range fs.snap.Modules { - modDir := filepath.Clean(candidate.Dir) - if modDir == dir { - modSnap = candidate - break - } - } - if modSnap == nil { - return nil, os.ErrNotExist - } - - src, exists := modSnap.Files[fn] - if !exists { - return nil, os.ErrNotExist - } - - return &snapshotFile{ - src: src, - }, nil -} - -func (fs snapshotFS) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { - return fs.Open(name) -} - -func (fs snapshotFS) Remove(name string) error { - return fmt.Errorf("cannot remove file inside configuration snapshot") -} - -func (fs snapshotFS) RemoveAll(path string) error { - return fmt.Errorf("cannot remove files inside configuration snapshot") -} - -func (fs snapshotFS) Rename(old, new string) error { - return fmt.Errorf("cannot rename file inside configuration snapshot") -} - -func (fs snapshotFS) Stat(name string) (os.FileInfo, error) { - f, err := fs.Open(name) - if err != nil { - return nil, err - } - _, isDir := f.(snapshotDir) - return snapshotFileInfo{ - name: filepath.Base(name), - isDir: isDir, - }, nil -} - -func (fs snapshotFS) Name() string { - return "ConfigSnapshotFS" -} - -func (fs snapshotFS) Chmod(name string, mode os.FileMode) error { - return fmt.Errorf("cannot set file mode inside configuration snapshot") -} - -func (fs snapshotFS) Chtimes(name string, atime, mtime time.Time) error { - return fmt.Errorf("cannot set file times inside configuration snapshot") -} - -type snapshotFile struct { - snapshotFileStub - src []byte - at int64 -} - -var _ afero.File = (*snapshotFile)(nil) - -func (f *snapshotFile) Read(p []byte) (n int, err error) { - if len(p) > 0 && f.at == int64(len(f.src)) { - return 0, io.EOF - } - if f.at > int64(len(f.src)) { - return 0, io.ErrUnexpectedEOF - } - if int64(len(f.src))-f.at >= int64(len(p)) { - n = len(p) - } else { - n = int(int64(len(f.src)) - f.at) - } - copy(p, f.src[f.at:f.at+int64(n)]) - f.at += int64(n) - return -} - -func (f *snapshotFile) ReadAt(p []byte, off int64) (n int, err error) { - f.at = off - return f.Read(p) -} - -func (f *snapshotFile) Seek(offset int64, whence int) (int64, error) { - switch whence { - case 0: - f.at = offset - case 1: - f.at += offset - case 2: - f.at = int64(len(f.src)) + offset - } - return f.at, nil -} - -type snapshotDir struct { - snapshotFileStub - filenames []string - at int -} - -var _ afero.File = snapshotDir{} - -func (f snapshotDir) Readdir(count int) ([]os.FileInfo, error) { - names, err := f.Readdirnames(count) - if err != nil { - return nil, err - } - ret := make([]os.FileInfo, len(names)) - for i, name := range names { - ret[i] = snapshotFileInfo{ - name: name, - isDir: false, - } - } - return ret, nil -} - -func (f snapshotDir) Readdirnames(count int) ([]string, error) { - var outLen int - names := f.filenames[f.at:] - if count > 0 { - if len(names) < count { - outLen = len(names) - } else { - outLen = count - } - if len(names) == 0 { - return nil, io.EOF - } - } else { - outLen = len(names) - } - f.at += outLen - - return names[:outLen], nil -} - -// snapshotFileInfo is a minimal implementation of os.FileInfo to support our -// virtual filesystem from snapshots. -type snapshotFileInfo struct { - name string - isDir bool -} - -var _ os.FileInfo = snapshotFileInfo{} - -func (fi snapshotFileInfo) Name() string { - return fi.name -} - -func (fi snapshotFileInfo) Size() int64 { - // In practice, our parser and loader never call Size - return -1 -} - -func (fi snapshotFileInfo) Mode() os.FileMode { - return os.ModePerm -} - -func (fi snapshotFileInfo) ModTime() time.Time { - return time.Now() -} - -func (fi snapshotFileInfo) IsDir() bool { - return fi.isDir -} - -func (fi snapshotFileInfo) Sys() interface{} { - return nil -} - -type snapshotFileStub struct{} - -func (f snapshotFileStub) Close() error { - return nil -} - -func (f snapshotFileStub) Read(p []byte) (n int, err error) { - return 0, fmt.Errorf("cannot read") -} - -func (f snapshotFileStub) ReadAt(p []byte, off int64) (n int, err error) { - return 0, fmt.Errorf("cannot read") -} - -func (f snapshotFileStub) Seek(offset int64, whence int) (int64, error) { - return 0, fmt.Errorf("cannot seek") -} - -func (f snapshotFileStub) Write(p []byte) (n int, err error) { - return f.WriteAt(p, 0) -} - -func (f snapshotFileStub) WriteAt(p []byte, off int64) (n int, err error) { - return 0, fmt.Errorf("cannot write to file in snapshot") -} - -func (f snapshotFileStub) WriteString(s string) (n int, err error) { - return 0, fmt.Errorf("cannot write to file in snapshot") -} - -func (f snapshotFileStub) Name() string { - // in practice, the loader and parser never use this - return "" -} - -func (f snapshotFileStub) Readdir(count int) ([]os.FileInfo, error) { - return nil, fmt.Errorf("cannot use Readdir on a file") -} - -func (f snapshotFileStub) Readdirnames(count int) ([]string, error) { - return nil, fmt.Errorf("cannot use Readdir on a file") -} - -func (f snapshotFileStub) Stat() (os.FileInfo, error) { - return nil, fmt.Errorf("cannot stat") -} - -func (f snapshotFileStub) Sync() error { - return nil -} - -func (f snapshotFileStub) Truncate(size int64) error { - return fmt.Errorf("cannot write to file in snapshot") -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/module_mgr.go b/vendor/github.com/hashicorp/terraform/configs/configload/module_mgr.go deleted file mode 100644 index 3c410eeb..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/module_mgr.go +++ /dev/null @@ -1,76 +0,0 @@ -package configload - -import ( - "os" - "path/filepath" - - "github.com/hashicorp/terraform/internal/modsdir" - "github.com/hashicorp/terraform/registry" - "github.com/hashicorp/terraform/svchost/disco" - "github.com/spf13/afero" -) - -type moduleMgr struct { - FS afero.Afero - - // CanInstall is true for a module manager that can support installation. - // - // This must be set only if FS is an afero.OsFs, because the installer - // (which uses go-getter) is not aware of the virtual filesystem - // abstraction and will always write into the "real" filesystem. - CanInstall bool - - // Dir is the path where descendent modules are (or will be) installed. - Dir string - - // Services is a service discovery client that will be used to find - // remote module registry endpoints. This object may be pre-loaded with - // cached discovery information. - Services *disco.Disco - - // Registry is a client for the module registry protocol, which is used - // when a module is requested from a registry source. - Registry *registry.Client - - // manifest tracks the currently-installed modules for this manager. - // - // The loader may read this. Only the installer may write to it, and - // after a set of updates are completed the installer must call - // writeModuleManifestSnapshot to persist a snapshot of the manifest - // to disk for use on subsequent runs. - manifest modsdir.Manifest -} - -func (m *moduleMgr) manifestSnapshotPath() string { - return filepath.Join(m.Dir, modsdir.ManifestSnapshotFilename) -} - -// readModuleManifestSnapshot loads a manifest snapshot from the filesystem. -func (m *moduleMgr) readModuleManifestSnapshot() error { - r, err := m.FS.Open(m.manifestSnapshotPath()) - if err != nil { - if os.IsNotExist(err) { - // We'll treat a missing file as an empty manifest - m.manifest = make(modsdir.Manifest) - return nil - } - return err - } - - m.manifest, err = modsdir.ReadManifestSnapshot(r) - return err -} - -// writeModuleManifestSnapshot writes a snapshot of the current manifest -// to the filesystem. -// -// The caller must guarantee no concurrent modifications of the manifest for -// the duration of a call to this function, or the behavior is undefined. -func (m *moduleMgr) writeModuleManifestSnapshot() error { - w, err := m.FS.Create(m.manifestSnapshotPath()) - if err != nil { - return err - } - - return m.manifest.WriteSnapshot(w) -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/source_addr.go b/vendor/github.com/hashicorp/terraform/configs/configload/source_addr.go deleted file mode 100644 index 594cf640..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/source_addr.go +++ /dev/null @@ -1,45 +0,0 @@ -package configload - -import ( - "strings" - - "github.com/hashicorp/go-getter" - - "github.com/hashicorp/terraform/registry/regsrc" -) - -var localSourcePrefixes = []string{ - "./", - "../", - ".\\", - "..\\", -} - -func isLocalSourceAddr(addr string) bool { - for _, prefix := range localSourcePrefixes { - if strings.HasPrefix(addr, prefix) { - return true - } - } - return false -} - -func isRegistrySourceAddr(addr string) bool { - _, err := regsrc.ParseModuleSource(addr) - return err == nil -} - -// splitAddrSubdir splits the given address (which is assumed to be a -// registry address or go-getter-style address) into a package portion -// and a sub-directory portion. -// -// The package portion defines what should be downloaded and then the -// sub-directory portion, if present, specifies a sub-directory within -// the downloaded object (an archive, VCS repository, etc) that contains -// the module's configuration files. -// -// The subDir portion will be returned as empty if no subdir separator -// ("//") is present in the address. -func splitAddrSubdir(addr string) (packageAddr, subDir string) { - return getter.SourceDirSubdir(addr) -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configload/testing.go b/vendor/github.com/hashicorp/terraform/configs/configload/testing.go deleted file mode 100644 index 86ca9d10..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configload/testing.go +++ /dev/null @@ -1,43 +0,0 @@ -package configload - -import ( - "io/ioutil" - "os" - "testing" -) - -// NewLoaderForTests is a variant of NewLoader that is intended to be more -// convenient for unit tests. -// -// The loader's modules directory is a separate temporary directory created -// for each call. Along with the created loader, this function returns a -// cleanup function that should be called before the test completes in order -// to remove that temporary directory. -// -// In the case of any errors, t.Fatal (or similar) will be called to halt -// execution of the test, so the calling test does not need to handle errors -// itself. -func NewLoaderForTests(t *testing.T) (*Loader, func()) { - t.Helper() - - modulesDir, err := ioutil.TempDir("", "tf-configs") - if err != nil { - t.Fatalf("failed to create temporary modules dir: %s", err) - return nil, func() {} - } - - cleanup := func() { - os.RemoveAll(modulesDir) - } - - loader, err := NewLoader(&Config{ - ModulesDir: modulesDir, - }) - if err != nil { - cleanup() - t.Fatalf("failed to create config loader: %s", err) - return nil, func() {} - } - - return loader, cleanup -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/coerce_value.go b/vendor/github.com/hashicorp/terraform/configs/configschema/coerce_value.go deleted file mode 100644 index 877e860f..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configschema/coerce_value.go +++ /dev/null @@ -1,270 +0,0 @@ -package configschema - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// CoerceValue attempts to force the given value to conform to the type -// implied by the receiever, while also applying the same validation and -// transformation rules that would be applied by the decoder specification -// returned by method DecoderSpec. -// -// This is useful in situations where a configuration must be derived from -// an already-decoded value. It is always better to decode directly from -// configuration where possible since then source location information is -// still available to produce diagnostics, but in special situations this -// function allows a compatible result to be obtained even if the -// configuration objects are not available. -// -// If the given value cannot be converted to conform to the receiving schema -// then an error is returned describing one of possibly many problems. This -// error may be a cty.PathError indicating a position within the nested -// data structure where the problem applies. -func (b *Block) CoerceValue(in cty.Value) (cty.Value, error) { - var path cty.Path - return b.coerceValue(in, path) -} - -func (b *Block) coerceValue(in cty.Value, path cty.Path) (cty.Value, error) { - switch { - case in.IsNull(): - return cty.NullVal(b.ImpliedType()), nil - case !in.IsKnown(): - return cty.UnknownVal(b.ImpliedType()), nil - } - - ty := in.Type() - if !ty.IsObjectType() { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("an object is required") - } - - for name := range ty.AttributeTypes() { - if _, defined := b.Attributes[name]; defined { - continue - } - if _, defined := b.BlockTypes[name]; defined { - continue - } - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("unexpected attribute %q", name) - } - - attrs := make(map[string]cty.Value) - - for name, attrS := range b.Attributes { - var val cty.Value - switch { - case ty.HasAttribute(name): - val = in.GetAttr(name) - case attrS.Computed || attrS.Optional: - val = cty.NullVal(attrS.Type) - default: - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("attribute %q is required", name) - } - - val, err := attrS.coerceValue(val, append(path, cty.GetAttrStep{Name: name})) - if err != nil { - return cty.UnknownVal(b.ImpliedType()), err - } - - attrs[name] = val - } - for typeName, blockS := range b.BlockTypes { - switch blockS.Nesting { - - case NestingSingle: - switch { - case ty.HasAttribute(typeName): - var err error - val := in.GetAttr(typeName) - attrs[typeName], err = blockS.coerceValue(val, append(path, cty.GetAttrStep{Name: typeName})) - if err != nil { - return cty.UnknownVal(b.ImpliedType()), err - } - case blockS.MinItems != 1 && blockS.MaxItems != 1: - attrs[typeName] = cty.NullVal(blockS.ImpliedType()) - default: - // We use the word "attribute" here because we're talking about - // the cty sense of that word rather than the HCL sense. - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("attribute %q is required", typeName) - } - - case NestingList: - switch { - case ty.HasAttribute(typeName): - coll := in.GetAttr(typeName) - - switch { - case coll.IsNull(): - attrs[typeName] = cty.NullVal(cty.List(blockS.ImpliedType())) - continue - case !coll.IsKnown(): - attrs[typeName] = cty.UnknownVal(cty.List(blockS.ImpliedType())) - continue - } - - if !coll.CanIterateElements() { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("must be a list") - } - l := coll.LengthInt() - if l < blockS.MinItems { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("insufficient items for attribute %q; must have at least %d", typeName, blockS.MinItems) - } - if l > blockS.MaxItems && blockS.MaxItems > 0 { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("too many items for attribute %q; cannot have more than %d", typeName, blockS.MaxItems) - } - if l == 0 { - attrs[typeName] = cty.ListValEmpty(blockS.ImpliedType()) - continue - } - elems := make([]cty.Value, 0, l) - { - path = append(path, cty.GetAttrStep{Name: typeName}) - for it := coll.ElementIterator(); it.Next(); { - var err error - idx, val := it.Element() - val, err = blockS.coerceValue(val, append(path, cty.IndexStep{Key: idx})) - if err != nil { - return cty.UnknownVal(b.ImpliedType()), err - } - elems = append(elems, val) - } - } - attrs[typeName] = cty.ListVal(elems) - case blockS.MinItems == 0: - attrs[typeName] = cty.ListValEmpty(blockS.ImpliedType()) - default: - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("attribute %q is required", typeName) - } - - case NestingSet: - switch { - case ty.HasAttribute(typeName): - coll := in.GetAttr(typeName) - - switch { - case coll.IsNull(): - attrs[typeName] = cty.NullVal(cty.Set(blockS.ImpliedType())) - continue - case !coll.IsKnown(): - attrs[typeName] = cty.UnknownVal(cty.Set(blockS.ImpliedType())) - continue - } - - if !coll.CanIterateElements() { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("must be a set") - } - l := coll.LengthInt() - if l < blockS.MinItems { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("insufficient items for attribute %q; must have at least %d", typeName, blockS.MinItems) - } - if l > blockS.MaxItems && blockS.MaxItems > 0 { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("too many items for attribute %q; cannot have more than %d", typeName, blockS.MaxItems) - } - if l == 0 { - attrs[typeName] = cty.SetValEmpty(blockS.ImpliedType()) - continue - } - elems := make([]cty.Value, 0, l) - { - path = append(path, cty.GetAttrStep{Name: typeName}) - for it := coll.ElementIterator(); it.Next(); { - var err error - idx, val := it.Element() - val, err = blockS.coerceValue(val, append(path, cty.IndexStep{Key: idx})) - if err != nil { - return cty.UnknownVal(b.ImpliedType()), err - } - elems = append(elems, val) - } - } - attrs[typeName] = cty.SetVal(elems) - case blockS.MinItems == 0: - attrs[typeName] = cty.SetValEmpty(blockS.ImpliedType()) - default: - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("attribute %q is required", typeName) - } - - case NestingMap: - switch { - case ty.HasAttribute(typeName): - coll := in.GetAttr(typeName) - - switch { - case coll.IsNull(): - attrs[typeName] = cty.NullVal(cty.Map(blockS.ImpliedType())) - continue - case !coll.IsKnown(): - attrs[typeName] = cty.UnknownVal(cty.Map(blockS.ImpliedType())) - continue - } - - if !coll.CanIterateElements() { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("must be a map") - } - l := coll.LengthInt() - if l == 0 { - attrs[typeName] = cty.MapValEmpty(blockS.ImpliedType()) - continue - } - elems := make(map[string]cty.Value) - { - path = append(path, cty.GetAttrStep{Name: typeName}) - for it := coll.ElementIterator(); it.Next(); { - var err error - key, val := it.Element() - if key.Type() != cty.String || key.IsNull() || !key.IsKnown() { - return cty.UnknownVal(b.ImpliedType()), path.NewErrorf("must be a map") - } - val, err = blockS.coerceValue(val, append(path, cty.IndexStep{Key: key})) - if err != nil { - return cty.UnknownVal(b.ImpliedType()), err - } - elems[key.AsString()] = val - } - } - - // If the attribute values here contain any DynamicPseudoTypes, - // the concrete type must be an object. - useObject := false - switch { - case coll.Type().IsObjectType(): - useObject = true - default: - // It's possible that we were given a map, and need to coerce it to an object - ety := coll.Type().ElementType() - for _, v := range elems { - if !v.Type().Equals(ety) { - useObject = true - break - } - } - } - - if useObject { - attrs[typeName] = cty.ObjectVal(elems) - } else { - attrs[typeName] = cty.MapVal(elems) - } - default: - attrs[typeName] = cty.MapValEmpty(blockS.ImpliedType()) - } - - default: - // should never happen because above is exhaustive - panic(fmt.Errorf("unsupported nesting mode %#v", blockS.Nesting)) - } - } - - return cty.ObjectVal(attrs), nil -} - -func (a *Attribute) coerceValue(in cty.Value, path cty.Path) (cty.Value, error) { - val, err := convert.Convert(in, a.Type) - if err != nil { - return cty.UnknownVal(a.Type), path.NewError(err) - } - return val, nil -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/decoder_spec.go b/vendor/github.com/hashicorp/terraform/configs/configschema/decoder_spec.go deleted file mode 100644 index f7702644..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configschema/decoder_spec.go +++ /dev/null @@ -1,109 +0,0 @@ -package configschema - -import ( - "github.com/hashicorp/hcl2/hcldec" -) - -var mapLabelNames = []string{"key"} - -// DecoderSpec returns a hcldec.Spec that can be used to decode a HCL Body -// using the facilities in the hcldec package. -// -// The returned specification is guaranteed to return a value of the same type -// returned by method ImpliedType, but it may contain null values if any of the -// block attributes are defined as optional and/or computed respectively. -func (b *Block) DecoderSpec() hcldec.Spec { - ret := hcldec.ObjectSpec{} - if b == nil { - return ret - } - - for name, attrS := range b.Attributes { - ret[name] = attrS.decoderSpec(name) - } - - for name, blockS := range b.BlockTypes { - if _, exists := ret[name]; exists { - // This indicates an invalid schema, since it's not valid to - // define both an attribute and a block type of the same name. - // However, we don't raise this here since it's checked by - // InternalValidate. - continue - } - - childSpec := blockS.Block.DecoderSpec() - - switch blockS.Nesting { - case NestingSingle: - ret[name] = &hcldec.BlockSpec{ - TypeName: name, - Nested: childSpec, - Required: blockS.MinItems == 1 && blockS.MaxItems >= 1, - } - case NestingList: - // We prefer to use a list where possible, since it makes our - // implied type more complete, but if there are any - // dynamically-typed attributes inside we must use a tuple - // instead, at the expense of our type then not being predictable. - if blockS.Block.ImpliedType().HasDynamicTypes() { - ret[name] = &hcldec.BlockTupleSpec{ - TypeName: name, - Nested: childSpec, - MinItems: blockS.MinItems, - MaxItems: blockS.MaxItems, - } - } else { - ret[name] = &hcldec.BlockListSpec{ - TypeName: name, - Nested: childSpec, - MinItems: blockS.MinItems, - MaxItems: blockS.MaxItems, - } - } - case NestingSet: - // We forbid dynamically-typed attributes inside NestingSet in - // InternalValidate, so we don't do anything special to handle - // that here. (There is no set analog to tuple and object types, - // because cty's set implementation depends on knowing the static - // type in order to properly compute its internal hashes.) - ret[name] = &hcldec.BlockSetSpec{ - TypeName: name, - Nested: childSpec, - MinItems: blockS.MinItems, - MaxItems: blockS.MaxItems, - } - case NestingMap: - // We prefer to use a list where possible, since it makes our - // implied type more complete, but if there are any - // dynamically-typed attributes inside we must use a tuple - // instead, at the expense of our type then not being predictable. - if blockS.Block.ImpliedType().HasDynamicTypes() { - ret[name] = &hcldec.BlockObjectSpec{ - TypeName: name, - Nested: childSpec, - LabelNames: mapLabelNames, - } - } else { - ret[name] = &hcldec.BlockMapSpec{ - TypeName: name, - Nested: childSpec, - LabelNames: mapLabelNames, - } - } - default: - // Invalid nesting type is just ignored. It's checked by - // InternalValidate. - continue - } - } - - return ret -} - -func (a *Attribute) decoderSpec(name string) hcldec.Spec { - return &hcldec.AttrSpec{ - Name: name, - Type: a.Type, - Required: a.Required, - } -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/implied_type.go b/vendor/github.com/hashicorp/terraform/configs/configschema/implied_type.go deleted file mode 100644 index c0ee8419..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configschema/implied_type.go +++ /dev/null @@ -1,42 +0,0 @@ -package configschema - -import ( - "github.com/hashicorp/hcl2/hcldec" - "github.com/zclconf/go-cty/cty" -) - -// ImpliedType returns the cty.Type that would result from decoding a -// configuration block using the receiving block schema. -// -// ImpliedType always returns a result, even if the given schema is -// inconsistent. Code that creates configschema.Block objects should be -// tested using the InternalValidate method to detect any inconsistencies -// that would cause this method to fall back on defaults and assumptions. -func (b *Block) ImpliedType() cty.Type { - if b == nil { - return cty.EmptyObject - } - - return hcldec.ImpliedType(b.DecoderSpec()) -} - -// ContainsSensitive returns true if any of the attributes of the receiving -// block or any of its descendent blocks are marked as sensitive. -// -// Blocks themselves cannot be sensitive as a whole -- sensitivity is a -// per-attribute idea -- but sometimes we want to include a whole object -// decoded from a block in some UI output, and that is safe to do only if -// none of the contained attributes are sensitive. -func (b *Block) ContainsSensitive() bool { - for _, attrS := range b.Attributes { - if attrS.Sensitive { - return true - } - } - for _, blockS := range b.BlockTypes { - if blockS.ContainsSensitive() { - return true - } - } - return false -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/none_required.go b/vendor/github.com/hashicorp/terraform/configs/configschema/none_required.go deleted file mode 100644 index 0be3b8fa..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configschema/none_required.go +++ /dev/null @@ -1,38 +0,0 @@ -package configschema - -// NoneRequired returns a deep copy of the receiver with any required -// attributes translated to optional. -func (b *Block) NoneRequired() *Block { - ret := &Block{} - - if b.Attributes != nil { - ret.Attributes = make(map[string]*Attribute, len(b.Attributes)) - } - for name, attrS := range b.Attributes { - ret.Attributes[name] = attrS.forceOptional() - } - - if b.BlockTypes != nil { - ret.BlockTypes = make(map[string]*NestedBlock, len(b.BlockTypes)) - } - for name, blockS := range b.BlockTypes { - ret.BlockTypes[name] = blockS.noneRequired() - } - - return ret -} - -func (b *NestedBlock) noneRequired() *NestedBlock { - ret := *b - ret.Block = *(ret.Block.NoneRequired()) - ret.MinItems = 0 - ret.MaxItems = 0 - return &ret -} - -func (a *Attribute) forceOptional() *Attribute { - ret := *a - ret.Optional = true - ret.Required = false - return &ret -} diff --git a/vendor/github.com/hashicorp/terraform/configs/configschema/validate_traversal.go b/vendor/github.com/hashicorp/terraform/configs/configschema/validate_traversal.go deleted file mode 100644 index 351d7677..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/configschema/validate_traversal.go +++ /dev/null @@ -1,173 +0,0 @@ -package configschema - -import ( - "fmt" - "sort" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/helper/didyoumean" - "github.com/hashicorp/terraform/tfdiags" -) - -// StaticValidateTraversal checks whether the given traversal (which must be -// relative) refers to a construct in the receiving schema, returning error -// diagnostics if any problems are found. -// -// This method is "optimistic" in that it will not return errors for possible -// problems that cannot be detected statically. It is possible that an -// traversal which passed static validation will still fail when evaluated. -func (b *Block) StaticValidateTraversal(traversal hcl.Traversal) tfdiags.Diagnostics { - if !traversal.IsRelative() { - panic("StaticValidateTraversal on absolute traversal") - } - if len(traversal) == 0 { - return nil - } - - var diags tfdiags.Diagnostics - - next := traversal[0] - after := traversal[1:] - - var name string - switch step := next.(type) { - case hcl.TraverseAttr: - name = step.Name - case hcl.TraverseIndex: - // No other traversal step types are allowed directly at a block. - // If it looks like the user was trying to use index syntax to - // access an attribute then we'll produce a specialized message. - key := step.Key - if key.Type() == cty.String && key.IsKnown() && !key.IsNull() { - maybeName := key.AsString() - if hclsyntax.ValidIdentifier(maybeName) { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid index operation`, - Detail: fmt.Sprintf(`Only attribute access is allowed here. Did you mean to access attribute %q using the dot operator?`, maybeName), - Subject: &step.SrcRange, - }) - return diags - } - } - // If it looks like some other kind of index then we'll use a generic error. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid index operation`, - Detail: `Only attribute access is allowed here, using the dot operator.`, - Subject: &step.SrcRange, - }) - return diags - default: - // No other traversal types should appear in a normal valid traversal, - // but we'll handle this with a generic error anyway to be robust. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid operation`, - Detail: `Only attribute access is allowed here, using the dot operator.`, - Subject: next.SourceRange().Ptr(), - }) - return diags - } - - if attrS, exists := b.Attributes[name]; exists { - // For attribute validation we will just apply the rest of the - // traversal to an unknown value of the attribute type and pass - // through HCL's own errors, since we don't want to replicate all of - // HCL's type checking rules here. - val := cty.UnknownVal(attrS.Type) - _, hclDiags := after.TraverseRel(val) - diags = diags.Append(hclDiags) - return diags - } - - if blockS, exists := b.BlockTypes[name]; exists { - moreDiags := blockS.staticValidateTraversal(name, after) - diags = diags.Append(moreDiags) - return diags - } - - // If we get here then the name isn't valid at all. We'll collect up - // all of the names that _are_ valid to use as suggestions. - var suggestions []string - for name := range b.Attributes { - suggestions = append(suggestions, name) - } - for name := range b.BlockTypes { - suggestions = append(suggestions, name) - } - sort.Strings(suggestions) - suggestion := didyoumean.NameSuggestion(name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Unsupported attribute`, - Detail: fmt.Sprintf(`This object has no argument, nested block, or exported attribute named %q.%s`, name, suggestion), - Subject: next.SourceRange().Ptr(), - }) - - return diags -} - -func (b *NestedBlock) staticValidateTraversal(typeName string, traversal hcl.Traversal) tfdiags.Diagnostics { - if b.Nesting == NestingSingle { - // Single blocks are easy: just pass right through. - return b.Block.StaticValidateTraversal(traversal) - } - - if len(traversal) == 0 { - // It's always valid to access a nested block's attribute directly. - return nil - } - - var diags tfdiags.Diagnostics - next := traversal[0] - after := traversal[1:] - - switch b.Nesting { - - case NestingSet: - // Can't traverse into a set at all, since it does not have any keys - // to index with. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Cannot index a set value`, - Detail: fmt.Sprintf(`Block type %q is represented by a set of objects, and set elements do not have addressable keys. To find elements matching specific criteria, use a "for" expression with an "if" clause.`, typeName), - Subject: next.SourceRange().Ptr(), - }) - return diags - - case NestingList: - if _, ok := next.(hcl.TraverseIndex); ok { - moreDiags := b.Block.StaticValidateTraversal(after) - diags = diags.Append(moreDiags) - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid operation`, - Detail: fmt.Sprintf(`Block type %q is represented by a list of objects, so it must be indexed using a numeric key, like .%s[0].`, typeName, typeName), - Subject: next.SourceRange().Ptr(), - }) - } - return diags - - case NestingMap: - // Both attribute and index steps are valid for maps, so we'll just - // pass through here and let normal evaluation catch an - // incorrectly-typed index key later, if present. - moreDiags := b.Block.StaticValidateTraversal(after) - diags = diags.Append(moreDiags) - return diags - - default: - // Invalid nesting type is just ignored. It's checked by - // InternalValidate. (Note that we handled NestingSingle separately - // back at the start of this function.) - return nil - } -} diff --git a/vendor/github.com/hashicorp/terraform/configs/depends_on.go b/vendor/github.com/hashicorp/terraform/configs/depends_on.go deleted file mode 100644 index b1984768..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/depends_on.go +++ /dev/null @@ -1,23 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl2/hcl" -) - -func decodeDependsOn(attr *hcl.Attribute) ([]hcl.Traversal, hcl.Diagnostics) { - var ret []hcl.Traversal - exprs, diags := hcl.ExprList(attr.Expr) - - for _, expr := range exprs { - expr, shimDiags := shimTraversalInString(expr, false) - diags = append(diags, shimDiags...) - - traversal, travDiags := hcl.AbsTraversalForExpr(expr) - diags = append(diags, travDiags...) - if len(traversal) != 0 { - ret = append(ret, traversal) - } - } - - return ret, diags -} diff --git a/vendor/github.com/hashicorp/terraform/configs/doc.go b/vendor/github.com/hashicorp/terraform/configs/doc.go deleted file mode 100644 index f01eb79f..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -// Package configs contains types that represent Terraform configurations and -// the different elements thereof. -// -// The functionality in this package can be used for some static analyses of -// Terraform configurations, but this package generally exposes representations -// of the configuration source code rather than the result of evaluating these -// objects. The sibling package "lang" deals with evaluation of structures -// and expressions in the configuration. -// -// Due to its close relationship with HCL, this package makes frequent use -// of types from the HCL API, including raw HCL diagnostic messages. Such -// diagnostics can be converted into Terraform-flavored diagnostics, if needed, -// using functions in the sibling package tfdiags. -// -// The Parser type is the main entry-point into this package. The LoadConfigDir -// method can be used to load a single module directory, and then a full -// configuration (including any descendent modules) can be produced using -// the top-level BuildConfig method. -package configs diff --git a/vendor/github.com/hashicorp/terraform/configs/module.go b/vendor/github.com/hashicorp/terraform/configs/module.go deleted file mode 100644 index 250f9d34..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/module.go +++ /dev/null @@ -1,404 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/hcl" - - "github.com/hashicorp/terraform/addrs" -) - -// Module is a container for a set of configuration constructs that are -// evaluated within a common namespace. -type Module struct { - // SourceDir is the filesystem directory that the module was loaded from. - // - // This is populated automatically only for configurations loaded with - // LoadConfigDir. If the parser is using a virtual filesystem then the - // path here will be in terms of that virtual filesystem. - - // Any other caller that constructs a module directly with NewModule may - // assign a suitable value to this attribute before using it for other - // purposes. It should be treated as immutable by all consumers of Module - // values. - SourceDir string - - CoreVersionConstraints []VersionConstraint - - Backend *Backend - ProviderConfigs map[string]*Provider - ProviderRequirements map[string][]VersionConstraint - - Variables map[string]*Variable - Locals map[string]*Local - Outputs map[string]*Output - - ModuleCalls map[string]*ModuleCall - - ManagedResources map[string]*Resource - DataResources map[string]*Resource -} - -// File describes the contents of a single configuration file. -// -// Individual files are not usually used alone, but rather combined together -// with other files (conventionally, those in the same directory) to produce -// a *Module, using NewModule. -// -// At the level of an individual file we represent directly the structural -// elements present in the file, without any attempt to detect conflicting -// declarations. A File object can therefore be used for some basic static -// analysis of individual elements, but must be built into a Module to detect -// duplicate declarations. -type File struct { - CoreVersionConstraints []VersionConstraint - - Backends []*Backend - ProviderConfigs []*Provider - ProviderRequirements []*ProviderRequirement - - Variables []*Variable - Locals []*Local - Outputs []*Output - - ModuleCalls []*ModuleCall - - ManagedResources []*Resource - DataResources []*Resource -} - -// NewModule takes a list of primary files and a list of override files and -// produces a *Module by combining the files together. -// -// If there are any conflicting declarations in the given files -- for example, -// if the same variable name is defined twice -- then the resulting module -// will be incomplete and error diagnostics will be returned. Careful static -// analysis of the returned Module is still possible in this case, but the -// module will probably not be semantically valid. -func NewModule(primaryFiles, overrideFiles []*File) (*Module, hcl.Diagnostics) { - var diags hcl.Diagnostics - mod := &Module{ - ProviderConfigs: map[string]*Provider{}, - ProviderRequirements: map[string][]VersionConstraint{}, - Variables: map[string]*Variable{}, - Locals: map[string]*Local{}, - Outputs: map[string]*Output{}, - ModuleCalls: map[string]*ModuleCall{}, - ManagedResources: map[string]*Resource{}, - DataResources: map[string]*Resource{}, - } - - for _, file := range primaryFiles { - fileDiags := mod.appendFile(file) - diags = append(diags, fileDiags...) - } - - for _, file := range overrideFiles { - fileDiags := mod.mergeFile(file) - diags = append(diags, fileDiags...) - } - - return mod, diags -} - -// ResourceByAddr returns the configuration for the resource with the given -// address, or nil if there is no such resource. -func (m *Module) ResourceByAddr(addr addrs.Resource) *Resource { - key := addr.String() - switch addr.Mode { - case addrs.ManagedResourceMode: - return m.ManagedResources[key] - case addrs.DataResourceMode: - return m.DataResources[key] - default: - return nil - } -} - -func (m *Module) appendFile(file *File) hcl.Diagnostics { - var diags hcl.Diagnostics - - for _, constraint := range file.CoreVersionConstraints { - // If there are any conflicting requirements then we'll catch them - // when we actually check these constraints. - m.CoreVersionConstraints = append(m.CoreVersionConstraints, constraint) - } - - for _, b := range file.Backends { - if m.Backend != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate backend configuration", - Detail: fmt.Sprintf("A module may have only one backend configuration. The backend was previously configured at %s.", m.Backend.DeclRange), - Subject: &b.DeclRange, - }) - continue - } - m.Backend = b - } - - for _, pc := range file.ProviderConfigs { - key := pc.moduleUniqueKey() - if existing, exists := m.ProviderConfigs[key]; exists { - if existing.Alias == "" { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate provider configuration", - Detail: fmt.Sprintf("A default (non-aliased) provider configuration for %q was already given at %s. If multiple configurations are required, set the \"alias\" argument for alternative configurations.", existing.Name, existing.DeclRange), - Subject: &pc.DeclRange, - }) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate provider configuration", - Detail: fmt.Sprintf("A provider configuration for %q with alias %q was already given at %s. Each configuration for the same provider must have a distinct alias.", existing.Name, existing.Alias, existing.DeclRange), - Subject: &pc.DeclRange, - }) - } - continue - } - m.ProviderConfigs[key] = pc - } - - for _, reqd := range file.ProviderRequirements { - m.ProviderRequirements[reqd.Name] = append(m.ProviderRequirements[reqd.Name], reqd.Requirement) - } - - for _, v := range file.Variables { - if existing, exists := m.Variables[v.Name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate variable declaration", - Detail: fmt.Sprintf("A variable named %q was already declared at %s. Variable names must be unique within a module.", existing.Name, existing.DeclRange), - Subject: &v.DeclRange, - }) - } - m.Variables[v.Name] = v - } - - for _, l := range file.Locals { - if existing, exists := m.Locals[l.Name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate local value definition", - Detail: fmt.Sprintf("A local value named %q was already defined at %s. Local value names must be unique within a module.", existing.Name, existing.DeclRange), - Subject: &l.DeclRange, - }) - } - m.Locals[l.Name] = l - } - - for _, o := range file.Outputs { - if existing, exists := m.Outputs[o.Name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate output definition", - Detail: fmt.Sprintf("An output named %q was already defined at %s. Output names must be unique within a module.", existing.Name, existing.DeclRange), - Subject: &o.DeclRange, - }) - } - m.Outputs[o.Name] = o - } - - for _, mc := range file.ModuleCalls { - if existing, exists := m.ModuleCalls[mc.Name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate module call", - Detail: fmt.Sprintf("An module call named %q was already defined at %s. Module calls must have unique names within a module.", existing.Name, existing.DeclRange), - Subject: &mc.DeclRange, - }) - } - m.ModuleCalls[mc.Name] = mc - } - - for _, r := range file.ManagedResources { - key := r.moduleUniqueKey() - if existing, exists := m.ManagedResources[key]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate resource %q configuration", existing.Type), - Detail: fmt.Sprintf("A %s resource named %q was already declared at %s. Resource names must be unique per type in each module.", existing.Type, existing.Name, existing.DeclRange), - Subject: &r.DeclRange, - }) - continue - } - m.ManagedResources[key] = r - } - - for _, r := range file.DataResources { - key := r.moduleUniqueKey() - if existing, exists := m.DataResources[key]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate data %q configuration", existing.Type), - Detail: fmt.Sprintf("A %s data resource named %q was already declared at %s. Resource names must be unique per type in each module.", existing.Type, existing.Name, existing.DeclRange), - Subject: &r.DeclRange, - }) - continue - } - m.DataResources[key] = r - } - - return diags -} - -func (m *Module) mergeFile(file *File) hcl.Diagnostics { - var diags hcl.Diagnostics - - if len(file.CoreVersionConstraints) != 0 { - // This is a bit of a strange case for overriding since we normally - // would union together across multiple files anyway, but we'll - // allow it and have each override file clobber any existing list. - m.CoreVersionConstraints = nil - for _, constraint := range file.CoreVersionConstraints { - m.CoreVersionConstraints = append(m.CoreVersionConstraints, constraint) - } - } - - if len(file.Backends) != 0 { - switch len(file.Backends) { - case 1: - m.Backend = file.Backends[0] - default: - // An override file with multiple backends is still invalid, even - // though it can override backends from _other_ files. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate backend configuration", - Detail: fmt.Sprintf("Each override file may have only one backend configuration. A backend was previously configured at %s.", file.Backends[0].DeclRange), - Subject: &file.Backends[1].DeclRange, - }) - } - } - - for _, pc := range file.ProviderConfigs { - key := pc.moduleUniqueKey() - existing, exists := m.ProviderConfigs[key] - if pc.Alias == "" { - // We allow overriding a non-existing _default_ provider configuration - // because the user model is that an absent provider configuration - // implies an empty provider configuration, which is what the user - // is therefore overriding here. - if exists { - mergeDiags := existing.merge(pc) - diags = append(diags, mergeDiags...) - } else { - m.ProviderConfigs[key] = pc - } - } else { - // For aliased providers, there must be a base configuration to - // override. This allows us to detect and report alias typos - // that might otherwise cause the override to not apply. - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing base provider configuration for override", - Detail: fmt.Sprintf("There is no %s provider configuration with the alias %q. An override file can only override an aliased provider configuration that was already defined in a primary configuration file.", pc.Name, pc.Alias), - Subject: &pc.DeclRange, - }) - continue - } - mergeDiags := existing.merge(pc) - diags = append(diags, mergeDiags...) - } - } - - if len(file.ProviderRequirements) != 0 { - mergeProviderVersionConstraints(m.ProviderRequirements, file.ProviderRequirements) - } - - for _, v := range file.Variables { - existing, exists := m.Variables[v.Name] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing base variable declaration to override", - Detail: fmt.Sprintf("There is no variable named %q. An override file can only override a variable that was already declared in a primary configuration file.", v.Name), - Subject: &v.DeclRange, - }) - continue - } - mergeDiags := existing.merge(v) - diags = append(diags, mergeDiags...) - } - - for _, l := range file.Locals { - existing, exists := m.Locals[l.Name] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing base local value definition to override", - Detail: fmt.Sprintf("There is no local value named %q. An override file can only override a local value that was already defined in a primary configuration file.", l.Name), - Subject: &l.DeclRange, - }) - continue - } - mergeDiags := existing.merge(l) - diags = append(diags, mergeDiags...) - } - - for _, o := range file.Outputs { - existing, exists := m.Outputs[o.Name] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing base output definition to override", - Detail: fmt.Sprintf("There is no output named %q. An override file can only override an output that was already defined in a primary configuration file.", o.Name), - Subject: &o.DeclRange, - }) - continue - } - mergeDiags := existing.merge(o) - diags = append(diags, mergeDiags...) - } - - for _, mc := range file.ModuleCalls { - existing, exists := m.ModuleCalls[mc.Name] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing module call to override", - Detail: fmt.Sprintf("There is no module call named %q. An override file can only override a module call that was defined in a primary configuration file.", mc.Name), - Subject: &mc.DeclRange, - }) - continue - } - mergeDiags := existing.merge(mc) - diags = append(diags, mergeDiags...) - } - - for _, r := range file.ManagedResources { - key := r.moduleUniqueKey() - existing, exists := m.ManagedResources[key] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing resource to override", - Detail: fmt.Sprintf("There is no %s resource named %q. An override file can only override a resource block defined in a primary configuration file.", r.Type, r.Name), - Subject: &r.DeclRange, - }) - continue - } - mergeDiags := existing.merge(r) - diags = append(diags, mergeDiags...) - } - - for _, r := range file.DataResources { - key := r.moduleUniqueKey() - existing, exists := m.DataResources[key] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing data resource to override", - Detail: fmt.Sprintf("There is no %s data resource named %q. An override file can only override a data block defined in a primary configuration file.", r.Type, r.Name), - Subject: &r.DeclRange, - }) - continue - } - mergeDiags := existing.merge(r) - diags = append(diags, mergeDiags...) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform/configs/module_call.go b/vendor/github.com/hashicorp/terraform/configs/module_call.go deleted file mode 100644 index 8c3ba67c..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/module_call.go +++ /dev/null @@ -1,188 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/gohcl" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" -) - -// ModuleCall represents a "module" block in a module or file. -type ModuleCall struct { - Name string - - SourceAddr string - SourceAddrRange hcl.Range - SourceSet bool - - Config hcl.Body - - Version VersionConstraint - - Count hcl.Expression - ForEach hcl.Expression - - Providers []PassedProviderConfig - - DependsOn []hcl.Traversal - - DeclRange hcl.Range -} - -func decodeModuleBlock(block *hcl.Block, override bool) (*ModuleCall, hcl.Diagnostics) { - mc := &ModuleCall{ - Name: block.Labels[0], - DeclRange: block.DefRange, - } - - schema := moduleBlockSchema - if override { - schema = schemaForOverrides(schema) - } - - content, remain, diags := block.Body.PartialContent(schema) - mc.Config = remain - - if !hclsyntax.ValidIdentifier(mc.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid module instance name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - - if attr, exists := content.Attributes["source"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &mc.SourceAddr) - diags = append(diags, valDiags...) - mc.SourceAddrRange = attr.Expr.Range() - mc.SourceSet = true - } - - if attr, exists := content.Attributes["version"]; exists { - var versionDiags hcl.Diagnostics - mc.Version, versionDiags = decodeVersionConstraint(attr) - diags = append(diags, versionDiags...) - } - - if attr, exists := content.Attributes["count"]; exists { - mc.Count = attr.Expr - - // We currently parse this, but don't yet do anything with it. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in module block", - Detail: fmt.Sprintf("The name %q is reserved for use in a future version of Terraform.", attr.Name), - Subject: &attr.NameRange, - }) - } - - if attr, exists := content.Attributes["for_each"]; exists { - mc.ForEach = attr.Expr - - // We currently parse this, but don't yet do anything with it. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in module block", - Detail: fmt.Sprintf("The name %q is reserved for use in a future version of Terraform.", attr.Name), - Subject: &attr.NameRange, - }) - } - - if attr, exists := content.Attributes["depends_on"]; exists { - deps, depsDiags := decodeDependsOn(attr) - diags = append(diags, depsDiags...) - mc.DependsOn = append(mc.DependsOn, deps...) - - // We currently parse this, but don't yet do anything with it. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in module block", - Detail: fmt.Sprintf("The name %q is reserved for use in a future version of Terraform.", attr.Name), - Subject: &attr.NameRange, - }) - } - - if attr, exists := content.Attributes["providers"]; exists { - seen := make(map[string]hcl.Range) - pairs, pDiags := hcl.ExprMap(attr.Expr) - diags = append(diags, pDiags...) - for _, pair := range pairs { - key, keyDiags := decodeProviderConfigRef(pair.Key, "providers") - diags = append(diags, keyDiags...) - value, valueDiags := decodeProviderConfigRef(pair.Value, "providers") - diags = append(diags, valueDiags...) - if keyDiags.HasErrors() || valueDiags.HasErrors() { - continue - } - - matchKey := key.String() - if prev, exists := seen[matchKey]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate provider address", - Detail: fmt.Sprintf("A provider configuration was already passed to %s at %s. Each child provider configuration can be assigned only once.", matchKey, prev), - Subject: pair.Value.Range().Ptr(), - }) - continue - } - - rng := hcl.RangeBetween(pair.Key.Range(), pair.Value.Range()) - seen[matchKey] = rng - mc.Providers = append(mc.Providers, PassedProviderConfig{ - InChild: key, - InParent: value, - }) - } - } - - // Reserved block types (all of them) - for _, block := range content.Blocks { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in module block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - - return mc, diags -} - -// PassedProviderConfig represents a provider config explicitly passed down to -// a child module, possibly giving it a new local address in the process. -type PassedProviderConfig struct { - InChild *ProviderConfigRef - InParent *ProviderConfigRef -} - -var moduleBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "source", - Required: true, - }, - { - Name: "version", - }, - { - Name: "count", - }, - { - Name: "for_each", - }, - { - Name: "depends_on", - }, - { - Name: "providers", - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - // These are all reserved for future use. - {Type: "lifecycle"}, - {Type: "locals"}, - {Type: "provider", LabelNames: []string{"type"}}, - }, -} diff --git a/vendor/github.com/hashicorp/terraform/configs/module_merge.go b/vendor/github.com/hashicorp/terraform/configs/module_merge.go deleted file mode 100644 index 12614c1d..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/module_merge.go +++ /dev/null @@ -1,247 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/terraform/addrs" - - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// The methods in this file are used by Module.mergeFile to apply overrides -// to our different configuration elements. These methods all follow the -// pattern of mutating the receiver to incorporate settings from the parameter, -// returning error diagnostics if any aspect of the parameter cannot be merged -// into the receiver for some reason. -// -// User expectation is that anything _explicitly_ set in the given object -// should take precedence over the corresponding settings in the receiver, -// but that anything omitted in the given object should be left unchanged. -// In some cases it may be reasonable to do a "deep merge" of certain nested -// features, if it is possible to unambiguously correlate the nested elements -// and their behaviors are orthogonal to each other. - -func (p *Provider) merge(op *Provider) hcl.Diagnostics { - var diags hcl.Diagnostics - - if op.Version.Required != nil { - p.Version = op.Version - } - - p.Config = MergeBodies(p.Config, op.Config) - - return diags -} - -func mergeProviderVersionConstraints(recv map[string][]VersionConstraint, ovrd []*ProviderRequirement) { - // Any provider name that's mentioned in the override gets nilled out in - // our map so that we'll rebuild it below. Any provider not mentioned is - // left unchanged. - for _, reqd := range ovrd { - delete(recv, reqd.Name) - } - for _, reqd := range ovrd { - recv[reqd.Name] = append(recv[reqd.Name], reqd.Requirement) - } -} - -func (v *Variable) merge(ov *Variable) hcl.Diagnostics { - var diags hcl.Diagnostics - - if ov.DescriptionSet { - v.Description = ov.Description - v.DescriptionSet = ov.DescriptionSet - } - if ov.Default != cty.NilVal { - v.Default = ov.Default - } - if ov.Type != cty.NilType { - v.Type = ov.Type - } - if ov.ParsingMode != 0 { - v.ParsingMode = ov.ParsingMode - } - - // If the override file overrode type without default or vice-versa then - // it may have created an invalid situation, which we'll catch now by - // attempting to re-convert the value. - // - // Note that here we may be re-converting an already-converted base value - // from the base config. This will be a no-op if the type was not changed, - // but in particular might be user-observable in the edge case where the - // literal value in config could've been converted to the overridden type - // constraint but the converted value cannot. In practice, this situation - // should be rare since most of our conversions are interchangable. - if v.Default != cty.NilVal { - val, err := convert.Convert(v.Default, v.Type) - if err != nil { - // What exactly we'll say in the error message here depends on whether - // it was Default or Type that was overridden here. - switch { - case ov.Type != cty.NilType && ov.Default == cty.NilVal: - // If only the type was overridden - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid default value for variable", - Detail: fmt.Sprintf("Overriding this variable's type constraint has made its default value invalid: %s.", err), - Subject: &ov.DeclRange, - }) - case ov.Type == cty.NilType && ov.Default != cty.NilVal: - // Only the default was overridden - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid default value for variable", - Detail: fmt.Sprintf("The overridden default value for this variable is not compatible with the variable's type constraint: %s.", err), - Subject: &ov.DeclRange, - }) - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid default value for variable", - Detail: fmt.Sprintf("This variable's default value is not compatible with its type constraint: %s.", err), - Subject: &ov.DeclRange, - }) - } - } else { - v.Default = val - } - } - - return diags -} - -func (l *Local) merge(ol *Local) hcl.Diagnostics { - var diags hcl.Diagnostics - - // Since a local is just a single expression in configuration, the - // override definition entirely replaces the base definition, including - // the source range so that we'll send the user to the right place if - // there is an error. - l.Expr = ol.Expr - l.DeclRange = ol.DeclRange - - return diags -} - -func (o *Output) merge(oo *Output) hcl.Diagnostics { - var diags hcl.Diagnostics - - if oo.Description != "" { - o.Description = oo.Description - } - if oo.Expr != nil { - o.Expr = oo.Expr - } - if oo.SensitiveSet { - o.Sensitive = oo.Sensitive - o.SensitiveSet = oo.SensitiveSet - } - - // We don't allow depends_on to be overridden because that is likely to - // cause confusing misbehavior. - if len(oo.DependsOn) != 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported override", - Detail: "The depends_on argument may not be overridden.", - Subject: oo.DependsOn[0].SourceRange().Ptr(), // the first item is the closest range we have - }) - } - - return diags -} - -func (mc *ModuleCall) merge(omc *ModuleCall) hcl.Diagnostics { - var diags hcl.Diagnostics - - if omc.SourceSet { - mc.SourceAddr = omc.SourceAddr - mc.SourceAddrRange = omc.SourceAddrRange - mc.SourceSet = omc.SourceSet - } - - if omc.Count != nil { - mc.Count = omc.Count - } - - if omc.ForEach != nil { - mc.ForEach = omc.ForEach - } - - if len(omc.Version.Required) != 0 { - mc.Version = omc.Version - } - - mc.Config = MergeBodies(mc.Config, omc.Config) - - // We don't allow depends_on to be overridden because that is likely to - // cause confusing misbehavior. - if len(mc.DependsOn) != 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported override", - Detail: "The depends_on argument may not be overridden.", - Subject: mc.DependsOn[0].SourceRange().Ptr(), // the first item is the closest range we have - }) - } - - return diags -} - -func (r *Resource) merge(or *Resource) hcl.Diagnostics { - var diags hcl.Diagnostics - - if r.Mode != or.Mode { - // This is always a programming error, since managed and data resources - // are kept in separate maps in the configuration structures. - panic(fmt.Errorf("can't merge %s into %s", or.Mode, r.Mode)) - } - - if or.Count != nil { - r.Count = or.Count - } - if or.ForEach != nil { - r.ForEach = or.ForEach - } - if or.ProviderConfigRef != nil { - r.ProviderConfigRef = or.ProviderConfigRef - } - if r.Mode == addrs.ManagedResourceMode { - // or.Managed is always non-nil for managed resource mode - - if or.Managed.Connection != nil { - r.Managed.Connection = or.Managed.Connection - } - if or.Managed.CreateBeforeDestroySet { - r.Managed.CreateBeforeDestroy = or.Managed.CreateBeforeDestroy - r.Managed.CreateBeforeDestroySet = or.Managed.CreateBeforeDestroySet - } - if len(or.Managed.IgnoreChanges) != 0 { - r.Managed.IgnoreChanges = or.Managed.IgnoreChanges - } - if or.Managed.PreventDestroySet { - r.Managed.PreventDestroy = or.Managed.PreventDestroy - r.Managed.PreventDestroySet = or.Managed.PreventDestroySet - } - if len(or.Managed.Provisioners) != 0 { - r.Managed.Provisioners = or.Managed.Provisioners - } - } - - r.Config = MergeBodies(r.Config, or.Config) - - // We don't allow depends_on to be overridden because that is likely to - // cause confusing misbehavior. - if len(or.DependsOn) != 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported override", - Detail: "The depends_on argument may not be overridden.", - Subject: or.DependsOn[0].SourceRange().Ptr(), // the first item is the closest range we have - }) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform/configs/module_merge_body.go b/vendor/github.com/hashicorp/terraform/configs/module_merge_body.go deleted file mode 100644 index bb40e268..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/module_merge_body.go +++ /dev/null @@ -1,129 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl2/hcl" -) - -// MergeBodies creates a new HCL body that contains a combination of the -// given base and override bodies. Attributes and blocks defined in the -// override body take precedence over those of the same name defined in -// the base body. -// -// If any block of a particular type appears in "override" then it will -// replace _all_ of the blocks of the same type in "base" in the new -// body. -func MergeBodies(base, override hcl.Body) hcl.Body { - return mergeBody{ - Base: base, - Override: override, - } -} - -// mergeBody is a hcl.Body implementation that wraps a pair of other bodies -// and allows attributes and blocks within the override to take precedence -// over those defined in the base body. -// -// This is used to deal with dynamically-processed bodies in Module.mergeFile. -// It uses a shallow-only merging strategy where direct attributes defined -// in Override will override attributes of the same name in Base, while any -// blocks defined in Override will hide all blocks of the same type in Base. -// -// This cannot possibly "do the right thing" in all cases, because we don't -// have enough information about user intent. However, this behavior is intended -// to be reasonable for simple overriding use-cases. -type mergeBody struct { - Base hcl.Body - Override hcl.Body -} - -var _ hcl.Body = mergeBody{} - -func (b mergeBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - var diags hcl.Diagnostics - oSchema := schemaForOverrides(schema) - - baseContent, cDiags := b.Base.Content(schema) - diags = append(diags, cDiags...) - overrideContent, cDiags := b.Override.Content(oSchema) - diags = append(diags, cDiags...) - - content := b.prepareContent(baseContent, overrideContent) - - return content, diags -} - -func (b mergeBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - var diags hcl.Diagnostics - oSchema := schemaForOverrides(schema) - - baseContent, baseRemain, cDiags := b.Base.PartialContent(schema) - diags = append(diags, cDiags...) - overrideContent, overrideRemain, cDiags := b.Override.PartialContent(oSchema) - diags = append(diags, cDiags...) - - content := b.prepareContent(baseContent, overrideContent) - - remain := MergeBodies(baseRemain, overrideRemain) - - return content, remain, diags -} - -func (b mergeBody) prepareContent(base *hcl.BodyContent, override *hcl.BodyContent) *hcl.BodyContent { - content := &hcl.BodyContent{ - Attributes: make(hcl.Attributes), - } - - // For attributes we just assign from each map in turn and let the override - // map clobber any matching entries from base. - for k, a := range base.Attributes { - content.Attributes[k] = a - } - for k, a := range override.Attributes { - content.Attributes[k] = a - } - - // Things are a little more interesting for blocks because they arrive - // as a flat list. Our merging semantics call for us to suppress blocks - // from base if at least one block of the same type appears in override. - // We explicitly do not try to correlate and deeply merge nested blocks, - // since we don't have enough context here to infer user intent. - - overriddenBlockTypes := make(map[string]bool) - for _, block := range override.Blocks { - overriddenBlockTypes[block.Type] = true - } - for _, block := range base.Blocks { - if overriddenBlockTypes[block.Type] { - continue - } - content.Blocks = append(content.Blocks, block) - } - for _, block := range override.Blocks { - content.Blocks = append(content.Blocks, block) - } - - return content -} - -func (b mergeBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - var diags hcl.Diagnostics - ret := make(hcl.Attributes) - - baseAttrs, aDiags := b.Base.JustAttributes() - diags = append(diags, aDiags...) - overrideAttrs, aDiags := b.Override.JustAttributes() - diags = append(diags, aDiags...) - - for k, a := range baseAttrs { - ret[k] = a - } - for k, a := range overrideAttrs { - ret[k] = a - } - - return ret, diags -} - -func (b mergeBody) MissingItemRange() hcl.Range { - return b.Base.MissingItemRange() -} diff --git a/vendor/github.com/hashicorp/terraform/configs/named_values.go b/vendor/github.com/hashicorp/terraform/configs/named_values.go deleted file mode 100644 index 6f6b469f..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/named_values.go +++ /dev/null @@ -1,364 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/ext/typeexpr" - "github.com/hashicorp/hcl2/gohcl" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform/addrs" -) - -// A consistent detail message for all "not a valid identifier" diagnostics. -const badIdentifierDetail = "A name must start with a letter and may contain only letters, digits, underscores, and dashes." - -// Variable represents a "variable" block in a module or file. -type Variable struct { - Name string - Description string - Default cty.Value - Type cty.Type - ParsingMode VariableParsingMode - - DescriptionSet bool - - DeclRange hcl.Range -} - -func decodeVariableBlock(block *hcl.Block, override bool) (*Variable, hcl.Diagnostics) { - v := &Variable{ - Name: block.Labels[0], - DeclRange: block.DefRange, - } - - // Unless we're building an override, we'll set some defaults - // which we might override with attributes below. We leave these - // as zero-value in the override case so we can recognize whether - // or not they are set when we merge. - if !override { - v.Type = cty.DynamicPseudoType - v.ParsingMode = VariableParseLiteral - } - - content, diags := block.Body.Content(variableBlockSchema) - - if !hclsyntax.ValidIdentifier(v.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid variable name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - - // Don't allow declaration of variables that would conflict with the - // reserved attribute and block type names in a "module" block, since - // these won't be usable for child modules. - for _, attr := range moduleBlockSchema.Attributes { - if attr.Name == v.Name { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid variable name", - Detail: fmt.Sprintf("The variable name %q is reserved due to its special meaning inside module blocks.", attr.Name), - Subject: &block.LabelRanges[0], - }) - } - } - for _, blockS := range moduleBlockSchema.Blocks { - if blockS.Type == v.Name { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid variable name", - Detail: fmt.Sprintf("The variable name %q is reserved due to its special meaning inside module blocks.", blockS.Type), - Subject: &block.LabelRanges[0], - }) - } - } - - if attr, exists := content.Attributes["description"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &v.Description) - diags = append(diags, valDiags...) - v.DescriptionSet = true - } - - if attr, exists := content.Attributes["type"]; exists { - ty, parseMode, tyDiags := decodeVariableType(attr.Expr) - diags = append(diags, tyDiags...) - v.Type = ty - v.ParsingMode = parseMode - } - - if attr, exists := content.Attributes["default"]; exists { - val, valDiags := attr.Expr.Value(nil) - diags = append(diags, valDiags...) - - // Convert the default to the expected type so we can catch invalid - // defaults early and allow later code to assume validity. - // Note that this depends on us having already processed any "type" - // attribute above. - // However, we can't do this if we're in an override file where - // the type might not be set; we'll catch that during merge. - if v.Type != cty.NilType { - var err error - val, err = convert.Convert(val, v.Type) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid default value for variable", - Detail: fmt.Sprintf("This default value is not compatible with the variable's type constraint: %s.", err), - Subject: attr.Expr.Range().Ptr(), - }) - val = cty.DynamicVal - } - } - - v.Default = val - } - - return v, diags -} - -func decodeVariableType(expr hcl.Expression) (cty.Type, VariableParsingMode, hcl.Diagnostics) { - if exprIsNativeQuotedString(expr) { - // Here we're accepting the pre-0.12 form of variable type argument where - // the string values "string", "list" and "map" are accepted has a hint - // about the type used primarily for deciding how to parse values - // given on the command line and in environment variables. - // Only the native syntax ends up in this codepath; we handle the - // JSON syntax (which is, of course, quoted even in the new format) - // in the normal codepath below. - val, diags := expr.Value(nil) - if diags.HasErrors() { - return cty.DynamicPseudoType, VariableParseHCL, diags - } - str := val.AsString() - switch str { - case "string": - return cty.String, VariableParseLiteral, diags - case "list": - return cty.List(cty.DynamicPseudoType), VariableParseHCL, diags - case "map": - return cty.Map(cty.DynamicPseudoType), VariableParseHCL, diags - default: - return cty.DynamicPseudoType, VariableParseHCL, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: "Invalid legacy variable type hint", - Detail: `The legacy variable type hint form, using a quoted string, allows only the values "string", "list", and "map". To provide a full type expression, remove the surrounding quotes and give the type expression directly.`, - Subject: expr.Range().Ptr(), - }} - } - } - - // First we'll deal with some shorthand forms that the HCL-level type - // expression parser doesn't include. These both emulate pre-0.12 behavior - // of allowing a list or map of any element type as long as all of the - // elements are consistent. This is the same as list(any) or map(any). - switch hcl.ExprAsKeyword(expr) { - case "list": - return cty.List(cty.DynamicPseudoType), VariableParseHCL, nil - case "map": - return cty.Map(cty.DynamicPseudoType), VariableParseHCL, nil - } - - ty, diags := typeexpr.TypeConstraint(expr) - if diags.HasErrors() { - return cty.DynamicPseudoType, VariableParseHCL, diags - } - - switch { - case ty.IsPrimitiveType(): - // Primitive types use literal parsing. - return ty, VariableParseLiteral, diags - default: - // Everything else uses HCL parsing - return ty, VariableParseHCL, diags - } -} - -// VariableParsingMode defines how values of a particular variable given by -// text-only mechanisms (command line arguments and environment variables) -// should be parsed to produce the final value. -type VariableParsingMode rune - -// VariableParseLiteral is a variable parsing mode that just takes the given -// string directly as a cty.String value. -const VariableParseLiteral VariableParsingMode = 'L' - -// VariableParseHCL is a variable parsing mode that attempts to parse the given -// string as an HCL expression and returns the result. -const VariableParseHCL VariableParsingMode = 'H' - -// Parse uses the receiving parsing mode to process the given variable value -// string, returning the result along with any diagnostics. -// -// A VariableParsingMode does not know the expected type of the corresponding -// variable, so it's the caller's responsibility to attempt to convert the -// result to the appropriate type and return to the user any diagnostics that -// conversion may produce. -// -// The given name is used to create a synthetic filename in case any diagnostics -// must be generated about the given string value. This should be the name -// of the root module variable whose value will be populated from the given -// string. -// -// If the returned diagnostics has errors, the returned value may not be -// valid. -func (m VariableParsingMode) Parse(name, value string) (cty.Value, hcl.Diagnostics) { - switch m { - case VariableParseLiteral: - return cty.StringVal(value), nil - case VariableParseHCL: - fakeFilename := fmt.Sprintf("", name) - expr, diags := hclsyntax.ParseExpression([]byte(value), fakeFilename, hcl.Pos{Line: 1, Column: 1}) - if diags.HasErrors() { - return cty.DynamicVal, diags - } - val, valDiags := expr.Value(nil) - diags = append(diags, valDiags...) - return val, diags - default: - // Should never happen - panic(fmt.Errorf("Parse called on invalid VariableParsingMode %#v", m)) - } -} - -// Output represents an "output" block in a module or file. -type Output struct { - Name string - Description string - Expr hcl.Expression - DependsOn []hcl.Traversal - Sensitive bool - - DescriptionSet bool - SensitiveSet bool - - DeclRange hcl.Range -} - -func decodeOutputBlock(block *hcl.Block, override bool) (*Output, hcl.Diagnostics) { - o := &Output{ - Name: block.Labels[0], - DeclRange: block.DefRange, - } - - schema := outputBlockSchema - if override { - schema = schemaForOverrides(schema) - } - - content, diags := block.Body.Content(schema) - - if !hclsyntax.ValidIdentifier(o.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid output name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - - if attr, exists := content.Attributes["description"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &o.Description) - diags = append(diags, valDiags...) - o.DescriptionSet = true - } - - if attr, exists := content.Attributes["value"]; exists { - o.Expr = attr.Expr - } - - if attr, exists := content.Attributes["sensitive"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &o.Sensitive) - diags = append(diags, valDiags...) - o.SensitiveSet = true - } - - if attr, exists := content.Attributes["depends_on"]; exists { - deps, depsDiags := decodeDependsOn(attr) - diags = append(diags, depsDiags...) - o.DependsOn = append(o.DependsOn, deps...) - } - - return o, diags -} - -// Local represents a single entry from a "locals" block in a module or file. -// The "locals" block itself is not represented, because it serves only to -// provide context for us to interpret its contents. -type Local struct { - Name string - Expr hcl.Expression - - DeclRange hcl.Range -} - -func decodeLocalsBlock(block *hcl.Block) ([]*Local, hcl.Diagnostics) { - attrs, diags := block.Body.JustAttributes() - if len(attrs) == 0 { - return nil, diags - } - - locals := make([]*Local, 0, len(attrs)) - for name, attr := range attrs { - if !hclsyntax.ValidIdentifier(name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid local value name", - Detail: badIdentifierDetail, - Subject: &attr.NameRange, - }) - } - - locals = append(locals, &Local{ - Name: name, - Expr: attr.Expr, - DeclRange: attr.Range, - }) - } - return locals, diags -} - -// Addr returns the address of the local value declared by the receiver, -// relative to its containing module. -func (l *Local) Addr() addrs.LocalValue { - return addrs.LocalValue{ - Name: l.Name, - } -} - -var variableBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "description", - }, - { - Name: "default", - }, - { - Name: "type", - }, - }, -} - -var outputBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "description", - }, - { - Name: "value", - Required: true, - }, - { - Name: "depends_on", - }, - { - Name: "sensitive", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform/configs/parser.go b/vendor/github.com/hashicorp/terraform/configs/parser.go deleted file mode 100644 index 8176fa1b..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/parser.go +++ /dev/null @@ -1,100 +0,0 @@ -package configs - -import ( - "fmt" - "strings" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hclparse" - "github.com/spf13/afero" -) - -// Parser is the main interface to read configuration files and other related -// files from disk. -// -// It retains a cache of all files that are loaded so that they can be used -// to create source code snippets in diagnostics, etc. -type Parser struct { - fs afero.Afero - p *hclparse.Parser -} - -// NewParser creates and returns a new Parser that reads files from the given -// filesystem. If a nil filesystem is passed then the system's "real" filesystem -// will be used, via afero.OsFs. -func NewParser(fs afero.Fs) *Parser { - if fs == nil { - fs = afero.OsFs{} - } - - return &Parser{ - fs: afero.Afero{Fs: fs}, - p: hclparse.NewParser(), - } -} - -// LoadHCLFile is a low-level method that reads the file at the given path, -// parses it, and returns the hcl.Body representing its root. In many cases -// it is better to use one of the other Load*File methods on this type, -// which additionally decode the root body in some way and return a higher-level -// construct. -// -// If the file cannot be read at all -- e.g. because it does not exist -- then -// this method will return a nil body and error diagnostics. In this case -// callers may wish to ignore the provided error diagnostics and produce -// a more context-sensitive error instead. -// -// The file will be parsed using the HCL native syntax unless the filename -// ends with ".json", in which case the HCL JSON syntax will be used. -func (p *Parser) LoadHCLFile(path string) (hcl.Body, hcl.Diagnostics) { - src, err := p.fs.ReadFile(path) - - if err != nil { - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Failed to read file", - Detail: fmt.Sprintf("The file %q could not be read.", path), - }, - } - } - - var file *hcl.File - var diags hcl.Diagnostics - switch { - case strings.HasSuffix(path, ".json"): - file, diags = p.p.ParseJSON(src, path) - default: - file, diags = p.p.ParseHCL(src, path) - } - - // If the returned file or body is nil, then we'll return a non-nil empty - // body so we'll meet our contract that nil means an error reading the file. - if file == nil || file.Body == nil { - return hcl.EmptyBody(), diags - } - - return file.Body, diags -} - -// Sources returns a map of the cached source buffers for all files that -// have been loaded through this parser, with source filenames (as requested -// when each file was opened) as the keys. -func (p *Parser) Sources() map[string][]byte { - return p.p.Sources() -} - -// ForceFileSource artificially adds source code to the cache of file sources, -// as if it had been loaded from the given filename. -// -// This should be used only in special situations where configuration is loaded -// some other way. Most callers should load configuration via methods of -// Parser, which will update the sources cache automatically. -func (p *Parser) ForceFileSource(filename string, src []byte) { - // We'll make a synthetic hcl.File here just so we can reuse the - // existing cache. - p.p.AddFile(filename, &hcl.File{ - Body: hcl.EmptyBody(), - Bytes: src, - }) -} diff --git a/vendor/github.com/hashicorp/terraform/configs/parser_config.go b/vendor/github.com/hashicorp/terraform/configs/parser_config.go deleted file mode 100644 index 7f2ff271..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/parser_config.go +++ /dev/null @@ -1,247 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl2/hcl" -) - -// LoadConfigFile reads the file at the given path and parses it as a config -// file. -// -// If the file cannot be read -- for example, if it does not exist -- then -// a nil *File will be returned along with error diagnostics. Callers may wish -// to disregard the returned diagnostics in this case and instead generate -// their own error message(s) with additional context. -// -// If the returned diagnostics has errors when a non-nil map is returned -// then the map may be incomplete but should be valid enough for careful -// static analysis. -// -// This method wraps LoadHCLFile, and so it inherits the syntax selection -// behaviors documented for that method. -func (p *Parser) LoadConfigFile(path string) (*File, hcl.Diagnostics) { - return p.loadConfigFile(path, false) -} - -// LoadConfigFileOverride is the same as LoadConfigFile except that it relaxes -// certain required attribute constraints in order to interpret the given -// file as an overrides file. -func (p *Parser) LoadConfigFileOverride(path string) (*File, hcl.Diagnostics) { - return p.loadConfigFile(path, true) -} - -func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnostics) { - - body, diags := p.LoadHCLFile(path) - if body == nil { - return nil, diags - } - - file := &File{} - - var reqDiags hcl.Diagnostics - file.CoreVersionConstraints, reqDiags = sniffCoreVersionRequirements(body) - diags = append(diags, reqDiags...) - - content, contentDiags := body.Content(configFileSchema) - diags = append(diags, contentDiags...) - - for _, block := range content.Blocks { - switch block.Type { - - case "terraform": - content, contentDiags := block.Body.Content(terraformBlockSchema) - diags = append(diags, contentDiags...) - - // We ignore the "terraform_version" attribute here because - // sniffCoreVersionRequirements already dealt with that above. - - for _, innerBlock := range content.Blocks { - switch innerBlock.Type { - - case "backend": - backendCfg, cfgDiags := decodeBackendBlock(innerBlock) - diags = append(diags, cfgDiags...) - if backendCfg != nil { - file.Backends = append(file.Backends, backendCfg) - } - - case "required_providers": - reqs, reqsDiags := decodeRequiredProvidersBlock(innerBlock) - diags = append(diags, reqsDiags...) - file.ProviderRequirements = append(file.ProviderRequirements, reqs...) - - default: - // Should never happen because the above cases should be exhaustive - // for all block type names in our schema. - continue - - } - } - - case "provider": - cfg, cfgDiags := decodeProviderBlock(block) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.ProviderConfigs = append(file.ProviderConfigs, cfg) - } - - case "variable": - cfg, cfgDiags := decodeVariableBlock(block, override) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.Variables = append(file.Variables, cfg) - } - - case "locals": - defs, defsDiags := decodeLocalsBlock(block) - diags = append(diags, defsDiags...) - file.Locals = append(file.Locals, defs...) - - case "output": - cfg, cfgDiags := decodeOutputBlock(block, override) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.Outputs = append(file.Outputs, cfg) - } - - case "module": - cfg, cfgDiags := decodeModuleBlock(block, override) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.ModuleCalls = append(file.ModuleCalls, cfg) - } - - case "resource": - cfg, cfgDiags := decodeResourceBlock(block) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.ManagedResources = append(file.ManagedResources, cfg) - } - - case "data": - cfg, cfgDiags := decodeDataBlock(block) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.DataResources = append(file.DataResources, cfg) - } - - default: - // Should never happen because the above cases should be exhaustive - // for all block type names in our schema. - continue - - } - } - - return file, diags -} - -// sniffCoreVersionRequirements does minimal parsing of the given body for -// "terraform" blocks with "required_version" attributes, returning the -// requirements found. -// -// This is intended to maximize the chance that we'll be able to read the -// requirements (syntax errors notwithstanding) even if the config file contains -// constructs that might've been added in future Terraform versions -// -// This is a "best effort" sort of method which will return constraints it is -// able to find, but may return no constraints at all if the given body is -// so invalid that it cannot be decoded at all. -func sniffCoreVersionRequirements(body hcl.Body) ([]VersionConstraint, hcl.Diagnostics) { - rootContent, _, diags := body.PartialContent(configFileVersionSniffRootSchema) - - var constraints []VersionConstraint - - for _, block := range rootContent.Blocks { - content, _, blockDiags := block.Body.PartialContent(configFileVersionSniffBlockSchema) - diags = append(diags, blockDiags...) - - attr, exists := content.Attributes["required_version"] - if !exists { - continue - } - - constraint, constraintDiags := decodeVersionConstraint(attr) - diags = append(diags, constraintDiags...) - if !constraintDiags.HasErrors() { - constraints = append(constraints, constraint) - } - } - - return constraints, diags -} - -// configFileSchema is the schema for the top-level of a config file. We use -// the low-level HCL API for this level so we can easily deal with each -// block type separately with its own decoding logic. -var configFileSchema = &hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "terraform", - }, - { - Type: "provider", - LabelNames: []string{"name"}, - }, - { - Type: "variable", - LabelNames: []string{"name"}, - }, - { - Type: "locals", - }, - { - Type: "output", - LabelNames: []string{"name"}, - }, - { - Type: "module", - LabelNames: []string{"name"}, - }, - { - Type: "resource", - LabelNames: []string{"type", "name"}, - }, - { - Type: "data", - LabelNames: []string{"type", "name"}, - }, - }, -} - -// terraformBlockSchema is the schema for a top-level "terraform" block in -// a configuration file. -var terraformBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "required_version", - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "backend", - LabelNames: []string{"type"}, - }, - { - Type: "required_providers", - }, - }, -} - -// configFileVersionSniffRootSchema is a schema for sniffCoreVersionRequirements -var configFileVersionSniffRootSchema = &hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "terraform", - }, - }, -} - -// configFileVersionSniffBlockSchema is a schema for sniffCoreVersionRequirements -var configFileVersionSniffBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "required_version", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform/configs/parser_config_dir.go b/vendor/github.com/hashicorp/terraform/configs/parser_config_dir.go deleted file mode 100644 index 3014cb4b..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/parser_config_dir.go +++ /dev/null @@ -1,142 +0,0 @@ -package configs - -import ( - "fmt" - "path/filepath" - "strings" - - "github.com/hashicorp/hcl2/hcl" -) - -// LoadConfigDir reads the .tf and .tf.json files in the given directory -// as config files (using LoadConfigFile) and then combines these files into -// a single Module. -// -// If this method returns nil, that indicates that the given directory does not -// exist at all or could not be opened for some reason. Callers may wish to -// detect this case and ignore the returned diagnostics so that they can -// produce a more context-aware error message in that case. -// -// If this method returns a non-nil module while error diagnostics are returned -// then the module may be incomplete but can be used carefully for static -// analysis. -// -// This file does not consider a directory with no files to be an error, and -// will simply return an empty module in that case. Callers should first call -// Parser.IsConfigDir if they wish to recognize that situation. -// -// .tf files are parsed using the HCL native syntax while .tf.json files are -// parsed using the HCL JSON syntax. -func (p *Parser) LoadConfigDir(path string) (*Module, hcl.Diagnostics) { - primaryPaths, overridePaths, diags := p.dirFiles(path) - if diags.HasErrors() { - return nil, diags - } - - primary, fDiags := p.loadFiles(primaryPaths, false) - diags = append(diags, fDiags...) - override, fDiags := p.loadFiles(overridePaths, true) - diags = append(diags, fDiags...) - - mod, modDiags := NewModule(primary, override) - diags = append(diags, modDiags...) - - mod.SourceDir = path - - return mod, diags -} - -// ConfigDirFiles returns lists of the primary and override files configuration -// files in the given directory. -// -// If the given directory does not exist or cannot be read, error diagnostics -// are returned. If errors are returned, the resulting lists may be incomplete. -func (p Parser) ConfigDirFiles(dir string) (primary, override []string, diags hcl.Diagnostics) { - return p.dirFiles(dir) -} - -// IsConfigDir determines whether the given path refers to a directory that -// exists and contains at least one Terraform config file (with a .tf or -// .tf.json extension.) -func (p *Parser) IsConfigDir(path string) bool { - primaryPaths, overridePaths, _ := p.dirFiles(path) - return (len(primaryPaths) + len(overridePaths)) > 0 -} - -func (p *Parser) loadFiles(paths []string, override bool) ([]*File, hcl.Diagnostics) { - var files []*File - var diags hcl.Diagnostics - - for _, path := range paths { - var f *File - var fDiags hcl.Diagnostics - if override { - f, fDiags = p.LoadConfigFileOverride(path) - } else { - f, fDiags = p.LoadConfigFile(path) - } - diags = append(diags, fDiags...) - if f != nil { - files = append(files, f) - } - } - - return files, diags -} - -func (p *Parser) dirFiles(dir string) (primary, override []string, diags hcl.Diagnostics) { - infos, err := p.fs.ReadDir(dir) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Failed to read module directory", - Detail: fmt.Sprintf("Module directory %s does not exist or cannot be read.", dir), - }) - return - } - - for _, info := range infos { - if info.IsDir() { - // We only care about files - continue - } - - name := info.Name() - ext := fileExt(name) - if ext == "" || IsIgnoredFile(name) { - continue - } - - baseName := name[:len(name)-len(ext)] // strip extension - isOverride := baseName == "override" || strings.HasSuffix(baseName, "_override") - - fullPath := filepath.Join(dir, name) - if isOverride { - override = append(override, fullPath) - } else { - primary = append(primary, fullPath) - } - } - - return -} - -// fileExt returns the Terraform configuration extension of the given -// path, or a blank string if it is not a recognized extension. -func fileExt(path string) string { - if strings.HasSuffix(path, ".tf") { - return ".tf" - } else if strings.HasSuffix(path, ".tf.json") { - return ".tf.json" - } else { - return "" - } -} - -// IsIgnoredFile returns true if the given filename (which must not have a -// directory path ahead of it) should be ignored as e.g. an editor swap file. -func IsIgnoredFile(name string) bool { - return strings.HasPrefix(name, ".") || // Unix-like hidden files - strings.HasSuffix(name, "~") || // vim - strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#") // emacs -} diff --git a/vendor/github.com/hashicorp/terraform/configs/parser_values.go b/vendor/github.com/hashicorp/terraform/configs/parser_values.go deleted file mode 100644 index b7f1c1c5..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/parser_values.go +++ /dev/null @@ -1,43 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" -) - -// LoadValuesFile reads the file at the given path and parses it as a "values -// file", which is an HCL config file whose top-level attributes are treated -// as arbitrary key.value pairs. -// -// If the file cannot be read -- for example, if it does not exist -- then -// a nil map will be returned along with error diagnostics. Callers may wish -// to disregard the returned diagnostics in this case and instead generate -// their own error message(s) with additional context. -// -// If the returned diagnostics has errors when a non-nil map is returned -// then the map may be incomplete but should be valid enough for careful -// static analysis. -// -// This method wraps LoadHCLFile, and so it inherits the syntax selection -// behaviors documented for that method. -func (p *Parser) LoadValuesFile(path string) (map[string]cty.Value, hcl.Diagnostics) { - body, diags := p.LoadHCLFile(path) - if body == nil { - return nil, diags - } - - vals := make(map[string]cty.Value) - attrs, attrDiags := body.JustAttributes() - diags = append(diags, attrDiags...) - if attrs == nil { - return vals, diags - } - - for name, attr := range attrs { - val, valDiags := attr.Expr.Value(nil) - diags = append(diags, valDiags...) - vals[name] = val - } - - return vals, diags -} diff --git a/vendor/github.com/hashicorp/terraform/configs/provider.go b/vendor/github.com/hashicorp/terraform/configs/provider.go deleted file mode 100644 index d01d5cf2..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/provider.go +++ /dev/null @@ -1,144 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/gohcl" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - - "github.com/hashicorp/terraform/addrs" -) - -// Provider represents a "provider" block in a module or file. A provider -// block is a provider configuration, and there can be zero or more -// configurations for each actual provider. -type Provider struct { - Name string - NameRange hcl.Range - Alias string - AliasRange *hcl.Range // nil if no alias set - - Version VersionConstraint - - Config hcl.Body - - DeclRange hcl.Range -} - -func decodeProviderBlock(block *hcl.Block) (*Provider, hcl.Diagnostics) { - content, config, diags := block.Body.PartialContent(providerBlockSchema) - - provider := &Provider{ - Name: block.Labels[0], - NameRange: block.LabelRanges[0], - Config: config, - DeclRange: block.DefRange, - } - - if attr, exists := content.Attributes["alias"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &provider.Alias) - diags = append(diags, valDiags...) - provider.AliasRange = attr.Expr.Range().Ptr() - - if !hclsyntax.ValidIdentifier(provider.Alias) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration alias", - Detail: fmt.Sprintf("An alias must be a valid name. %s", badIdentifierDetail), - }) - } - } - - if attr, exists := content.Attributes["version"]; exists { - var versionDiags hcl.Diagnostics - provider.Version, versionDiags = decodeVersionConstraint(attr) - diags = append(diags, versionDiags...) - } - - // Reserved attribute names - for _, name := range []string{"count", "depends_on", "for_each", "source"} { - if attr, exists := content.Attributes[name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in provider block", - Detail: fmt.Sprintf("The provider argument name %q is reserved for use by Terraform in a future version.", name), - Subject: &attr.NameRange, - }) - } - } - - // Reserved block types (all of them) - for _, block := range content.Blocks { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in provider block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - - return provider, diags -} - -// Addr returns the address of the receiving provider configuration, relative -// to its containing module. -func (p *Provider) Addr() addrs.ProviderConfig { - return addrs.ProviderConfig{ - Type: p.Name, - Alias: p.Alias, - } -} - -func (p *Provider) moduleUniqueKey() string { - if p.Alias != "" { - return fmt.Sprintf("%s.%s", p.Name, p.Alias) - } - return p.Name -} - -// ProviderRequirement represents a declaration of a dependency on a particular -// provider version without actually configuring that provider. This is used in -// child modules that expect a provider to be passed in from their parent. -type ProviderRequirement struct { - Name string - Requirement VersionConstraint -} - -func decodeRequiredProvidersBlock(block *hcl.Block) ([]*ProviderRequirement, hcl.Diagnostics) { - attrs, diags := block.Body.JustAttributes() - var reqs []*ProviderRequirement - for name, attr := range attrs { - req, reqDiags := decodeVersionConstraint(attr) - diags = append(diags, reqDiags...) - if !diags.HasErrors() { - reqs = append(reqs, &ProviderRequirement{ - Name: name, - Requirement: req, - }) - } - } - return reqs, diags -} - -var providerBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "alias", - }, - { - Name: "version", - }, - - // Attribute names reserved for future expansion. - {Name: "count"}, - {Name: "depends_on"}, - {Name: "for_each"}, - {Name: "source"}, - }, - Blocks: []hcl.BlockHeaderSchema{ - // _All_ of these are reserved for future expansion. - {Type: "lifecycle"}, - {Type: "locals"}, - }, -} diff --git a/vendor/github.com/hashicorp/terraform/configs/provisioner.go b/vendor/github.com/hashicorp/terraform/configs/provisioner.go deleted file mode 100644 index b031dd0b..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/provisioner.go +++ /dev/null @@ -1,150 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/hcl" -) - -// Provisioner represents a "provisioner" block when used within a -// "resource" block in a module or file. -type Provisioner struct { - Type string - Config hcl.Body - Connection *Connection - When ProvisionerWhen - OnFailure ProvisionerOnFailure - - DeclRange hcl.Range - TypeRange hcl.Range -} - -func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) { - pv := &Provisioner{ - Type: block.Labels[0], - TypeRange: block.LabelRanges[0], - DeclRange: block.DefRange, - When: ProvisionerWhenCreate, - OnFailure: ProvisionerOnFailureFail, - } - - content, config, diags := block.Body.PartialContent(provisionerBlockSchema) - pv.Config = config - - if attr, exists := content.Attributes["when"]; exists { - expr, shimDiags := shimTraversalInString(attr.Expr, true) - diags = append(diags, shimDiags...) - - switch hcl.ExprAsKeyword(expr) { - case "create": - pv.When = ProvisionerWhenCreate - case "destroy": - pv.When = ProvisionerWhenDestroy - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid \"when\" keyword", - Detail: "The \"when\" argument requires one of the following keywords: create or destroy.", - Subject: expr.Range().Ptr(), - }) - } - } - - if attr, exists := content.Attributes["on_failure"]; exists { - expr, shimDiags := shimTraversalInString(attr.Expr, true) - diags = append(diags, shimDiags...) - - switch hcl.ExprAsKeyword(expr) { - case "continue": - pv.OnFailure = ProvisionerOnFailureContinue - case "fail": - pv.OnFailure = ProvisionerOnFailureFail - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid \"on_failure\" keyword", - Detail: "The \"on_failure\" argument requires one of the following keywords: continue or fail.", - Subject: attr.Expr.Range().Ptr(), - }) - } - } - - var seenConnection *hcl.Block - for _, block := range content.Blocks { - switch block.Type { - - case "connection": - if seenConnection != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate connection block", - Detail: fmt.Sprintf("This provisioner already has a connection block at %s.", seenConnection.DefRange), - Subject: &block.DefRange, - }) - continue - } - seenConnection = block - - //conn, connDiags := decodeConnectionBlock(block) - //diags = append(diags, connDiags...) - pv.Connection = &Connection{ - Config: block.Body, - DeclRange: block.DefRange, - } - - default: - // Any other block types are ones we've reserved for future use, - // so they get a generic message. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in provisioner block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - } - - return pv, diags -} - -// Connection represents a "connection" block when used within either a -// "resource" or "provisioner" block in a module or file. -type Connection struct { - Config hcl.Body - - DeclRange hcl.Range -} - -// ProvisionerWhen is an enum for valid values for when to run provisioners. -type ProvisionerWhen int - -//go:generate stringer -type ProvisionerWhen - -const ( - ProvisionerWhenInvalid ProvisionerWhen = iota - ProvisionerWhenCreate - ProvisionerWhenDestroy -) - -// ProvisionerOnFailure is an enum for valid values for on_failure options -// for provisioners. -type ProvisionerOnFailure int - -//go:generate stringer -type ProvisionerOnFailure - -const ( - ProvisionerOnFailureInvalid ProvisionerOnFailure = iota - ProvisionerOnFailureContinue - ProvisionerOnFailureFail -) - -var provisionerBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - {Name: "when"}, - {Name: "on_failure"}, - }, - Blocks: []hcl.BlockHeaderSchema{ - {Type: "connection"}, - {Type: "lifecycle"}, // reserved for future use - }, -} diff --git a/vendor/github.com/hashicorp/terraform/configs/provisioneronfailure_string.go b/vendor/github.com/hashicorp/terraform/configs/provisioneronfailure_string.go deleted file mode 100644 index 8704b086..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/provisioneronfailure_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by "stringer -type ProvisionerOnFailure"; DO NOT EDIT. - -package configs - -import "strconv" - -const _ProvisionerOnFailure_name = "ProvisionerOnFailureInvalidProvisionerOnFailureContinueProvisionerOnFailureFail" - -var _ProvisionerOnFailure_index = [...]uint8{0, 27, 55, 79} - -func (i ProvisionerOnFailure) String() string { - if i < 0 || i >= ProvisionerOnFailure(len(_ProvisionerOnFailure_index)-1) { - return "ProvisionerOnFailure(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _ProvisionerOnFailure_name[_ProvisionerOnFailure_index[i]:_ProvisionerOnFailure_index[i+1]] -} diff --git a/vendor/github.com/hashicorp/terraform/configs/provisionerwhen_string.go b/vendor/github.com/hashicorp/terraform/configs/provisionerwhen_string.go deleted file mode 100644 index cbecb20a..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/provisionerwhen_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by "stringer -type ProvisionerWhen"; DO NOT EDIT. - -package configs - -import "strconv" - -const _ProvisionerWhen_name = "ProvisionerWhenInvalidProvisionerWhenCreateProvisionerWhenDestroy" - -var _ProvisionerWhen_index = [...]uint8{0, 22, 43, 65} - -func (i ProvisionerWhen) String() string { - if i < 0 || i >= ProvisionerWhen(len(_ProvisionerWhen_index)-1) { - return "ProvisionerWhen(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _ProvisionerWhen_name[_ProvisionerWhen_index[i]:_ProvisionerWhen_index[i+1]] -} diff --git a/vendor/github.com/hashicorp/terraform/configs/resource.go b/vendor/github.com/hashicorp/terraform/configs/resource.go deleted file mode 100644 index de1a3434..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/resource.go +++ /dev/null @@ -1,486 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/gohcl" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - - "github.com/hashicorp/terraform/addrs" -) - -// Resource represents a "resource" or "data" block in a module or file. -type Resource struct { - Mode addrs.ResourceMode - Name string - Type string - Config hcl.Body - Count hcl.Expression - ForEach hcl.Expression - - ProviderConfigRef *ProviderConfigRef - - DependsOn []hcl.Traversal - - // Managed is populated only for Mode = addrs.ManagedResourceMode, - // containing the additional fields that apply to managed resources. - // For all other resource modes, this field is nil. - Managed *ManagedResource - - DeclRange hcl.Range - TypeRange hcl.Range -} - -// ManagedResource represents a "resource" block in a module or file. -type ManagedResource struct { - Connection *Connection - Provisioners []*Provisioner - - CreateBeforeDestroy bool - PreventDestroy bool - IgnoreChanges []hcl.Traversal - IgnoreAllChanges bool - - CreateBeforeDestroySet bool - PreventDestroySet bool -} - -func (r *Resource) moduleUniqueKey() string { - return r.Addr().String() -} - -// Addr returns a resource address for the receiver that is relative to the -// resource's containing module. -func (r *Resource) Addr() addrs.Resource { - return addrs.Resource{ - Mode: r.Mode, - Type: r.Type, - Name: r.Name, - } -} - -// ProviderConfigAddr returns the address for the provider configuration -// that should be used for this resource. This function implements the -// default behavior of extracting the type from the resource type name if -// an explicit "provider" argument was not provided. -func (r *Resource) ProviderConfigAddr() addrs.ProviderConfig { - if r.ProviderConfigRef == nil { - return r.Addr().DefaultProviderConfig() - } - - return addrs.ProviderConfig{ - Type: r.ProviderConfigRef.Name, - Alias: r.ProviderConfigRef.Alias, - } -} - -func decodeResourceBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { - r := &Resource{ - Mode: addrs.ManagedResourceMode, - Type: block.Labels[0], - Name: block.Labels[1], - DeclRange: block.DefRange, - TypeRange: block.LabelRanges[0], - Managed: &ManagedResource{}, - } - - content, remain, diags := block.Body.PartialContent(resourceBlockSchema) - r.Config = remain - - if !hclsyntax.ValidIdentifier(r.Type) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource type name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - if !hclsyntax.ValidIdentifier(r.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[1], - }) - } - - if attr, exists := content.Attributes["count"]; exists { - r.Count = attr.Expr - } - - if attr, exists := content.Attributes["for_each"]; exists { - r.ForEach = attr.Expr - // We currently parse this, but don't yet do anything with it. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in resource block", - Detail: fmt.Sprintf("The name %q is reserved for use in a future version of Terraform.", attr.Name), - Subject: &attr.NameRange, - }) - } - - if attr, exists := content.Attributes["provider"]; exists { - var providerDiags hcl.Diagnostics - r.ProviderConfigRef, providerDiags = decodeProviderConfigRef(attr.Expr, "provider") - diags = append(diags, providerDiags...) - } - - if attr, exists := content.Attributes["depends_on"]; exists { - deps, depsDiags := decodeDependsOn(attr) - diags = append(diags, depsDiags...) - r.DependsOn = append(r.DependsOn, deps...) - } - - var seenLifecycle *hcl.Block - var seenConnection *hcl.Block - for _, block := range content.Blocks { - switch block.Type { - case "lifecycle": - if seenLifecycle != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate lifecycle block", - Detail: fmt.Sprintf("This resource already has a lifecycle block at %s.", seenLifecycle.DefRange), - Subject: &block.DefRange, - }) - continue - } - seenLifecycle = block - - lcContent, lcDiags := block.Body.Content(resourceLifecycleBlockSchema) - diags = append(diags, lcDiags...) - - if attr, exists := lcContent.Attributes["create_before_destroy"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &r.Managed.CreateBeforeDestroy) - diags = append(diags, valDiags...) - r.Managed.CreateBeforeDestroySet = true - } - - if attr, exists := lcContent.Attributes["prevent_destroy"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &r.Managed.PreventDestroy) - diags = append(diags, valDiags...) - r.Managed.PreventDestroySet = true - } - - if attr, exists := lcContent.Attributes["ignore_changes"]; exists { - - // ignore_changes can either be a list of relative traversals - // or it can be just the keyword "all" to ignore changes to this - // resource entirely. - // ignore_changes = [ami, instance_type] - // ignore_changes = all - // We also allow two legacy forms for compatibility with earlier - // versions: - // ignore_changes = ["ami", "instance_type"] - // ignore_changes = ["*"] - - kw := hcl.ExprAsKeyword(attr.Expr) - - switch { - case kw == "all": - r.Managed.IgnoreAllChanges = true - default: - exprs, listDiags := hcl.ExprList(attr.Expr) - diags = append(diags, listDiags...) - - var ignoreAllRange hcl.Range - - for _, expr := range exprs { - - // our expr might be the literal string "*", which - // we accept as a deprecated way of saying "all". - if shimIsIgnoreChangesStar(expr) { - r.Managed.IgnoreAllChanges = true - ignoreAllRange = expr.Range() - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Deprecated ignore_changes wildcard", - Detail: "The [\"*\"] form of ignore_changes wildcard is deprecated. Use \"ignore_changes = all\" to ignore changes to all attributes.", - Subject: attr.Expr.Range().Ptr(), - }) - continue - } - - expr, shimDiags := shimTraversalInString(expr, false) - diags = append(diags, shimDiags...) - - traversal, travDiags := hcl.RelTraversalForExpr(expr) - diags = append(diags, travDiags...) - if len(traversal) != 0 { - r.Managed.IgnoreChanges = append(r.Managed.IgnoreChanges, traversal) - } - } - - if r.Managed.IgnoreAllChanges && len(r.Managed.IgnoreChanges) != 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid ignore_changes ruleset", - Detail: "Cannot mix wildcard string \"*\" with non-wildcard references.", - Subject: &ignoreAllRange, - Context: attr.Expr.Range().Ptr(), - }) - } - - } - - } - - case "connection": - if seenConnection != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate connection block", - Detail: fmt.Sprintf("This resource already has a connection block at %s.", seenConnection.DefRange), - Subject: &block.DefRange, - }) - continue - } - seenConnection = block - - r.Managed.Connection = &Connection{ - Config: block.Body, - DeclRange: block.DefRange, - } - - case "provisioner": - pv, pvDiags := decodeProvisionerBlock(block) - diags = append(diags, pvDiags...) - if pv != nil { - r.Managed.Provisioners = append(r.Managed.Provisioners, pv) - } - - default: - // Any other block types are ones we've reserved for future use, - // so they get a generic message. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in resource block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - } - - return r, diags -} - -func decodeDataBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { - r := &Resource{ - Mode: addrs.DataResourceMode, - Type: block.Labels[0], - Name: block.Labels[1], - DeclRange: block.DefRange, - TypeRange: block.LabelRanges[0], - } - - content, remain, diags := block.Body.PartialContent(dataBlockSchema) - r.Config = remain - - if !hclsyntax.ValidIdentifier(r.Type) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid data source name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - if !hclsyntax.ValidIdentifier(r.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid data resource name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[1], - }) - } - - if attr, exists := content.Attributes["count"]; exists { - r.Count = attr.Expr - } - - if attr, exists := content.Attributes["for_each"]; exists { - r.ForEach = attr.Expr - // We currently parse this, but don't yet do anything with it. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in module block", - Detail: fmt.Sprintf("The name %q is reserved for use in a future version of Terraform.", attr.Name), - Subject: &attr.NameRange, - }) - } - - if attr, exists := content.Attributes["provider"]; exists { - var providerDiags hcl.Diagnostics - r.ProviderConfigRef, providerDiags = decodeProviderConfigRef(attr.Expr, "provider") - diags = append(diags, providerDiags...) - } - - if attr, exists := content.Attributes["depends_on"]; exists { - deps, depsDiags := decodeDependsOn(attr) - diags = append(diags, depsDiags...) - r.DependsOn = append(r.DependsOn, deps...) - } - - for _, block := range content.Blocks { - // All of the block types we accept are just reserved for future use, but some get a specialized error message. - switch block.Type { - case "lifecycle": - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported lifecycle block", - Detail: "Data resources do not have lifecycle settings, so a lifecycle block is not allowed.", - Subject: &block.DefRange, - }) - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in data block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - } - - return r, diags -} - -type ProviderConfigRef struct { - Name string - NameRange hcl.Range - Alias string - AliasRange *hcl.Range // nil if alias not set -} - -func decodeProviderConfigRef(expr hcl.Expression, argName string) (*ProviderConfigRef, hcl.Diagnostics) { - var diags hcl.Diagnostics - - var shimDiags hcl.Diagnostics - expr, shimDiags = shimTraversalInString(expr, false) - diags = append(diags, shimDiags...) - - traversal, travDiags := hcl.AbsTraversalForExpr(expr) - - // AbsTraversalForExpr produces only generic errors, so we'll discard - // the errors given and produce our own with extra context. If we didn't - // get any errors then we might still have warnings, though. - if !travDiags.HasErrors() { - diags = append(diags, travDiags...) - } - - if len(traversal) < 1 || len(traversal) > 2 { - // A provider reference was given as a string literal in the legacy - // configuration language and there are lots of examples out there - // showing that usage, so we'll sniff for that situation here and - // produce a specialized error message for it to help users find - // the new correct form. - if exprIsNativeQuotedString(expr) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration reference", - Detail: "A provider configuration reference must not be given in quotes.", - Subject: expr.Range().Ptr(), - }) - return nil, diags - } - - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration reference", - Detail: fmt.Sprintf("The %s argument requires a provider type name, optionally followed by a period and then a configuration alias.", argName), - Subject: expr.Range().Ptr(), - }) - return nil, diags - } - - ret := &ProviderConfigRef{ - Name: traversal.RootName(), - NameRange: traversal[0].SourceRange(), - } - - if len(traversal) > 1 { - aliasStep, ok := traversal[1].(hcl.TraverseAttr) - if !ok { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration reference", - Detail: "Provider name must either stand alone or be followed by a period and then a configuration alias.", - Subject: traversal[1].SourceRange().Ptr(), - }) - return ret, diags - } - - ret.Alias = aliasStep.Name - ret.AliasRange = aliasStep.SourceRange().Ptr() - } - - return ret, diags -} - -// Addr returns the provider config address corresponding to the receiving -// config reference. -// -// This is a trivial conversion, essentially just discarding the source -// location information and keeping just the addressing information. -func (r *ProviderConfigRef) Addr() addrs.ProviderConfig { - return addrs.ProviderConfig{ - Type: r.Name, - Alias: r.Alias, - } -} - -func (r *ProviderConfigRef) String() string { - if r == nil { - return "" - } - if r.Alias != "" { - return fmt.Sprintf("%s.%s", r.Name, r.Alias) - } - return r.Name -} - -var commonResourceAttributes = []hcl.AttributeSchema{ - { - Name: "count", - }, - { - Name: "for_each", - }, - { - Name: "provider", - }, - { - Name: "depends_on", - }, -} - -var resourceBlockSchema = &hcl.BodySchema{ - Attributes: commonResourceAttributes, - Blocks: []hcl.BlockHeaderSchema{ - {Type: "locals"}, // reserved for future use - {Type: "lifecycle"}, - {Type: "connection"}, - {Type: "provisioner", LabelNames: []string{"type"}}, - }, -} - -var dataBlockSchema = &hcl.BodySchema{ - Attributes: commonResourceAttributes, - Blocks: []hcl.BlockHeaderSchema{ - {Type: "lifecycle"}, // reserved for future use - {Type: "locals"}, // reserved for future use - }, -} - -var resourceLifecycleBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "create_before_destroy", - }, - { - Name: "prevent_destroy", - }, - { - Name: "ignore_changes", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform/configs/synth_body.go b/vendor/github.com/hashicorp/terraform/configs/synth_body.go deleted file mode 100644 index 3ae1bff6..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/synth_body.go +++ /dev/null @@ -1,118 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - "github.com/zclconf/go-cty/cty" -) - -// SynthBody produces a synthetic hcl.Body that behaves as if it had attributes -// corresponding to the elements given in the values map. -// -// This is useful in situations where, for example, values provided on the -// command line can override values given in configuration, using MergeBodies. -// -// The given filename is used in case any diagnostics are returned. Since -// the created body is synthetic, it is likely that this will not be a "real" -// filename. For example, if from a command line argument it could be -// a representation of that argument's name, such as "-var=...". -func SynthBody(filename string, values map[string]cty.Value) hcl.Body { - return synthBody{ - Filename: filename, - Values: values, - } -} - -type synthBody struct { - Filename string - Values map[string]cty.Value -} - -func (b synthBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - content, remain, diags := b.PartialContent(schema) - remainS := remain.(synthBody) - for name := range remainS.Values { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported attribute", - Detail: fmt.Sprintf("An attribute named %q is not expected here.", name), - Subject: b.synthRange().Ptr(), - }) - } - return content, diags -} - -func (b synthBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - var diags hcl.Diagnostics - content := &hcl.BodyContent{ - Attributes: make(hcl.Attributes), - MissingItemRange: b.synthRange(), - } - - remainValues := make(map[string]cty.Value) - for attrName, val := range b.Values { - remainValues[attrName] = val - } - - for _, attrS := range schema.Attributes { - delete(remainValues, attrS.Name) - val, defined := b.Values[attrS.Name] - if !defined { - if attrS.Required { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing required attribute", - Detail: fmt.Sprintf("The attribute %q is required, but no definition was found.", attrS.Name), - Subject: b.synthRange().Ptr(), - }) - } - continue - } - content.Attributes[attrS.Name] = b.synthAttribute(attrS.Name, val) - } - - // We just ignore blocks altogether, because this body type never has - // nested blocks. - - remain := synthBody{ - Filename: b.Filename, - Values: remainValues, - } - - return content, remain, diags -} - -func (b synthBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - ret := make(hcl.Attributes) - for name, val := range b.Values { - ret[name] = b.synthAttribute(name, val) - } - return ret, nil -} - -func (b synthBody) MissingItemRange() hcl.Range { - return b.synthRange() -} - -func (b synthBody) synthAttribute(name string, val cty.Value) *hcl.Attribute { - rng := b.synthRange() - return &hcl.Attribute{ - Name: name, - Expr: &hclsyntax.LiteralValueExpr{ - Val: val, - SrcRange: rng, - }, - NameRange: rng, - Range: rng, - } -} - -func (b synthBody) synthRange() hcl.Range { - return hcl.Range{ - Filename: b.Filename, - Start: hcl.Pos{Line: 1, Column: 1}, - End: hcl.Pos{Line: 1, Column: 1}, - } -} diff --git a/vendor/github.com/hashicorp/terraform/configs/util.go b/vendor/github.com/hashicorp/terraform/configs/util.go deleted file mode 100644 index 002bb8cb..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/util.go +++ /dev/null @@ -1,45 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" -) - -// exprIsNativeQuotedString determines whether the given expression looks like -// it's a quoted string in the HCL native syntax. -// -// This should be used sparingly only for situations where our legacy HCL -// decoding would've expected a keyword or reference in quotes but our new -// decoding expects the keyword or reference to be provided directly as -// an identifier-based expression. -func exprIsNativeQuotedString(expr hcl.Expression) bool { - _, ok := expr.(*hclsyntax.TemplateExpr) - return ok -} - -// schemaForOverrides takes a *hcl.BodySchema and produces a new one that is -// equivalent except that any required attributes are forced to not be required. -// -// This is useful for dealing with "override" config files, which are allowed -// to omit things that they don't wish to override from the main configuration. -// -// The returned schema may have some pointers in common with the given schema, -// so neither the given schema nor the returned schema should be modified after -// using this function in order to avoid confusion. -// -// Overrides are rarely used, so it's recommended to just create the override -// schema on the fly only when it's needed, rather than storing it in a global -// variable as we tend to do for a primary schema. -func schemaForOverrides(schema *hcl.BodySchema) *hcl.BodySchema { - ret := &hcl.BodySchema{ - Attributes: make([]hcl.AttributeSchema, len(schema.Attributes)), - Blocks: schema.Blocks, - } - - for i, attrS := range schema.Attributes { - ret.Attributes[i] = attrS - ret.Attributes[i].Required = false - } - - return ret -} diff --git a/vendor/github.com/hashicorp/terraform/configs/variable_type_hint.go b/vendor/github.com/hashicorp/terraform/configs/variable_type_hint.go deleted file mode 100644 index 204efd12..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/variable_type_hint.go +++ /dev/null @@ -1,45 +0,0 @@ -package configs - -// VariableTypeHint is an enumeration used for the Variable.TypeHint field, -// which is an incompletely-specified type for the variable which is used -// as a hint for whether a value provided in an ambiguous context (on the -// command line or in an environment variable) should be taken literally as a -// string or parsed as an HCL expression to produce a data structure. -// -// The type hint is applied to runtime values as well, but since it does not -// accurately describe a precise type it is not fully-sufficient to infer -// the dynamic type of a value passed through a variable. -// -// These hints use inaccurate terminology for historical reasons. Full details -// are in the documentation for each constant in this enumeration, but in -// summary: -// -// TypeHintString requires a primitive type -// TypeHintList requires a type that could be converted to a tuple -// TypeHintMap requires a type that could be converted to an object -type VariableTypeHint rune - -//go:generate stringer -type VariableTypeHint - -// TypeHintNone indicates the absense of a type hint. Values specified in -// ambiguous contexts will be treated as literal strings, as if TypeHintString -// were selected, but no runtime value checks will be applied. This is reasonable -// type hint for a module that is never intended to be used at the top-level -// of a configuration, since descendent modules never recieve values from -// ambiguous contexts. -const TypeHintNone VariableTypeHint = 0 - -// TypeHintString spec indicates that a value provided in an ambiguous context -// should be treated as a literal string, and additionally requires that the -// runtime value for the variable is of a primitive type (string, number, bool). -const TypeHintString VariableTypeHint = 'S' - -// TypeHintList indicates that a value provided in an ambiguous context should -// be treated as an HCL expression, and additionally requires that the -// runtime value for the variable is of an tuple, list, or set type. -const TypeHintList VariableTypeHint = 'L' - -// TypeHintMap indicates that a value provided in an ambiguous context should -// be treated as an HCL expression, and additionally requires that the -// runtime value for the variable is of an object or map type. -const TypeHintMap VariableTypeHint = 'M' diff --git a/vendor/github.com/hashicorp/terraform/configs/variabletypehint_string.go b/vendor/github.com/hashicorp/terraform/configs/variabletypehint_string.go deleted file mode 100644 index 4447cf55..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/variabletypehint_string.go +++ /dev/null @@ -1,29 +0,0 @@ -// Code generated by "stringer -type VariableTypeHint"; DO NOT EDIT. - -package configs - -import "strconv" - -const ( - _VariableTypeHint_name_0 = "TypeHintNone" - _VariableTypeHint_name_1 = "TypeHintListTypeHintMap" - _VariableTypeHint_name_2 = "TypeHintString" -) - -var ( - _VariableTypeHint_index_1 = [...]uint8{0, 12, 23} -) - -func (i VariableTypeHint) String() string { - switch { - case i == 0: - return _VariableTypeHint_name_0 - case 76 <= i && i <= 77: - i -= 76 - return _VariableTypeHint_name_1[_VariableTypeHint_index_1[i]:_VariableTypeHint_index_1[i+1]] - case i == 83: - return _VariableTypeHint_name_2 - default: - return "VariableTypeHint(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform/configs/version_constraint.go b/vendor/github.com/hashicorp/terraform/configs/version_constraint.go deleted file mode 100644 index 00dc739a..00000000 --- a/vendor/github.com/hashicorp/terraform/configs/version_constraint.go +++ /dev/null @@ -1,61 +0,0 @@ -package configs - -import ( - "fmt" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// VersionConstraint represents a version constraint on some resource -// (e.g. Terraform Core, a provider, a module, ...) that carries with it -// a source range so that a helpful diagnostic can be printed in the event -// that a particular constraint does not match. -type VersionConstraint struct { - Required version.Constraints - DeclRange hcl.Range -} - -func decodeVersionConstraint(attr *hcl.Attribute) (VersionConstraint, hcl.Diagnostics) { - ret := VersionConstraint{ - DeclRange: attr.Range, - } - - val, diags := attr.Expr.Value(nil) - var err error - val, err = convert.Convert(val, cty.String) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid version constraint", - Detail: fmt.Sprintf("A string value is required for %s.", attr.Name), - Subject: attr.Expr.Range().Ptr(), - }) - return ret, diags - } - - if val.IsNull() { - // A null version constraint is strange, but we'll just treat it - // like an empty constraint set. - return ret, diags - } - - constraintStr := val.AsString() - constraints, err := version.NewConstraint(constraintStr) - if err != nil { - // NewConstraint doesn't return user-friendly errors, so we'll just - // ignore the provided error and produce our own generic one. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid version constraint", - Detail: "This string does not use correct version constraint syntax.", // Not very actionable :( - Subject: attr.Expr.Range().Ptr(), - }) - return ret, diags - } - - ret.Required = constraints - return ret, diags -} diff --git a/vendor/github.com/hashicorp/terraform/dag/dag.go b/vendor/github.com/hashicorp/terraform/dag/dag.go index 77c67eff..b7eb10c3 100644 --- a/vendor/github.com/hashicorp/terraform/dag/dag.go +++ b/vendor/github.com/hashicorp/terraform/dag/dag.go @@ -5,8 +5,6 @@ import ( "sort" "strings" - "github.com/hashicorp/terraform/tfdiags" - "github.com/hashicorp/go-multierror" ) @@ -17,7 +15,7 @@ type AcyclicGraph struct { } // WalkFunc is the callback used for walking the graph. -type WalkFunc func(Vertex) tfdiags.Diagnostics +type WalkFunc func(Vertex) error // DepthWalkFunc is a walk function that also receives the current depth of the // walk as an argument @@ -163,9 +161,9 @@ func (g *AcyclicGraph) Cycles() [][]Vertex { } // Walk walks the graph, calling your callback as each node is visited. -// This will walk nodes in parallel if it can. The resulting diagnostics -// contains problems from all graphs visited, in no particular order. -func (g *AcyclicGraph) Walk(cb WalkFunc) tfdiags.Diagnostics { +// This will walk nodes in parallel if it can. Because the walk is done +// in parallel, the error returned will be a multierror. +func (g *AcyclicGraph) Walk(cb WalkFunc) error { defer g.debug.BeginOperation(typeWalk, "").End("") w := &Walker{Callback: cb, Reverse: true} diff --git a/vendor/github.com/hashicorp/terraform/dag/walk.go b/vendor/github.com/hashicorp/terraform/dag/walk.go index 1c926c2c..f03b1003 100644 --- a/vendor/github.com/hashicorp/terraform/dag/walk.go +++ b/vendor/github.com/hashicorp/terraform/dag/walk.go @@ -2,11 +2,12 @@ package dag import ( "errors" + "fmt" "log" "sync" "time" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/go-multierror" ) // Walker is used to walk every vertex of a graph in parallel. @@ -53,15 +54,10 @@ type Walker struct { // if new vertices are added. wait sync.WaitGroup - // diagsMap contains the diagnostics recorded so far for execution, - // and upstreamFailed contains all the vertices whose problems were - // caused by upstream failures, and thus whose diagnostics should be - // excluded from the final set. - // - // Readers and writers of either map must hold diagsLock. - diagsMap map[Vertex]tfdiags.Diagnostics - upstreamFailed map[Vertex]struct{} - diagsLock sync.Mutex + // errMap contains the errors recorded so far for execution. Reading + // and writing should hold errLock. + errMap map[Vertex]error + errLock sync.Mutex } type walkerVertex struct { @@ -102,30 +98,31 @@ type walkerVertex struct { // user-returned error. var errWalkUpstream = errors.New("upstream dependency failed") -// Wait waits for the completion of the walk and returns diagnostics describing -// any problems that arose. Update should be called to populate the walk with -// vertices and edges prior to calling this. +// Wait waits for the completion of the walk and returns any errors ( +// in the form of a multierror) that occurred. Update should be called +// to populate the walk with vertices and edges prior to calling this. // // Wait will return as soon as all currently known vertices are complete. // If you plan on calling Update with more vertices in the future, you // should not call Wait until after this is done. -func (w *Walker) Wait() tfdiags.Diagnostics { +func (w *Walker) Wait() error { // Wait for completion w.wait.Wait() - var diags tfdiags.Diagnostics - w.diagsLock.Lock() - for v, vDiags := range w.diagsMap { - if _, upstream := w.upstreamFailed[v]; upstream { - // Ignore diagnostics for nodes that had failed upstreams, since - // the downstream diagnostics are likely to be redundant. - continue - } - diags = diags.Append(vDiags) - } - w.diagsLock.Unlock() + // Grab the error lock + w.errLock.Lock() + defer w.errLock.Unlock() - return diags + // Build the error + var result error + for v, err := range w.errMap { + if err != nil && err != errWalkUpstream { + result = multierror.Append(result, fmt.Errorf( + "%s: %s", VertexName(v), err)) + } + } + + return result } // Update updates the currently executing walk with the given graph. @@ -139,7 +136,6 @@ func (w *Walker) Wait() tfdiags.Diagnostics { // Multiple Updates can be called in parallel. Update can be called at any // time during a walk. func (w *Walker) Update(g *AcyclicGraph) { - log.Print("[TRACE] dag/walk: updating graph") var v, e *Set if g != nil { v, e = g.vertices, g.edges @@ -385,34 +381,25 @@ func (w *Walker) walkVertex(v Vertex, info *walkerVertex) { } // Run our callback or note that our upstream failed - var diags tfdiags.Diagnostics - var upstreamFailed bool + var err error if depsSuccess { - log.Printf("[TRACE] dag/walk: visiting %q", VertexName(v)) - diags = w.Callback(v) + log.Printf("[TRACE] dag/walk: walking %q", VertexName(v)) + err = w.Callback(v) } else { - log.Printf("[TRACE] dag/walk: upstream of %q errored, so skipping", VertexName(v)) - // This won't be displayed to the user because we'll set upstreamFailed, - // but we need to ensure there's at least one error in here so that - // the failures will cascade downstream. - diags = diags.Append(errors.New("upstream dependencies failed")) - upstreamFailed = true + log.Printf("[TRACE] dag/walk: upstream errored, not walking %q", VertexName(v)) + err = errWalkUpstream } - // Record the result (we must do this after execution because we mustn't - // hold diagsLock while visiting a vertex.) - w.diagsLock.Lock() - if w.diagsMap == nil { - w.diagsMap = make(map[Vertex]tfdiags.Diagnostics) + // Record the error + if err != nil { + w.errLock.Lock() + defer w.errLock.Unlock() + + if w.errMap == nil { + w.errMap = make(map[Vertex]error) + } + w.errMap[v] = err } - w.diagsMap[v] = diags - if w.upstreamFailed == nil { - w.upstreamFailed = make(map[Vertex]struct{}) - } - if upstreamFailed { - w.upstreamFailed[v] = struct{}{} - } - w.diagsLock.Unlock() } func (w *Walker) waitDeps( @@ -420,7 +407,6 @@ func (w *Walker) waitDeps( deps map[Vertex]<-chan struct{}, doneCh chan<- bool, cancelCh <-chan struct{}) { - // For each dependency given to us, wait for it to complete for dep, depCh := range deps { DepSatisfied: @@ -437,17 +423,17 @@ func (w *Walker) waitDeps( return case <-time.After(time.Second * 5): - log.Printf("[TRACE] dag/walk: vertex %q is waiting for %q", + log.Printf("[TRACE] dag/walk: vertex %q, waiting for: %q", VertexName(v), VertexName(dep)) } } } // Dependencies satisfied! We need to check if any errored - w.diagsLock.Lock() - defer w.diagsLock.Unlock() - for dep := range deps { - if w.diagsMap[dep].HasErrors() { + w.errLock.Lock() + defer w.errLock.Unlock() + for dep, _ := range deps { + if w.errMap[dep] != nil { // One of our dependencies failed, so return false doneCh <- false return diff --git a/vendor/github.com/hashicorp/terraform/helper/didyoumean/name_suggestion.go b/vendor/github.com/hashicorp/terraform/helper/didyoumean/name_suggestion.go deleted file mode 100644 index 54899bc6..00000000 --- a/vendor/github.com/hashicorp/terraform/helper/didyoumean/name_suggestion.go +++ /dev/null @@ -1,24 +0,0 @@ -package didyoumean - -import ( - "github.com/agext/levenshtein" -) - -// NameSuggestion tries to find a name from the given slice of suggested names -// that is close to the given name and returns it if found. If no suggestion -// is close enough, returns the empty string. -// -// The suggestions are tried in order, so earlier suggestions take precedence -// if the given string is similar to two or more suggestions. -// -// This function is intended to be used with a relatively-small number of -// suggestions. It's not optimized for hundreds or thousands of them. -func NameSuggestion(given string, suggestions []string) string { - for _, suggestion := range suggestions { - dist := levenshtein.Distance(given, suggestion, nil) - if dist < 3 { // threshold determined experimentally - return suggestion - } - } - return "" -} diff --git a/vendor/github.com/hashicorp/terraform/helper/plugin/doc.go b/vendor/github.com/hashicorp/terraform/helper/plugin/doc.go deleted file mode 100644 index 82b5937b..00000000 --- a/vendor/github.com/hashicorp/terraform/helper/plugin/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Package plugin contains types and functions to help Terraform plugins -// implement the plugin rpc interface. -// The primary Provider type will be responsible for converting from the grpc -// wire protocol to the types and methods known to the provider -// implementations. -package plugin diff --git a/vendor/github.com/hashicorp/terraform/helper/plugin/grpc_provider.go b/vendor/github.com/hashicorp/terraform/helper/plugin/grpc_provider.go deleted file mode 100644 index 8a4f253c..00000000 --- a/vendor/github.com/hashicorp/terraform/helper/plugin/grpc_provider.go +++ /dev/null @@ -1,1299 +0,0 @@ -package plugin - -import ( - "encoding/json" - "errors" - "fmt" - "regexp" - "sort" - "strconv" - "strings" - - "github.com/zclconf/go-cty/cty" - ctyconvert "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/msgpack" - context "golang.org/x/net/context" - - "github.com/hashicorp/terraform/config/hcl2shim" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/helper/schema" - proto "github.com/hashicorp/terraform/internal/tfplugin5" - "github.com/hashicorp/terraform/plugin/convert" - "github.com/hashicorp/terraform/terraform" -) - -const newExtraKey = "_new_extra_shim" - -// NewGRPCProviderServerShim wraps a terraform.ResourceProvider in a -// proto.ProviderServer implementation. If the provided provider is not a -// *schema.Provider, this will return nil, -func NewGRPCProviderServerShim(p terraform.ResourceProvider) *GRPCProviderServer { - sp, ok := p.(*schema.Provider) - if !ok { - return nil - } - - return &GRPCProviderServer{ - provider: sp, - } -} - -// GRPCProviderServer handles the server, or plugin side of the rpc connection. -type GRPCProviderServer struct { - provider *schema.Provider -} - -func (s *GRPCProviderServer) GetSchema(_ context.Context, req *proto.GetProviderSchema_Request) (*proto.GetProviderSchema_Response, error) { - // Here we are certain that the provider is being called through grpc, so - // make sure the feature flag for helper/schema is set - schema.SetProto5() - - resp := &proto.GetProviderSchema_Response{ - ResourceSchemas: make(map[string]*proto.Schema), - DataSourceSchemas: make(map[string]*proto.Schema), - } - - resp.Provider = &proto.Schema{ - Block: convert.ConfigSchemaToProto(s.getProviderSchemaBlock()), - } - - for typ, res := range s.provider.ResourcesMap { - resp.ResourceSchemas[typ] = &proto.Schema{ - Version: int64(res.SchemaVersion), - Block: convert.ConfigSchemaToProto(res.CoreConfigSchema()), - } - } - - for typ, dat := range s.provider.DataSourcesMap { - resp.DataSourceSchemas[typ] = &proto.Schema{ - Version: int64(dat.SchemaVersion), - Block: convert.ConfigSchemaToProto(dat.CoreConfigSchema()), - } - } - - return resp, nil -} - -func (s *GRPCProviderServer) getProviderSchemaBlock() *configschema.Block { - return schema.InternalMap(s.provider.Schema).CoreConfigSchema() -} - -func (s *GRPCProviderServer) getResourceSchemaBlock(name string) *configschema.Block { - res := s.provider.ResourcesMap[name] - return res.CoreConfigSchema() -} - -func (s *GRPCProviderServer) getDatasourceSchemaBlock(name string) *configschema.Block { - dat := s.provider.DataSourcesMap[name] - return dat.CoreConfigSchema() -} - -func (s *GRPCProviderServer) PrepareProviderConfig(_ context.Context, req *proto.PrepareProviderConfig_Request) (*proto.PrepareProviderConfig_Response, error) { - resp := &proto.PrepareProviderConfig_Response{} - - block := s.getProviderSchemaBlock() - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // lookup any required, top-level attributes that are Null, and see if we - // have a Default value available. - configVal, err = cty.Transform(configVal, func(path cty.Path, val cty.Value) (cty.Value, error) { - // we're only looking for top-level attributes - if len(path) != 1 { - return val, nil - } - - // nothing to do if we already have a value - if !val.IsNull() { - return val, nil - } - - // get the Schema definition for this attribute - getAttr, ok := path[0].(cty.GetAttrStep) - // these should all exist, but just ignore anything strange - if !ok { - return val, nil - } - - attrSchema := s.provider.Schema[getAttr.Name] - // continue to ignore anything that doesn't match - if attrSchema == nil { - return val, nil - } - - // this is deprecated, so don't set it - if attrSchema.Deprecated != "" || attrSchema.Removed != "" { - return val, nil - } - - // find a default value if it exists - def, err := attrSchema.DefaultValue() - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("error getting default for %q: %s", getAttr.Name, err)) - return val, err - } - - // no default - if def == nil { - return val, nil - } - - // create a cty.Value and make sure it's the correct type - tmpVal := hcl2shim.HCL2ValueFromConfigValue(def) - - // helper/schema used to allow setting "" to a bool - if val.Type() == cty.Bool && tmpVal.RawEquals(cty.StringVal("")) { - // return a warning about the conversion - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, "provider set empty string as default value for bool "+getAttr.Name) - tmpVal = cty.False - } - - val, err = ctyconvert.Convert(tmpVal, val.Type()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("error setting default for %q: %s", getAttr.Name, err)) - } - - return val, err - }) - if err != nil { - // any error here was already added to the diagnostics - return resp, nil - } - - configVal, err = block.CoerceValue(configVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, block) - - warns, errs := s.provider.Validate(config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, convert.WarnsAndErrsToProto(warns, errs)) - - preparedConfigMP, err := msgpack.Marshal(configVal, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - resp.PreparedConfig = &proto.DynamicValue{Msgpack: preparedConfigMP} - - return resp, nil -} - -func (s *GRPCProviderServer) ValidateResourceTypeConfig(_ context.Context, req *proto.ValidateResourceTypeConfig_Request) (*proto.ValidateResourceTypeConfig_Response, error) { - resp := &proto.ValidateResourceTypeConfig_Response{} - - block := s.getResourceSchemaBlock(req.TypeName) - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, block) - - warns, errs := s.provider.ValidateResource(req.TypeName, config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, convert.WarnsAndErrsToProto(warns, errs)) - - return resp, nil -} - -func (s *GRPCProviderServer) ValidateDataSourceConfig(_ context.Context, req *proto.ValidateDataSourceConfig_Request) (*proto.ValidateDataSourceConfig_Response, error) { - resp := &proto.ValidateDataSourceConfig_Response{} - - block := s.getDatasourceSchemaBlock(req.TypeName) - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, block) - - warns, errs := s.provider.ValidateDataSource(req.TypeName, config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, convert.WarnsAndErrsToProto(warns, errs)) - - return resp, nil -} - -func (s *GRPCProviderServer) UpgradeResourceState(_ context.Context, req *proto.UpgradeResourceState_Request) (*proto.UpgradeResourceState_Response, error) { - resp := &proto.UpgradeResourceState_Response{} - - res := s.provider.ResourcesMap[req.TypeName] - block := res.CoreConfigSchema() - - version := int(req.Version) - - var jsonMap map[string]interface{} - var err error - - // if there's a JSON state, we need to decode it. - if len(req.RawState.Json) > 0 { - err = json.Unmarshal(req.RawState.Json, &jsonMap) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - - // We first need to upgrade a flatmap state if it exists. - // There should never be both a JSON and Flatmap state in the request. - if req.RawState.Flatmap != nil { - jsonMap, version, err = s.upgradeFlatmapState(version, req.RawState.Flatmap, res) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - - // complete the upgrade of the JSON states - jsonMap, err = s.upgradeJSONState(version, jsonMap, res) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // now we need to turn the state into the default json representation, so - // that it can be re-decoded using the actual schema. - val, err := schema.JSONMapToStateValue(jsonMap, block) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // encode the final state to the expected msgpack format - newStateMP, err := msgpack.Marshal(val, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - resp.UpgradedState = &proto.DynamicValue{Msgpack: newStateMP} - return resp, nil -} - -// upgradeFlatmapState takes a legacy flatmap state, upgrades it using Migrate -// state if necessary, and converts it to the new JSON state format decoded as a -// map[string]interface{}. -// upgradeFlatmapState returns the json map along with the corresponding schema -// version. -func (s *GRPCProviderServer) upgradeFlatmapState(version int, m map[string]string, res *schema.Resource) (map[string]interface{}, int, error) { - // this will be the version we've upgraded so, defaulting to the given - // version in case no migration was called. - upgradedVersion := version - - // first determine if we need to call the legacy MigrateState func - requiresMigrate := version < res.SchemaVersion - - schemaType := res.CoreConfigSchema().ImpliedType() - - // if there are any StateUpgraders, then we need to only compare - // against the first version there - if len(res.StateUpgraders) > 0 { - requiresMigrate = version < res.StateUpgraders[0].Version - } - - if requiresMigrate { - if res.MigrateState == nil { - return nil, 0, errors.New("cannot upgrade state, missing MigrateState function") - } - - is := &terraform.InstanceState{ - ID: m["id"], - Attributes: m, - Meta: map[string]interface{}{ - "schema_version": strconv.Itoa(version), - }, - } - - is, err := res.MigrateState(version, is, s.provider.Meta()) - if err != nil { - return nil, 0, err - } - - // re-assign the map in case there was a copy made, making sure to keep - // the ID - m := is.Attributes - m["id"] = is.ID - - // if there are further upgraders, then we've only updated that far - if len(res.StateUpgraders) > 0 { - schemaType = res.StateUpgraders[0].Type - upgradedVersion = res.StateUpgraders[0].Version - } - } else { - // the schema version may be newer than the MigrateState functions - // handled and older than the current, but still stored in the flatmap - // form. If that's the case, we need to find the correct schema type to - // convert the state. - for _, upgrader := range res.StateUpgraders { - if upgrader.Version == version { - schemaType = upgrader.Type - break - } - } - } - - // now we know the state is up to the latest version that handled the - // flatmap format state. Now we can upgrade the format and continue from - // there. - newConfigVal, err := hcl2shim.HCL2ValueFromFlatmap(m, schemaType) - if err != nil { - return nil, 0, err - } - - jsonMap, err := schema.StateValueToJSONMap(newConfigVal, schemaType) - return jsonMap, upgradedVersion, err -} - -func (s *GRPCProviderServer) upgradeJSONState(version int, m map[string]interface{}, res *schema.Resource) (map[string]interface{}, error) { - var err error - - for _, upgrader := range res.StateUpgraders { - if version != upgrader.Version { - continue - } - - m, err = upgrader.Upgrade(m, s.provider.Meta()) - if err != nil { - return nil, err - } - version++ - } - - return m, nil -} - -func (s *GRPCProviderServer) Stop(_ context.Context, _ *proto.Stop_Request) (*proto.Stop_Response, error) { - resp := &proto.Stop_Response{} - - err := s.provider.Stop() - if err != nil { - resp.Error = err.Error() - } - - return resp, nil -} - -func (s *GRPCProviderServer) Configure(_ context.Context, req *proto.Configure_Request) (*proto.Configure_Response, error) { - resp := &proto.Configure_Response{} - - block := s.getProviderSchemaBlock() - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - s.provider.TerraformVersion = req.TerraformVersion - - config := terraform.NewResourceConfigShimmed(configVal, block) - err = s.provider.Configure(config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - - return resp, nil -} - -func (s *GRPCProviderServer) ReadResource(_ context.Context, req *proto.ReadResource_Request) (*proto.ReadResource_Response, error) { - resp := &proto.ReadResource_Response{} - - res := s.provider.ResourcesMap[req.TypeName] - block := res.CoreConfigSchema() - - stateVal, err := msgpack.Unmarshal(req.CurrentState.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - instanceState, err := res.ShimInstanceStateFromValue(stateVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newInstanceState, err := res.RefreshWithoutUpgrade(instanceState, s.provider.Meta()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - if newInstanceState != nil { - // here we use the prior state to check for unknown/zero containers values - // when normalizing the flatmap. - stateAttrs := hcl2shim.FlatmapValueFromHCL2(stateVal) - newInstanceState.Attributes = normalizeFlatmapContainers(stateAttrs, newInstanceState.Attributes, true) - } - - if newInstanceState == nil || newInstanceState.ID == "" { - // The old provider API used an empty id to signal that the remote - // object appears to have been deleted, but our new protocol expects - // to see a null value (in the cty sense) in that case. - newStateMP, err := msgpack.Marshal(cty.NullVal(block.ImpliedType()), block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - } - resp.NewState = &proto.DynamicValue{ - Msgpack: newStateMP, - } - return resp, nil - } - - // helper/schema should always copy the ID over, but do it again just to be safe - newInstanceState.Attributes["id"] = newInstanceState.ID - - newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(newInstanceState.Attributes, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateVal = copyTimeoutValues(newStateVal, stateVal) - - newStateMP, err := msgpack.Marshal(newStateVal, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - resp.NewState = &proto.DynamicValue{ - Msgpack: newStateMP, - } - - return resp, nil -} - -func (s *GRPCProviderServer) PlanResourceChange(_ context.Context, req *proto.PlanResourceChange_Request) (*proto.PlanResourceChange_Response, error) { - resp := &proto.PlanResourceChange_Response{} - - // This is a signal to Terraform Core that we're doing the best we can to - // shim the legacy type system of the SDK onto the Terraform type system - // but we need it to cut us some slack. This setting should not be taken - // forward to any new SDK implementations, since setting it prevents us - // from catching certain classes of provider bug that can lead to - // confusing downstream errors. - resp.LegacyTypeSystem = true - - res := s.provider.ResourcesMap[req.TypeName] - block := res.CoreConfigSchema() - - priorStateVal, err := msgpack.Unmarshal(req.PriorState.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - proposedNewStateVal, err := msgpack.Unmarshal(req.ProposedNewState.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // We don't usually plan destroys, but this can return early in any case. - if proposedNewStateVal.IsNull() { - resp.PlannedState = req.ProposedNewState - return resp, nil - } - - info := &terraform.InstanceInfo{ - Type: req.TypeName, - } - - priorState, err := res.ShimInstanceStateFromValue(priorStateVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - priorPrivate := make(map[string]interface{}) - if len(req.PriorPrivate) > 0 { - if err := json.Unmarshal(req.PriorPrivate, &priorPrivate); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - - priorState.Meta = priorPrivate - - // turn the proposed state into a legacy configuration - cfg := terraform.NewResourceConfigShimmed(proposedNewStateVal, block) - - diff, err := s.provider.SimpleDiff(info, priorState, cfg) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // if this is a new instance, we need to make sure ID is going to be computed - if priorStateVal.IsNull() { - if diff == nil { - diff = terraform.NewInstanceDiff() - } - - diff.Attributes["id"] = &terraform.ResourceAttrDiff{ - NewComputed: true, - } - } - - if diff == nil || len(diff.Attributes) == 0 { - // schema.Provider.Diff returns nil if it ends up making a diff with no - // changes, but our new interface wants us to return an actual change - // description that _shows_ there are no changes. This is always the - // prior state, because we force a diff above if this is a new instance. - resp.PlannedState = req.PriorState - return resp, nil - } - - if priorState == nil { - priorState = &terraform.InstanceState{} - } - - // now we need to apply the diff to the prior state, so get the planned state - plannedAttrs, err := diff.Apply(priorState.Attributes, block) - - plannedAttrs = normalizeFlatmapContainers(priorState.Attributes, plannedAttrs, false) - - plannedStateVal, err := hcl2shim.HCL2ValueFromFlatmap(plannedAttrs, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - plannedStateVal, err = block.CoerceValue(plannedStateVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - plannedStateVal = normalizeNullValues(plannedStateVal, proposedNewStateVal, true) - - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - plannedStateVal = copyTimeoutValues(plannedStateVal, proposedNewStateVal) - - // The old SDK code has some imprecisions that cause it to sometimes - // generate differences that the SDK itself does not consider significant - // but Terraform Core would. To avoid producing weird do-nothing diffs - // in that case, we'll check if the provider as produced something we - // think is "equivalent" to the prior state and just return the prior state - // itself if so, thus ensuring that Terraform Core will treat this as - // a no-op. See the docs for ValuesSDKEquivalent for some caveats on its - // accuracy. - forceNoChanges := false - if hcl2shim.ValuesSDKEquivalent(priorStateVal, plannedStateVal) { - plannedStateVal = priorStateVal - forceNoChanges = true - } - - // if this was creating the resource, we need to set any remaining computed - // fields - if priorStateVal.IsNull() { - plannedStateVal = SetUnknowns(plannedStateVal, block) - } - - plannedMP, err := msgpack.Marshal(plannedStateVal, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.PlannedState = &proto.DynamicValue{ - Msgpack: plannedMP, - } - - // Now we need to store any NewExtra values, which are where any actual - // StateFunc modified config fields are hidden. - privateMap := diff.Meta - if privateMap == nil { - privateMap = map[string]interface{}{} - } - - newExtra := map[string]interface{}{} - - for k, v := range diff.Attributes { - if v.NewExtra != nil { - newExtra[k] = v.NewExtra - } - } - privateMap[newExtraKey] = newExtra - - // the Meta field gets encoded into PlannedPrivate - plannedPrivate, err := json.Marshal(privateMap) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.PlannedPrivate = plannedPrivate - - // collect the attributes that require instance replacement, and convert - // them to cty.Paths. - var requiresNew []string - if !forceNoChanges { - for attr, d := range diff.Attributes { - if d.RequiresNew { - requiresNew = append(requiresNew, attr) - } - } - } - - // If anything requires a new resource already, or the "id" field indicates - // that we will be creating a new resource, then we need to add that to - // RequiresReplace so that core can tell if the instance is being replaced - // even if changes are being suppressed via "ignore_changes". - id := plannedStateVal.GetAttr("id") - if len(requiresNew) > 0 || id.IsNull() || !id.IsKnown() { - requiresNew = append(requiresNew, "id") - } - - requiresReplace, err := hcl2shim.RequiresReplace(requiresNew, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // convert these to the protocol structures - for _, p := range requiresReplace { - resp.RequiresReplace = append(resp.RequiresReplace, pathToAttributePath(p)) - } - - return resp, nil -} - -func (s *GRPCProviderServer) ApplyResourceChange(_ context.Context, req *proto.ApplyResourceChange_Request) (*proto.ApplyResourceChange_Response, error) { - resp := &proto.ApplyResourceChange_Response{ - // Start with the existing state as a fallback - NewState: req.PriorState, - } - - res := s.provider.ResourcesMap[req.TypeName] - block := res.CoreConfigSchema() - - priorStateVal, err := msgpack.Unmarshal(req.PriorState.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - plannedStateVal, err := msgpack.Unmarshal(req.PlannedState.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - info := &terraform.InstanceInfo{ - Type: req.TypeName, - } - - priorState, err := res.ShimInstanceStateFromValue(priorStateVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - private := make(map[string]interface{}) - if len(req.PlannedPrivate) > 0 { - if err := json.Unmarshal(req.PlannedPrivate, &private); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - - var diff *terraform.InstanceDiff - destroy := false - - // a null state means we are destroying the instance - if plannedStateVal.IsNull() { - destroy = true - diff = &terraform.InstanceDiff{ - Attributes: make(map[string]*terraform.ResourceAttrDiff), - Meta: make(map[string]interface{}), - Destroy: true, - } - } else { - diff, err = schema.DiffFromValues(priorStateVal, plannedStateVal, stripResourceModifiers(res)) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - - if diff == nil { - diff = &terraform.InstanceDiff{ - Attributes: make(map[string]*terraform.ResourceAttrDiff), - Meta: make(map[string]interface{}), - } - } - - // add NewExtra Fields that may have been stored in the private data - if newExtra := private[newExtraKey]; newExtra != nil { - for k, v := range newExtra.(map[string]interface{}) { - d := diff.Attributes[k] - - if d == nil { - d = &terraform.ResourceAttrDiff{} - } - - d.NewExtra = v - diff.Attributes[k] = d - } - } - - if private != nil { - diff.Meta = private - } - - // We need to turn off any RequiresNew. There could be attributes - // without changes in here inserted by helper/schema, but if they have - // RequiresNew then the state will will be dropped from the ResourceData. - for k := range diff.Attributes { - diff.Attributes[k].RequiresNew = false - } - - // check that any "removed" attributes actually exist in the prior state, or - // helper/schema will confuse itself - for k, d := range diff.Attributes { - if d.NewRemoved { - if _, ok := priorState.Attributes[k]; !ok { - delete(diff.Attributes, k) - } - } - } - - newInstanceState, err := s.provider.Apply(info, priorState, diff) - // we record the error here, but continue processing any returned state. - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - } - - newStateVal := cty.NullVal(block.ImpliedType()) - - // Always return a null value for destroy. - // While this is usually indicated by a nil state, check for missing ID or - // attributes in the case of a provider failure. - if destroy || newInstanceState == nil || newInstanceState.Attributes == nil || newInstanceState.ID == "" { - newStateMP, err := msgpack.Marshal(newStateVal, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.NewState = &proto.DynamicValue{ - Msgpack: newStateMP, - } - return resp, nil - } - - // here we use the planned state to check for unknown/zero containers values - // when normalizing the flatmap. - plannedState := hcl2shim.FlatmapValueFromHCL2(plannedStateVal) - newInstanceState.Attributes = normalizeFlatmapContainers(plannedState, newInstanceState.Attributes, true) - - // We keep the null val if we destroyed the resource, otherwise build the - // entire object, even if the new state was nil. - newStateVal, err = schema.StateValueFromInstanceState(newInstanceState, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateVal = normalizeNullValues(newStateVal, plannedStateVal, false) - newStateVal = copyTimeoutValues(newStateVal, plannedStateVal) - - newStateMP, err := msgpack.Marshal(newStateVal, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.NewState = &proto.DynamicValue{ - Msgpack: newStateMP, - } - - meta, err := json.Marshal(newInstanceState.Meta) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.Private = meta - - // This is a signal to Terraform Core that we're doing the best we can to - // shim the legacy type system of the SDK onto the Terraform type system - // but we need it to cut us some slack. This setting should not be taken - // forward to any new SDK implementations, since setting it prevents us - // from catching certain classes of provider bug that can lead to - // confusing downstream errors. - resp.LegacyTypeSystem = true - - return resp, nil -} - -func (s *GRPCProviderServer) ImportResourceState(_ context.Context, req *proto.ImportResourceState_Request) (*proto.ImportResourceState_Response, error) { - resp := &proto.ImportResourceState_Response{} - - info := &terraform.InstanceInfo{ - Type: req.TypeName, - } - - newInstanceStates, err := s.provider.ImportState(info, req.Id) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - for _, is := range newInstanceStates { - // copy the ID again just to be sure it wasn't missed - is.Attributes["id"] = is.ID - - resourceType := is.Ephemeral.Type - if resourceType == "" { - resourceType = req.TypeName - } - - block := s.getResourceSchemaBlock(resourceType) - newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(is.Attributes, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateMP, err := msgpack.Marshal(newStateVal, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - meta, err := json.Marshal(is.Meta) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - importedResource := &proto.ImportResourceState_ImportedResource{ - TypeName: resourceType, - State: &proto.DynamicValue{ - Msgpack: newStateMP, - }, - Private: meta, - } - - resp.ImportedResources = append(resp.ImportedResources, importedResource) - } - - return resp, nil -} - -func (s *GRPCProviderServer) ReadDataSource(_ context.Context, req *proto.ReadDataSource_Request) (*proto.ReadDataSource_Response, error) { - resp := &proto.ReadDataSource_Response{} - - res := s.provider.DataSourcesMap[req.TypeName] - block := res.CoreConfigSchema() - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - info := &terraform.InstanceInfo{ - Type: req.TypeName, - } - - config := terraform.NewResourceConfigShimmed(configVal, block) - - // we need to still build the diff separately with the Read method to match - // the old behavior - diff, err := s.provider.ReadDataDiff(info, config) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // now we can get the new complete data source - newInstanceState, err := s.provider.ReadDataApply(info, diff) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateVal, err := schema.StateValueFromInstanceState(newInstanceState, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateVal = copyTimeoutValues(newStateVal, configVal) - - newStateMP, err := msgpack.Marshal(newStateVal, block.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.State = &proto.DynamicValue{ - Msgpack: newStateMP, - } - return resp, nil -} - -func pathToAttributePath(path cty.Path) *proto.AttributePath { - var steps []*proto.AttributePath_Step - - for _, step := range path { - switch s := step.(type) { - case cty.GetAttrStep: - steps = append(steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_AttributeName{ - AttributeName: s.Name, - }, - }) - case cty.IndexStep: - ty := s.Key.Type() - switch ty { - case cty.Number: - i, _ := s.Key.AsBigFloat().Int64() - steps = append(steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_ElementKeyInt{ - ElementKeyInt: i, - }, - }) - case cty.String: - steps = append(steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_ElementKeyString{ - ElementKeyString: s.Key.AsString(), - }, - }) - } - } - } - - return &proto.AttributePath{Steps: steps} -} - -// normalizeFlatmapContainers removes empty containers, and fixes counts in a -// set of flatmapped attributes. The prior value is used to determine if there -// could be zero-length flatmap containers which we need to preserve. This -// allows a provider to set an empty computed container in the state without -// creating perpetual diff. This can differ slightly between plan and apply, so -// the apply flag is passed when called from ApplyResourceChange. -func normalizeFlatmapContainers(prior map[string]string, attrs map[string]string, apply bool) map[string]string { - isCount := regexp.MustCompile(`.\.[%#]$`).MatchString - - // While we can't determine if the value was actually computed here, we will - // trust that our shims stored and retrieved a zero-value container - // correctly. - zeros := map[string]bool{} - // Empty blocks have a count of 1 with no other attributes. Just record all - // "1"s here to override 0-length blocks when setting the count below. - ones := map[string]bool{} - for k, v := range prior { - if isCount(k) && (v == "0" || v == hcl2shim.UnknownVariableValue) { - zeros[k] = true - } - - // fixup any 1->0 conversions that happened during Apply - if apply && isCount(k) && v == "1" && attrs[k] == "0" { - attrs[k] = "1" - } - } - - for k, v := range attrs { - // store any "1" values, since if the length was 1 and there are no - // items, it was probably an empty set block. Hopefully checking for a 1 - // value with no items is sufficient, without cross-referencing the - // schema. - if isCount(k) && v == "1" { - ones[k] = true - // make sure we don't have the same key under both categories. - delete(zeros, k) - } - } - - // The "ones" were stored to look for sets with an empty value, so we need - // to verify that we only store ones with no attrs. - expectedEmptySets := map[string]bool{} - for one := range ones { - prefix := one[:len(one)-1] - - found := 0 - for k := range attrs { - // since this can be recursive, we check that the attrs isn't also a #. - if strings.HasPrefix(k, prefix) && !isCount(k) { - found++ - } - } - - if found == 0 { - expectedEmptySets[one] = true - } - } - - // find container keys - var keys []string - for k, v := range attrs { - if !isCount(k) { - continue - } - - if v == hcl2shim.UnknownVariableValue { - // if the index value indicates the container is unknown, skip - // updating the counts. - continue - } - - keys = append(keys, k) - } - - // sort the keys in reverse, so that we check the longest subkeys first - sort.Slice(keys, func(i, j int) bool { - a, b := keys[i], keys[j] - - if strings.HasPrefix(a, b) { - return true - } - - if strings.HasPrefix(b, a) { - return false - } - - return a > b - }) - - for _, k := range keys { - prefix := k[:len(k)-1] - indexes := map[string]int{} - for cand := range attrs { - if cand == k { - continue - } - - if strings.HasPrefix(cand, prefix) { - idx := cand[len(prefix):] - dot := strings.Index(idx, ".") - if dot > 0 { - idx = idx[:dot] - } - indexes[idx]++ - } - } - - switch { - case len(indexes) == 0 && zeros[k]: - // if there were no keys, but the value was known to be zero, the provider - // must have set the computed value to an empty container, and we - // need to leave it in the flatmap. - attrs[k] = "0" - case len(indexes) == 0 && ones[k]: - // We need to retain any empty blocks that had a 1 count with no attributes. - attrs[k] = "1" - case len(indexes) > 0: - attrs[k] = strconv.Itoa(len(indexes)) - default: - delete(attrs, k) - } - } - - for k := range expectedEmptySets { - if _, ok := attrs[k]; !ok { - attrs[k] = "1" - } - } - - return attrs -} - -// helper/schema throws away timeout values from the config and stores them in -// the Private/Meta fields. we need to copy those values into the planned state -// so that core doesn't see a perpetual diff with the timeout block. -func copyTimeoutValues(to cty.Value, from cty.Value) cty.Value { - // if `from` is null, then there are no attributes, and if `to` is null we - // are planning to remove it altogether. - if from.IsNull() || to.IsNull() { - return to - } - - fromAttrs := from.AsValueMap() - timeouts, ok := fromAttrs[schema.TimeoutsConfigKey] - - // no timeouts to copy - // timeouts shouldn't be unknown, but don't copy possibly invalid values - if !ok || timeouts.IsNull() || !timeouts.IsWhollyKnown() { - return to - } - - toAttrs := to.AsValueMap() - toAttrs[schema.TimeoutsConfigKey] = timeouts - - return cty.ObjectVal(toAttrs) -} - -// stripResourceModifiers takes a *schema.Resource and returns a deep copy with all -// StateFuncs and CustomizeDiffs removed. This will be used during apply to -// create a diff from a planned state where the diff modifications have already -// been applied. -func stripResourceModifiers(r *schema.Resource) *schema.Resource { - if r == nil { - return nil - } - // start with a shallow copy - newResource := new(schema.Resource) - *newResource = *r - - newResource.CustomizeDiff = nil - newResource.Schema = map[string]*schema.Schema{} - - for k, s := range r.Schema { - newResource.Schema[k] = stripSchema(s) - } - - return newResource -} - -func stripSchema(s *schema.Schema) *schema.Schema { - if s == nil { - return nil - } - // start with a shallow copy - newSchema := new(schema.Schema) - *newSchema = *s - - newSchema.StateFunc = nil - - switch e := newSchema.Elem.(type) { - case *schema.Schema: - newSchema.Elem = stripSchema(e) - case *schema.Resource: - newSchema.Elem = stripResourceModifiers(e) - } - - return newSchema -} - -// Zero values and empty containers may be interchanged by the apply process. -// When there is a discrepency between src and dst value being null or empty, -// prefer the src value. This takes a little more liberty with set types, since -// we can't correlate modified set values. In the case of sets, if the src set -// was wholly known we assume the value was correctly applied and copy that -// entirely to the new value. -// While apply prefers the src value, during plan we prefer dst whenever there -// is an unknown or a set is involved, since the plan can alter the value -// however it sees fit. This however means that a CustomizeDiffFunction may not -// be able to change a null to an empty value or vice versa, but that should be -// very uncommon nor was it reliable before 0.12 either. -func normalizeNullValues(dst, src cty.Value, plan bool) cty.Value { - ty := dst.Type() - - if !src.IsNull() && !src.IsKnown() { - return dst - } - - // handle null/empty changes for collections - if ty.IsCollectionType() { - if src.IsNull() && !dst.IsNull() && dst.IsKnown() { - if dst.LengthInt() == 0 { - return src - } - } - - if dst.IsNull() && !src.IsNull() && src.IsKnown() { - if src.LengthInt() == 0 { - return src - } - } - } - - if src.IsNull() || !src.IsKnown() || !dst.IsKnown() { - return dst - } - - switch { - case ty.IsMapType(), ty.IsObjectType(): - var dstMap map[string]cty.Value - if !dst.IsNull() { - dstMap = dst.AsValueMap() - } - if dstMap == nil { - dstMap = map[string]cty.Value{} - } - - ei := src.ElementIterator() - for ei.Next() { - k, v := ei.Element() - key := k.AsString() - - dstVal := dstMap[key] - if dstVal == cty.NilVal { - if plan && ty.IsMapType() { - // let plan shape this map however it wants - continue - } - dstVal = cty.NullVal(v.Type()) - } - dstMap[key] = normalizeNullValues(dstVal, v, plan) - } - - // you can't call MapVal/ObjectVal with empty maps, but nothing was - // copied in anyway. If the dst is nil, and the src is known, assume the - // src is correct. - if len(dstMap) == 0 { - if dst.IsNull() && src.IsWhollyKnown() && !plan { - return src - } - return dst - } - - if ty.IsMapType() { - return cty.MapVal(dstMap) - } - - return cty.ObjectVal(dstMap) - - case ty.IsSetType(): - // If the original was wholly known, then we expect that is what the - // provider applied. The apply process loses too much information to - // reliably re-create the set. - if src.IsWhollyKnown() && !plan { - return src - } - - case ty.IsListType(), ty.IsTupleType(): - // If the dst is nil, and the src is known, then we lost an empty value - // so take the original. - if dst.IsNull() { - if src.IsWhollyKnown() && !plan { - return src - } - return dst - } - - // if the lengths are identical, then iterate over each element in succession. - srcLen := src.LengthInt() - dstLen := dst.LengthInt() - if srcLen == dstLen && srcLen > 0 { - srcs := src.AsValueSlice() - dsts := dst.AsValueSlice() - - for i := 0; i < srcLen; i++ { - dsts[i] = normalizeNullValues(dsts[i], srcs[i], plan) - } - - if ty.IsTupleType() { - return cty.TupleVal(dsts) - } - return cty.ListVal(dsts) - } - - case ty.IsPrimitiveType(): - if dst.IsNull() && src.IsWhollyKnown() && !plan { - return src - } - } - - return dst -} diff --git a/vendor/github.com/hashicorp/terraform/helper/plugin/grpc_provisioner.go b/vendor/github.com/hashicorp/terraform/helper/plugin/grpc_provisioner.go deleted file mode 100644 index 14494e46..00000000 --- a/vendor/github.com/hashicorp/terraform/helper/plugin/grpc_provisioner.go +++ /dev/null @@ -1,147 +0,0 @@ -package plugin - -import ( - "log" - - "github.com/hashicorp/terraform/helper/schema" - proto "github.com/hashicorp/terraform/internal/tfplugin5" - "github.com/hashicorp/terraform/plugin/convert" - "github.com/hashicorp/terraform/terraform" - "github.com/zclconf/go-cty/cty" - ctyconvert "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/msgpack" - context "golang.org/x/net/context" -) - -// NewGRPCProvisionerServerShim wraps a terraform.ResourceProvisioner in a -// proto.ProvisionerServer implementation. If the provided provisioner is not a -// *schema.Provisioner, this will return nil, -func NewGRPCProvisionerServerShim(p terraform.ResourceProvisioner) *GRPCProvisionerServer { - sp, ok := p.(*schema.Provisioner) - if !ok { - return nil - } - return &GRPCProvisionerServer{ - provisioner: sp, - } -} - -type GRPCProvisionerServer struct { - provisioner *schema.Provisioner -} - -func (s *GRPCProvisionerServer) GetSchema(_ context.Context, req *proto.GetProvisionerSchema_Request) (*proto.GetProvisionerSchema_Response, error) { - resp := &proto.GetProvisionerSchema_Response{} - - resp.Provisioner = &proto.Schema{ - Block: convert.ConfigSchemaToProto(schema.InternalMap(s.provisioner.Schema).CoreConfigSchema()), - } - - return resp, nil -} - -func (s *GRPCProvisionerServer) ValidateProvisionerConfig(_ context.Context, req *proto.ValidateProvisionerConfig_Request) (*proto.ValidateProvisionerConfig_Response, error) { - resp := &proto.ValidateProvisionerConfig_Response{} - - cfgSchema := schema.InternalMap(s.provisioner.Schema).CoreConfigSchema() - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, cfgSchema.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, cfgSchema) - - warns, errs := s.provisioner.Validate(config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, convert.WarnsAndErrsToProto(warns, errs)) - - return resp, nil -} - -// stringMapFromValue converts a cty.Value to a map[stirng]string. -// This will panic if the val is not a cty.Map(cty.String). -func stringMapFromValue(val cty.Value) map[string]string { - m := map[string]string{} - if val.IsNull() || !val.IsKnown() { - return m - } - - for it := val.ElementIterator(); it.Next(); { - ak, av := it.Element() - name := ak.AsString() - - if !av.IsKnown() || av.IsNull() { - continue - } - - av, _ = ctyconvert.Convert(av, cty.String) - m[name] = av.AsString() - } - - return m -} - -// uiOutput implements the terraform.UIOutput interface to adapt the grpc -// stream to the legacy Provisioner.Apply method. -type uiOutput struct { - srv proto.Provisioner_ProvisionResourceServer -} - -func (o uiOutput) Output(s string) { - err := o.srv.Send(&proto.ProvisionResource_Response{ - Output: s, - }) - if err != nil { - log.Printf("[ERROR] %s", err) - } -} - -func (s *GRPCProvisionerServer) ProvisionResource(req *proto.ProvisionResource_Request, srv proto.Provisioner_ProvisionResourceServer) error { - // We send back a diagnostics over the stream if there was a - // provisioner-side problem. - srvResp := &proto.ProvisionResource_Response{} - - cfgSchema := schema.InternalMap(s.provisioner.Schema).CoreConfigSchema() - cfgVal, err := msgpack.Unmarshal(req.Config.Msgpack, cfgSchema.ImpliedType()) - if err != nil { - srvResp.Diagnostics = convert.AppendProtoDiag(srvResp.Diagnostics, err) - srv.Send(srvResp) - return nil - } - resourceConfig := terraform.NewResourceConfigShimmed(cfgVal, cfgSchema) - - connVal, err := msgpack.Unmarshal(req.Connection.Msgpack, cty.Map(cty.String)) - if err != nil { - srvResp.Diagnostics = convert.AppendProtoDiag(srvResp.Diagnostics, err) - srv.Send(srvResp) - return nil - } - - conn := stringMapFromValue(connVal) - - instanceState := &terraform.InstanceState{ - Ephemeral: terraform.EphemeralState{ - ConnInfo: conn, - }, - Meta: make(map[string]interface{}), - } - - err = s.provisioner.Apply(uiOutput{srv}, instanceState, resourceConfig) - if err != nil { - srvResp.Diagnostics = convert.AppendProtoDiag(srvResp.Diagnostics, err) - srv.Send(srvResp) - } - return nil -} - -func (s *GRPCProvisionerServer) Stop(_ context.Context, req *proto.Stop_Request) (*proto.Stop_Response, error) { - resp := &proto.Stop_Response{} - - err := s.provisioner.Stop() - if err != nil { - resp.Error = err.Error() - } - - return resp, nil -} diff --git a/vendor/github.com/hashicorp/terraform/helper/plugin/unknown.go b/vendor/github.com/hashicorp/terraform/helper/plugin/unknown.go deleted file mode 100644 index 48e24e5d..00000000 --- a/vendor/github.com/hashicorp/terraform/helper/plugin/unknown.go +++ /dev/null @@ -1,131 +0,0 @@ -package plugin - -import ( - "fmt" - - "github.com/hashicorp/terraform/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// SetUnknowns takes a cty.Value, and compares it to the schema setting any null -// values which are computed to unknown. -func SetUnknowns(val cty.Value, schema *configschema.Block) cty.Value { - if !val.IsKnown() { - return val - } - - // If the object was null, we still need to handle the top level attributes - // which might be computed, but we don't need to expand the blocks. - if val.IsNull() { - objMap := map[string]cty.Value{} - allNull := true - for name, attr := range schema.Attributes { - switch { - case attr.Computed: - objMap[name] = cty.UnknownVal(attr.Type) - allNull = false - default: - objMap[name] = cty.NullVal(attr.Type) - } - } - - // If this object has no unknown attributes, then we can leave it null. - if allNull { - return val - } - - return cty.ObjectVal(objMap) - } - - valMap := val.AsValueMap() - newVals := make(map[string]cty.Value) - - for name, attr := range schema.Attributes { - v := valMap[name] - - if attr.Computed && v.IsNull() { - newVals[name] = cty.UnknownVal(attr.Type) - continue - } - - newVals[name] = v - } - - for name, blockS := range schema.BlockTypes { - blockVal := valMap[name] - if blockVal.IsNull() || !blockVal.IsKnown() { - newVals[name] = blockVal - continue - } - - blockValType := blockVal.Type() - blockElementType := blockS.Block.ImpliedType() - - // This switches on the value type here, so we can correctly switch - // between Tuples/Lists and Maps/Objects. - switch { - case blockS.Nesting == configschema.NestingSingle: - // NestingSingle is the only exception here, where we treat the - // block directly as an object - newVals[name] = SetUnknowns(blockVal, &blockS.Block) - - case blockValType.IsSetType(), blockValType.IsListType(), blockValType.IsTupleType(): - listVals := blockVal.AsValueSlice() - newListVals := make([]cty.Value, 0, len(listVals)) - - for _, v := range listVals { - newListVals = append(newListVals, SetUnknowns(v, &blockS.Block)) - } - - switch { - case blockValType.IsSetType(): - switch len(newListVals) { - case 0: - newVals[name] = cty.SetValEmpty(blockElementType) - default: - newVals[name] = cty.SetVal(newListVals) - } - case blockValType.IsListType(): - switch len(newListVals) { - case 0: - newVals[name] = cty.ListValEmpty(blockElementType) - default: - newVals[name] = cty.ListVal(newListVals) - } - case blockValType.IsTupleType(): - newVals[name] = cty.TupleVal(newListVals) - } - - case blockValType.IsMapType(), blockValType.IsObjectType(): - mapVals := blockVal.AsValueMap() - newMapVals := make(map[string]cty.Value) - - for k, v := range mapVals { - newMapVals[k] = SetUnknowns(v, &blockS.Block) - } - - switch { - case blockValType.IsMapType(): - switch len(newMapVals) { - case 0: - newVals[name] = cty.MapValEmpty(blockElementType) - default: - newVals[name] = cty.MapVal(newMapVals) - } - case blockValType.IsObjectType(): - if len(newMapVals) == 0 { - // We need to populate empty values to make a valid object. - for attr, ty := range blockElementType.AttributeTypes() { - newMapVals[attr] = cty.NullVal(ty) - } - } - newVals[name] = cty.ObjectVal(newMapVals) - } - - default: - panic(fmt.Sprintf("failed to set unknown values for nested block %q:%#v", name, blockValType)) - } - } - - return cty.ObjectVal(newVals) -} diff --git a/vendor/github.com/hashicorp/terraform/helper/resource/grpc_test_provider.go b/vendor/github.com/hashicorp/terraform/helper/resource/grpc_test_provider.go deleted file mode 100644 index 8cfa8e7f..00000000 --- a/vendor/github.com/hashicorp/terraform/helper/resource/grpc_test_provider.go +++ /dev/null @@ -1,43 +0,0 @@ -package resource - -import ( - "context" - "net" - "time" - - "github.com/hashicorp/terraform/helper/plugin" - proto "github.com/hashicorp/terraform/internal/tfplugin5" - tfplugin "github.com/hashicorp/terraform/plugin" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/terraform" - "google.golang.org/grpc" - "google.golang.org/grpc/test/bufconn" -) - -// GRPCTestProvider takes a legacy ResourceProvider, wraps it in the new GRPC -// shim and starts it in a grpc server using an inmem connection. It returns a -// GRPCClient for this new server to test the shimmed resource provider. -func GRPCTestProvider(rp terraform.ResourceProvider) providers.Interface { - listener := bufconn.Listen(256 * 1024) - grpcServer := grpc.NewServer() - - p := plugin.NewGRPCProviderServerShim(rp) - proto.RegisterProviderServer(grpcServer, p) - - go grpcServer.Serve(listener) - - conn, err := grpc.Dial("", grpc.WithDialer(func(string, time.Duration) (net.Conn, error) { - return listener.Dial() - }), grpc.WithInsecure()) - if err != nil { - panic(err) - } - - var pp tfplugin.GRPCProviderPlugin - client, _ := pp.GRPCClient(context.Background(), nil, conn) - - grpcClient := client.(*tfplugin.GRPCProvider) - grpcClient.TestListener = listener - - return grpcClient -} diff --git a/vendor/github.com/hashicorp/terraform/helper/resource/state_shim.go b/vendor/github.com/hashicorp/terraform/helper/resource/state_shim.go deleted file mode 100644 index 5514426b..00000000 --- a/vendor/github.com/hashicorp/terraform/helper/resource/state_shim.go +++ /dev/null @@ -1,162 +0,0 @@ -package resource - -import ( - "fmt" - - "github.com/hashicorp/terraform/addrs" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/config/hcl2shim" - "github.com/hashicorp/terraform/helper/schema" - - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/terraform" -) - -// shimState takes a new *states.State and reverts it to a legacy state for the provider ACC tests -func shimNewState(newState *states.State, providers map[string]terraform.ResourceProvider) (*terraform.State, error) { - state := terraform.NewState() - - // in the odd case of a nil state, let the helper packages handle it - if newState == nil { - return nil, nil - } - - for _, newMod := range newState.Modules { - mod := state.AddModule(newMod.Addr) - - for name, out := range newMod.OutputValues { - outputType := "" - val := hcl2shim.ConfigValueFromHCL2(out.Value) - ty := out.Value.Type() - switch { - case ty == cty.String: - outputType = "string" - case ty.IsTupleType() || ty.IsListType(): - outputType = "list" - case ty.IsMapType(): - outputType = "map" - } - - mod.Outputs[name] = &terraform.OutputState{ - Type: outputType, - Value: val, - Sensitive: out.Sensitive, - } - } - - for _, res := range newMod.Resources { - resType := res.Addr.Type - providerType := res.ProviderConfig.ProviderConfig.Type - - resource := getResource(providers, providerType, res.Addr) - - for key, i := range res.Instances { - flatmap, err := shimmedAttributes(i.Current, resource) - if err != nil { - return nil, fmt.Errorf("error decoding state for %q: %s", resType, err) - } - - resState := &terraform.ResourceState{ - Type: resType, - Primary: &terraform.InstanceState{ - ID: flatmap["id"], - Attributes: flatmap, - Tainted: i.Current.Status == states.ObjectTainted, - }, - } - if i.Current.SchemaVersion != 0 { - resState.Primary.Meta = map[string]interface{}{ - "schema_version": i.Current.SchemaVersion, - } - } - - for _, dep := range i.Current.Dependencies { - resState.Dependencies = append(resState.Dependencies, dep.String()) - } - - // convert the indexes to the old style flapmap indexes - idx := "" - switch key.(type) { - case addrs.IntKey: - // don't add numeric index values to resources with a count of 0 - if len(res.Instances) > 1 { - idx = fmt.Sprintf(".%d", key) - } - case addrs.StringKey: - idx = "." + key.String() - } - - mod.Resources[res.Addr.String()+idx] = resState - - // add any deposed instances - for _, dep := range i.Deposed { - flatmap, err := shimmedAttributes(dep, resource) - if err != nil { - return nil, fmt.Errorf("error decoding deposed state for %q: %s", resType, err) - } - - deposed := &terraform.InstanceState{ - ID: flatmap["id"], - Attributes: flatmap, - Tainted: dep.Status == states.ObjectTainted, - } - if dep.SchemaVersion != 0 { - deposed.Meta = map[string]interface{}{ - "schema_version": dep.SchemaVersion, - } - } - - resState.Deposed = append(resState.Deposed, deposed) - } - } - } - } - - return state, nil -} - -func getResource(providers map[string]terraform.ResourceProvider, providerName string, addr addrs.Resource) *schema.Resource { - p := providers[providerName] - if p == nil { - panic(fmt.Sprintf("provider %q not found in test step", providerName)) - } - - // this is only for tests, so should only see schema.Providers - provider := p.(*schema.Provider) - - switch addr.Mode { - case addrs.ManagedResourceMode: - resource := provider.ResourcesMap[addr.Type] - if resource != nil { - return resource - } - case addrs.DataResourceMode: - resource := provider.DataSourcesMap[addr.Type] - if resource != nil { - return resource - } - } - - panic(fmt.Sprintf("resource %s not found in test step", addr.Type)) -} - -func shimmedAttributes(instance *states.ResourceInstanceObjectSrc, res *schema.Resource) (map[string]string, error) { - flatmap := instance.AttrsFlat - if flatmap != nil { - return flatmap, nil - } - - // if we have json attrs, they need to be decoded - rio, err := instance.Decode(res.CoreConfigSchema().ImpliedType()) - if err != nil { - return nil, err - } - - instanceState, err := res.ShimInstanceStateFromValue(rio.Value) - if err != nil { - return nil, err - } - - return instanceState.Attributes, nil -} diff --git a/vendor/github.com/hashicorp/terraform/helper/resource/testing.go b/vendor/github.com/hashicorp/terraform/helper/resource/testing.go index aa7454d4..b97673fd 100644 --- a/vendor/github.com/hashicorp/terraform/helper/resource/testing.go +++ b/vendor/github.com/hashicorp/terraform/helper/resource/testing.go @@ -1,7 +1,6 @@ package resource import ( - "bytes" "flag" "fmt" "io" @@ -19,18 +18,9 @@ import ( "github.com/hashicorp/errwrap" "github.com/hashicorp/go-multierror" "github.com/hashicorp/logutils" - "github.com/mitchellh/colorstring" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/command/format" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/configs/configload" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/helper/logging" - "github.com/hashicorp/terraform/internal/initwd" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" "github.com/hashicorp/terraform/terraform" - "github.com/hashicorp/terraform/tfdiags" ) // flagSweep is a flag available when running tests on the command line. It @@ -383,10 +373,6 @@ type TestStep struct { // be refreshed and don't matter. ImportStateVerify bool ImportStateVerifyIgnore []string - - // provider s is used internally to maintain a reference to the - // underlying providers during the tests - providers map[string]terraform.ResourceProvider } // Set to a file mask in sprintf format where %s is test name @@ -481,22 +467,10 @@ func Test(t TestT, c TestCase) { c.PreCheck() } - // get instances of all providers, so we can use the individual - // resources to shim the state during the tests. - providers := make(map[string]terraform.ResourceProvider) - for name, pf := range testProviderFactories(c) { - p, err := pf() - if err != nil { - t.Fatal(err) - } - providers[name] = p - } - providerResolver, err := testProviderResolver(c) if err != nil { t.Fatal(err) } - opts := terraform.ContextOpts{ProviderResolver: providerResolver} // A single state variable to track the lifecycle, starting with no state @@ -507,10 +481,6 @@ func Test(t TestT, c TestCase) { idRefresh := c.IDRefreshName != "" errored := false for i, step := range c.Steps { - // insert the providers into the step so we can get the resources for - // shimming the state - step.providers = providers - var err error log.Printf("[DEBUG] Test: Executing step %d", i) @@ -565,7 +535,8 @@ func Test(t TestT, c TestCase) { } } else { errored = true - t.Error(fmt.Sprintf("Step %d error: %s", i, detailedErrorMessage(err))) + t.Error(fmt.Sprintf( + "Step %d error: %s", i, err)) break } } @@ -620,7 +591,6 @@ func Test(t TestT, c TestCase) { Destroy: true, PreventDiskCleanup: lastStep.PreventDiskCleanup, PreventPostDestroyRefresh: c.PreventPostDestroyRefresh, - providers: providers, } log.Printf("[WARN] Test: Executing destroy step") @@ -650,50 +620,39 @@ func testProviderConfig(c TestCase) string { return strings.Join(lines, "") } -// testProviderFactories combines the fixed Providers and -// ResourceProviderFactory functions into a single map of -// ResourceProviderFactory functions. -func testProviderFactories(c TestCase) map[string]terraform.ResourceProviderFactory { - ctxProviders := make(map[string]terraform.ResourceProviderFactory) - for k, pf := range c.ProviderFactories { - ctxProviders[k] = pf +// testProviderResolver is a helper to build a ResourceProviderResolver +// with pre instantiated ResourceProviders, so that we can reset them for the +// test, while only calling the factory function once. +// Any errors are stored so that they can be returned by the factory in +// terraform to match non-test behavior. +func testProviderResolver(c TestCase) (terraform.ResourceProviderResolver, error) { + ctxProviders := c.ProviderFactories + if ctxProviders == nil { + ctxProviders = make(map[string]terraform.ResourceProviderFactory) } // add any fixed providers for k, p := range c.Providers { ctxProviders[k] = terraform.ResourceProviderFactoryFixed(p) } - return ctxProviders -} - -// testProviderResolver is a helper to build a ResourceProviderResolver -// with pre instantiated ResourceProviders, so that we can reset them for the -// test, while only calling the factory function once. -// Any errors are stored so that they can be returned by the factory in -// terraform to match non-test behavior. -func testProviderResolver(c TestCase) (providers.Resolver, error) { - ctxProviders := testProviderFactories(c) - - // wrap the old provider factories in the test grpc server so they can be - // called from terraform. - newProviders := make(map[string]providers.Factory) + // reset the providers if needed for k, pf := range ctxProviders { - factory := pf // must copy to ensure each closure sees its own value - newProviders[k] = func() (providers.Interface, error) { - p, err := factory() + // we can ignore any errors here, if we don't have a provider to reset + // the error will be handled later + p, err := pf() + if err != nil { + return nil, err + } + if p, ok := p.(TestProvider); ok { + err := p.TestReset() if err != nil { - return nil, err + return nil, fmt.Errorf("[ERROR] failed to reset provider %q: %s", k, err) } - - // The provider is wrapped in a GRPCTestProvider so that it can be - // passed back to terraform core as a providers.Interface, rather - // than the legacy ResourceProvider. - return GRPCTestProvider(p), nil } } - return providers.ResolverFixed(newProviders), nil + return terraform.ResourceProviderResolverFixed(ctxProviders), nil } // UnitTest is a helper to force the acceptance testing harness to run in the @@ -711,40 +670,33 @@ func testIDOnlyRefresh(c TestCase, opts terraform.ContextOpts, step TestStep, r return nil } - addr := addrs.Resource{ - Mode: addrs.ManagedResourceMode, - Type: r.Type, - Name: "foo", - }.Instance(addrs.NoKey) - absAddr := addr.Absolute(addrs.RootModuleInstance) + name := fmt.Sprintf("%s.foo", r.Type) // Build the state. The state is just the resource with an ID. There // are no attributes. We only set what is needed to perform a refresh. - state := states.NewState() - state.RootModule().SetResourceInstanceCurrent( - addr, - &states.ResourceInstanceObjectSrc{ - AttrsFlat: r.Primary.Attributes, - Status: states.ObjectReady, + state := terraform.NewState() + state.RootModule().Resources[name] = &terraform.ResourceState{ + Type: r.Type, + Primary: &terraform.InstanceState{ + ID: r.Primary.ID, }, - addrs.ProviderConfig{Type: "placeholder"}.Absolute(addrs.RootModuleInstance), - ) + } // Create the config module. We use the full config because Refresh // doesn't have access to it and we may need things like provider // configurations. The initial implementation of id-only checks used // an empty config module, but that caused the aforementioned problems. - cfg, err := testConfig(opts, step) + mod, err := testModule(opts, step) if err != nil { return err } // Initialize the context - opts.Config = cfg + opts.Module = mod opts.State = state - ctx, ctxDiags := terraform.NewContext(&opts) - if ctxDiags.HasErrors() { - return ctxDiags.Err() + ctx, err := terraform.NewContext(&opts) + if err != nil { + return err } if diags := ctx.Validate(); len(diags) > 0 { if diags.HasErrors() { @@ -755,20 +707,20 @@ func testIDOnlyRefresh(c TestCase, opts terraform.ContextOpts, step TestStep, r } // Refresh! - state, refreshDiags := ctx.Refresh() - if refreshDiags.HasErrors() { - return refreshDiags.Err() + state, err = ctx.Refresh() + if err != nil { + return fmt.Errorf("Error refreshing: %s", err) } // Verify attribute equivalence. - actualR := state.ResourceInstance(absAddr) + actualR := state.RootModule().Resources[name] if actualR == nil { return fmt.Errorf("Resource gone!") } - if actualR.Current == nil { + if actualR.Primary == nil { return fmt.Errorf("Resource has no primary instance") } - actual := actualR.Current.AttrsFlat + actual := actualR.Primary.Attributes expected := r.Primary.Attributes // Remove fields we're ignoring for _, v := range c.IDRefreshIgnore { @@ -804,14 +756,15 @@ func testIDOnlyRefresh(c TestCase, opts terraform.ContextOpts, step TestStep, r return nil } -func testConfig(opts terraform.ContextOpts, step TestStep) (*configs.Config, error) { +func testModule(opts terraform.ContextOpts, step TestStep) (*module.Tree, error) { if step.PreConfig != nil { step.PreConfig() } cfgPath, err := ioutil.TempDir("", "tf-test") if err != nil { - return nil, fmt.Errorf("Error creating temporary directory for config: %s", err) + return nil, fmt.Errorf( + "Error creating temporary directory for config: %s", err) } if step.PreventDiskCleanup { @@ -820,38 +773,38 @@ func testConfig(opts terraform.ContextOpts, step TestStep) (*configs.Config, err defer os.RemoveAll(cfgPath) } - // Write the main configuration file - err = ioutil.WriteFile(filepath.Join(cfgPath, "main.tf"), []byte(step.Config), os.ModePerm) + // Write the configuration + cfgF, err := os.Create(filepath.Join(cfgPath, "main.tf")) if err != nil { - return nil, fmt.Errorf("Error creating temporary file for config: %s", err) + return nil, fmt.Errorf( + "Error creating temporary file for config: %s", err) } - // Create directory for our child modules, if any. - modulesDir := filepath.Join(cfgPath, ".modules") - err = os.Mkdir(modulesDir, os.ModePerm) + _, err = io.Copy(cfgF, strings.NewReader(step.Config)) + cfgF.Close() if err != nil { - return nil, fmt.Errorf("Error creating child modules directory: %s", err) + return nil, fmt.Errorf( + "Error creating temporary file for config: %s", err) } - inst := initwd.NewModuleInstaller(modulesDir, nil) - _, installDiags := inst.InstallModules(cfgPath, true, initwd.ModuleInstallHooksImpl{}) - if installDiags.HasErrors() { - return nil, installDiags.Err() - } - - loader, err := configload.NewLoader(&configload.Config{ - ModulesDir: modulesDir, - }) + // Parse the configuration + mod, err := module.NewTreeModule("", cfgPath) if err != nil { - return nil, fmt.Errorf("failed to create config loader: %s", err) + return nil, fmt.Errorf( + "Error loading configuration: %s", err) } - config, configDiags := loader.LoadConfig(cfgPath) - if configDiags.HasErrors() { - return nil, configDiags + // Load the modules + modStorage := &module.Storage{ + StorageDir: filepath.Join(cfgPath, ".tfmodules"), + Mode: module.GetModeGet, + } + err = mod.Load(modStorage) + if err != nil { + return nil, fmt.Errorf("Error downloading modules: %s", err) } - return config, nil + return mod, nil } func testResource(c TestStep, state *terraform.State) (*terraform.ResourceState, error) { @@ -928,9 +881,8 @@ func TestCheckResourceAttrSet(name, key string) TestCheckFunc { // TestCheckModuleResourceAttrSet - as per TestCheckResourceAttrSet but with // support for non-root modules func TestCheckModuleResourceAttrSet(mp []string, name string, key string) TestCheckFunc { - mpt := addrs.Module(mp).UnkeyedInstanceShim() return func(s *terraform.State) error { - is, err := modulePathPrimaryInstanceState(s, mpt, name) + is, err := modulePathPrimaryInstanceState(s, mp, name) if err != nil { return err } @@ -963,9 +915,8 @@ func TestCheckResourceAttr(name, key, value string) TestCheckFunc { // TestCheckModuleResourceAttr - as per TestCheckResourceAttr but with // support for non-root modules func TestCheckModuleResourceAttr(mp []string, name string, key string, value string) TestCheckFunc { - mpt := addrs.Module(mp).UnkeyedInstanceShim() return func(s *terraform.State) error { - is, err := modulePathPrimaryInstanceState(s, mpt, name) + is, err := modulePathPrimaryInstanceState(s, mp, name) if err != nil { return err } @@ -975,19 +926,7 @@ func TestCheckModuleResourceAttr(mp []string, name string, key string, value str } func testCheckResourceAttr(is *terraform.InstanceState, name string, key string, value string) error { - // Empty containers may be elided from the state. - // If the intent here is to check for an empty container, allow the key to - // also be non-existent. - emptyCheck := false - if value == "0" && (strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { - emptyCheck = true - } - if v, ok := is.Attributes[key]; !ok || v != value { - if emptyCheck && !ok { - return nil - } - if !ok { return fmt.Errorf("%s: Attribute '%s' not found", name, key) } @@ -1018,9 +957,8 @@ func TestCheckNoResourceAttr(name, key string) TestCheckFunc { // TestCheckModuleNoResourceAttr - as per TestCheckNoResourceAttr but with // support for non-root modules func TestCheckModuleNoResourceAttr(mp []string, name string, key string) TestCheckFunc { - mpt := addrs.Module(mp).UnkeyedInstanceShim() return func(s *terraform.State) error { - is, err := modulePathPrimaryInstanceState(s, mpt, name) + is, err := modulePathPrimaryInstanceState(s, mp, name) if err != nil { return err } @@ -1030,20 +968,7 @@ func TestCheckModuleNoResourceAttr(mp []string, name string, key string) TestChe } func testCheckNoResourceAttr(is *terraform.InstanceState, name string, key string) error { - // Empty containers may sometimes be included in the state. - // If the intent here is to check for an empty container, allow the value to - // also be "0". - emptyCheck := false - if strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%") { - emptyCheck = true - } - - val, exists := is.Attributes[key] - if emptyCheck && val == "0" { - return nil - } - - if exists { + if _, ok := is.Attributes[key]; ok { return fmt.Errorf("%s: Attribute '%s' found when not expected", name, key) } @@ -1066,9 +991,8 @@ func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc { // TestModuleMatchResourceAttr - as per TestMatchResourceAttr but with // support for non-root modules func TestModuleMatchResourceAttr(mp []string, name string, key string, r *regexp.Regexp) TestCheckFunc { - mpt := addrs.Module(mp).UnkeyedInstanceShim() return func(s *terraform.State) error { - is, err := modulePathPrimaryInstanceState(s, mpt, name) + is, err := modulePathPrimaryInstanceState(s, mp, name) if err != nil { return err } @@ -1128,15 +1052,13 @@ func TestCheckResourceAttrPair(nameFirst, keyFirst, nameSecond, keySecond string // TestCheckModuleResourceAttrPair - as per TestCheckResourceAttrPair but with // support for non-root modules func TestCheckModuleResourceAttrPair(mpFirst []string, nameFirst string, keyFirst string, mpSecond []string, nameSecond string, keySecond string) TestCheckFunc { - mptFirst := addrs.Module(mpFirst).UnkeyedInstanceShim() - mptSecond := addrs.Module(mpSecond).UnkeyedInstanceShim() return func(s *terraform.State) error { - isFirst, err := modulePathPrimaryInstanceState(s, mptFirst, nameFirst) + isFirst, err := modulePathPrimaryInstanceState(s, mpFirst, nameFirst) if err != nil { return err } - isSecond, err := modulePathPrimaryInstanceState(s, mptSecond, nameSecond) + isSecond, err := modulePathPrimaryInstanceState(s, mpSecond, nameSecond) if err != nil { return err } @@ -1146,32 +1068,14 @@ func TestCheckModuleResourceAttrPair(mpFirst []string, nameFirst string, keyFirs } func testCheckResourceAttrPair(isFirst *terraform.InstanceState, nameFirst string, keyFirst string, isSecond *terraform.InstanceState, nameSecond string, keySecond string) error { - vFirst, okFirst := isFirst.Attributes[keyFirst] - vSecond, okSecond := isSecond.Attributes[keySecond] - - // Container count values of 0 should not be relied upon, and not reliably - // maintained by helper/schema. For the purpose of tests, consider unset and - // 0 to be equal. - if len(keyFirst) > 2 && len(keySecond) > 2 && keyFirst[len(keyFirst)-2:] == keySecond[len(keySecond)-2:] && - (strings.HasSuffix(keyFirst, ".#") || strings.HasSuffix(keyFirst, ".%")) { - // they have the same suffix, and it is a collection count key. - if vFirst == "0" || vFirst == "" { - okFirst = false - } - if vSecond == "0" || vSecond == "" { - okSecond = false - } + vFirst, ok := isFirst.Attributes[keyFirst] + if !ok { + return fmt.Errorf("%s: Attribute '%s' not found", nameFirst, keyFirst) } - if okFirst != okSecond { - if !okFirst { - return fmt.Errorf("%s: Attribute %q not set, but %q is set in %s as %q", nameFirst, keyFirst, keySecond, nameSecond, vSecond) - } - return fmt.Errorf("%s: Attribute %q is %q, but %q is not set in %s", nameFirst, keyFirst, vFirst, keySecond, nameSecond) - } - if !(okFirst || okSecond) { - // If they both don't exist then they are equally unset, so that's okay. - return nil + vSecond, ok := isSecond.Attributes[keySecond] + if !ok { + return fmt.Errorf("%s: Attribute '%s' not found", nameSecond, keySecond) } if vFirst != vSecond { @@ -1259,7 +1163,7 @@ func modulePrimaryInstanceState(s *terraform.State, ms *terraform.ModuleState, n // modulePathPrimaryInstanceState returns the primary instance state for the // given resource name in a given module path. -func modulePathPrimaryInstanceState(s *terraform.State, mp addrs.ModuleInstance, name string) (*terraform.InstanceState, error) { +func modulePathPrimaryInstanceState(s *terraform.State, mp []string, name string) (*terraform.InstanceState, error) { ms := s.ModuleByPath(mp) if ms == nil { return nil, fmt.Errorf("No module found at: %s", mp) @@ -1274,47 +1178,3 @@ func primaryInstanceState(s *terraform.State, name string) (*terraform.InstanceS ms := s.RootModule() return modulePrimaryInstanceState(s, ms, name) } - -// operationError is a specialized implementation of error used to describe -// failures during one of the several operations performed for a particular -// test case. -type operationError struct { - OpName string - Diags tfdiags.Diagnostics -} - -func newOperationError(opName string, diags tfdiags.Diagnostics) error { - return operationError{opName, diags} -} - -// Error returns a terse error string containing just the basic diagnostic -// messages, for situations where normal Go error behavior is appropriate. -func (err operationError) Error() string { - return fmt.Sprintf("errors during %s: %s", err.OpName, err.Diags.Err().Error()) -} - -// ErrorDetail is like Error except it includes verbosely-rendered diagnostics -// similar to what would come from a normal Terraform run, which include -// additional context not included in Error(). -func (err operationError) ErrorDetail() string { - var buf bytes.Buffer - fmt.Fprintf(&buf, "errors during %s:", err.OpName) - clr := &colorstring.Colorize{Disable: true, Colors: colorstring.DefaultColors} - for _, diag := range err.Diags { - diagStr := format.Diagnostic(diag, nil, clr, 78) - buf.WriteByte('\n') - buf.WriteString(diagStr) - } - return buf.String() -} - -// detailedErrorMessage is a helper for calling ErrorDetail on an error if -// it is an operationError or just taking Error otherwise. -func detailedErrorMessage(err error) string { - switch tErr := err.(type) { - case operationError: - return tErr.ErrorDetail() - default: - return err.Error() - } -} diff --git a/vendor/github.com/hashicorp/terraform/helper/resource/testing_config.go b/vendor/github.com/hashicorp/terraform/helper/resource/testing_config.go index 7635a705..033f1266 100644 --- a/vendor/github.com/hashicorp/terraform/helper/resource/testing_config.go +++ b/vendor/github.com/hashicorp/terraform/helper/resource/testing_config.go @@ -1,23 +1,13 @@ package resource import ( - "bufio" - "bytes" "errors" "fmt" "log" - "sort" "strings" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/hcl2shim" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/terraform/plans" "github.com/hashicorp/terraform/terraform" - "github.com/hashicorp/terraform/tfdiags" ) // testStepConfig runs a config-mode test step @@ -28,79 +18,69 @@ func testStepConfig( return testStep(opts, state, step) } -func testStep(opts terraform.ContextOpts, state *terraform.State, step TestStep) (*terraform.State, error) { +func testStep( + opts terraform.ContextOpts, + state *terraform.State, + step TestStep) (*terraform.State, error) { + // Pre-taint any resources that have been defined in Taint, as long as this + // is not a destroy step. if !step.Destroy { if err := testStepTaint(state, step); err != nil { return state, err } } - cfg, err := testConfig(opts, step) + mod, err := testModule(opts, step) if err != nil { return state, err } - var stepDiags tfdiags.Diagnostics - // Build the context - opts.Config = cfg - opts.State, err = terraform.ShimLegacyState(state) - if err != nil { - return nil, err - } - + opts.Module = mod + opts.State = state opts.Destroy = step.Destroy - ctx, stepDiags := terraform.NewContext(&opts) - if stepDiags.HasErrors() { - return state, fmt.Errorf("Error initializing context: %s", stepDiags.Err()) + ctx, err := terraform.NewContext(&opts) + if err != nil { + return state, fmt.Errorf("Error initializing context: %s", err) } - if stepDiags := ctx.Validate(); len(stepDiags) > 0 { - if stepDiags.HasErrors() { - return state, errwrap.Wrapf("config is invalid: {{err}}", stepDiags.Err()) + if diags := ctx.Validate(); len(diags) > 0 { + if diags.HasErrors() { + return nil, errwrap.Wrapf("config is invalid: {{err}}", diags.Err()) } - log.Printf("[WARN] Config warnings:\n%s", stepDiags) + log.Printf("[WARN] Config warnings:\n%s", diags) } // Refresh! - newState, stepDiags := ctx.Refresh() - // shim the state first so the test can check the state on errors - - state, err = shimNewState(newState, step.providers) + state, err = ctx.Refresh() if err != nil { - return nil, err - } - if stepDiags.HasErrors() { - return state, newOperationError("refresh", stepDiags) + return state, fmt.Errorf( + "Error refreshing: %s", err) } // If this step is a PlanOnly step, skip over this first Plan and subsequent // Apply, and use the follow up Plan that checks for perpetual diffs if !step.PlanOnly { // Plan! - if p, stepDiags := ctx.Plan(); stepDiags.HasErrors() { - return state, newOperationError("plan", stepDiags) + if p, err := ctx.Plan(); err != nil { + return state, fmt.Errorf( + "Error planning: %s", err) } else { - log.Printf("[WARN] Test: Step plan: %s", legacyPlanComparisonString(newState, p.Changes)) + log.Printf("[WARN] Test: Step plan: %s", p) } // We need to keep a copy of the state prior to destroying - // such that destroy steps can verify their behavior in the check + // such that destroy steps can verify their behaviour in the check // function stateBeforeApplication := state.DeepCopy() - // Apply the diff, creating real resources. - newState, stepDiags = ctx.Apply() - // shim the state first so the test can check the state on errors - state, err = shimNewState(newState, step.providers) + // Apply! + state, err = ctx.Apply() if err != nil { - return nil, err - } - if stepDiags.HasErrors() { - return state, newOperationError("apply", stepDiags) + return state, fmt.Errorf("Error applying: %s", err) } - // Run any configured checks + // Check! Excitement! if step.Check != nil { if step.Destroy { if err := step.Check(stateBeforeApplication); err != nil { @@ -116,35 +96,31 @@ func testStep(opts terraform.ContextOpts, state *terraform.State, step TestStep) // Now, verify that Plan is now empty and we don't have a perpetual diff issue // We do this with TWO plans. One without a refresh. - var p *plans.Plan - if p, stepDiags = ctx.Plan(); stepDiags.HasErrors() { - return state, newOperationError("follow-up plan", stepDiags) + var p *terraform.Plan + if p, err = ctx.Plan(); err != nil { + return state, fmt.Errorf("Error on follow-up plan: %s", err) } - if !p.Changes.Empty() { + if p.Diff != nil && !p.Diff.Empty() { if step.ExpectNonEmptyPlan { - log.Printf("[INFO] Got non-empty plan, as expected:\n\n%s", legacyPlanComparisonString(newState, p.Changes)) + log.Printf("[INFO] Got non-empty plan, as expected:\n\n%s", p) } else { return state, fmt.Errorf( - "After applying this step, the plan was not empty:\n\n%s", legacyPlanComparisonString(newState, p.Changes)) + "After applying this step, the plan was not empty:\n\n%s", p) } } // And another after a Refresh. if !step.Destroy || (step.Destroy && !step.PreventPostDestroyRefresh) { - newState, stepDiags = ctx.Refresh() - if stepDiags.HasErrors() { - return state, newOperationError("follow-up refresh", stepDiags) - } - - state, err = shimNewState(newState, step.providers) + state, err = ctx.Refresh() if err != nil { - return nil, err + return state, fmt.Errorf( + "Error on follow-up refresh: %s", err) } } - if p, stepDiags = ctx.Plan(); stepDiags.HasErrors() { - return state, newOperationError("second follow-up refresh", stepDiags) + if p, err = ctx.Plan(); err != nil { + return state, fmt.Errorf("Error on second follow-up plan: %s", err) } - empty := p.Changes.Empty() + empty := p.Diff == nil || p.Diff.Empty() // Data resources are tricky because they legitimately get instantiated // during refresh so that they will be already populated during the @@ -152,28 +128,35 @@ func testStep(opts terraform.ContextOpts, state *terraform.State, step TestStep) // config we'll end up wanting to destroy them again here. This is // acceptable and expected, and we'll treat it as "empty" for the // sake of this testing. - if step.Destroy && !empty { + if step.Destroy { empty = true - for _, change := range p.Changes.Resources { - if change.Addr.Resource.Resource.Mode != addrs.DataResourceMode { - empty = false - break + + for _, moduleDiff := range p.Diff.Modules { + for k, instanceDiff := range moduleDiff.Resources { + if !strings.HasPrefix(k, "data.") { + empty = false + break + } + + if !instanceDiff.Destroy { + empty = false + } } } } if !empty { if step.ExpectNonEmptyPlan { - log.Printf("[INFO] Got non-empty plan, as expected:\n\n%s", legacyPlanComparisonString(newState, p.Changes)) + log.Printf("[INFO] Got non-empty plan, as expected:\n\n%s", p) } else { return state, fmt.Errorf( "After applying this step and refreshing, "+ - "the plan was not empty:\n\n%s", legacyPlanComparisonString(newState, p.Changes)) + "the plan was not empty:\n\n%s", p) } } // Made it here, but expected a non-empty plan, fail! - if step.ExpectNonEmptyPlan && empty { + if step.ExpectNonEmptyPlan && (p.Diff == nil || p.Diff.Empty()) { return state, fmt.Errorf("Expected a non-empty plan, but got an empty plan!") } @@ -181,194 +164,6 @@ func testStep(opts terraform.ContextOpts, state *terraform.State, step TestStep) return state, nil } -// legacyPlanComparisonString produces a string representation of the changes -// from a plan and a given state togther, as was formerly produced by the -// String method of terraform.Plan. -// -// This is here only for compatibility with existing tests that predate our -// new plan and state types, and should not be used in new tests. Instead, use -// a library like "cmp" to do a deep equality and diff on the two -// data structures. -func legacyPlanComparisonString(state *states.State, changes *plans.Changes) string { - return fmt.Sprintf( - "DIFF:\n\n%s\n\nSTATE:\n\n%s", - legacyDiffComparisonString(changes), - state.String(), - ) -} - -// legacyDiffComparisonString produces a string representation of the changes -// from a planned changes object, as was formerly produced by the String method -// of terraform.Diff. -// -// This is here only for compatibility with existing tests that predate our -// new plan types, and should not be used in new tests. Instead, use a library -// like "cmp" to do a deep equality check and diff on the two data structures. -func legacyDiffComparisonString(changes *plans.Changes) string { - // The old string representation of a plan was grouped by module, but - // our new plan structure is not grouped in that way and so we'll need - // to preprocess it in order to produce that grouping. - type ResourceChanges struct { - Current *plans.ResourceInstanceChangeSrc - Deposed map[states.DeposedKey]*plans.ResourceInstanceChangeSrc - } - byModule := map[string]map[string]*ResourceChanges{} - resourceKeys := map[string][]string{} - var moduleKeys []string - for _, rc := range changes.Resources { - if rc.Action == plans.NoOp { - // We won't mention no-op changes here at all, since the old plan - // model we are emulating here didn't have such a concept. - continue - } - moduleKey := rc.Addr.Module.String() - if _, exists := byModule[moduleKey]; !exists { - moduleKeys = append(moduleKeys, moduleKey) - byModule[moduleKey] = make(map[string]*ResourceChanges) - } - resourceKey := rc.Addr.Resource.String() - if _, exists := byModule[moduleKey][resourceKey]; !exists { - resourceKeys[moduleKey] = append(resourceKeys[moduleKey], resourceKey) - byModule[moduleKey][resourceKey] = &ResourceChanges{ - Deposed: make(map[states.DeposedKey]*plans.ResourceInstanceChangeSrc), - } - } - - if rc.DeposedKey == states.NotDeposed { - byModule[moduleKey][resourceKey].Current = rc - } else { - byModule[moduleKey][resourceKey].Deposed[rc.DeposedKey] = rc - } - } - sort.Strings(moduleKeys) - for _, ks := range resourceKeys { - sort.Strings(ks) - } - - var buf bytes.Buffer - - for _, moduleKey := range moduleKeys { - rcs := byModule[moduleKey] - var mBuf bytes.Buffer - - for _, resourceKey := range resourceKeys[moduleKey] { - rc := rcs[resourceKey] - - crud := "UPDATE" - if rc.Current != nil { - switch rc.Current.Action { - case plans.DeleteThenCreate: - crud = "DESTROY/CREATE" - case plans.CreateThenDelete: - crud = "CREATE/DESTROY" - case plans.Delete: - crud = "DESTROY" - case plans.Create: - crud = "CREATE" - } - } else { - // We must be working on a deposed object then, in which - // case destroying is the only possible action. - crud = "DESTROY" - } - - extra := "" - if rc.Current == nil && len(rc.Deposed) > 0 { - extra = " (deposed only)" - } - - fmt.Fprintf( - &mBuf, "%s: %s%s\n", - crud, resourceKey, extra, - ) - - attrNames := map[string]bool{} - var oldAttrs map[string]string - var newAttrs map[string]string - if rc.Current != nil { - if before := rc.Current.Before; before != nil { - ty, err := before.ImpliedType() - if err == nil { - val, err := before.Decode(ty) - if err == nil { - oldAttrs = hcl2shim.FlatmapValueFromHCL2(val) - for k := range oldAttrs { - attrNames[k] = true - } - } - } - } - if after := rc.Current.After; after != nil { - ty, err := after.ImpliedType() - if err == nil { - val, err := after.Decode(ty) - if err == nil { - newAttrs = hcl2shim.FlatmapValueFromHCL2(val) - for k := range newAttrs { - attrNames[k] = true - } - } - } - } - } - if oldAttrs == nil { - oldAttrs = make(map[string]string) - } - if newAttrs == nil { - newAttrs = make(map[string]string) - } - - attrNamesOrder := make([]string, 0, len(attrNames)) - keyLen := 0 - for n := range attrNames { - attrNamesOrder = append(attrNamesOrder, n) - if len(n) > keyLen { - keyLen = len(n) - } - } - sort.Strings(attrNamesOrder) - - for _, attrK := range attrNamesOrder { - v := newAttrs[attrK] - u := oldAttrs[attrK] - - if v == config.UnknownVariableValue { - v = "" - } - // NOTE: we don't support here because we would - // need schema to do that. Excluding sensitive values - // is now done at the UI layer, and so should not be tested - // at the core layer. - - updateMsg := "" - // TODO: Mark " (forces new resource)" in updateMsg when appropriate. - - fmt.Fprintf( - &mBuf, " %s:%s %#v => %#v%s\n", - attrK, - strings.Repeat(" ", keyLen-len(attrK)), - u, v, - updateMsg, - ) - } - } - - if moduleKey == "" { // root module - buf.Write(mBuf.Bytes()) - buf.WriteByte('\n') - continue - } - - fmt.Fprintf(&buf, "%s:\n", moduleKey) - s := bufio.NewScanner(&mBuf) - for s.Scan() { - buf.WriteString(fmt.Sprintf(" %s\n", s.Text())) - } - } - - return buf.String() -} - func testStepTaint(state *terraform.State, step TestStep) error { for _, p := range step.Taint { m := state.RootModule() diff --git a/vendor/github.com/hashicorp/terraform/helper/resource/testing_import_state.go b/vendor/github.com/hashicorp/terraform/helper/resource/testing_import_state.go index 97a69c59..94fef3cf 100644 --- a/vendor/github.com/hashicorp/terraform/helper/resource/testing_import_state.go +++ b/vendor/github.com/hashicorp/terraform/helper/resource/testing_import_state.go @@ -7,11 +7,6 @@ import ( "strings" "github.com/davecgh/go-spew/spew" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/states" "github.com/hashicorp/terraform/terraform" ) @@ -20,7 +15,6 @@ func testStepImportState( opts terraform.ContextOpts, state *terraform.State, step TestStep) (*terraform.State, error) { - // Determine the ID to import var importId string switch { @@ -47,53 +41,33 @@ func testStepImportState( // Setup the context. We initialize with an empty state. We use the // full config for provider configurations. - cfg, err := testConfig(opts, step) + mod, err := testModule(opts, step) if err != nil { return state, err } - opts.Config = cfg - - // import tests start with empty state - opts.State = states.NewState() - - ctx, stepDiags := terraform.NewContext(&opts) - if stepDiags.HasErrors() { - return state, stepDiags.Err() + opts.Module = mod + opts.State = terraform.NewState() + ctx, err := terraform.NewContext(&opts) + if err != nil { + return state, err } - // The test step provides the resource address as a string, so we need - // to parse it to get an addrs.AbsResourceAddress to pass in to the - // import method. - traversal, hclDiags := hclsyntax.ParseTraversalAbs([]byte(step.ResourceName), "", hcl.Pos{}) - if hclDiags.HasErrors() { - return nil, hclDiags - } - importAddr, stepDiags := addrs.ParseAbsResourceInstance(traversal) - if stepDiags.HasErrors() { - return nil, stepDiags.Err() - } - - // Do the import - importedState, stepDiags := ctx.Import(&terraform.ImportOpts{ + // Do the import! + newState, err := ctx.Import(&terraform.ImportOpts{ // Set the module so that any provider config is loaded - Config: cfg, + Module: mod, Targets: []*terraform.ImportTarget{ &terraform.ImportTarget{ - Addr: importAddr, + Addr: step.ResourceName, ID: importId, }, }, }) - if stepDiags.HasErrors() { - log.Printf("[ERROR] Test: ImportState failure: %s", stepDiags.Err()) - return state, stepDiags.Err() - } - - newState, err := shimNewState(importedState, step.providers) if err != nil { - return nil, err + log.Printf("[ERROR] Test: ImportState failure: %s", err) + return state, err } // Go through the new state and verify @@ -101,9 +75,7 @@ func testStepImportState( var states []*terraform.InstanceState for _, r := range newState.RootModule().Resources { if r.Primary != nil { - is := r.Primary.DeepCopy() - is.Ephemeral.Type = r.Type // otherwise the check function cannot see the type - states = append(states, is) + states = append(states, r.Primary) } } if err := step.ImportStateCheck(states); err != nil { @@ -130,31 +102,13 @@ func testStepImportState( r.Primary.ID) } - // don't add empty flatmapped containers, so we can more easily - // compare the attributes - skipEmpty := func(k, v string) bool { - if strings.HasSuffix(k, ".#") || strings.HasSuffix(k, ".%") { - if v == "0" { - return true - } - } - return false - } - // Compare their attributes actual := make(map[string]string) for k, v := range r.Primary.Attributes { - if skipEmpty(k, v) { - continue - } actual[k] = v } - expected := make(map[string]string) for k, v := range oldR.Primary.Attributes { - if skipEmpty(k, v) { - continue - } expected[k] = v } diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/backend.go b/vendor/github.com/hashicorp/terraform/helper/schema/backend.go index 64c3b9f6..57fbba74 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/backend.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/backend.go @@ -2,15 +2,8 @@ package schema import ( "context" - "fmt" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/config/hcl2shim" - "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/terraform" - ctyconvert "github.com/zclconf/go-cty/cty/convert" ) // Backend represents a partial backend.Backend implementation and simplifies @@ -45,123 +38,41 @@ func FromContextBackendConfig(ctx context.Context) *ResourceData { return ctx.Value(backendConfigKey).(*ResourceData) } -func (b *Backend) ConfigSchema() *configschema.Block { - // This is an alias of CoreConfigSchema just to implement the - // backend.Backend interface. - return b.CoreConfigSchema() -} - -func (b *Backend) PrepareConfig(configVal cty.Value) (cty.Value, tfdiags.Diagnostics) { +func (b *Backend) Input( + input terraform.UIInput, + c *terraform.ResourceConfig) (*terraform.ResourceConfig, error) { if b == nil { - return configVal, nil - } - var diags tfdiags.Diagnostics - var err error - - // In order to use Transform below, this needs to be filled out completely - // according the schema. - configVal, err = b.CoreConfigSchema().CoerceValue(configVal) - if err != nil { - return configVal, diags.Append(err) + return c, nil } - // lookup any required, top-level attributes that are Null, and see if we - // have a Default value available. - configVal, err = cty.Transform(configVal, func(path cty.Path, val cty.Value) (cty.Value, error) { - // we're only looking for top-level attributes - if len(path) != 1 { - return val, nil - } - - // nothing to do if we already have a value - if !val.IsNull() { - return val, nil - } - - // get the Schema definition for this attribute - getAttr, ok := path[0].(cty.GetAttrStep) - // these should all exist, but just ignore anything strange - if !ok { - return val, nil - } - - attrSchema := b.Schema[getAttr.Name] - // continue to ignore anything that doesn't match - if attrSchema == nil { - return val, nil - } - - // this is deprecated, so don't set it - if attrSchema.Deprecated != "" || attrSchema.Removed != "" { - return val, nil - } - - // find a default value if it exists - def, err := attrSchema.DefaultValue() - if err != nil { - diags = diags.Append(fmt.Errorf("error getting default for %q: %s", getAttr.Name, err)) - return val, err - } - - // no default - if def == nil { - return val, nil - } - - // create a cty.Value and make sure it's the correct type - tmpVal := hcl2shim.HCL2ValueFromConfigValue(def) - - // helper/schema used to allow setting "" to a bool - if val.Type() == cty.Bool && tmpVal.RawEquals(cty.StringVal("")) { - // return a warning about the conversion - diags = diags.Append("provider set empty string as default value for bool " + getAttr.Name) - tmpVal = cty.False - } - - val, err = ctyconvert.Convert(tmpVal, val.Type()) - if err != nil { - diags = diags.Append(fmt.Errorf("error setting default for %q: %s", getAttr.Name, err)) - } - - return val, err - }) - if err != nil { - // any error here was already added to the diagnostics - return configVal, diags - } - - shimRC := b.shimConfig(configVal) - warns, errs := schemaMap(b.Schema).Validate(shimRC) - for _, warn := range warns { - diags = diags.Append(tfdiags.SimpleWarning(warn)) - } - for _, err := range errs { - diags = diags.Append(err) - } - return configVal, diags + return schemaMap(b.Schema).Input(input, c) } -func (b *Backend) Configure(obj cty.Value) tfdiags.Diagnostics { +func (b *Backend) Validate(c *terraform.ResourceConfig) ([]string, []error) { + if b == nil { + return nil, nil + } + + return schemaMap(b.Schema).Validate(c) +} + +func (b *Backend) Configure(c *terraform.ResourceConfig) error { if b == nil { return nil } - var diags tfdiags.Diagnostics sm := schemaMap(b.Schema) - shimRC := b.shimConfig(obj) // Get a ResourceData for this configuration. To do this, we actually // generate an intermediary "diff" although that is never exposed. - diff, err := sm.Diff(nil, shimRC, nil, nil, true) + diff, err := sm.Diff(nil, c, nil, nil) if err != nil { - diags = diags.Append(err) - return diags + return err } data, err := sm.Data(nil, diff) if err != nil { - diags = diags.Append(err) - return diags + return err } b.config = data @@ -169,24 +80,11 @@ func (b *Backend) Configure(obj cty.Value) tfdiags.Diagnostics { err = b.ConfigureFunc(context.WithValue( context.Background(), backendConfigKey, data)) if err != nil { - diags = diags.Append(err) - return diags + return err } } - return diags -} - -// shimConfig turns a new-style cty.Value configuration (which must be of -// an object type) into a minimal old-style *terraform.ResourceConfig object -// that should be populated enough to appease the not-yet-updated functionality -// in this package. This should be removed once everything is updated. -func (b *Backend) shimConfig(obj cty.Value) *terraform.ResourceConfig { - shimMap := hcl2shim.ConfigValueFromHCL2(obj).(map[string]interface{}) - return &terraform.ResourceConfig{ - Config: shimMap, - Raw: shimMap, - } + return nil } // Config returns the configuration. This is available after Configure is diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/core_schema.go b/vendor/github.com/hashicorp/terraform/helper/schema/core_schema.go index 727b164b..bf952f66 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/core_schema.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/core_schema.go @@ -3,7 +3,7 @@ package schema import ( "fmt" - "github.com/hashicorp/terraform/configs/configschema" + "github.com/hashicorp/terraform/config/configschema" "github.com/zclconf/go-cty/cty" ) @@ -39,23 +39,8 @@ func (m schemaMap) CoreConfigSchema() *configschema.Block { ret.Attributes[name] = schema.coreConfigSchemaAttribute() continue } - if schema.Type == TypeMap { - // For TypeMap in particular, it isn't valid for Elem to be a - // *Resource (since that would be ambiguous in flatmap) and - // so Elem is treated as a TypeString schema if so. This matches - // how the field readers treat this situation, for compatibility - // with configurations targeting Terraform 0.11 and earlier. - if _, isResource := schema.Elem.(*Resource); isResource { - sch := *schema // shallow copy - sch.Elem = &Schema{ - Type: TypeString, - } - ret.Attributes[name] = sch.coreConfigSchemaAttribute() - continue - } - } switch schema.Elem.(type) { - case *Schema, ValueType: + case *Schema: ret.Attributes[name] = schema.coreConfigSchemaAttribute() case *Resource: ret.BlockTypes[name] = schema.coreConfigSchemaBlock() @@ -73,42 +58,12 @@ func (m schemaMap) CoreConfigSchema() *configschema.Block { // Elem is an instance of Schema. Use coreConfigSchemaBlock for collections // whose elem is a whole resource. func (s *Schema) coreConfigSchemaAttribute() *configschema.Attribute { - // The Schema.DefaultFunc capability adds some extra weirdness here since - // it can be combined with "Required: true" to create a sitution where - // required-ness is conditional. Terraform Core doesn't share this concept, - // so we must sniff for this possibility here and conditionally turn - // off the "Required" flag if it looks like the DefaultFunc is going - // to provide a value. - // This is not 100% true to the original interface of DefaultFunc but - // works well enough for the EnvDefaultFunc and MultiEnvDefaultFunc - // situations, which are the main cases we care about. - // - // Note that this also has a consequence for commands that return schema - // information for documentation purposes: running those for certain - // providers will produce different results depending on which environment - // variables are set. We accept that weirdness in order to keep this - // interface to core otherwise simple. - reqd := s.Required - opt := s.Optional - if reqd && s.DefaultFunc != nil { - v, err := s.DefaultFunc() - // We can't report errors from here, so we'll instead just force - // "Required" to false and let the provider try calling its - // DefaultFunc again during the validate step, where it can then - // return the error. - if err != nil || (err == nil && v != nil) { - reqd = false - opt = true - } - } - return &configschema.Attribute{ - Type: s.coreConfigSchemaType(), - Optional: opt, - Required: reqd, - Computed: s.Computed, - Sensitive: s.Sensitive, - Description: s.Description, + Type: s.coreConfigSchemaType(), + Optional: s.Optional, + Required: s.Required, + Computed: s.Computed, + Sensitive: s.Sensitive, } } @@ -117,7 +72,7 @@ func (s *Schema) coreConfigSchemaAttribute() *configschema.Attribute { // of Resource, and will panic otherwise. func (s *Schema) coreConfigSchemaBlock() *configschema.NestedBlock { ret := &configschema.NestedBlock{} - if nested := s.Elem.(*Resource).coreConfigSchema(); nested != nil { + if nested := s.Elem.(*Resource).CoreConfigSchema(); nested != nil { ret.Block = *nested } switch s.Type { @@ -140,20 +95,6 @@ func (s *Schema) coreConfigSchemaBlock() *configschema.NestedBlock { // blocks, but we can fake it by requiring at least one item. ret.MinItems = 1 } - if s.Optional && s.MinItems > 0 { - // Historically helper/schema would ignore MinItems if Optional were - // set, so we must mimic this behavior here to ensure that providers - // relying on that undocumented behavior can continue to operate as - // they did before. - ret.MinItems = 0 - } - if s.Computed && !s.Optional { - // MinItems/MaxItems are meaningless for computed nested blocks, since - // they are never set by the user anyway. This ensures that we'll never - // generate weird errors about them. - ret.MinItems = 0 - ret.MaxItems = 0 - } return ret } @@ -176,15 +117,11 @@ func (s *Schema) coreConfigSchemaType() cty.Type { switch set := s.Elem.(type) { case *Schema: elemType = set.coreConfigSchemaType() - case ValueType: - // This represents a mistake in the provider code, but it's a - // common one so we'll just shim it. - elemType = (&Schema{Type: set}).coreConfigSchemaType() case *Resource: // In practice we don't actually use this for normal schema // construction because we construct a NestedBlock in that // case instead. See schemaMap.CoreConfigSchema. - elemType = set.coreConfigSchema().ImpliedType() + elemType = set.CoreConfigSchema().ImpliedType() default: if set != nil { // Should never happen for a valid schema @@ -211,85 +148,8 @@ func (s *Schema) coreConfigSchemaType() cty.Type { } } -// CoreConfigSchema is a convenient shortcut for calling CoreConfigSchema on -// the resource's schema. CoreConfigSchema adds the implicitly required "id" -// attribute for top level resources if it doesn't exist. -func (r *Resource) CoreConfigSchema() *configschema.Block { - block := r.coreConfigSchema() - - if block.Attributes == nil { - block.Attributes = map[string]*configschema.Attribute{} - } - - // Add the implicitly required "id" field if it doesn't exist - if block.Attributes["id"] == nil { - block.Attributes["id"] = &configschema.Attribute{ - Type: cty.String, - Optional: true, - Computed: true, - } - } - - _, timeoutsAttr := block.Attributes[TimeoutsConfigKey] - _, timeoutsBlock := block.BlockTypes[TimeoutsConfigKey] - - // Insert configured timeout values into the schema, as long as the schema - // didn't define anything else by that name. - if r.Timeouts != nil && !timeoutsAttr && !timeoutsBlock { - timeouts := configschema.Block{ - Attributes: map[string]*configschema.Attribute{}, - } - - if r.Timeouts.Create != nil { - timeouts.Attributes[TimeoutCreate] = &configschema.Attribute{ - Type: cty.String, - Optional: true, - } - } - - if r.Timeouts.Read != nil { - timeouts.Attributes[TimeoutRead] = &configschema.Attribute{ - Type: cty.String, - Optional: true, - } - } - - if r.Timeouts.Update != nil { - timeouts.Attributes[TimeoutUpdate] = &configschema.Attribute{ - Type: cty.String, - Optional: true, - } - } - - if r.Timeouts.Delete != nil { - timeouts.Attributes[TimeoutDelete] = &configschema.Attribute{ - Type: cty.String, - Optional: true, - } - } - - if r.Timeouts.Default != nil { - timeouts.Attributes[TimeoutDefault] = &configschema.Attribute{ - Type: cty.String, - Optional: true, - } - } - - block.BlockTypes[TimeoutsConfigKey] = &configschema.NestedBlock{ - Nesting: configschema.NestingSingle, - Block: timeouts, - } - } - - return block -} - -func (r *Resource) coreConfigSchema() *configschema.Block { - return schemaMap(r.Schema).CoreConfigSchema() -} - // CoreConfigSchema is a convenient shortcut for calling CoreConfigSchema -// on the backends's schema. -func (r *Backend) CoreConfigSchema() *configschema.Block { +// on the resource's schema. +func (r *Resource) CoreConfigSchema() *configschema.Block { return schemaMap(r.Schema).CoreConfigSchema() } diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_diff.go b/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_diff.go index ae35b4a8..d558a5bc 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_diff.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_diff.go @@ -174,9 +174,6 @@ func (r *DiffFieldReader) readPrimitive( func (r *DiffFieldReader) readSet( address []string, schema *Schema) (FieldReadResult, error) { - // copy address to ensure we don't modify the argument - address = append([]string(nil), address...) - prefix := strings.Join(address, ".") + "." // Create the set that will be our result diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_map.go b/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_map.go index 53f73b71..054efe08 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_map.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_map.go @@ -98,9 +98,6 @@ func (r *MapFieldReader) readPrimitive( func (r *MapFieldReader) readSet( address []string, schema *Schema) (FieldReadResult, error) { - // copy address to ensure we don't modify the argument - address = append([]string(nil), address...) - // Get the number of elements in the list countRaw, err := r.readPrimitive( append(address, "#"), &Schema{Type: TypeInt}) diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/field_writer_map.go b/vendor/github.com/hashicorp/terraform/helper/schema/field_writer_map.go index 08ee11c3..814c7ba8 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/field_writer_map.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/field_writer_map.go @@ -297,14 +297,13 @@ func (w *MapFieldWriter) setSet( // we get the proper order back based on the hash code. if v := reflect.ValueOf(value); v.Kind() == reflect.Slice { // Build a temp *ResourceData to use for the conversion - tempAddr := addr[len(addr)-1:] tempSchema := *schema tempSchema.Type = TypeList - tempSchemaMap := map[string]*Schema{tempAddr[0]: &tempSchema} + tempSchemaMap := map[string]*Schema{addr[0]: &tempSchema} tempW := &MapFieldWriter{Schema: tempSchemaMap} // Set the entire list, this lets us get sane values out of it - if err := tempW.WriteField(tempAddr, value); err != nil { + if err := tempW.WriteField(addr, value); err != nil { return err } @@ -320,7 +319,7 @@ func (w *MapFieldWriter) setSet( } for i := 0; i < v.Len(); i++ { is := strconv.FormatInt(int64(i), 10) - result, err := tempR.ReadField(append(tempAddr, is)) + result, err := tempR.ReadField(append(addrCopy, is)) if err != nil { return err } diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/provider.go b/vendor/github.com/hashicorp/terraform/helper/schema/provider.go index 97024479..6cd325da 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/provider.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/provider.go @@ -9,7 +9,7 @@ import ( "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/configs/configschema" + "github.com/hashicorp/terraform/config/configschema" "github.com/hashicorp/terraform/terraform" ) @@ -64,8 +64,6 @@ type Provider struct { stopCtx context.Context stopCtxCancel context.CancelFunc stopOnce sync.Once - - TerraformVersion string } // ConfigureFunc is the function used to configure a Provider. @@ -253,7 +251,7 @@ func (p *Provider) Configure(c *terraform.ResourceConfig) error { // Get a ResourceData for this configuration. To do this, we actually // generate an intermediary "diff" although that is never exposed. - diff, err := sm.Diff(nil, c, nil, p.meta, true) + diff, err := sm.Diff(nil, c, nil, p.meta) if err != nil { return err } @@ -298,20 +296,6 @@ func (p *Provider) Diff( return r.Diff(s, c, p.meta) } -// SimpleDiff is used by the new protocol wrappers to get a diff that doesn't -// attempt to calculate ignore_changes. -func (p *Provider) SimpleDiff( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { - r, ok := p.ResourcesMap[info.Type] - if !ok { - return nil, fmt.Errorf("unknown resource type: %s", info.Type) - } - - return r.simpleDiff(s, c, p.meta) -} - // Refresh implementation of terraform.ResourceProvider interface. func (p *Provider) Refresh( info *terraform.InstanceInfo, @@ -327,7 +311,7 @@ func (p *Provider) Refresh( // Resources implementation of terraform.ResourceProvider interface. func (p *Provider) Resources() []terraform.ResourceType { keys := make([]string, 0, len(p.ResourcesMap)) - for k := range p.ResourcesMap { + for k, _ := range p.ResourcesMap { keys = append(keys, k) } sort.Strings(keys) diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go b/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go index 637e221e..a8d42dbd 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go @@ -8,7 +8,6 @@ import ( "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/terraform" ) @@ -122,11 +121,6 @@ func (p *Provisioner) Stop() error { return nil } -// GetConfigSchema implementation of terraform.ResourceProvisioner interface. -func (p *Provisioner) GetConfigSchema() (*configschema.Block, error) { - return schemaMap(p.Schema).CoreConfigSchema(), nil -} - // Apply implementation of terraform.ResourceProvisioner interface. func (p *Provisioner) Apply( o terraform.UIOutput, @@ -152,7 +146,7 @@ func (p *Provisioner) Apply( } sm := schemaMap(p.ConnSchema) - diff, err := sm.Diff(nil, terraform.NewResourceConfig(c), nil, nil, true) + diff, err := sm.Diff(nil, terraform.NewResourceConfig(c), nil, nil) if err != nil { return err } @@ -166,7 +160,7 @@ func (p *Provisioner) Apply( // Build the configuration data. Doing this requires making a "diff" // even though that's never used. We use that just to get the correct types. configMap := schemaMap(p.Schema) - diff, err := configMap.Diff(nil, c, nil, nil, true) + diff, err := configMap.Diff(nil, c, nil, nil) if err != nil { return err } diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/resource.go b/vendor/github.com/hashicorp/terraform/helper/schema/resource.go index d96bbcfd..d3be2d61 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/resource.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/resource.go @@ -8,7 +8,6 @@ import ( "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/terraform" - "github.com/zclconf/go-cty/cty" ) // Resource represents a thing in Terraform that has a set of configurable @@ -45,12 +44,6 @@ type Resource struct { // their Versioning at any integer >= 1 SchemaVersion int - // MigrateState is deprecated and any new changes to a resource's schema - // should be handled by StateUpgraders. Existing MigrateState implementations - // should remain for compatibility with existing state. MigrateState will - // still be called if the stored SchemaVersion is less than the - // first version of the StateUpgraders. - // // MigrateState is responsible for updating an InstanceState with an old // version to the format expected by the current version of the Schema. // @@ -63,18 +56,6 @@ type Resource struct { // needs to make any remote API calls. MigrateState StateMigrateFunc - // StateUpgraders contains the functions responsible for upgrading an - // existing state with an old schema version to a newer schema. It is - // called specifically by Terraform when the stored schema version is less - // than the current SchemaVersion of the Resource. - // - // StateUpgraders map specific schema versions to a StateUpgrader - // function. The registered versions are expected to be ordered, - // consecutive values. The initial value may be greater than 0 to account - // for legacy schemas that weren't recorded and can be handled by - // MigrateState. - StateUpgraders []StateUpgrader - // The functions below are the CRUD operations for this resource. // // The only optional operation is Update. If Update is not implemented, @@ -155,27 +136,6 @@ type Resource struct { Timeouts *ResourceTimeout } -// ShimInstanceStateFromValue converts a cty.Value to a -// terraform.InstanceState. -func (r *Resource) ShimInstanceStateFromValue(state cty.Value) (*terraform.InstanceState, error) { - // Get the raw shimmed value. While this is correct, the set hashes don't - // match those from the Schema. - s := terraform.NewInstanceStateShimmedFromValue(state, r.SchemaVersion) - - // We now rebuild the state through the ResourceData, so that the set indexes - // match what helper/schema expects. - data, err := schemaMap(r.Schema).Data(s, nil) - if err != nil { - return nil, err - } - - s = data.State() - if s == nil { - s = &terraform.InstanceState{} - } - return s, nil -} - // See Resource documentation. type CreateFunc func(*ResourceData, interface{}) error @@ -195,27 +155,6 @@ type ExistsFunc func(*ResourceData, interface{}) (bool, error) type StateMigrateFunc func( int, *terraform.InstanceState, interface{}) (*terraform.InstanceState, error) -type StateUpgrader struct { - // Version is the version schema that this Upgrader will handle, converting - // it to Version+1. - Version int - - // Type describes the schema that this function can upgrade. Type is - // required to decode the schema if the state was stored in a legacy - // flatmap format. - Type cty.Type - - // Upgrade takes the JSON encoded state and the provider meta value, and - // upgrades the state one single schema version. The provided state is - // deocded into the default json types using a map[string]interface{}. It - // is up to the StateUpgradeFunc to ensure that the returned value can be - // encoded using the new schema. - Upgrade StateUpgradeFunc -} - -// See StateUpgrader -type StateUpgradeFunc func(rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) - // See Resource documentation. type CustomizeDiffFunc func(*ResourceDiff, interface{}) error @@ -308,7 +247,7 @@ func (r *Resource) Diff( return nil, fmt.Errorf("[ERR] Error decoding timeout: %s", err) } - instanceDiff, err := schemaMap(r.Schema).Diff(s, c, r.CustomizeDiff, meta, true) + instanceDiff, err := schemaMap(r.Schema).Diff(s, c, r.CustomizeDiff, meta) if err != nil { return instanceDiff, err } @@ -324,45 +263,6 @@ func (r *Resource) Diff( return instanceDiff, err } -func (r *Resource) simpleDiff( - s *terraform.InstanceState, - c *terraform.ResourceConfig, - meta interface{}) (*terraform.InstanceDiff, error) { - - t := &ResourceTimeout{} - err := t.ConfigDecode(r, c) - - if err != nil { - return nil, fmt.Errorf("[ERR] Error decoding timeout: %s", err) - } - - instanceDiff, err := schemaMap(r.Schema).Diff(s, c, r.CustomizeDiff, meta, false) - if err != nil { - return instanceDiff, err - } - - if instanceDiff == nil { - log.Printf("[DEBUG] Instance Diff is nil in SimpleDiff()") - return nil, err - } - - // Make sure the old value is set in each of the instance diffs. - // This was done by the RequiresNew logic in the full legacy Diff. - for k, attr := range instanceDiff.Attributes { - if attr == nil { - continue - } - if s != nil { - attr.Old = s.Attributes[k] - } - } - - if err := t.DiffEncode(instanceDiff); err != nil { - log.Printf("[ERR] Error encoding timeout to instance diff: %s", err) - } - return instanceDiff, err -} - // Validate validates the resource configuration against the schema. func (r *Resource) Validate(c *terraform.ResourceConfig) ([]string, []error) { warns, errs := schemaMap(r.Schema).Validate(c) @@ -400,59 +300,6 @@ func (r *Resource) ReadDataApply( return r.recordCurrentSchemaVersion(state), err } -// RefreshWithoutUpgrade reads the instance state, but does not call -// MigrateState or the StateUpgraders, since those are now invoked in a -// separate API call. -// RefreshWithoutUpgrade is part of the new plugin shims. -func (r *Resource) RefreshWithoutUpgrade( - s *terraform.InstanceState, - meta interface{}) (*terraform.InstanceState, error) { - // If the ID is already somehow blank, it doesn't exist - if s.ID == "" { - return nil, nil - } - - rt := ResourceTimeout{} - if _, ok := s.Meta[TimeoutKey]; ok { - if err := rt.StateDecode(s); err != nil { - log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) - } - } - - if r.Exists != nil { - // Make a copy of data so that if it is modified it doesn't - // affect our Read later. - data, err := schemaMap(r.Schema).Data(s, nil) - data.timeouts = &rt - - if err != nil { - return s, err - } - - exists, err := r.Exists(data, meta) - if err != nil { - return s, err - } - if !exists { - return nil, nil - } - } - - data, err := schemaMap(r.Schema).Data(s, nil) - data.timeouts = &rt - if err != nil { - return s, err - } - - err = r.Read(data, meta) - state := data.State() - if state != nil && state.ID == "" { - state = nil - } - - return r.recordCurrentSchemaVersion(state), err -} - // Refresh refreshes the state of the resource. func (r *Resource) Refresh( s *terraform.InstanceState, @@ -488,10 +335,12 @@ func (r *Resource) Refresh( } } - // there may be new StateUpgraders that need to be run - s, err := r.upgradeState(s, meta) - if err != nil { - return s, err + needsMigration, stateSchemaVersion := r.checkSchemaVersion(s) + if needsMigration && r.MigrateState != nil { + s, err := r.MigrateState(stateSchemaVersion, s, meta) + if err != nil { + return s, err + } } data, err := schemaMap(r.Schema).Data(s, nil) @@ -509,71 +358,6 @@ func (r *Resource) Refresh( return r.recordCurrentSchemaVersion(state), err } -func (r *Resource) upgradeState(s *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { - var err error - - needsMigration, stateSchemaVersion := r.checkSchemaVersion(s) - migrate := needsMigration && r.MigrateState != nil - - if migrate { - s, err = r.MigrateState(stateSchemaVersion, s, meta) - if err != nil { - return s, err - } - } - - if len(r.StateUpgraders) == 0 { - return s, nil - } - - // If we ran MigrateState, then the stateSchemaVersion value is no longer - // correct. We can expect the first upgrade function to be the correct - // schema type version. - if migrate { - stateSchemaVersion = r.StateUpgraders[0].Version - } - - schemaType := r.CoreConfigSchema().ImpliedType() - // find the expected type to convert the state - for _, upgrader := range r.StateUpgraders { - if stateSchemaVersion == upgrader.Version { - schemaType = upgrader.Type - } - } - - // StateUpgraders only operate on the new JSON format state, so the state - // need to be converted. - stateVal, err := StateValueFromInstanceState(s, schemaType) - if err != nil { - return nil, err - } - - jsonState, err := StateValueToJSONMap(stateVal, schemaType) - if err != nil { - return nil, err - } - - for _, upgrader := range r.StateUpgraders { - if stateSchemaVersion != upgrader.Version { - continue - } - - jsonState, err = upgrader.Upgrade(jsonState, meta) - if err != nil { - return nil, err - } - stateSchemaVersion++ - } - - // now we need to re-flatmap the new state - stateVal, err = JSONMapToStateValue(jsonState, r.CoreConfigSchema()) - if err != nil { - return nil, err - } - - return r.ShimInstanceStateFromValue(stateVal) -} - // InternalValidate should be called to validate the structure // of the resource. // @@ -653,31 +437,6 @@ func (r *Resource) InternalValidate(topSchemaMap schemaMap, writable bool) error } } - lastVersion := -1 - for _, u := range r.StateUpgraders { - if lastVersion >= 0 && u.Version-lastVersion > 1 { - return fmt.Errorf("missing schema version between %d and %d", lastVersion, u.Version) - } - - if u.Version >= r.SchemaVersion { - return fmt.Errorf("StateUpgrader version %d is >= current version %d", u.Version, r.SchemaVersion) - } - - if !u.Type.IsObjectType() { - return fmt.Errorf("StateUpgrader %d type is not cty.Object", u.Version) - } - - if u.Upgrade == nil { - return fmt.Errorf("StateUpgrader %d missing StateUpgradeFunc", u.Version) - } - - lastVersion = u.Version - } - - if lastVersion >= 0 && lastVersion != r.SchemaVersion-1 { - return fmt.Errorf("missing StateUpgrader between %d and %d", lastVersion, r.SchemaVersion) - } - // Data source if r.isTopLevel() && !writable { tsm = schemaMap(r.Schema) @@ -779,15 +538,7 @@ func (r *Resource) checkSchemaVersion(is *terraform.InstanceState) (bool, int) { } stateSchemaVersion, _ := strconv.Atoi(rawString) - - // Don't run MigrateState if the version is handled by a StateUpgrader, - // since StateMigrateFuncs are not required to handle unknown versions - maxVersion := r.SchemaVersion - if len(r.StateUpgraders) > 0 { - maxVersion = r.StateUpgraders[0].Version - } - - return stateSchemaVersion < maxVersion, stateSchemaVersion + return stateSchemaVersion < r.SchemaVersion, stateSchemaVersion } func (r *Resource) recordCurrentSchemaVersion( diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/resource_data.go b/vendor/github.com/hashicorp/terraform/helper/schema/resource_data.go index 1c390709..6cc01ee0 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/resource_data.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/resource_data.go @@ -52,8 +52,6 @@ type getResult struct { // UnsafeSetFieldRaw allows setting arbitrary values in state to arbitrary // values, bypassing schema. This MUST NOT be used in normal circumstances - // it exists only to support the remote_state data source. -// -// Deprecated: Fully define schema attributes and use Set() instead. func (d *ResourceData) UnsafeSetFieldRaw(key string, value string) { d.once.Do(d.init) @@ -221,16 +219,10 @@ func (d *ResourceData) Id() string { if d.state != nil { result = d.state.ID - if result == "" { - result = d.state.Attributes["id"] - } } if d.newState != nil { result = d.newState.ID - if result == "" { - result = d.newState.Attributes["id"] - } } return result @@ -254,18 +246,6 @@ func (d *ResourceData) ConnInfo() map[string]string { func (d *ResourceData) SetId(v string) { d.once.Do(d.init) d.newState.ID = v - - // once we transition away from the legacy state types, "id" will no longer - // be a special field, and will become a normal attribute. - // set the attribute normally - d.setWriter.unsafeWriteField("id", v) - - // Make sure the newState is also set, otherwise the old value - // may get precedence. - if d.newState.Attributes == nil { - d.newState.Attributes = map[string]string{} - } - d.newState.Attributes["id"] = v } // SetConnInfo sets the connection info for a resource. diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/resource_timeout.go b/vendor/github.com/hashicorp/terraform/helper/schema/resource_timeout.go index 9e422c1a..445819f0 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/resource_timeout.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/resource_timeout.go @@ -5,7 +5,6 @@ import ( "log" "time" - "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/terraform" "github.com/mitchellh/copystructure" ) @@ -63,70 +62,55 @@ func (t *ResourceTimeout) ConfigDecode(s *Resource, c *terraform.ResourceConfig) } if raw, ok := c.Config[TimeoutsConfigKey]; ok { - var rawTimeouts []map[string]interface{} - switch raw := raw.(type) { - case map[string]interface{}: - rawTimeouts = append(rawTimeouts, raw) - case []map[string]interface{}: - rawTimeouts = raw - case string: - if raw == config.UnknownVariableValue { - // Timeout is not defined in the config - // Defaults will be used instead - return nil - } else { - log.Printf("[ERROR] Invalid timeout value: %q", raw) - return fmt.Errorf("Invalid Timeout value found") - } - default: - log.Printf("[ERROR] Invalid timeout structure: %#v", raw) - return fmt.Errorf("Invalid Timeout structure found") - } - - for _, timeoutValues := range rawTimeouts { - for timeKey, timeValue := range timeoutValues { - // validate that we're dealing with the normal CRUD actions - var found bool - for _, key := range timeoutKeys() { - if timeKey == key { - found = true - break + if configTimeouts, ok := raw.([]map[string]interface{}); ok { + for _, timeoutValues := range configTimeouts { + // loop through each Timeout given in the configuration and validate they + // the Timeout defined in the resource + for timeKey, timeValue := range timeoutValues { + // validate that we're dealing with the normal CRUD actions + var found bool + for _, key := range timeoutKeys() { + if timeKey == key { + found = true + break + } } - } - if !found { - return fmt.Errorf("Unsupported Timeout configuration key found (%s)", timeKey) - } + if !found { + return fmt.Errorf("Unsupported Timeout configuration key found (%s)", timeKey) + } - // Get timeout - rt, err := time.ParseDuration(timeValue.(string)) - if err != nil { - return fmt.Errorf("Error parsing %q timeout: %s", timeKey, err) - } + // Get timeout + rt, err := time.ParseDuration(timeValue.(string)) + if err != nil { + return fmt.Errorf("Error parsing Timeout for (%s): %s", timeKey, err) + } - var timeout *time.Duration - switch timeKey { - case TimeoutCreate: - timeout = t.Create - case TimeoutUpdate: - timeout = t.Update - case TimeoutRead: - timeout = t.Read - case TimeoutDelete: - timeout = t.Delete - case TimeoutDefault: - timeout = t.Default - } + var timeout *time.Duration + switch timeKey { + case TimeoutCreate: + timeout = t.Create + case TimeoutUpdate: + timeout = t.Update + case TimeoutRead: + timeout = t.Read + case TimeoutDelete: + timeout = t.Delete + case TimeoutDefault: + timeout = t.Default + } - // If the resource has not delcared this in the definition, then error - // with an unsupported message - if timeout == nil { - return unsupportedTimeoutKeyError(timeKey) - } + // If the resource has not delcared this in the definition, then error + // with an unsupported message + if timeout == nil { + return unsupportedTimeoutKeyError(timeKey) + } - *timeout = rt + *timeout = rt + } } - return nil + } else { + log.Printf("[WARN] Invalid Timeout structure found, skipping timeouts") } } diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/schema.go b/vendor/github.com/hashicorp/terraform/helper/schema/schema.go index 31b23607..0ea5aad5 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/schema.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/schema.go @@ -19,9 +19,7 @@ import ( "sort" "strconv" "strings" - "sync" - "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/terraform" "github.com/mitchellh/copystructure" "github.com/mitchellh/mapstructure" @@ -33,27 +31,6 @@ const PanicOnErr = "TF_SCHEMA_PANIC_ON_ERROR" // type used for schema package context keys type contextKey string -var ( - protoVersionMu sync.Mutex - protoVersion5 = false -) - -func isProto5() bool { - protoVersionMu.Lock() - defer protoVersionMu.Unlock() - return protoVersion5 - -} - -// SetProto5 enables a feature flag for any internal changes required required -// to work with the new plugin protocol. This should not be called by -// provider. -func SetProto5() { - protoVersionMu.Lock() - defer protoVersionMu.Unlock() - protoVersion5 = true -} - // Schema is used to describe the structure of a value. // // Read the documentation of the struct elements for important details. @@ -164,17 +141,13 @@ type Schema struct { // used to wrap a complex structure, however less than one instance would // cause instability. // - // If the field Optional is set to true then MinItems is ignored and thus - // effectively zero. - MaxItems int - MinItems int - - // PromoteSingle originally allowed for a single element to be assigned - // where a primitive list was expected, but this no longer works from - // Terraform v0.12 onwards (Terraform Core will require a list to be set - // regardless of what this is set to) and so only applies to Terraform v0.11 - // and earlier, and so should be used only to retain this functionality - // for those still using v0.11 with a provider that formerly used this. + // PromoteSingle, if true, will allow single elements to be standalone + // and promote them to a list. For example "foo" would be promoted to + // ["foo"] automatically. This is primarily for legacy reasons and the + // ambiguity is not recommended for new usage. Promotion is only allowed + // for primitive element types. + MaxItems int + MinItems int PromoteSingle bool // The following fields are only valid for a TypeSet type. @@ -391,11 +364,6 @@ func (s *Schema) finalizeDiff(d *terraform.ResourceAttrDiff, customized bool) *t return d } -// InternalMap is used to aid in the transition to the new schema types and -// protocol. The name is not meant to convey any usefulness, as this is not to -// be used directly by any providers. -type InternalMap = schemaMap - // schemaMap is a wrapper that adds nice functions on top of schemas. type schemaMap map[string]*Schema @@ -436,8 +404,7 @@ func (m schemaMap) Diff( s *terraform.InstanceState, c *terraform.ResourceConfig, customizeDiff CustomizeDiffFunc, - meta interface{}, - handleRequiresNew bool) (*terraform.InstanceDiff, error) { + meta interface{}) (*terraform.InstanceDiff, error) { result := new(terraform.InstanceDiff) result.Attributes = make(map[string]*terraform.ResourceAttrDiff) @@ -483,85 +450,82 @@ func (m schemaMap) Diff( } } - if handleRequiresNew { - // If the diff requires a new resource, then we recompute the diff - // so we have the complete new resource diff, and preserve the - // RequiresNew fields where necessary so the user knows exactly what - // caused that. - if result.RequiresNew() { - // Create the new diff - result2 := new(terraform.InstanceDiff) - result2.Attributes = make(map[string]*terraform.ResourceAttrDiff) + // If the diff requires a new resource, then we recompute the diff + // so we have the complete new resource diff, and preserve the + // RequiresNew fields where necessary so the user knows exactly what + // caused that. + if result.RequiresNew() { + // Create the new diff + result2 := new(terraform.InstanceDiff) + result2.Attributes = make(map[string]*terraform.ResourceAttrDiff) - // Preserve the DestroyTainted flag - result2.DestroyTainted = result.DestroyTainted + // Preserve the DestroyTainted flag + result2.DestroyTainted = result.DestroyTainted - // Reset the data to not contain state. We have to call init() - // again in order to reset the FieldReaders. - d.state = nil - d.init() + // Reset the data to not contain state. We have to call init() + // again in order to reset the FieldReaders. + d.state = nil + d.init() - // Perform the diff again - for k, schema := range m { - err := m.diff(k, schema, result2, d, false) + // Perform the diff again + for k, schema := range m { + err := m.diff(k, schema, result2, d, false) + if err != nil { + return nil, err + } + } + + // Re-run customization + if !result2.DestroyTainted && customizeDiff != nil { + mc := m.DeepCopy() + rd := newResourceDiff(mc, c, d.state, result2) + if err := customizeDiff(rd, meta); err != nil { + return nil, err + } + for _, k := range rd.UpdatedKeys() { + err := m.diff(k, mc[k], result2, rd, false) if err != nil { return nil, err } } - - // Re-run customization - if !result2.DestroyTainted && customizeDiff != nil { - mc := m.DeepCopy() - rd := newResourceDiff(mc, c, d.state, result2) - if err := customizeDiff(rd, meta); err != nil { - return nil, err - } - for _, k := range rd.UpdatedKeys() { - err := m.diff(k, mc[k], result2, rd, false) - if err != nil { - return nil, err - } - } - } - - // Force all the fields to not force a new since we know what we - // want to force new. - for k, attr := range result2.Attributes { - if attr == nil { - continue - } - - if attr.RequiresNew { - attr.RequiresNew = false - } - - if s != nil { - attr.Old = s.Attributes[k] - } - } - - // Now copy in all the requires new diffs... - for k, attr := range result.Attributes { - if attr == nil { - continue - } - - newAttr, ok := result2.Attributes[k] - if !ok { - newAttr = attr - } - - if attr.RequiresNew { - newAttr.RequiresNew = true - } - - result2.Attributes[k] = newAttr - } - - // And set the diff! - result = result2 } + // Force all the fields to not force a new since we know what we + // want to force new. + for k, attr := range result2.Attributes { + if attr == nil { + continue + } + + if attr.RequiresNew { + attr.RequiresNew = false + } + + if s != nil { + attr.Old = s.Attributes[k] + } + } + + // Now copy in all the requires new diffs... + for k, attr := range result.Attributes { + if attr == nil { + continue + } + + newAttr, ok := result2.Attributes[k] + if !ok { + newAttr = attr + } + + if attr.RequiresNew { + newAttr.RequiresNew = true + } + + result2.Attributes[k] = newAttr + } + + // And set the diff! + result = result2 } // Go through and detect all of the ComputedWhens now that we've @@ -821,19 +785,10 @@ func (m schemaMap) diff( for attrK, attrV := range unsupressedDiff.Attributes { switch rd := d.(type) { case *ResourceData: - if schema.DiffSuppressFunc != nil && attrV != nil && + if schema.DiffSuppressFunc != nil && + attrV != nil && schema.DiffSuppressFunc(attrK, attrV.Old, attrV.New, rd) { - // If this attr diff is suppressed, we may still need it in the - // overall diff if it's contained within a set. Rather than - // dropping the diff, make it a NOOP. - if !all { - continue - } - - attrV = &terraform.ResourceAttrDiff{ - Old: attrV.Old, - New: attrV.Old, - } + continue } } diff.Attributes[attrK] = attrV @@ -1216,7 +1171,7 @@ func (m schemaMap) diffString( return fmt.Errorf("%s: %s", k, err) } - if os == ns && !all && !computed { + if os == ns && !all { // They're the same value. If there old value is not blank or we // have an ID, then return right away since we're already setup. if os != "" || d.Id() != "" { @@ -1224,7 +1179,7 @@ func (m schemaMap) diffString( } // Otherwise, only continue if we're computed - if !schema.Computed { + if !schema.Computed && !computed { return nil } } @@ -1297,13 +1252,6 @@ func (m schemaMap) validate( "%q: this field cannot be set", k)} } - if raw == config.UnknownVariableValue { - // If the value is unknown then we can't validate it yet. - // In particular, this avoids spurious type errors where downstream - // validation code sees UnknownVariableValue as being just a string. - return nil, nil - } - err := m.validateConflictingAttributes(k, schema, c) if err != nil { return nil, []error{err} @@ -1321,15 +1269,10 @@ func (m schemaMap) validateConflictingAttributes( return nil } - for _, conflictingKey := range schema.ConflictsWith { - if raw, ok := c.Get(conflictingKey); ok { - if raw == config.UnknownVariableValue { - // An unknown value might become unset (null) once known, so - // we must defer validation until it's known. - continue - } + for _, conflicting_key := range schema.ConflictsWith { + if _, ok := c.Get(conflicting_key); ok { return fmt.Errorf( - "%q: conflicts with %s", k, conflictingKey) + "%q: conflicts with %s", k, conflicting_key) } } @@ -1341,13 +1284,6 @@ func (m schemaMap) validateList( raw interface{}, schema *Schema, c *terraform.ResourceConfig) ([]string, []error) { - // first check if the list is wholly unknown - if s, ok := raw.(string); ok { - if s == config.UnknownVariableValue { - return nil, nil - } - } - // We use reflection to verify the slice because you can't // case to []interface{} unless the slice is exactly that type. rawV := reflect.ValueOf(raw) @@ -1419,13 +1355,6 @@ func (m schemaMap) validateMap( raw interface{}, schema *Schema, c *terraform.ResourceConfig) ([]string, []error) { - // first check if the list is wholly unknown - if s, ok := raw.(string); ok { - if s == config.UnknownVariableValue { - return nil, nil - } - } - // We use reflection to verify the slice because you can't // case to []interface{} unless the slice is exactly that type. rawV := reflect.ValueOf(raw) diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/set.go b/vendor/github.com/hashicorp/terraform/helper/schema/set.go index 8ee89e47..cba28903 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/set.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/set.go @@ -198,16 +198,6 @@ func (s *Set) add(item interface{}, computed bool) string { code := s.hash(item) if computed { code = "~" + code - - if isProto5() { - tmpCode := code - count := 0 - for _, exists := s.m[tmpCode]; exists; _, exists = s.m[tmpCode] { - count++ - tmpCode = fmt.Sprintf("%s%d", code, count) - } - code = tmpCode - } } if _, ok := s.m[code]; !ok { diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/shims.go b/vendor/github.com/hashicorp/terraform/helper/schema/shims.go deleted file mode 100644 index d99fb396..00000000 --- a/vendor/github.com/hashicorp/terraform/helper/schema/shims.go +++ /dev/null @@ -1,90 +0,0 @@ -package schema - -import ( - "encoding/json" - - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/terraform" -) - -// DiffFromValues takes the current state and desired state as cty.Values and -// derives a terraform.InstanceDiff to give to the legacy providers. This is -// used to take the states provided by the new ApplyResourceChange method and -// convert them to a state+diff required for the legacy Apply method. -func DiffFromValues(prior, planned cty.Value, res *Resource) (*terraform.InstanceDiff, error) { - return diffFromValues(prior, planned, res, nil) -} - -// diffFromValues takes an additional CustomizeDiffFunc, so we can generate our -// test fixtures from the legacy tests. In the new provider protocol the diff -// only needs to be created for the apply operation, and any customizations -// have already been done. -func diffFromValues(prior, planned cty.Value, res *Resource, cust CustomizeDiffFunc) (*terraform.InstanceDiff, error) { - instanceState, err := res.ShimInstanceStateFromValue(prior) - if err != nil { - return nil, err - } - - configSchema := res.CoreConfigSchema() - - cfg := terraform.NewResourceConfigShimmed(planned, configSchema) - - diff, err := schemaMap(res.Schema).Diff(instanceState, cfg, cust, nil, false) - if err != nil { - return nil, err - } - - return diff, err -} - -// ApplyDiff takes a cty.Value state and applies a terraform.InstanceDiff to -// get a new cty.Value state. This is used to convert the diff returned from -// the legacy provider Diff method to the state required for the new -// PlanResourceChange method. -func ApplyDiff(base cty.Value, d *terraform.InstanceDiff, schema *configschema.Block) (cty.Value, error) { - return d.ApplyToValue(base, schema) -} - -// StateValueToJSONMap converts a cty.Value to generic JSON map via the cty JSON -// encoding. -func StateValueToJSONMap(val cty.Value, ty cty.Type) (map[string]interface{}, error) { - js, err := ctyjson.Marshal(val, ty) - if err != nil { - return nil, err - } - - var m map[string]interface{} - if err := json.Unmarshal(js, &m); err != nil { - return nil, err - } - - return m, nil -} - -// JSONMapToStateValue takes a generic json map[string]interface{} and converts it -// to the specific type, ensuring that the values conform to the schema. -func JSONMapToStateValue(m map[string]interface{}, block *configschema.Block) (cty.Value, error) { - var val cty.Value - - js, err := json.Marshal(m) - if err != nil { - return val, err - } - - val, err = ctyjson.Unmarshal(js, block.ImpliedType()) - if err != nil { - return val, err - } - - return block.CoerceValue(val) -} - -// StateValueFromInstanceState converts a terraform.InstanceState to a -// cty.Value as described by the provided cty.Type, and maintains the resource -// ID as the "id" attribute. -func StateValueFromInstanceState(is *terraform.InstanceState, ty cty.Type) (cty.Value, error) { - return is.AttrsAsObjectValue(ty) -} diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/testing.go b/vendor/github.com/hashicorp/terraform/helper/schema/testing.go index a367a1fd..da754ac7 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/testing.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/testing.go @@ -18,7 +18,7 @@ func TestResourceDataRaw( } sm := schemaMap(schema) - diff, err := sm.Diff(nil, terraform.NewResourceConfig(c), nil, nil, true) + diff, err := sm.Diff(nil, terraform.NewResourceConfig(c), nil, nil) if err != nil { t.Fatalf("err: %s", err) } diff --git a/vendor/github.com/hashicorp/terraform/helper/validation/validation.go b/vendor/github.com/hashicorp/terraform/helper/validation/validation.go index 8c8ac54f..e9edcd33 100644 --- a/vendor/github.com/hashicorp/terraform/helper/validation/validation.go +++ b/vendor/github.com/hashicorp/terraform/helper/validation/validation.go @@ -13,39 +13,6 @@ import ( "github.com/hashicorp/terraform/helper/structure" ) -// All returns a SchemaValidateFunc which tests if the provided value -// passes all provided SchemaValidateFunc -func All(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc { - return func(i interface{}, k string) ([]string, []error) { - var allErrors []error - var allWarnings []string - for _, validator := range validators { - validatorWarnings, validatorErrors := validator(i, k) - allWarnings = append(allWarnings, validatorWarnings...) - allErrors = append(allErrors, validatorErrors...) - } - return allWarnings, allErrors - } -} - -// Any returns a SchemaValidateFunc which tests if the provided value -// passes any of the provided SchemaValidateFunc -func Any(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc { - return func(i interface{}, k string) ([]string, []error) { - var allErrors []error - var allWarnings []string - for _, validator := range validators { - validatorWarnings, validatorErrors := validator(i, k) - if len(validatorWarnings) == 0 && len(validatorErrors) == 0 { - return []string{}, []error{} - } - allWarnings = append(allWarnings, validatorWarnings...) - allErrors = append(allErrors, validatorErrors...) - } - return allWarnings, allErrors - } -} - // IntBetween returns a SchemaValidateFunc which tests if the provided value // is of type int and is between min and max (inclusive) func IntBetween(min, max int) schema.SchemaValidateFunc { @@ -103,27 +70,6 @@ func IntAtMost(max int) schema.SchemaValidateFunc { } } -// IntInSlice returns a SchemaValidateFunc which tests if the provided value -// is of type int and matches the value of an element in the valid slice -func IntInSlice(valid []int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (s []string, es []error) { - v, ok := i.(int) - if !ok { - es = append(es, fmt.Errorf("expected type of %s to be an integer", k)) - return - } - - for _, validInt := range valid { - if v == validInt { - return - } - } - - es = append(es, fmt.Errorf("expected %s to be one of %v, got %d", k, valid, v)) - return - } -} - // StringInSlice returns a SchemaValidateFunc which tests if the provided value // is of type string and matches the value of an element in the valid slice // will test with in lower case if ignoreCase is true diff --git a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/config.go b/vendor/github.com/hashicorp/terraform/internal/earlyconfig/config.go deleted file mode 100644 index 32c1327a..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/config.go +++ /dev/null @@ -1,123 +0,0 @@ -package earlyconfig - -import ( - "fmt" - "sort" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/moduledeps" - "github.com/hashicorp/terraform/plugin/discovery" - "github.com/hashicorp/terraform/tfdiags" -) - -// A Config is a node in the tree of modules within a configuration. -// -// The module tree is constructed by following ModuleCall instances recursively -// through the root module transitively into descendent modules. -type Config struct { - // RootModule points to the Config for the root module within the same - // module tree as this module. If this module _is_ the root module then - // this is self-referential. - Root *Config - - // ParentModule points to the Config for the module that directly calls - // this module. If this is the root module then this field is nil. - Parent *Config - - // Path is a sequence of module logical names that traverse from the root - // module to this config. Path is empty for the root module. - // - // This should only be used to display paths to the end-user in rare cases - // where we are talking about the static module tree, before module calls - // have been resolved. In most cases, a addrs.ModuleInstance describing - // a node in the dynamic module tree is better, since it will then include - // any keys resulting from evaluating "count" and "for_each" arguments. - Path addrs.Module - - // ChildModules points to the Config for each of the direct child modules - // called from this module. The keys in this map match the keys in - // Module.ModuleCalls. - Children map[string]*Config - - // Module points to the object describing the configuration for the - // various elements (variables, resources, etc) defined by this module. - Module *tfconfig.Module - - // CallPos is the source position for the header of the module block that - // requested this module. - // - // This field is meaningless for the root module, where its contents are undefined. - CallPos tfconfig.SourcePos - - // SourceAddr is the source address that the referenced module was requested - // from, as specified in configuration. - // - // This field is meaningless for the root module, where its contents are undefined. - SourceAddr string - - // Version is the specific version that was selected for this module, - // based on version constraints given in configuration. - // - // This field is nil if the module was loaded from a non-registry source, - // since versions are not supported for other sources. - // - // This field is meaningless for the root module, where it will always - // be nil. - Version *version.Version -} - -// ProviderDependencies returns the provider dependencies for the recieving -// config, including all of its descendent modules. -func (c *Config) ProviderDependencies() (*moduledeps.Module, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - var name string - if len(c.Path) > 0 { - name = c.Path[len(c.Path)-1] - } - - ret := &moduledeps.Module{ - Name: name, - } - - providers := make(moduledeps.Providers) - for name, reqs := range c.Module.RequiredProviders { - inst := moduledeps.ProviderInstance(name) - var constraints version.Constraints - for _, reqStr := range reqs { - if reqStr != "" { - constraint, err := version.NewConstraint(reqStr) - if err != nil { - diags = diags.Append(wrapDiagnostic(tfconfig.Diagnostic{ - Severity: tfconfig.DiagError, - Summary: "Invalid provider version constraint", - Detail: fmt.Sprintf("Invalid version constraint %q for provider %s.", reqStr, name), - })) - continue - } - constraints = append(constraints, constraint...) - } - } - providers[inst] = moduledeps.ProviderDependency{ - Constraints: discovery.NewConstraints(constraints), - Reason: moduledeps.ProviderDependencyExplicit, - } - } - ret.Providers = providers - - childNames := make([]string, 0, len(c.Children)) - for name := range c.Children { - childNames = append(childNames, name) - } - sort.Strings(childNames) - - for _, name := range childNames { - child, childDiags := c.Children[name].ProviderDependencies() - ret.Children = append(ret.Children, child) - diags = diags.Append(childDiags) - } - - return ret, diags -} diff --git a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/config_build.go b/vendor/github.com/hashicorp/terraform/internal/earlyconfig/config_build.go deleted file mode 100644 index 770d5dfb..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/config_build.go +++ /dev/null @@ -1,144 +0,0 @@ -package earlyconfig - -import ( - "fmt" - "sort" - "strings" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/tfdiags" -) - -// BuildConfig constructs a Config from a root module by loading all of its -// descendent modules via the given ModuleWalker. -func BuildConfig(root *tfconfig.Module, walker ModuleWalker) (*Config, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - cfg := &Config{ - Module: root, - } - cfg.Root = cfg // Root module is self-referential. - cfg.Children, diags = buildChildModules(cfg, walker) - return cfg, diags -} - -func buildChildModules(parent *Config, walker ModuleWalker) (map[string]*Config, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - ret := map[string]*Config{} - calls := parent.Module.ModuleCalls - - // We'll sort the calls by their local names so that they'll appear in a - // predictable order in any logging that's produced during the walk. - callNames := make([]string, 0, len(calls)) - for k := range calls { - callNames = append(callNames, k) - } - sort.Strings(callNames) - - for _, callName := range callNames { - call := calls[callName] - path := make([]string, len(parent.Path)+1) - copy(path, parent.Path) - path[len(path)-1] = call.Name - - var vc version.Constraints - if strings.TrimSpace(call.Version) != "" { - var err error - vc, err = version.NewConstraint(call.Version) - if err != nil { - diags = diags.Append(wrapDiagnostic(tfconfig.Diagnostic{ - Severity: tfconfig.DiagError, - Summary: "Invalid version constraint", - Detail: fmt.Sprintf("Module %q (declared at %s line %d) has invalid version constraint %q: %s.", callName, call.Pos.Filename, call.Pos.Line, call.Version, err), - })) - continue - } - } - - req := ModuleRequest{ - Name: call.Name, - Path: path, - SourceAddr: call.Source, - VersionConstraints: vc, - Parent: parent, - CallPos: call.Pos, - } - - mod, ver, modDiags := walker.LoadModule(&req) - diags = append(diags, modDiags...) - if mod == nil { - // nil can be returned if the source address was invalid and so - // nothing could be loaded whatsoever. LoadModule should've - // returned at least one error diagnostic in that case. - continue - } - - child := &Config{ - Parent: parent, - Root: parent.Root, - Path: path, - Module: mod, - CallPos: call.Pos, - SourceAddr: call.Source, - Version: ver, - } - - child.Children, modDiags = buildChildModules(child, walker) - diags = diags.Append(modDiags) - - ret[call.Name] = child - } - - return ret, diags -} - -// ModuleRequest is used as part of the ModuleWalker interface used with -// function BuildConfig. -type ModuleRequest struct { - // Name is the "logical name" of the module call within configuration. - // This is provided in case the name is used as part of a storage key - // for the module, but implementations must otherwise treat it as an - // opaque string. It is guaranteed to have already been validated as an - // HCL identifier and UTF-8 encoded. - Name string - - // Path is a list of logical names that traverse from the root module to - // this module. This can be used, for example, to form a lookup key for - // each distinct module call in a configuration, allowing for multiple - // calls with the same name at different points in the tree. - Path addrs.Module - - // SourceAddr is the source address string provided by the user in - // configuration. - SourceAddr string - - // VersionConstraint is the version constraint applied to the module in - // configuration. - VersionConstraints version.Constraints - - // Parent is the partially-constructed module tree node that the loaded - // module will be added to. Callers may refer to any field of this - // structure except Children, which is still under construction when - // ModuleRequest objects are created and thus has undefined content. - // The main reason this is provided is so that full module paths can - // be constructed for uniqueness. - Parent *Config - - // CallRange is the source position for the header of the "module" block - // in configuration that prompted this request. - CallPos tfconfig.SourcePos -} - -// ModuleWalker is an interface used with BuildConfig. -type ModuleWalker interface { - LoadModule(req *ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) -} - -// ModuleWalkerFunc is an implementation of ModuleWalker that directly wraps -// a callback function, for more convenient use of that interface. -type ModuleWalkerFunc func(req *ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) - -func (f ModuleWalkerFunc) LoadModule(req *ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) { - return f(req) -} diff --git a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/diagnostics.go b/vendor/github.com/hashicorp/terraform/internal/earlyconfig/diagnostics.go deleted file mode 100644 index 9b2fd7f7..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/diagnostics.go +++ /dev/null @@ -1,78 +0,0 @@ -package earlyconfig - -import ( - "fmt" - - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform/tfdiags" -) - -func wrapDiagnostics(diags tfconfig.Diagnostics) tfdiags.Diagnostics { - ret := make(tfdiags.Diagnostics, len(diags)) - for i, diag := range diags { - ret[i] = wrapDiagnostic(diag) - } - return ret -} - -func wrapDiagnostic(diag tfconfig.Diagnostic) tfdiags.Diagnostic { - return wrappedDiagnostic{ - d: diag, - } -} - -type wrappedDiagnostic struct { - d tfconfig.Diagnostic -} - -func (d wrappedDiagnostic) Severity() tfdiags.Severity { - switch d.d.Severity { - case tfconfig.DiagError: - return tfdiags.Error - case tfconfig.DiagWarning: - return tfdiags.Warning - default: - // Should never happen since there are no other severities - return 0 - } -} - -func (d wrappedDiagnostic) Description() tfdiags.Description { - // Since the inspect library doesn't produce precise source locations, - // we include the position information as part of the error message text. - // See the comment inside method "Source" for more information. - switch { - case d.d.Pos == nil: - return tfdiags.Description{ - Summary: d.d.Summary, - Detail: d.d.Detail, - } - case d.d.Detail != "": - return tfdiags.Description{ - Summary: d.d.Summary, - Detail: fmt.Sprintf("On %s line %d: %s", d.d.Pos.Filename, d.d.Pos.Line, d.d.Detail), - } - default: - return tfdiags.Description{ - Summary: fmt.Sprintf("%s (on %s line %d)", d.d.Summary, d.d.Pos.Filename, d.d.Pos.Line), - } - } -} - -func (d wrappedDiagnostic) Source() tfdiags.Source { - // Since the inspect library is constrained by the lowest common denominator - // between legacy HCL and modern HCL, it only returns ranges at whole-line - // granularity, and that isn't sufficient to populate a tfdiags.Source - // and so we'll just omit ranges altogether and include the line number in - // the Description text. - // - // Callers that want to return nicer errors should consider reacting to - // earlyconfig errors by attempting a follow-up parse with the normal - // config loader, which can produce more precise source location - // information. - return tfdiags.Source{} -} - -func (d wrappedDiagnostic) FromExpr() *tfdiags.FromExpr { - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/doc.go b/vendor/github.com/hashicorp/terraform/internal/earlyconfig/doc.go deleted file mode 100644 index a9cf10f3..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package earlyconfig is a specialized alternative to the top-level "configs" -// package that does only shallow processing of configuration and is therefore -// able to be much more liberal than the full config loader in what it accepts. -// -// In particular, it can accept both current and legacy HCL syntax, and it -// ignores top-level blocks that it doesn't recognize. These two characteristics -// make this package ideal for dependency-checking use-cases so that we are -// more likely to be able to return an error message about an explicit -// incompatibility than to return a less-actionable message about a construct -// not being supported. -// -// However, its liberal approach also means it should be used sparingly. It -// exists primarily for "terraform init", so that it is able to detect -// incompatibilities more robustly when installing dependencies. For most -// other use-cases, use the "configs" and "configs/configload" packages. -// -// Package earlyconfig is a wrapper around the terraform-config-inspect -// codebase, adding to it just some helper functionality for Terraform's own -// use-cases. -package earlyconfig diff --git a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/module.go b/vendor/github.com/hashicorp/terraform/internal/earlyconfig/module.go deleted file mode 100644 index d2d62879..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/earlyconfig/module.go +++ /dev/null @@ -1,13 +0,0 @@ -package earlyconfig - -import ( - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform/tfdiags" -) - -// LoadModule loads some top-level metadata for the module in the given -// directory. -func LoadModule(dir string) (*tfconfig.Module, tfdiags.Diagnostics) { - mod, diags := tfconfig.LoadModule(dir) - return mod, wrapDiagnostics(diags) -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/copy_dir.go b/vendor/github.com/hashicorp/terraform/internal/initwd/copy_dir.go deleted file mode 100644 index 8e414cda..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/copy_dir.go +++ /dev/null @@ -1,114 +0,0 @@ -package initwd - -import ( - "io" - "os" - "path/filepath" - "strings" -) - -// copyDir copies the src directory contents into dst. Both directories -// should already exist. -func copyDir(dst, src string) error { - src, err := filepath.EvalSymlinks(src) - if err != nil { - return err - } - - walkFn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if path == src { - return nil - } - - if strings.HasPrefix(filepath.Base(path), ".") { - // Skip any dot files - if info.IsDir() { - return filepath.SkipDir - } else { - return nil - } - } - - // The "path" has the src prefixed to it. We need to join our - // destination with the path without the src on it. - dstPath := filepath.Join(dst, path[len(src):]) - - // we don't want to try and copy the same file over itself. - if eq, err := sameFile(path, dstPath); eq { - return nil - } else if err != nil { - return err - } - - // If we have a directory, make that subdirectory, then continue - // the walk. - if info.IsDir() { - if path == filepath.Join(src, dst) { - // dst is in src; don't walk it. - return nil - } - - if err := os.MkdirAll(dstPath, 0755); err != nil { - return err - } - - return nil - } - - // If we have a file, copy the contents. - srcF, err := os.Open(path) - if err != nil { - return err - } - defer srcF.Close() - - dstF, err := os.Create(dstPath) - if err != nil { - return err - } - defer dstF.Close() - - if _, err := io.Copy(dstF, srcF); err != nil { - return err - } - - // Chmod it - return os.Chmod(dstPath, info.Mode()) - } - - return filepath.Walk(src, walkFn) -} - -// sameFile tried to determine if to paths are the same file. -// If the paths don't match, we lookup the inode on supported systems. -func sameFile(a, b string) (bool, error) { - if a == b { - return true, nil - } - - aIno, err := inode(a) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - bIno, err := inode(b) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - if aIno > 0 && aIno == bIno { - return true, nil - } - - return false, nil -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/doc.go b/vendor/github.com/hashicorp/terraform/internal/initwd/doc.go deleted file mode 100644 index b9d938db..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package initwd contains various helper functions used by the "terraform init" -// command to initialize a working directory. -// -// These functions may also be used from testing code to simulate the behaviors -// of "terraform init" against test fixtures, but should not be used elsewhere -// in the main code. -package initwd diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/from_module.go b/vendor/github.com/hashicorp/terraform/internal/initwd/from_module.go deleted file mode 100644 index 6b40d08d..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/from_module.go +++ /dev/null @@ -1,363 +0,0 @@ -package initwd - -import ( - "fmt" - "github.com/hashicorp/terraform/internal/earlyconfig" - "io/ioutil" - "log" - "os" - "path/filepath" - "sort" - "strings" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform/internal/modsdir" - "github.com/hashicorp/terraform/registry" - "github.com/hashicorp/terraform/tfdiags" -) - -const initFromModuleRootCallName = "root" -const initFromModuleRootKeyPrefix = initFromModuleRootCallName + "." - -// DirFromModule populates the given directory (which must exist and be -// empty) with the contents of the module at the given source address. -// -// It does this by installing the given module and all of its descendent -// modules in a temporary root directory and then copying the installed -// files into suitable locations. As a consequence, any diagnostics it -// generates will reveal the location of this temporary directory to the -// user. -// -// This rather roundabout installation approach is taken to ensure that -// installation proceeds in a manner identical to normal module installation. -// -// If the given source address specifies a sub-directory of the given -// package then only the sub-directory and its descendents will be copied -// into the given root directory, which will cause any relative module -// references using ../ from that module to be unresolvable. Error diagnostics -// are produced in that case, to prompt the user to rewrite the source strings -// to be absolute references to the original remote module. -func DirFromModule(rootDir, modulesDir, sourceAddr string, reg *registry.Client, hooks ModuleInstallHooks) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - // The way this function works is pretty ugly, but we accept it because - // -from-module is a less important case than normal module installation - // and so it's better to keep this ugly complexity out here rather than - // adding even more complexity to the normal module installer. - - // The target directory must exist but be empty. - { - entries, err := ioutil.ReadDir(rootDir) - if err != nil { - if os.IsNotExist(err) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Target directory does not exist", - fmt.Sprintf("Cannot initialize non-existent directory %s.", rootDir), - )) - } else { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to read target directory", - fmt.Sprintf("Error reading %s to ensure it is empty: %s.", rootDir, err), - )) - } - return diags - } - haveEntries := false - for _, entry := range entries { - if entry.Name() == "." || entry.Name() == ".." || entry.Name() == ".terraform" { - continue - } - haveEntries = true - } - if haveEntries { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Can't populate non-empty directory", - fmt.Sprintf("The target directory %s is not empty, so it cannot be initialized with the -from-module=... option.", rootDir), - )) - return diags - } - } - - instDir := filepath.Join(rootDir, ".terraform/init-from-module") - inst := NewModuleInstaller(instDir, reg) - log.Printf("[DEBUG] installing modules in %s to initialize working directory from %q", instDir, sourceAddr) - os.RemoveAll(instDir) // if this fails then we'll fail on MkdirAll below too - err := os.MkdirAll(instDir, os.ModePerm) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to create temporary directory", - fmt.Sprintf("Failed to create temporary directory %s: %s.", instDir, err), - )) - return diags - } - - instManifest := make(modsdir.Manifest) - retManifest := make(modsdir.Manifest) - - fakeFilename := fmt.Sprintf("-from-module=%q", sourceAddr) - fakePos := tfconfig.SourcePos{ - Filename: fakeFilename, - Line: 1, - } - - // -from-module allows relative paths but it's different than a normal - // module address where it'd be resolved relative to the module call - // (which is synthetic, here.) To address this, we'll just patch up any - // relative paths to be absolute paths before we run, ensuring we'll - // get the right result. This also, as an important side-effect, ensures - // that the result will be "downloaded" with go-getter (copied from the - // source location), rather than just recorded as a relative path. - { - maybePath := filepath.ToSlash(sourceAddr) - if maybePath == "." || strings.HasPrefix(maybePath, "./") || strings.HasPrefix(maybePath, "../") { - if wd, err := os.Getwd(); err == nil { - sourceAddr = filepath.Join(wd, sourceAddr) - log.Printf("[TRACE] -from-module relative path rewritten to absolute path %s", sourceAddr) - } - } - } - - // Now we need to create an artificial root module that will seed our - // installation process. - fakeRootModule := &tfconfig.Module{ - ModuleCalls: map[string]*tfconfig.ModuleCall{ - initFromModuleRootCallName: { - Name: initFromModuleRootCallName, - Source: sourceAddr, - Pos: fakePos, - }, - }, - } - - // wrapHooks filters hook notifications to only include Download calls - // and to trim off the initFromModuleRootCallName prefix. We'll produce - // our own Install notifications directly below. - wrapHooks := installHooksInitDir{ - Wrapped: hooks, - } - getter := reusingGetter{} - _, instDiags := inst.installDescendentModules(fakeRootModule, rootDir, instManifest, true, wrapHooks, getter) - diags = append(diags, instDiags...) - if instDiags.HasErrors() { - return diags - } - - // If all of that succeeded then we'll now migrate what was installed - // into the final directory structure. - err = os.MkdirAll(modulesDir, os.ModePerm) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to create local modules directory", - fmt.Sprintf("Failed to create modules directory %s: %s.", modulesDir, err), - )) - return diags - } - - recordKeys := make([]string, 0, len(instManifest)) - for k := range instManifest { - recordKeys = append(recordKeys, k) - } - sort.Strings(recordKeys) - - for _, recordKey := range recordKeys { - record := instManifest[recordKey] - - if record.Key == initFromModuleRootCallName { - // We've found the module the user requested, which we must - // now copy into rootDir so it can be used directly. - log.Printf("[TRACE] copying new root module from %s to %s", record.Dir, rootDir) - err := copyDir(rootDir, record.Dir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to copy root module", - fmt.Sprintf("Error copying root module %q from %s to %s: %s.", sourceAddr, record.Dir, rootDir, err), - )) - continue - } - - // We'll try to load the newly-copied module here just so we can - // sniff for any module calls that ../ out of the root directory - // and must thus be rewritten to be absolute addresses again. - // For now we can't do this rewriting automatically, but we'll - // generate an error to help the user do it manually. - mod, _ := earlyconfig.LoadModule(rootDir) // ignore diagnostics since we're just doing value-add here anyway - if mod != nil { - for _, mc := range mod.ModuleCalls { - if pathTraversesUp(mc.Source) { - packageAddr, givenSubdir := splitAddrSubdir(sourceAddr) - newSubdir := filepath.Join(givenSubdir, mc.Source) - if pathTraversesUp(newSubdir) { - // This should never happen in any reasonable - // configuration since this suggests a path that - // traverses up out of the package root. We'll just - // ignore this, since we'll fail soon enough anyway - // trying to resolve this path when this module is - // loaded. - continue - } - - var newAddr = packageAddr - if newSubdir != "" { - newAddr = fmt.Sprintf("%s//%s", newAddr, filepath.ToSlash(newSubdir)) - } - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Root module references parent directory", - fmt.Sprintf("The requested module %q refers to a module via its parent directory. To use this as a new root module this source string must be rewritten as a remote source address, such as %q.", sourceAddr, newAddr), - )) - continue - } - } - } - - retManifest[""] = modsdir.Record{ - Key: "", - Dir: rootDir, - } - continue - } - - if !strings.HasPrefix(record.Key, initFromModuleRootKeyPrefix) { - // Ignore the *real* root module, whose key is empty, since - // we're only interested in the module named "root" and its - // descendents. - continue - } - - newKey := record.Key[len(initFromModuleRootKeyPrefix):] - instPath := filepath.Join(modulesDir, newKey) - tempPath := filepath.Join(instDir, record.Key) - - // tempPath won't be present for a module that was installed from - // a relative path, so in that case we just record the installation - // directory and assume it was already copied into place as part - // of its parent. - if _, err := os.Stat(tempPath); err != nil { - if !os.IsNotExist(err) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to stat temporary module install directory", - fmt.Sprintf("Error from stat %s for module %s: %s.", instPath, newKey, err), - )) - continue - } - - var parentKey string - if lastDot := strings.LastIndexByte(newKey, '.'); lastDot != -1 { - parentKey = newKey[:lastDot] - } else { - parentKey = "" // parent is the root module - } - - parentOld := instManifest[initFromModuleRootKeyPrefix+parentKey] - parentNew := retManifest[parentKey] - - // We need to figure out which portion of our directory is the - // parent package path and which portion is the subdirectory - // under that. - baseDirRel, err := filepath.Rel(parentOld.Dir, record.Dir) - if err != nil { - // Should never happen, because we constructed both directories - // from the same base and so they must have a common prefix. - panic(err) - } - - newDir := filepath.Join(parentNew.Dir, baseDirRel) - log.Printf("[TRACE] relative reference for %s rewritten from %s to %s", newKey, record.Dir, newDir) - newRecord := record // shallow copy - newRecord.Dir = newDir - newRecord.Key = newKey - retManifest[newKey] = newRecord - hooks.Install(newRecord.Key, newRecord.Version, newRecord.Dir) - continue - } - - err = os.MkdirAll(instPath, os.ModePerm) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to create module install directory", - fmt.Sprintf("Error creating directory %s for module %s: %s.", instPath, newKey, err), - )) - continue - } - - // We copy rather than "rename" here because renaming between directories - // can be tricky in edge-cases like network filesystems, etc. - log.Printf("[TRACE] copying new module %s from %s to %s", newKey, record.Dir, instPath) - err := copyDir(instPath, tempPath) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to copy descendent module", - fmt.Sprintf("Error copying module %q from %s to %s: %s.", newKey, tempPath, rootDir, err), - )) - continue - } - - subDir, err := filepath.Rel(tempPath, record.Dir) - if err != nil { - // Should never happen, because we constructed both directories - // from the same base and so they must have a common prefix. - panic(err) - } - - newRecord := record // shallow copy - newRecord.Dir = filepath.Join(instPath, subDir) - newRecord.Key = newKey - retManifest[newKey] = newRecord - hooks.Install(newRecord.Key, newRecord.Version, newRecord.Dir) - } - - retManifest.WriteSnapshotToDir(modulesDir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to write module manifest", - fmt.Sprintf("Error writing module manifest: %s.", err), - )) - } - - if !diags.HasErrors() { - // Try to clean up our temporary directory, but don't worry if we don't - // succeed since it shouldn't hurt anything. - os.RemoveAll(instDir) - } - - return diags -} - -func pathTraversesUp(path string) bool { - return strings.HasPrefix(filepath.ToSlash(path), "../") -} - -// installHooksInitDir is an adapter wrapper for an InstallHooks that -// does some fakery to make downloads look like they are happening in their -// final locations, rather than in the temporary loader we use. -// -// It also suppresses "Install" calls entirely, since InitDirFromModule -// does its own installation steps after the initial installation pass -// has completed. -type installHooksInitDir struct { - Wrapped ModuleInstallHooks - ModuleInstallHooksImpl -} - -func (h installHooksInitDir) Download(moduleAddr, packageAddr string, version *version.Version) { - if !strings.HasPrefix(moduleAddr, initFromModuleRootKeyPrefix) { - // We won't announce the root module, since hook implementations - // don't expect to see that and the caller will usually have produced - // its own user-facing notification about what it's doing anyway. - return - } - - trimAddr := moduleAddr[len(initFromModuleRootKeyPrefix):] - h.Wrapped.Download(trimAddr, packageAddr, version) -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/getter.go b/vendor/github.com/hashicorp/terraform/internal/initwd/getter.go deleted file mode 100644 index ada192b5..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/getter.go +++ /dev/null @@ -1,188 +0,0 @@ -package initwd - -import ( - "fmt" - "log" - "os" - "path/filepath" - "strings" - - cleanhttp "github.com/hashicorp/go-cleanhttp" - getter "github.com/hashicorp/go-getter" - "github.com/hashicorp/terraform/registry/regsrc" -) - -// We configure our own go-getter detector and getter sets here, because -// the set of sources we support is part of Terraform's documentation and -// so we don't want any new sources introduced in go-getter to sneak in here -// and work even though they aren't documented. This also insulates us from -// any meddling that might be done by other go-getter callers linked into our -// executable. - -var goGetterDetectors = []getter.Detector{ - new(getter.GitHubDetector), - new(getter.BitBucketDetector), - new(getter.S3Detector), - new(getter.FileDetector), -} - -var goGetterNoDetectors = []getter.Detector{} - -var goGetterDecompressors = map[string]getter.Decompressor{ - "bz2": new(getter.Bzip2Decompressor), - "gz": new(getter.GzipDecompressor), - "xz": new(getter.XzDecompressor), - "zip": new(getter.ZipDecompressor), - - "tar.bz2": new(getter.TarBzip2Decompressor), - "tar.tbz2": new(getter.TarBzip2Decompressor), - - "tar.gz": new(getter.TarGzipDecompressor), - "tgz": new(getter.TarGzipDecompressor), - - "tar.xz": new(getter.TarXzDecompressor), - "txz": new(getter.TarXzDecompressor), -} - -var goGetterGetters = map[string]getter.Getter{ - "file": new(getter.FileGetter), - "git": new(getter.GitGetter), - "hg": new(getter.HgGetter), - "s3": new(getter.S3Getter), - "http": getterHTTPGetter, - "https": getterHTTPGetter, -} - -var getterHTTPClient = cleanhttp.DefaultClient() - -var getterHTTPGetter = &getter.HttpGetter{ - Client: getterHTTPClient, - Netrc: true, -} - -// A reusingGetter is a helper for the module installer that remembers -// the final resolved addresses of all of the sources it has already been -// asked to install, and will copy from a prior installation directory if -// it has the same resolved source address. -// -// The keys in a reusingGetter are resolved and trimmed source addresses -// (with a scheme always present, and without any "subdir" component), -// and the values are the paths where each source was previously installed. -type reusingGetter map[string]string - -// getWithGoGetter retrieves the package referenced in the given address -// into the installation path and then returns the full path to any subdir -// indicated in the address. -// -// The errors returned by this function are those surfaced by the underlying -// go-getter library, which have very inconsistent quality as -// end-user-actionable error messages. At this time we do not have any -// reasonable way to improve these error messages at this layer because -// the underlying errors are not separatelyr recognizable. -func (g reusingGetter) getWithGoGetter(instPath, addr string) (string, error) { - packageAddr, subDir := splitAddrSubdir(addr) - - log.Printf("[DEBUG] will download %q to %s", packageAddr, instPath) - - realAddr, err := getter.Detect(packageAddr, instPath, getter.Detectors) - if err != nil { - return "", err - } - - var realSubDir string - realAddr, realSubDir = splitAddrSubdir(realAddr) - if realSubDir != "" { - subDir = filepath.Join(realSubDir, subDir) - } - - if realAddr != packageAddr { - log.Printf("[TRACE] go-getter detectors rewrote %q to %q", packageAddr, realAddr) - } - - if prevDir, exists := g[realAddr]; exists { - log.Printf("[TRACE] copying previous install %s to %s", prevDir, instPath) - err := os.Mkdir(instPath, os.ModePerm) - if err != nil { - return "", fmt.Errorf("failed to create directory %s: %s", instPath, err) - } - err = copyDir(instPath, prevDir) - if err != nil { - return "", fmt.Errorf("failed to copy from %s to %s: %s", prevDir, instPath, err) - } - } else { - log.Printf("[TRACE] fetching %q to %q", realAddr, instPath) - client := getter.Client{ - Src: realAddr, - Dst: instPath, - Pwd: instPath, - - Mode: getter.ClientModeDir, - - Detectors: goGetterNoDetectors, // we already did detection above - Decompressors: goGetterDecompressors, - Getters: goGetterGetters, - } - err = client.Get() - if err != nil { - return "", err - } - // Remember where we installed this so we might reuse this directory - // on subsequent calls to avoid re-downloading. - g[realAddr] = instPath - } - - // Our subDir string can contain wildcards until this point, so that - // e.g. a subDir of * can expand to one top-level directory in a .tar.gz - // archive. Now that we've expanded the archive successfully we must - // resolve that into a concrete path. - var finalDir string - if subDir != "" { - finalDir, err = getter.SubdirGlob(instPath, subDir) - log.Printf("[TRACE] expanded %q to %q", subDir, finalDir) - if err != nil { - return "", err - } - } else { - finalDir = instPath - } - - // If we got this far then we have apparently succeeded in downloading - // the requested object! - return filepath.Clean(finalDir), nil -} - -// splitAddrSubdir splits the given address (which is assumed to be a -// registry address or go-getter-style address) into a package portion -// and a sub-directory portion. -// -// The package portion defines what should be downloaded and then the -// sub-directory portion, if present, specifies a sub-directory within -// the downloaded object (an archive, VCS repository, etc) that contains -// the module's configuration files. -// -// The subDir portion will be returned as empty if no subdir separator -// ("//") is present in the address. -func splitAddrSubdir(addr string) (packageAddr, subDir string) { - return getter.SourceDirSubdir(addr) -} - -var localSourcePrefixes = []string{ - "./", - "../", - ".\\", - "..\\", -} - -func isLocalSourceAddr(addr string) bool { - for _, prefix := range localSourcePrefixes { - if strings.HasPrefix(addr, prefix) { - return true - } - } - return false -} - -func isRegistrySourceAddr(addr string) bool { - _, err := regsrc.ParseModuleSource(addr) - return err == nil -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/inode.go b/vendor/github.com/hashicorp/terraform/internal/initwd/inode.go deleted file mode 100644 index 1150b093..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/inode.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build linux darwin openbsd netbsd solaris dragonfly - -package initwd - -import ( - "fmt" - "os" - "syscall" -) - -// lookup the inode of a file on posix systems -func inode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - if st, ok := stat.Sys().(*syscall.Stat_t); ok { - return st.Ino, nil - } - return 0, fmt.Errorf("could not determine file inode") -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/inode_freebsd.go b/vendor/github.com/hashicorp/terraform/internal/initwd/inode_freebsd.go deleted file mode 100644 index 30532f54..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/inode_freebsd.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build freebsd - -package initwd - -import ( - "fmt" - "os" - "syscall" -) - -// lookup the inode of a file on posix systems -func inode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - if st, ok := stat.Sys().(*syscall.Stat_t); ok { - return uint64(st.Ino), nil - } - return 0, fmt.Errorf("could not determine file inode") -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/inode_windows.go b/vendor/github.com/hashicorp/terraform/internal/initwd/inode_windows.go deleted file mode 100644 index 3ed58e4b..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/inode_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build windows - -package initwd - -// no syscall.Stat_t on windows, return 0 for inodes -func inode(path string) (uint64, error) { - return 0, nil -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/load_config.go b/vendor/github.com/hashicorp/terraform/internal/initwd/load_config.go deleted file mode 100644 index 6f77dcd8..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/load_config.go +++ /dev/null @@ -1,56 +0,0 @@ -package initwd - -import ( - "fmt" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform/internal/earlyconfig" - "github.com/hashicorp/terraform/internal/modsdir" - "github.com/hashicorp/terraform/tfdiags" -) - -// LoadConfig loads a full configuration tree that has previously had all of -// its dependent modules installed to the given modulesDir using a -// ModuleInstaller. -// -// This uses the early configuration loader and thus only reads top-level -// metadata from the modules in the configuration. Most callers should use -// the configs/configload package to fully load a configuration. -func LoadConfig(rootDir, modulesDir string) (*earlyconfig.Config, tfdiags.Diagnostics) { - rootMod, diags := earlyconfig.LoadModule(rootDir) - if rootMod == nil { - return nil, diags - } - - manifest, err := modsdir.ReadManifestSnapshotForDir(modulesDir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to read module manifest", - fmt.Sprintf("Terraform failed to read its manifest of locally-cached modules: %s.", err), - )) - return nil, diags - } - - return earlyconfig.BuildConfig(rootMod, earlyconfig.ModuleWalkerFunc( - func(req *earlyconfig.ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - key := manifest.ModuleKey(req.Path) - record, exists := manifest[key] - if !exists { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Module not installed", - fmt.Sprintf("Module %s is not yet installed. Run \"terraform init\" to install all modules required by this configuration.", req.Path.String()), - )) - return nil, nil, diags - } - - mod, mDiags := earlyconfig.LoadModule(record.Dir) - diags = diags.Append(mDiags) - return mod, record.Version, diags - }, - )) -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/module_install.go b/vendor/github.com/hashicorp/terraform/internal/initwd/module_install.go deleted file mode 100644 index 3bb4d023..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/module_install.go +++ /dev/null @@ -1,519 +0,0 @@ -package initwd - -import ( - "fmt" - "github.com/hashicorp/terraform/registry" - "log" - "os" - "path/filepath" - "strings" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/internal/earlyconfig" - "github.com/hashicorp/terraform/internal/modsdir" - "github.com/hashicorp/terraform/registry/regsrc" - "github.com/hashicorp/terraform/tfdiags" -) - -type ModuleInstaller struct { - modsDir string - reg *registry.Client -} - -func NewModuleInstaller(modsDir string, reg *registry.Client) *ModuleInstaller { - return &ModuleInstaller{ - modsDir: modsDir, - reg: reg, - } -} - -// InstallModules analyses the root module in the given directory and installs -// all of its direct and transitive dependencies into the given modules -// directory, which must already exist. -// -// Since InstallModules makes possibly-time-consuming calls to remote services, -// a hook interface is supported to allow the caller to be notified when -// each module is installed and, for remote modules, when downloading begins. -// LoadConfig guarantees that two hook calls will not happen concurrently but -// it does not guarantee any particular ordering of hook calls. This mechanism -// is for UI feedback only and does not give the caller any control over the -// process. -// -// If modules are already installed in the target directory, they will be -// skipped unless their source address or version have changed or unless -// the upgrade flag is set. -// -// InstallModules never deletes any directory, except in the case where it -// needs to replace a directory that is already present with a newly-extracted -// package. -// -// If the returned diagnostics contains errors then the module installation -// may have wholly or partially completed. Modules must be loaded in order -// to find their dependencies, so this function does many of the same checks -// as LoadConfig as a side-effect. -// -// If successful (the returned diagnostics contains no errors) then the -// first return value is the early configuration tree that was constructed by -// the installation process. -func (i *ModuleInstaller) InstallModules(rootDir string, upgrade bool, hooks ModuleInstallHooks) (*earlyconfig.Config, tfdiags.Diagnostics) { - log.Printf("[TRACE] ModuleInstaller: installing child modules for %s into %s", rootDir, i.modsDir) - - rootMod, diags := earlyconfig.LoadModule(rootDir) - if rootMod == nil { - return nil, diags - } - - manifest, err := modsdir.ReadManifestSnapshotForDir(i.modsDir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to read modules manifest file", - fmt.Sprintf("Error reading manifest for %s: %s.", i.modsDir, err), - )) - return nil, diags - } - - getter := reusingGetter{} - cfg, instDiags := i.installDescendentModules(rootMod, rootDir, manifest, upgrade, hooks, getter) - diags = append(diags, instDiags...) - - return cfg, diags -} - -func (i *ModuleInstaller) installDescendentModules(rootMod *tfconfig.Module, rootDir string, manifest modsdir.Manifest, upgrade bool, hooks ModuleInstallHooks, getter reusingGetter) (*earlyconfig.Config, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - if hooks == nil { - // Use our no-op implementation as a placeholder - hooks = ModuleInstallHooksImpl{} - } - - // Create a manifest record for the root module. This will be used if - // there are any relative-pathed modules in the root. - manifest[""] = modsdir.Record{ - Key: "", - Dir: rootDir, - } - - cfg, cDiags := earlyconfig.BuildConfig(rootMod, earlyconfig.ModuleWalkerFunc( - func(req *earlyconfig.ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) { - - key := manifest.ModuleKey(req.Path) - instPath := i.packageInstallPath(req.Path) - - log.Printf("[DEBUG] Module installer: begin %s", key) - - // First we'll check if we need to upgrade/replace an existing - // installed module, and delete it out of the way if so. - replace := upgrade - if !replace { - record, recorded := manifest[key] - switch { - case !recorded: - log.Printf("[TRACE] ModuleInstaller: %s is not yet installed", key) - replace = true - case record.SourceAddr != req.SourceAddr: - log.Printf("[TRACE] ModuleInstaller: %s source address has changed from %q to %q", key, record.SourceAddr, req.SourceAddr) - replace = true - case record.Version != nil && !req.VersionConstraints.Check(record.Version): - log.Printf("[TRACE] ModuleInstaller: %s version %s no longer compatible with constraints %s", key, record.Version, req.VersionConstraints) - replace = true - } - } - - // If we _are_ planning to replace this module, then we'll remove - // it now so our installation code below won't conflict with any - // existing remnants. - if replace { - if _, recorded := manifest[key]; recorded { - log.Printf("[TRACE] ModuleInstaller: discarding previous record of %s prior to reinstall", key) - } - delete(manifest, key) - // Deleting a module invalidates all of its descendent modules too. - keyPrefix := key + "." - for subKey := range manifest { - if strings.HasPrefix(subKey, keyPrefix) { - if _, recorded := manifest[subKey]; recorded { - log.Printf("[TRACE] ModuleInstaller: also discarding downstream %s", subKey) - } - delete(manifest, subKey) - } - } - } - - record, recorded := manifest[key] - if !recorded { - // Clean up any stale cache directory that might be present. - // If this is a local (relative) source then the dir will - // not exist, but we'll ignore that. - log.Printf("[TRACE] ModuleInstaller: cleaning directory %s prior to install of %s", instPath, key) - err := os.RemoveAll(instPath) - if err != nil && !os.IsNotExist(err) { - log.Printf("[TRACE] ModuleInstaller: failed to remove %s: %s", key, err) - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to remove local module cache", - fmt.Sprintf( - "Terraform tried to remove %s in order to reinstall this module, but encountered an error: %s", - instPath, err, - ), - )) - return nil, nil, diags - } - } else { - // If this module is already recorded and its root directory - // exists then we will just load what's already there and - // keep our existing record. - info, err := os.Stat(record.Dir) - if err == nil && info.IsDir() { - mod, mDiags := earlyconfig.LoadModule(record.Dir) - diags = diags.Append(mDiags) - - log.Printf("[TRACE] ModuleInstaller: Module installer: %s %s already installed in %s", key, record.Version, record.Dir) - return mod, record.Version, diags - } - } - - // If we get down here then it's finally time to actually install - // the module. There are some variants to this process depending - // on what type of module source address we have. - switch { - - case isLocalSourceAddr(req.SourceAddr): - log.Printf("[TRACE] ModuleInstaller: %s has local path %q", key, req.SourceAddr) - mod, mDiags := i.installLocalModule(req, key, manifest, hooks) - diags = append(diags, mDiags...) - return mod, nil, diags - - case isRegistrySourceAddr(req.SourceAddr): - addr, err := regsrc.ParseModuleSource(req.SourceAddr) - if err != nil { - // Should never happen because isRegistrySourceAddr already validated - panic(err) - } - log.Printf("[TRACE] ModuleInstaller: %s is a registry module at %s", key, addr) - - mod, v, mDiags := i.installRegistryModule(req, key, instPath, addr, manifest, hooks, getter) - diags = append(diags, mDiags...) - return mod, v, diags - - default: - log.Printf("[TRACE] ModuleInstaller: %s address %q will be handled by go-getter", key, req.SourceAddr) - - mod, mDiags := i.installGoGetterModule(req, key, instPath, manifest, hooks, getter) - diags = append(diags, mDiags...) - return mod, nil, diags - } - - }, - )) - diags = append(diags, cDiags...) - - err := manifest.WriteSnapshotToDir(i.modsDir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to update module manifest", - fmt.Sprintf("Unable to write the module manifest file: %s", err), - )) - } - - return cfg, diags -} - -func (i *ModuleInstaller) installLocalModule(req *earlyconfig.ModuleRequest, key string, manifest modsdir.Manifest, hooks ModuleInstallHooks) (*tfconfig.Module, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - parentKey := manifest.ModuleKey(req.Parent.Path) - parentRecord, recorded := manifest[parentKey] - if !recorded { - // This is indicative of a bug rather than a user-actionable error - panic(fmt.Errorf("missing manifest record for parent module %s", parentKey)) - } - - if len(req.VersionConstraints) != 0 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid version constraint", - fmt.Sprintf("Cannot apply a version constraint to module %q (at %s:%d) because it has a relative local path.", req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - } - - // For local sources we don't actually need to modify the - // filesystem at all because the parent already wrote - // the files we need, and so we just load up what's already here. - newDir := filepath.Join(parentRecord.Dir, req.SourceAddr) - log.Printf("[TRACE] ModuleInstaller: %s uses directory from parent: %s", key, newDir) - mod, mDiags := earlyconfig.LoadModule(newDir) - if mod == nil { - // nil indicates missing or unreadable directory, so we'll - // discard the returned diags and return a more specific - // error message here. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unreadable module directory", - fmt.Sprintf("The directory %s could not be read for module %q at %s:%d.", newDir, req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - } else { - diags = diags.Append(mDiags) - } - - // Note the local location in our manifest. - manifest[key] = modsdir.Record{ - Key: key, - Dir: newDir, - SourceAddr: req.SourceAddr, - } - log.Printf("[DEBUG] Module installer: %s installed at %s", key, newDir) - hooks.Install(key, nil, newDir) - - return mod, diags -} - -func (i *ModuleInstaller) installRegistryModule(req *earlyconfig.ModuleRequest, key string, instPath string, addr *regsrc.Module, manifest modsdir.Manifest, hooks ModuleInstallHooks, getter reusingGetter) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - hostname, err := addr.SvcHost() - if err != nil { - // If it looks like the user was trying to use punycode then we'll generate - // a specialized error for that case. We require the unicode form of - // hostname so that hostnames are always human-readable in configuration - // and punycode can't be used to hide a malicious module hostname. - if strings.HasPrefix(addr.RawHost.Raw, "xn--") { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid module registry hostname", - fmt.Sprintf("The hostname portion of the module %q source address (at %s:%d) is not an acceptable hostname. Internationalized domain names must be given in unicode form rather than ASCII (\"punycode\") form.", req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - } else { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid module registry hostname", - fmt.Sprintf("The hostname portion of the module %q source address (at %s:%d) is not a valid hostname.", req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - } - return nil, nil, diags - } - - reg := i.reg - - log.Printf("[DEBUG] %s listing available versions of %s at %s", key, addr, hostname) - resp, err := reg.ModuleVersions(addr) - if err != nil { - if registry.IsModuleNotFound(err) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Module not found", - fmt.Sprintf("Module %q (from %s:%d) cannot be found in the module registry at %s.", req.Name, req.CallPos.Filename, req.CallPos.Line, hostname), - )) - } else { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Error accessing remote module registry", - fmt.Sprintf("Failed to retrieve available versions for module %q (%s:%d) from %s: %s.", req.Name, req.CallPos.Filename, req.CallPos.Line, hostname, err), - )) - } - return nil, nil, diags - } - - // The response might contain information about dependencies to allow us - // to potentially optimize future requests, but we don't currently do that - // and so for now we'll just take the first item which is guaranteed to - // be the address we requested. - if len(resp.Modules) < 1 { - // Should never happen, but since this is a remote service that may - // be implemented by third-parties we will handle it gracefully. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid response from remote module registry", - fmt.Sprintf("The registry at %s returned an invalid response when Terraform requested available versions for module %q (%s:%d).", hostname, req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - return nil, nil, diags - } - - modMeta := resp.Modules[0] - - var latestMatch *version.Version - var latestVersion *version.Version - for _, mv := range modMeta.Versions { - v, err := version.NewVersion(mv.Version) - if err != nil { - // Should never happen if the registry server is compliant with - // the protocol, but we'll warn if not to assist someone who - // might be developing a module registry server. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Warning, - "Invalid response from remote module registry", - fmt.Sprintf("The registry at %s returned an invalid version string %q for module %q (%s:%d), which Terraform ignored.", hostname, mv.Version, req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - continue - } - - // If we've found a pre-release version then we'll ignore it unless - // it was exactly requested. - if v.Prerelease() != "" && req.VersionConstraints.String() != v.String() { - log.Printf("[TRACE] ModuleInstaller: %s ignoring %s because it is a pre-release and was not requested exactly", key, v) - continue - } - - if latestVersion == nil || v.GreaterThan(latestVersion) { - latestVersion = v - } - - if req.VersionConstraints.Check(v) { - if latestMatch == nil || v.GreaterThan(latestMatch) { - latestMatch = v - } - } - } - - if latestVersion == nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Module has no versions", - fmt.Sprintf("Module %q (%s:%d) has no versions available on %s.", addr, req.CallPos.Filename, req.CallPos.Line, hostname), - )) - return nil, nil, diags - } - - if latestMatch == nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unresolvable module version constraint", - fmt.Sprintf("There is no available version of module %q (%s:%d) which matches the given version constraint. The newest available version is %s.", addr, req.CallPos.Filename, req.CallPos.Line, latestVersion), - )) - return nil, nil, diags - } - - // Report up to the caller that we're about to start downloading. - packageAddr, _ := splitAddrSubdir(req.SourceAddr) - hooks.Download(key, packageAddr, latestMatch) - - // If we manage to get down here then we've found a suitable version to - // install, so we need to ask the registry where we should download it from. - // The response to this is a go-getter-style address string. - dlAddr, err := reg.ModuleLocation(addr, latestMatch.String()) - if err != nil { - log.Printf("[ERROR] %s from %s %s: %s", key, addr, latestMatch, err) - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid response from remote module registry", - fmt.Sprintf("The remote registry at %s failed to return a download URL for %s %s.", hostname, addr, latestMatch), - )) - return nil, nil, diags - } - - log.Printf("[TRACE] ModuleInstaller: %s %s %s is available at %q", key, addr, latestMatch, dlAddr) - - modDir, err := getter.getWithGoGetter(instPath, dlAddr) - if err != nil { - // Errors returned by go-getter have very inconsistent quality as - // end-user error messages, but for now we're accepting that because - // we have no way to recognize any specific errors to improve them - // and masking the error entirely would hide valuable diagnostic - // information from the user. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to download module", - fmt.Sprintf("Error attempting to download module %q (%s:%d) source code from %q: %s.", req.Name, req.CallPos.Filename, req.CallPos.Line, dlAddr, err), - )) - return nil, nil, diags - } - - log.Printf("[TRACE] ModuleInstaller: %s %q was downloaded to %s", key, dlAddr, modDir) - - if addr.RawSubmodule != "" { - // Append the user's requested subdirectory to any subdirectory that - // was implied by any of the nested layers we expanded within go-getter. - modDir = filepath.Join(modDir, addr.RawSubmodule) - } - - log.Printf("[TRACE] ModuleInstaller: %s should now be at %s", key, modDir) - - // Finally we are ready to try actually loading the module. - mod, mDiags := earlyconfig.LoadModule(modDir) - if mod == nil { - // nil indicates missing or unreadable directory, so we'll - // discard the returned diags and return a more specific - // error message here. For registry modules this actually - // indicates a bug in the code above, since it's not the - // user's responsibility to create the directory in this case. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unreadable module directory", - fmt.Sprintf("The directory %s could not be read. This is a bug in Terraform and should be reported.", modDir), - )) - } else { - diags = append(diags, mDiags...) - } - - // Note the local location in our manifest. - manifest[key] = modsdir.Record{ - Key: key, - Version: latestMatch, - Dir: modDir, - SourceAddr: req.SourceAddr, - } - log.Printf("[DEBUG] Module installer: %s installed at %s", key, modDir) - hooks.Install(key, latestMatch, modDir) - - return mod, latestMatch, diags -} - -func (i *ModuleInstaller) installGoGetterModule(req *earlyconfig.ModuleRequest, key string, instPath string, manifest modsdir.Manifest, hooks ModuleInstallHooks, getter reusingGetter) (*tfconfig.Module, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // Report up to the caller that we're about to start downloading. - packageAddr, _ := splitAddrSubdir(req.SourceAddr) - hooks.Download(key, packageAddr, nil) - - modDir, err := getter.getWithGoGetter(instPath, req.SourceAddr) - if err != nil { - // Errors returned by go-getter have very inconsistent quality as - // end-user error messages, but for now we're accepting that because - // we have no way to recognize any specific errors to improve them - // and masking the error entirely would hide valuable diagnostic - // information from the user. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to download module", - fmt.Sprintf("Error attempting to download module %q (%s:%d) source code from %q: %s", req.Name, req.CallPos.Filename, req.CallPos.Line, packageAddr, err), - )) - return nil, diags - } - - log.Printf("[TRACE] ModuleInstaller: %s %q was downloaded to %s", key, req.SourceAddr, modDir) - - mod, mDiags := earlyconfig.LoadModule(modDir) - if mod == nil { - // nil indicates missing or unreadable directory, so we'll - // discard the returned diags and return a more specific - // error message here. For go-getter modules this actually - // indicates a bug in the code above, since it's not the - // user's responsibility to create the directory in this case. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unreadable module directory", - fmt.Sprintf("The directory %s could not be read. This is a bug in Terraform and should be reported.", modDir), - )) - } else { - diags = append(diags, mDiags...) - } - - // Note the local location in our manifest. - manifest[key] = modsdir.Record{ - Key: key, - Dir: modDir, - SourceAddr: req.SourceAddr, - } - log.Printf("[DEBUG] Module installer: %s installed at %s", key, modDir) - hooks.Install(key, nil, modDir) - - return mod, diags -} - -func (i *ModuleInstaller) packageInstallPath(modulePath addrs.Module) string { - return filepath.Join(i.modsDir, strings.Join(modulePath, ".")) -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/module_install_hooks.go b/vendor/github.com/hashicorp/terraform/internal/initwd/module_install_hooks.go deleted file mode 100644 index 817a6dc8..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/module_install_hooks.go +++ /dev/null @@ -1,36 +0,0 @@ -package initwd - -import ( - version "github.com/hashicorp/go-version" -) - -// ModuleInstallHooks is an interface used to provide notifications about the -// installation process being orchestrated by InstallModules. -// -// This interface may have new methods added in future, so implementers should -// embed InstallHooksImpl to get no-op implementations of any unimplemented -// methods. -type ModuleInstallHooks interface { - // Download is called for modules that are retrieved from a remote source - // before that download begins, to allow a caller to give feedback - // on progress through a possibly-long sequence of downloads. - Download(moduleAddr, packageAddr string, version *version.Version) - - // Install is called for each module that is installed, even if it did - // not need to be downloaded from a remote source. - Install(moduleAddr string, version *version.Version, localPath string) -} - -// ModuleInstallHooksImpl is a do-nothing implementation of InstallHooks that -// can be embedded in another implementation struct to allow only partial -// implementation of the interface. -type ModuleInstallHooksImpl struct { -} - -func (h ModuleInstallHooksImpl) Download(moduleAddr, packageAddr string, version *version.Version) { -} - -func (h ModuleInstallHooksImpl) Install(moduleAddr string, version *version.Version, localPath string) { -} - -var _ ModuleInstallHooks = ModuleInstallHooksImpl{} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/testing.go b/vendor/github.com/hashicorp/terraform/internal/initwd/testing.go deleted file mode 100644 index 8cef80a3..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/testing.go +++ /dev/null @@ -1,73 +0,0 @@ -package initwd - -import ( - "github.com/hashicorp/terraform/registry" - "testing" - - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/configs/configload" - "github.com/hashicorp/terraform/tfdiags" -) - -// LoadConfigForTests is a convenience wrapper around configload.NewLoaderForTests, -// ModuleInstaller.InstallModules and configload.Loader.LoadConfig that allows -// a test configuration to be loaded in a single step. -// -// If module installation fails, t.Fatal (or similar) is called to halt -// execution of the test, under the assumption that installation failures are -// not expected. If installation failures _are_ expected then use -// NewLoaderForTests and work with the loader object directly. If module -// installation succeeds but generates warnings, these warnings are discarded. -// -// If installation succeeds but errors are detected during loading then a -// possibly-incomplete config is returned along with error diagnostics. The -// test run is not aborted in this case, so that the caller can make assertions -// against the returned diagnostics. -// -// As with NewLoaderForTests, a cleanup function is returned which must be -// called before the test completes in order to remove the temporary -// modules directory. -func LoadConfigForTests(t *testing.T, rootDir string) (*configs.Config, *configload.Loader, func(), tfdiags.Diagnostics) { - t.Helper() - - var diags tfdiags.Diagnostics - - loader, cleanup := configload.NewLoaderForTests(t) - inst := NewModuleInstaller(loader.ModulesDir(), registry.NewClient(nil, nil)) - - _, moreDiags := inst.InstallModules(rootDir, true, ModuleInstallHooksImpl{}) - diags = diags.Append(moreDiags) - if diags.HasErrors() { - cleanup() - t.Fatal(diags.Err()) - return nil, nil, func() {}, diags - } - - // Since module installer has modified the module manifest on disk, we need - // to refresh the cache of it in the loader. - if err := loader.RefreshModules(); err != nil { - t.Fatalf("failed to refresh modules after installation: %s", err) - } - - config, hclDiags := loader.LoadConfig(rootDir) - diags = diags.Append(hclDiags) - return config, loader, cleanup, diags -} - -// MustLoadConfigForTests is a variant of LoadConfigForTests which calls -// t.Fatal (or similar) if there are any errors during loading, and thus -// does not return diagnostics at all. -// -// This is useful for concisely writing tests that don't expect errors at -// all. For tests that expect errors and need to assert against them, use -// LoadConfigForTests instead. -func MustLoadConfigForTests(t *testing.T, rootDir string) (*configs.Config, *configload.Loader, func()) { - t.Helper() - - config, loader, cleanup, diags := LoadConfigForTests(t, rootDir) - if diags.HasErrors() { - cleanup() - t.Fatal(diags.Err()) - } - return config, loader, cleanup -} diff --git a/vendor/github.com/hashicorp/terraform/internal/initwd/version_required.go b/vendor/github.com/hashicorp/terraform/internal/initwd/version_required.go deleted file mode 100644 index 104840b9..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/initwd/version_required.go +++ /dev/null @@ -1,83 +0,0 @@ -package initwd - -import ( - "fmt" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform/internal/earlyconfig" - "github.com/hashicorp/terraform/tfdiags" - tfversion "github.com/hashicorp/terraform/version" -) - -// CheckCoreVersionRequirements visits each of the modules in the given -// early configuration tree and verifies that any given Core version constraints -// match with the version of Terraform Core that is being used. -// -// The returned diagnostics will contain errors if any constraints do not match. -// The returned diagnostics might also return warnings, which should be -// displayed to the user. -func CheckCoreVersionRequirements(earlyConfig *earlyconfig.Config) tfdiags.Diagnostics { - if earlyConfig == nil { - return nil - } - - var diags tfdiags.Diagnostics - module := earlyConfig.Module - - var constraints version.Constraints - for _, constraintStr := range module.RequiredCore { - constraint, err := version.NewConstraint(constraintStr) - if err != nil { - // Unfortunately the early config parser doesn't preserve a source - // location for this, so we're unable to indicate a specific - // location where this constraint came from, but we can at least - // say which module set it. - switch { - case len(earlyConfig.Path) == 0: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid provider version constraint", - fmt.Sprintf("Invalid version core constraint %q in the root module.", constraintStr), - )) - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid provider version constraint", - fmt.Sprintf("Invalid version core constraint %q in %s.", constraintStr, earlyConfig.Path), - )) - } - continue - } - constraints = append(constraints, constraint...) - } - - if !constraints.Check(tfversion.SemVer) { - switch { - case len(earlyConfig.Path) == 0: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unsupported Terraform Core version", - fmt.Sprintf( - "This configuration does not support Terraform version %s. To proceed, either choose another supported Terraform version or update the root module's version constraint. Version constraints are normally set for good reason, so updating the constraint may lead to other errors or unexpected behavior.", - tfversion.String(), - ), - )) - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unsupported Terraform Core version", - fmt.Sprintf( - "Module %s (from %q) does not support Terraform version %s. To proceed, either choose another supported Terraform version or update the module's version constraint. Version constraints are normally set for good reason, so updating the constraint may lead to other errors or unexpected behavior.", - earlyConfig.Path, earlyConfig.SourceAddr, tfversion.String(), - ), - )) - } - } - - for _, c := range earlyConfig.Children { - childDiags := CheckCoreVersionRequirements(c) - diags = diags.Append(childDiags) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform/internal/modsdir/doc.go b/vendor/github.com/hashicorp/terraform/internal/modsdir/doc.go deleted file mode 100644 index 0d7d664f..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/modsdir/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package modsdir is an internal package containing the model types used to -// represent the manifest of modules in a local modules cache directory. -package modsdir diff --git a/vendor/github.com/hashicorp/terraform/internal/modsdir/manifest.go b/vendor/github.com/hashicorp/terraform/internal/modsdir/manifest.go deleted file mode 100644 index 36f6c033..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/modsdir/manifest.go +++ /dev/null @@ -1,138 +0,0 @@ -package modsdir - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "log" - "os" - "path/filepath" - - version "github.com/hashicorp/go-version" - - "github.com/hashicorp/terraform/addrs" -) - -// Record represents some metadata about an installed module, as part -// of a ModuleManifest. -type Record struct { - // Key is a unique identifier for this particular module, based on its - // position within the static module tree. - Key string `json:"Key"` - - // SourceAddr is the source address given for this module in configuration. - // This is used only to detect if the source was changed in configuration - // since the module was last installed, which means that the installer - // must re-install it. - SourceAddr string `json:"Source"` - - // Version is the exact version of the module, which results from parsing - // VersionStr. nil for un-versioned modules. - Version *version.Version `json:"-"` - - // VersionStr is the version specifier string. This is used only for - // serialization in snapshots and should not be accessed or updated - // by any other codepaths; use "Version" instead. - VersionStr string `json:"Version,omitempty"` - - // Dir is the path to the local directory where the module is installed. - Dir string `json:"Dir"` -} - -// Manifest is a map used to keep track of the filesystem locations -// and other metadata about installed modules. -// -// The configuration loader refers to this, while the module installer updates -// it to reflect any changes to the installed modules. -type Manifest map[string]Record - -func (m Manifest) ModuleKey(path addrs.Module) string { - return path.String() -} - -// manifestSnapshotFile is an internal struct used only to assist in our JSON -// serialization of manifest snapshots. It should not be used for any other -// purpose. -type manifestSnapshotFile struct { - Records []Record `json:"Modules"` -} - -func ReadManifestSnapshot(r io.Reader) (Manifest, error) { - src, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - if len(src) == 0 { - // This should never happen, but we'll tolerate it as if it were - // a valid empty JSON object. - return make(Manifest), nil - } - - var read manifestSnapshotFile - err = json.Unmarshal(src, &read) - - new := make(Manifest) - for _, record := range read.Records { - if record.VersionStr != "" { - record.Version, err = version.NewVersion(record.VersionStr) - if err != nil { - return nil, fmt.Errorf("invalid version %q for %s: %s", record.VersionStr, record.Key, err) - } - } - if _, exists := new[record.Key]; exists { - // This should never happen in any valid file, so we'll catch it - // and report it to avoid confusing/undefined behavior if the - // snapshot file was edited incorrectly outside of Terraform. - return nil, fmt.Errorf("snapshot file contains two records for path %s", record.Key) - } - new[record.Key] = record - } - return new, nil -} - -func ReadManifestSnapshotForDir(dir string) (Manifest, error) { - fn := filepath.Join(dir, ManifestSnapshotFilename) - r, err := os.Open(fn) - if err != nil { - if os.IsNotExist(err) { - return make(Manifest), nil // missing file is okay and treated as empty - } - return nil, err - } - return ReadManifestSnapshot(r) -} - -func (m Manifest) WriteSnapshot(w io.Writer) error { - var write manifestSnapshotFile - - for _, record := range m { - // Make sure VersionStr is in sync with Version, since we encourage - // callers to manipulate Version and ignore VersionStr. - if record.Version != nil { - record.VersionStr = record.Version.String() - } else { - record.VersionStr = "" - } - write.Records = append(write.Records, record) - } - - src, err := json.Marshal(write) - if err != nil { - return err - } - - _, err = w.Write(src) - return err -} - -func (m Manifest) WriteSnapshotToDir(dir string) error { - fn := filepath.Join(dir, ManifestSnapshotFilename) - log.Printf("[TRACE] modsdir: writing modules manifest to %s", fn) - w, err := os.Create(fn) - if err != nil { - return err - } - return m.WriteSnapshot(w) -} diff --git a/vendor/github.com/hashicorp/terraform/internal/modsdir/paths.go b/vendor/github.com/hashicorp/terraform/internal/modsdir/paths.go deleted file mode 100644 index 9ebb5243..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/modsdir/paths.go +++ /dev/null @@ -1,3 +0,0 @@ -package modsdir - -const ManifestSnapshotFilename = "modules.json" diff --git a/vendor/github.com/hashicorp/terraform/internal/tfplugin5/generate.sh b/vendor/github.com/hashicorp/terraform/internal/tfplugin5/generate.sh deleted file mode 100644 index de1d693c..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/tfplugin5/generate.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -# We do not run protoc under go:generate because we want to ensure that all -# dependencies of go:generate are "go get"-able for general dev environment -# usability. To compile all protobuf files in this repository, run -# "make protobuf" at the top-level. - -set -eu - -SOURCE="${BASH_SOURCE[0]}" -while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done -DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" - -cd "$DIR" - -protoc -I ./ tfplugin5.proto --go_out=plugins=grpc:./ diff --git a/vendor/github.com/hashicorp/terraform/internal/tfplugin5/tfplugin5.pb.go b/vendor/github.com/hashicorp/terraform/internal/tfplugin5/tfplugin5.pb.go deleted file mode 100644 index 6905f958..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/tfplugin5/tfplugin5.pb.go +++ /dev/null @@ -1,3451 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: tfplugin5.proto - -package tfplugin5 - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Diagnostic_Severity int32 - -const ( - Diagnostic_INVALID Diagnostic_Severity = 0 - Diagnostic_ERROR Diagnostic_Severity = 1 - Diagnostic_WARNING Diagnostic_Severity = 2 -) - -var Diagnostic_Severity_name = map[int32]string{ - 0: "INVALID", - 1: "ERROR", - 2: "WARNING", -} -var Diagnostic_Severity_value = map[string]int32{ - "INVALID": 0, - "ERROR": 1, - "WARNING": 2, -} - -func (x Diagnostic_Severity) String() string { - return proto.EnumName(Diagnostic_Severity_name, int32(x)) -} -func (Diagnostic_Severity) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{1, 0} -} - -type Schema_NestedBlock_NestingMode int32 - -const ( - Schema_NestedBlock_INVALID Schema_NestedBlock_NestingMode = 0 - Schema_NestedBlock_SINGLE Schema_NestedBlock_NestingMode = 1 - Schema_NestedBlock_LIST Schema_NestedBlock_NestingMode = 2 - Schema_NestedBlock_SET Schema_NestedBlock_NestingMode = 3 - Schema_NestedBlock_MAP Schema_NestedBlock_NestingMode = 4 -) - -var Schema_NestedBlock_NestingMode_name = map[int32]string{ - 0: "INVALID", - 1: "SINGLE", - 2: "LIST", - 3: "SET", - 4: "MAP", -} -var Schema_NestedBlock_NestingMode_value = map[string]int32{ - "INVALID": 0, - "SINGLE": 1, - "LIST": 2, - "SET": 3, - "MAP": 4, -} - -func (x Schema_NestedBlock_NestingMode) String() string { - return proto.EnumName(Schema_NestedBlock_NestingMode_name, int32(x)) -} -func (Schema_NestedBlock_NestingMode) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{5, 2, 0} -} - -// DynamicValue is an opaque encoding of terraform data, with the field name -// indicating the encoding scheme used. -type DynamicValue struct { - Msgpack []byte `protobuf:"bytes,1,opt,name=msgpack,proto3" json:"msgpack,omitempty"` - Json []byte `protobuf:"bytes,2,opt,name=json,proto3" json:"json,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DynamicValue) Reset() { *m = DynamicValue{} } -func (m *DynamicValue) String() string { return proto.CompactTextString(m) } -func (*DynamicValue) ProtoMessage() {} -func (*DynamicValue) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{0} -} -func (m *DynamicValue) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DynamicValue.Unmarshal(m, b) -} -func (m *DynamicValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DynamicValue.Marshal(b, m, deterministic) -} -func (dst *DynamicValue) XXX_Merge(src proto.Message) { - xxx_messageInfo_DynamicValue.Merge(dst, src) -} -func (m *DynamicValue) XXX_Size() int { - return xxx_messageInfo_DynamicValue.Size(m) -} -func (m *DynamicValue) XXX_DiscardUnknown() { - xxx_messageInfo_DynamicValue.DiscardUnknown(m) -} - -var xxx_messageInfo_DynamicValue proto.InternalMessageInfo - -func (m *DynamicValue) GetMsgpack() []byte { - if m != nil { - return m.Msgpack - } - return nil -} - -func (m *DynamicValue) GetJson() []byte { - if m != nil { - return m.Json - } - return nil -} - -type Diagnostic struct { - Severity Diagnostic_Severity `protobuf:"varint,1,opt,name=severity,proto3,enum=tfplugin5.Diagnostic_Severity" json:"severity,omitempty"` - Summary string `protobuf:"bytes,2,opt,name=summary,proto3" json:"summary,omitempty"` - Detail string `protobuf:"bytes,3,opt,name=detail,proto3" json:"detail,omitempty"` - Attribute *AttributePath `protobuf:"bytes,4,opt,name=attribute,proto3" json:"attribute,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Diagnostic) Reset() { *m = Diagnostic{} } -func (m *Diagnostic) String() string { return proto.CompactTextString(m) } -func (*Diagnostic) ProtoMessage() {} -func (*Diagnostic) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{1} -} -func (m *Diagnostic) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Diagnostic.Unmarshal(m, b) -} -func (m *Diagnostic) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Diagnostic.Marshal(b, m, deterministic) -} -func (dst *Diagnostic) XXX_Merge(src proto.Message) { - xxx_messageInfo_Diagnostic.Merge(dst, src) -} -func (m *Diagnostic) XXX_Size() int { - return xxx_messageInfo_Diagnostic.Size(m) -} -func (m *Diagnostic) XXX_DiscardUnknown() { - xxx_messageInfo_Diagnostic.DiscardUnknown(m) -} - -var xxx_messageInfo_Diagnostic proto.InternalMessageInfo - -func (m *Diagnostic) GetSeverity() Diagnostic_Severity { - if m != nil { - return m.Severity - } - return Diagnostic_INVALID -} - -func (m *Diagnostic) GetSummary() string { - if m != nil { - return m.Summary - } - return "" -} - -func (m *Diagnostic) GetDetail() string { - if m != nil { - return m.Detail - } - return "" -} - -func (m *Diagnostic) GetAttribute() *AttributePath { - if m != nil { - return m.Attribute - } - return nil -} - -type AttributePath struct { - Steps []*AttributePath_Step `protobuf:"bytes,1,rep,name=steps,proto3" json:"steps,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AttributePath) Reset() { *m = AttributePath{} } -func (m *AttributePath) String() string { return proto.CompactTextString(m) } -func (*AttributePath) ProtoMessage() {} -func (*AttributePath) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{2} -} -func (m *AttributePath) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AttributePath.Unmarshal(m, b) -} -func (m *AttributePath) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AttributePath.Marshal(b, m, deterministic) -} -func (dst *AttributePath) XXX_Merge(src proto.Message) { - xxx_messageInfo_AttributePath.Merge(dst, src) -} -func (m *AttributePath) XXX_Size() int { - return xxx_messageInfo_AttributePath.Size(m) -} -func (m *AttributePath) XXX_DiscardUnknown() { - xxx_messageInfo_AttributePath.DiscardUnknown(m) -} - -var xxx_messageInfo_AttributePath proto.InternalMessageInfo - -func (m *AttributePath) GetSteps() []*AttributePath_Step { - if m != nil { - return m.Steps - } - return nil -} - -type AttributePath_Step struct { - // Types that are valid to be assigned to Selector: - // *AttributePath_Step_AttributeName - // *AttributePath_Step_ElementKeyString - // *AttributePath_Step_ElementKeyInt - Selector isAttributePath_Step_Selector `protobuf_oneof:"selector"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AttributePath_Step) Reset() { *m = AttributePath_Step{} } -func (m *AttributePath_Step) String() string { return proto.CompactTextString(m) } -func (*AttributePath_Step) ProtoMessage() {} -func (*AttributePath_Step) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{2, 0} -} -func (m *AttributePath_Step) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AttributePath_Step.Unmarshal(m, b) -} -func (m *AttributePath_Step) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AttributePath_Step.Marshal(b, m, deterministic) -} -func (dst *AttributePath_Step) XXX_Merge(src proto.Message) { - xxx_messageInfo_AttributePath_Step.Merge(dst, src) -} -func (m *AttributePath_Step) XXX_Size() int { - return xxx_messageInfo_AttributePath_Step.Size(m) -} -func (m *AttributePath_Step) XXX_DiscardUnknown() { - xxx_messageInfo_AttributePath_Step.DiscardUnknown(m) -} - -var xxx_messageInfo_AttributePath_Step proto.InternalMessageInfo - -type isAttributePath_Step_Selector interface { - isAttributePath_Step_Selector() -} - -type AttributePath_Step_AttributeName struct { - AttributeName string `protobuf:"bytes,1,opt,name=attribute_name,json=attributeName,proto3,oneof"` -} - -type AttributePath_Step_ElementKeyString struct { - ElementKeyString string `protobuf:"bytes,2,opt,name=element_key_string,json=elementKeyString,proto3,oneof"` -} - -type AttributePath_Step_ElementKeyInt struct { - ElementKeyInt int64 `protobuf:"varint,3,opt,name=element_key_int,json=elementKeyInt,proto3,oneof"` -} - -func (*AttributePath_Step_AttributeName) isAttributePath_Step_Selector() {} - -func (*AttributePath_Step_ElementKeyString) isAttributePath_Step_Selector() {} - -func (*AttributePath_Step_ElementKeyInt) isAttributePath_Step_Selector() {} - -func (m *AttributePath_Step) GetSelector() isAttributePath_Step_Selector { - if m != nil { - return m.Selector - } - return nil -} - -func (m *AttributePath_Step) GetAttributeName() string { - if x, ok := m.GetSelector().(*AttributePath_Step_AttributeName); ok { - return x.AttributeName - } - return "" -} - -func (m *AttributePath_Step) GetElementKeyString() string { - if x, ok := m.GetSelector().(*AttributePath_Step_ElementKeyString); ok { - return x.ElementKeyString - } - return "" -} - -func (m *AttributePath_Step) GetElementKeyInt() int64 { - if x, ok := m.GetSelector().(*AttributePath_Step_ElementKeyInt); ok { - return x.ElementKeyInt - } - return 0 -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*AttributePath_Step) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _AttributePath_Step_OneofMarshaler, _AttributePath_Step_OneofUnmarshaler, _AttributePath_Step_OneofSizer, []interface{}{ - (*AttributePath_Step_AttributeName)(nil), - (*AttributePath_Step_ElementKeyString)(nil), - (*AttributePath_Step_ElementKeyInt)(nil), - } -} - -func _AttributePath_Step_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*AttributePath_Step) - // selector - switch x := m.Selector.(type) { - case *AttributePath_Step_AttributeName: - b.EncodeVarint(1<<3 | proto.WireBytes) - b.EncodeStringBytes(x.AttributeName) - case *AttributePath_Step_ElementKeyString: - b.EncodeVarint(2<<3 | proto.WireBytes) - b.EncodeStringBytes(x.ElementKeyString) - case *AttributePath_Step_ElementKeyInt: - b.EncodeVarint(3<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.ElementKeyInt)) - case nil: - default: - return fmt.Errorf("AttributePath_Step.Selector has unexpected type %T", x) - } - return nil -} - -func _AttributePath_Step_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*AttributePath_Step) - switch tag { - case 1: // selector.attribute_name - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Selector = &AttributePath_Step_AttributeName{x} - return true, err - case 2: // selector.element_key_string - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Selector = &AttributePath_Step_ElementKeyString{x} - return true, err - case 3: // selector.element_key_int - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Selector = &AttributePath_Step_ElementKeyInt{int64(x)} - return true, err - default: - return false, nil - } -} - -func _AttributePath_Step_OneofSizer(msg proto.Message) (n int) { - m := msg.(*AttributePath_Step) - // selector - switch x := m.Selector.(type) { - case *AttributePath_Step_AttributeName: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.AttributeName))) - n += len(x.AttributeName) - case *AttributePath_Step_ElementKeyString: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.ElementKeyString))) - n += len(x.ElementKeyString) - case *AttributePath_Step_ElementKeyInt: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.ElementKeyInt)) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type Stop struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Stop) Reset() { *m = Stop{} } -func (m *Stop) String() string { return proto.CompactTextString(m) } -func (*Stop) ProtoMessage() {} -func (*Stop) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{3} -} -func (m *Stop) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Stop.Unmarshal(m, b) -} -func (m *Stop) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Stop.Marshal(b, m, deterministic) -} -func (dst *Stop) XXX_Merge(src proto.Message) { - xxx_messageInfo_Stop.Merge(dst, src) -} -func (m *Stop) XXX_Size() int { - return xxx_messageInfo_Stop.Size(m) -} -func (m *Stop) XXX_DiscardUnknown() { - xxx_messageInfo_Stop.DiscardUnknown(m) -} - -var xxx_messageInfo_Stop proto.InternalMessageInfo - -type Stop_Request struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Stop_Request) Reset() { *m = Stop_Request{} } -func (m *Stop_Request) String() string { return proto.CompactTextString(m) } -func (*Stop_Request) ProtoMessage() {} -func (*Stop_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{3, 0} -} -func (m *Stop_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Stop_Request.Unmarshal(m, b) -} -func (m *Stop_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Stop_Request.Marshal(b, m, deterministic) -} -func (dst *Stop_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Stop_Request.Merge(dst, src) -} -func (m *Stop_Request) XXX_Size() int { - return xxx_messageInfo_Stop_Request.Size(m) -} -func (m *Stop_Request) XXX_DiscardUnknown() { - xxx_messageInfo_Stop_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Stop_Request proto.InternalMessageInfo - -type Stop_Response struct { - Error string `protobuf:"bytes,1,opt,name=Error,json=error,proto3" json:"Error,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Stop_Response) Reset() { *m = Stop_Response{} } -func (m *Stop_Response) String() string { return proto.CompactTextString(m) } -func (*Stop_Response) ProtoMessage() {} -func (*Stop_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{3, 1} -} -func (m *Stop_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Stop_Response.Unmarshal(m, b) -} -func (m *Stop_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Stop_Response.Marshal(b, m, deterministic) -} -func (dst *Stop_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_Stop_Response.Merge(dst, src) -} -func (m *Stop_Response) XXX_Size() int { - return xxx_messageInfo_Stop_Response.Size(m) -} -func (m *Stop_Response) XXX_DiscardUnknown() { - xxx_messageInfo_Stop_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_Stop_Response proto.InternalMessageInfo - -func (m *Stop_Response) GetError() string { - if m != nil { - return m.Error - } - return "" -} - -// RawState holds the stored state for a resource to be upgraded by the -// provider. It can be in one of two formats, the current json encoded format -// in bytes, or the legacy flatmap format as a map of strings. -type RawState struct { - Json []byte `protobuf:"bytes,1,opt,name=json,proto3" json:"json,omitempty"` - Flatmap map[string]string `protobuf:"bytes,2,rep,name=flatmap,proto3" json:"flatmap,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RawState) Reset() { *m = RawState{} } -func (m *RawState) String() string { return proto.CompactTextString(m) } -func (*RawState) ProtoMessage() {} -func (*RawState) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{4} -} -func (m *RawState) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RawState.Unmarshal(m, b) -} -func (m *RawState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RawState.Marshal(b, m, deterministic) -} -func (dst *RawState) XXX_Merge(src proto.Message) { - xxx_messageInfo_RawState.Merge(dst, src) -} -func (m *RawState) XXX_Size() int { - return xxx_messageInfo_RawState.Size(m) -} -func (m *RawState) XXX_DiscardUnknown() { - xxx_messageInfo_RawState.DiscardUnknown(m) -} - -var xxx_messageInfo_RawState proto.InternalMessageInfo - -func (m *RawState) GetJson() []byte { - if m != nil { - return m.Json - } - return nil -} - -func (m *RawState) GetFlatmap() map[string]string { - if m != nil { - return m.Flatmap - } - return nil -} - -// Schema is the configuration schema for a Resource, Provider, or Provisioner. -type Schema struct { - // The version of the schema. - // Schemas are versioned, so that providers can upgrade a saved resource - // state when the schema is changed. - Version int64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` - // Block is the top level configuration block for this schema. - Block *Schema_Block `protobuf:"bytes,2,opt,name=block,proto3" json:"block,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Schema) Reset() { *m = Schema{} } -func (m *Schema) String() string { return proto.CompactTextString(m) } -func (*Schema) ProtoMessage() {} -func (*Schema) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{5} -} -func (m *Schema) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Schema.Unmarshal(m, b) -} -func (m *Schema) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Schema.Marshal(b, m, deterministic) -} -func (dst *Schema) XXX_Merge(src proto.Message) { - xxx_messageInfo_Schema.Merge(dst, src) -} -func (m *Schema) XXX_Size() int { - return xxx_messageInfo_Schema.Size(m) -} -func (m *Schema) XXX_DiscardUnknown() { - xxx_messageInfo_Schema.DiscardUnknown(m) -} - -var xxx_messageInfo_Schema proto.InternalMessageInfo - -func (m *Schema) GetVersion() int64 { - if m != nil { - return m.Version - } - return 0 -} - -func (m *Schema) GetBlock() *Schema_Block { - if m != nil { - return m.Block - } - return nil -} - -type Schema_Block struct { - Version int64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` - Attributes []*Schema_Attribute `protobuf:"bytes,2,rep,name=attributes,proto3" json:"attributes,omitempty"` - BlockTypes []*Schema_NestedBlock `protobuf:"bytes,3,rep,name=block_types,json=blockTypes,proto3" json:"block_types,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Schema_Block) Reset() { *m = Schema_Block{} } -func (m *Schema_Block) String() string { return proto.CompactTextString(m) } -func (*Schema_Block) ProtoMessage() {} -func (*Schema_Block) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{5, 0} -} -func (m *Schema_Block) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Schema_Block.Unmarshal(m, b) -} -func (m *Schema_Block) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Schema_Block.Marshal(b, m, deterministic) -} -func (dst *Schema_Block) XXX_Merge(src proto.Message) { - xxx_messageInfo_Schema_Block.Merge(dst, src) -} -func (m *Schema_Block) XXX_Size() int { - return xxx_messageInfo_Schema_Block.Size(m) -} -func (m *Schema_Block) XXX_DiscardUnknown() { - xxx_messageInfo_Schema_Block.DiscardUnknown(m) -} - -var xxx_messageInfo_Schema_Block proto.InternalMessageInfo - -func (m *Schema_Block) GetVersion() int64 { - if m != nil { - return m.Version - } - return 0 -} - -func (m *Schema_Block) GetAttributes() []*Schema_Attribute { - if m != nil { - return m.Attributes - } - return nil -} - -func (m *Schema_Block) GetBlockTypes() []*Schema_NestedBlock { - if m != nil { - return m.BlockTypes - } - return nil -} - -type Schema_Attribute struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Type []byte `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` - Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` - Required bool `protobuf:"varint,4,opt,name=required,proto3" json:"required,omitempty"` - Optional bool `protobuf:"varint,5,opt,name=optional,proto3" json:"optional,omitempty"` - Computed bool `protobuf:"varint,6,opt,name=computed,proto3" json:"computed,omitempty"` - Sensitive bool `protobuf:"varint,7,opt,name=sensitive,proto3" json:"sensitive,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Schema_Attribute) Reset() { *m = Schema_Attribute{} } -func (m *Schema_Attribute) String() string { return proto.CompactTextString(m) } -func (*Schema_Attribute) ProtoMessage() {} -func (*Schema_Attribute) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{5, 1} -} -func (m *Schema_Attribute) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Schema_Attribute.Unmarshal(m, b) -} -func (m *Schema_Attribute) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Schema_Attribute.Marshal(b, m, deterministic) -} -func (dst *Schema_Attribute) XXX_Merge(src proto.Message) { - xxx_messageInfo_Schema_Attribute.Merge(dst, src) -} -func (m *Schema_Attribute) XXX_Size() int { - return xxx_messageInfo_Schema_Attribute.Size(m) -} -func (m *Schema_Attribute) XXX_DiscardUnknown() { - xxx_messageInfo_Schema_Attribute.DiscardUnknown(m) -} - -var xxx_messageInfo_Schema_Attribute proto.InternalMessageInfo - -func (m *Schema_Attribute) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Schema_Attribute) GetType() []byte { - if m != nil { - return m.Type - } - return nil -} - -func (m *Schema_Attribute) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *Schema_Attribute) GetRequired() bool { - if m != nil { - return m.Required - } - return false -} - -func (m *Schema_Attribute) GetOptional() bool { - if m != nil { - return m.Optional - } - return false -} - -func (m *Schema_Attribute) GetComputed() bool { - if m != nil { - return m.Computed - } - return false -} - -func (m *Schema_Attribute) GetSensitive() bool { - if m != nil { - return m.Sensitive - } - return false -} - -type Schema_NestedBlock struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - Block *Schema_Block `protobuf:"bytes,2,opt,name=block,proto3" json:"block,omitempty"` - Nesting Schema_NestedBlock_NestingMode `protobuf:"varint,3,opt,name=nesting,proto3,enum=tfplugin5.Schema_NestedBlock_NestingMode" json:"nesting,omitempty"` - MinItems int64 `protobuf:"varint,4,opt,name=min_items,json=minItems,proto3" json:"min_items,omitempty"` - MaxItems int64 `protobuf:"varint,5,opt,name=max_items,json=maxItems,proto3" json:"max_items,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Schema_NestedBlock) Reset() { *m = Schema_NestedBlock{} } -func (m *Schema_NestedBlock) String() string { return proto.CompactTextString(m) } -func (*Schema_NestedBlock) ProtoMessage() {} -func (*Schema_NestedBlock) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{5, 2} -} -func (m *Schema_NestedBlock) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Schema_NestedBlock.Unmarshal(m, b) -} -func (m *Schema_NestedBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Schema_NestedBlock.Marshal(b, m, deterministic) -} -func (dst *Schema_NestedBlock) XXX_Merge(src proto.Message) { - xxx_messageInfo_Schema_NestedBlock.Merge(dst, src) -} -func (m *Schema_NestedBlock) XXX_Size() int { - return xxx_messageInfo_Schema_NestedBlock.Size(m) -} -func (m *Schema_NestedBlock) XXX_DiscardUnknown() { - xxx_messageInfo_Schema_NestedBlock.DiscardUnknown(m) -} - -var xxx_messageInfo_Schema_NestedBlock proto.InternalMessageInfo - -func (m *Schema_NestedBlock) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *Schema_NestedBlock) GetBlock() *Schema_Block { - if m != nil { - return m.Block - } - return nil -} - -func (m *Schema_NestedBlock) GetNesting() Schema_NestedBlock_NestingMode { - if m != nil { - return m.Nesting - } - return Schema_NestedBlock_INVALID -} - -func (m *Schema_NestedBlock) GetMinItems() int64 { - if m != nil { - return m.MinItems - } - return 0 -} - -func (m *Schema_NestedBlock) GetMaxItems() int64 { - if m != nil { - return m.MaxItems - } - return 0 -} - -type GetProviderSchema struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetProviderSchema) Reset() { *m = GetProviderSchema{} } -func (m *GetProviderSchema) String() string { return proto.CompactTextString(m) } -func (*GetProviderSchema) ProtoMessage() {} -func (*GetProviderSchema) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{6} -} -func (m *GetProviderSchema) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetProviderSchema.Unmarshal(m, b) -} -func (m *GetProviderSchema) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetProviderSchema.Marshal(b, m, deterministic) -} -func (dst *GetProviderSchema) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetProviderSchema.Merge(dst, src) -} -func (m *GetProviderSchema) XXX_Size() int { - return xxx_messageInfo_GetProviderSchema.Size(m) -} -func (m *GetProviderSchema) XXX_DiscardUnknown() { - xxx_messageInfo_GetProviderSchema.DiscardUnknown(m) -} - -var xxx_messageInfo_GetProviderSchema proto.InternalMessageInfo - -type GetProviderSchema_Request struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetProviderSchema_Request) Reset() { *m = GetProviderSchema_Request{} } -func (m *GetProviderSchema_Request) String() string { return proto.CompactTextString(m) } -func (*GetProviderSchema_Request) ProtoMessage() {} -func (*GetProviderSchema_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{6, 0} -} -func (m *GetProviderSchema_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetProviderSchema_Request.Unmarshal(m, b) -} -func (m *GetProviderSchema_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetProviderSchema_Request.Marshal(b, m, deterministic) -} -func (dst *GetProviderSchema_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetProviderSchema_Request.Merge(dst, src) -} -func (m *GetProviderSchema_Request) XXX_Size() int { - return xxx_messageInfo_GetProviderSchema_Request.Size(m) -} -func (m *GetProviderSchema_Request) XXX_DiscardUnknown() { - xxx_messageInfo_GetProviderSchema_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_GetProviderSchema_Request proto.InternalMessageInfo - -type GetProviderSchema_Response struct { - Provider *Schema `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"` - ResourceSchemas map[string]*Schema `protobuf:"bytes,2,rep,name=resource_schemas,json=resourceSchemas,proto3" json:"resource_schemas,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - DataSourceSchemas map[string]*Schema `protobuf:"bytes,3,rep,name=data_source_schemas,json=dataSourceSchemas,proto3" json:"data_source_schemas,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Diagnostics []*Diagnostic `protobuf:"bytes,4,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetProviderSchema_Response) Reset() { *m = GetProviderSchema_Response{} } -func (m *GetProviderSchema_Response) String() string { return proto.CompactTextString(m) } -func (*GetProviderSchema_Response) ProtoMessage() {} -func (*GetProviderSchema_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{6, 1} -} -func (m *GetProviderSchema_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetProviderSchema_Response.Unmarshal(m, b) -} -func (m *GetProviderSchema_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetProviderSchema_Response.Marshal(b, m, deterministic) -} -func (dst *GetProviderSchema_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetProviderSchema_Response.Merge(dst, src) -} -func (m *GetProviderSchema_Response) XXX_Size() int { - return xxx_messageInfo_GetProviderSchema_Response.Size(m) -} -func (m *GetProviderSchema_Response) XXX_DiscardUnknown() { - xxx_messageInfo_GetProviderSchema_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_GetProviderSchema_Response proto.InternalMessageInfo - -func (m *GetProviderSchema_Response) GetProvider() *Schema { - if m != nil { - return m.Provider - } - return nil -} - -func (m *GetProviderSchema_Response) GetResourceSchemas() map[string]*Schema { - if m != nil { - return m.ResourceSchemas - } - return nil -} - -func (m *GetProviderSchema_Response) GetDataSourceSchemas() map[string]*Schema { - if m != nil { - return m.DataSourceSchemas - } - return nil -} - -func (m *GetProviderSchema_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type PrepareProviderConfig struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PrepareProviderConfig) Reset() { *m = PrepareProviderConfig{} } -func (m *PrepareProviderConfig) String() string { return proto.CompactTextString(m) } -func (*PrepareProviderConfig) ProtoMessage() {} -func (*PrepareProviderConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{7} -} -func (m *PrepareProviderConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PrepareProviderConfig.Unmarshal(m, b) -} -func (m *PrepareProviderConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PrepareProviderConfig.Marshal(b, m, deterministic) -} -func (dst *PrepareProviderConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_PrepareProviderConfig.Merge(dst, src) -} -func (m *PrepareProviderConfig) XXX_Size() int { - return xxx_messageInfo_PrepareProviderConfig.Size(m) -} -func (m *PrepareProviderConfig) XXX_DiscardUnknown() { - xxx_messageInfo_PrepareProviderConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_PrepareProviderConfig proto.InternalMessageInfo - -type PrepareProviderConfig_Request struct { - Config *DynamicValue `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PrepareProviderConfig_Request) Reset() { *m = PrepareProviderConfig_Request{} } -func (m *PrepareProviderConfig_Request) String() string { return proto.CompactTextString(m) } -func (*PrepareProviderConfig_Request) ProtoMessage() {} -func (*PrepareProviderConfig_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{7, 0} -} -func (m *PrepareProviderConfig_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PrepareProviderConfig_Request.Unmarshal(m, b) -} -func (m *PrepareProviderConfig_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PrepareProviderConfig_Request.Marshal(b, m, deterministic) -} -func (dst *PrepareProviderConfig_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_PrepareProviderConfig_Request.Merge(dst, src) -} -func (m *PrepareProviderConfig_Request) XXX_Size() int { - return xxx_messageInfo_PrepareProviderConfig_Request.Size(m) -} -func (m *PrepareProviderConfig_Request) XXX_DiscardUnknown() { - xxx_messageInfo_PrepareProviderConfig_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_PrepareProviderConfig_Request proto.InternalMessageInfo - -func (m *PrepareProviderConfig_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -type PrepareProviderConfig_Response struct { - PreparedConfig *DynamicValue `protobuf:"bytes,1,opt,name=prepared_config,json=preparedConfig,proto3" json:"prepared_config,omitempty"` - Diagnostics []*Diagnostic `protobuf:"bytes,2,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PrepareProviderConfig_Response) Reset() { *m = PrepareProviderConfig_Response{} } -func (m *PrepareProviderConfig_Response) String() string { return proto.CompactTextString(m) } -func (*PrepareProviderConfig_Response) ProtoMessage() {} -func (*PrepareProviderConfig_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{7, 1} -} -func (m *PrepareProviderConfig_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PrepareProviderConfig_Response.Unmarshal(m, b) -} -func (m *PrepareProviderConfig_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PrepareProviderConfig_Response.Marshal(b, m, deterministic) -} -func (dst *PrepareProviderConfig_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_PrepareProviderConfig_Response.Merge(dst, src) -} -func (m *PrepareProviderConfig_Response) XXX_Size() int { - return xxx_messageInfo_PrepareProviderConfig_Response.Size(m) -} -func (m *PrepareProviderConfig_Response) XXX_DiscardUnknown() { - xxx_messageInfo_PrepareProviderConfig_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_PrepareProviderConfig_Response proto.InternalMessageInfo - -func (m *PrepareProviderConfig_Response) GetPreparedConfig() *DynamicValue { - if m != nil { - return m.PreparedConfig - } - return nil -} - -func (m *PrepareProviderConfig_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type UpgradeResourceState struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpgradeResourceState) Reset() { *m = UpgradeResourceState{} } -func (m *UpgradeResourceState) String() string { return proto.CompactTextString(m) } -func (*UpgradeResourceState) ProtoMessage() {} -func (*UpgradeResourceState) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{8} -} -func (m *UpgradeResourceState) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpgradeResourceState.Unmarshal(m, b) -} -func (m *UpgradeResourceState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpgradeResourceState.Marshal(b, m, deterministic) -} -func (dst *UpgradeResourceState) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpgradeResourceState.Merge(dst, src) -} -func (m *UpgradeResourceState) XXX_Size() int { - return xxx_messageInfo_UpgradeResourceState.Size(m) -} -func (m *UpgradeResourceState) XXX_DiscardUnknown() { - xxx_messageInfo_UpgradeResourceState.DiscardUnknown(m) -} - -var xxx_messageInfo_UpgradeResourceState proto.InternalMessageInfo - -type UpgradeResourceState_Request struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - // version is the schema_version number recorded in the state file - Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` - // raw_state is the raw states as stored for the resource. Core does - // not have access to the schema of prior_version, so it's the - // provider's responsibility to interpret this value using the - // appropriate older schema. The raw_state will be the json encoded - // state, or a legacy flat-mapped format. - RawState *RawState `protobuf:"bytes,3,opt,name=raw_state,json=rawState,proto3" json:"raw_state,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpgradeResourceState_Request) Reset() { *m = UpgradeResourceState_Request{} } -func (m *UpgradeResourceState_Request) String() string { return proto.CompactTextString(m) } -func (*UpgradeResourceState_Request) ProtoMessage() {} -func (*UpgradeResourceState_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{8, 0} -} -func (m *UpgradeResourceState_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpgradeResourceState_Request.Unmarshal(m, b) -} -func (m *UpgradeResourceState_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpgradeResourceState_Request.Marshal(b, m, deterministic) -} -func (dst *UpgradeResourceState_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpgradeResourceState_Request.Merge(dst, src) -} -func (m *UpgradeResourceState_Request) XXX_Size() int { - return xxx_messageInfo_UpgradeResourceState_Request.Size(m) -} -func (m *UpgradeResourceState_Request) XXX_DiscardUnknown() { - xxx_messageInfo_UpgradeResourceState_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_UpgradeResourceState_Request proto.InternalMessageInfo - -func (m *UpgradeResourceState_Request) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *UpgradeResourceState_Request) GetVersion() int64 { - if m != nil { - return m.Version - } - return 0 -} - -func (m *UpgradeResourceState_Request) GetRawState() *RawState { - if m != nil { - return m.RawState - } - return nil -} - -type UpgradeResourceState_Response struct { - // new_state is a msgpack-encoded data structure that, when interpreted with - // the _current_ schema for this resource type, is functionally equivalent to - // that which was given in prior_state_raw. - UpgradedState *DynamicValue `protobuf:"bytes,1,opt,name=upgraded_state,json=upgradedState,proto3" json:"upgraded_state,omitempty"` - // diagnostics describes any errors encountered during migration that could not - // be safely resolved, and warnings about any possibly-risky assumptions made - // in the upgrade process. - Diagnostics []*Diagnostic `protobuf:"bytes,2,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpgradeResourceState_Response) Reset() { *m = UpgradeResourceState_Response{} } -func (m *UpgradeResourceState_Response) String() string { return proto.CompactTextString(m) } -func (*UpgradeResourceState_Response) ProtoMessage() {} -func (*UpgradeResourceState_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{8, 1} -} -func (m *UpgradeResourceState_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpgradeResourceState_Response.Unmarshal(m, b) -} -func (m *UpgradeResourceState_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpgradeResourceState_Response.Marshal(b, m, deterministic) -} -func (dst *UpgradeResourceState_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpgradeResourceState_Response.Merge(dst, src) -} -func (m *UpgradeResourceState_Response) XXX_Size() int { - return xxx_messageInfo_UpgradeResourceState_Response.Size(m) -} -func (m *UpgradeResourceState_Response) XXX_DiscardUnknown() { - xxx_messageInfo_UpgradeResourceState_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_UpgradeResourceState_Response proto.InternalMessageInfo - -func (m *UpgradeResourceState_Response) GetUpgradedState() *DynamicValue { - if m != nil { - return m.UpgradedState - } - return nil -} - -func (m *UpgradeResourceState_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type ValidateResourceTypeConfig struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateResourceTypeConfig) Reset() { *m = ValidateResourceTypeConfig{} } -func (m *ValidateResourceTypeConfig) String() string { return proto.CompactTextString(m) } -func (*ValidateResourceTypeConfig) ProtoMessage() {} -func (*ValidateResourceTypeConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{9} -} -func (m *ValidateResourceTypeConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateResourceTypeConfig.Unmarshal(m, b) -} -func (m *ValidateResourceTypeConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateResourceTypeConfig.Marshal(b, m, deterministic) -} -func (dst *ValidateResourceTypeConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateResourceTypeConfig.Merge(dst, src) -} -func (m *ValidateResourceTypeConfig) XXX_Size() int { - return xxx_messageInfo_ValidateResourceTypeConfig.Size(m) -} -func (m *ValidateResourceTypeConfig) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateResourceTypeConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateResourceTypeConfig proto.InternalMessageInfo - -type ValidateResourceTypeConfig_Request struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - Config *DynamicValue `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateResourceTypeConfig_Request) Reset() { *m = ValidateResourceTypeConfig_Request{} } -func (m *ValidateResourceTypeConfig_Request) String() string { return proto.CompactTextString(m) } -func (*ValidateResourceTypeConfig_Request) ProtoMessage() {} -func (*ValidateResourceTypeConfig_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{9, 0} -} -func (m *ValidateResourceTypeConfig_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateResourceTypeConfig_Request.Unmarshal(m, b) -} -func (m *ValidateResourceTypeConfig_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateResourceTypeConfig_Request.Marshal(b, m, deterministic) -} -func (dst *ValidateResourceTypeConfig_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateResourceTypeConfig_Request.Merge(dst, src) -} -func (m *ValidateResourceTypeConfig_Request) XXX_Size() int { - return xxx_messageInfo_ValidateResourceTypeConfig_Request.Size(m) -} -func (m *ValidateResourceTypeConfig_Request) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateResourceTypeConfig_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateResourceTypeConfig_Request proto.InternalMessageInfo - -func (m *ValidateResourceTypeConfig_Request) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *ValidateResourceTypeConfig_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -type ValidateResourceTypeConfig_Response struct { - Diagnostics []*Diagnostic `protobuf:"bytes,1,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateResourceTypeConfig_Response) Reset() { *m = ValidateResourceTypeConfig_Response{} } -func (m *ValidateResourceTypeConfig_Response) String() string { return proto.CompactTextString(m) } -func (*ValidateResourceTypeConfig_Response) ProtoMessage() {} -func (*ValidateResourceTypeConfig_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{9, 1} -} -func (m *ValidateResourceTypeConfig_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateResourceTypeConfig_Response.Unmarshal(m, b) -} -func (m *ValidateResourceTypeConfig_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateResourceTypeConfig_Response.Marshal(b, m, deterministic) -} -func (dst *ValidateResourceTypeConfig_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateResourceTypeConfig_Response.Merge(dst, src) -} -func (m *ValidateResourceTypeConfig_Response) XXX_Size() int { - return xxx_messageInfo_ValidateResourceTypeConfig_Response.Size(m) -} -func (m *ValidateResourceTypeConfig_Response) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateResourceTypeConfig_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateResourceTypeConfig_Response proto.InternalMessageInfo - -func (m *ValidateResourceTypeConfig_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type ValidateDataSourceConfig struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateDataSourceConfig) Reset() { *m = ValidateDataSourceConfig{} } -func (m *ValidateDataSourceConfig) String() string { return proto.CompactTextString(m) } -func (*ValidateDataSourceConfig) ProtoMessage() {} -func (*ValidateDataSourceConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{10} -} -func (m *ValidateDataSourceConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateDataSourceConfig.Unmarshal(m, b) -} -func (m *ValidateDataSourceConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateDataSourceConfig.Marshal(b, m, deterministic) -} -func (dst *ValidateDataSourceConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateDataSourceConfig.Merge(dst, src) -} -func (m *ValidateDataSourceConfig) XXX_Size() int { - return xxx_messageInfo_ValidateDataSourceConfig.Size(m) -} -func (m *ValidateDataSourceConfig) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateDataSourceConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateDataSourceConfig proto.InternalMessageInfo - -type ValidateDataSourceConfig_Request struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - Config *DynamicValue `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateDataSourceConfig_Request) Reset() { *m = ValidateDataSourceConfig_Request{} } -func (m *ValidateDataSourceConfig_Request) String() string { return proto.CompactTextString(m) } -func (*ValidateDataSourceConfig_Request) ProtoMessage() {} -func (*ValidateDataSourceConfig_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{10, 0} -} -func (m *ValidateDataSourceConfig_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateDataSourceConfig_Request.Unmarshal(m, b) -} -func (m *ValidateDataSourceConfig_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateDataSourceConfig_Request.Marshal(b, m, deterministic) -} -func (dst *ValidateDataSourceConfig_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateDataSourceConfig_Request.Merge(dst, src) -} -func (m *ValidateDataSourceConfig_Request) XXX_Size() int { - return xxx_messageInfo_ValidateDataSourceConfig_Request.Size(m) -} -func (m *ValidateDataSourceConfig_Request) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateDataSourceConfig_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateDataSourceConfig_Request proto.InternalMessageInfo - -func (m *ValidateDataSourceConfig_Request) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *ValidateDataSourceConfig_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -type ValidateDataSourceConfig_Response struct { - Diagnostics []*Diagnostic `protobuf:"bytes,1,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateDataSourceConfig_Response) Reset() { *m = ValidateDataSourceConfig_Response{} } -func (m *ValidateDataSourceConfig_Response) String() string { return proto.CompactTextString(m) } -func (*ValidateDataSourceConfig_Response) ProtoMessage() {} -func (*ValidateDataSourceConfig_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{10, 1} -} -func (m *ValidateDataSourceConfig_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateDataSourceConfig_Response.Unmarshal(m, b) -} -func (m *ValidateDataSourceConfig_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateDataSourceConfig_Response.Marshal(b, m, deterministic) -} -func (dst *ValidateDataSourceConfig_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateDataSourceConfig_Response.Merge(dst, src) -} -func (m *ValidateDataSourceConfig_Response) XXX_Size() int { - return xxx_messageInfo_ValidateDataSourceConfig_Response.Size(m) -} -func (m *ValidateDataSourceConfig_Response) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateDataSourceConfig_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateDataSourceConfig_Response proto.InternalMessageInfo - -func (m *ValidateDataSourceConfig_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type Configure struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Configure) Reset() { *m = Configure{} } -func (m *Configure) String() string { return proto.CompactTextString(m) } -func (*Configure) ProtoMessage() {} -func (*Configure) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{11} -} -func (m *Configure) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Configure.Unmarshal(m, b) -} -func (m *Configure) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Configure.Marshal(b, m, deterministic) -} -func (dst *Configure) XXX_Merge(src proto.Message) { - xxx_messageInfo_Configure.Merge(dst, src) -} -func (m *Configure) XXX_Size() int { - return xxx_messageInfo_Configure.Size(m) -} -func (m *Configure) XXX_DiscardUnknown() { - xxx_messageInfo_Configure.DiscardUnknown(m) -} - -var xxx_messageInfo_Configure proto.InternalMessageInfo - -type Configure_Request struct { - TerraformVersion string `protobuf:"bytes,1,opt,name=terraform_version,json=terraformVersion,proto3" json:"terraform_version,omitempty"` - Config *DynamicValue `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Configure_Request) Reset() { *m = Configure_Request{} } -func (m *Configure_Request) String() string { return proto.CompactTextString(m) } -func (*Configure_Request) ProtoMessage() {} -func (*Configure_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{11, 0} -} -func (m *Configure_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Configure_Request.Unmarshal(m, b) -} -func (m *Configure_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Configure_Request.Marshal(b, m, deterministic) -} -func (dst *Configure_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Configure_Request.Merge(dst, src) -} -func (m *Configure_Request) XXX_Size() int { - return xxx_messageInfo_Configure_Request.Size(m) -} -func (m *Configure_Request) XXX_DiscardUnknown() { - xxx_messageInfo_Configure_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Configure_Request proto.InternalMessageInfo - -func (m *Configure_Request) GetTerraformVersion() string { - if m != nil { - return m.TerraformVersion - } - return "" -} - -func (m *Configure_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -type Configure_Response struct { - Diagnostics []*Diagnostic `protobuf:"bytes,1,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Configure_Response) Reset() { *m = Configure_Response{} } -func (m *Configure_Response) String() string { return proto.CompactTextString(m) } -func (*Configure_Response) ProtoMessage() {} -func (*Configure_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{11, 1} -} -func (m *Configure_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Configure_Response.Unmarshal(m, b) -} -func (m *Configure_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Configure_Response.Marshal(b, m, deterministic) -} -func (dst *Configure_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_Configure_Response.Merge(dst, src) -} -func (m *Configure_Response) XXX_Size() int { - return xxx_messageInfo_Configure_Response.Size(m) -} -func (m *Configure_Response) XXX_DiscardUnknown() { - xxx_messageInfo_Configure_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_Configure_Response proto.InternalMessageInfo - -func (m *Configure_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type ReadResource struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadResource) Reset() { *m = ReadResource{} } -func (m *ReadResource) String() string { return proto.CompactTextString(m) } -func (*ReadResource) ProtoMessage() {} -func (*ReadResource) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{12} -} -func (m *ReadResource) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadResource.Unmarshal(m, b) -} -func (m *ReadResource) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadResource.Marshal(b, m, deterministic) -} -func (dst *ReadResource) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadResource.Merge(dst, src) -} -func (m *ReadResource) XXX_Size() int { - return xxx_messageInfo_ReadResource.Size(m) -} -func (m *ReadResource) XXX_DiscardUnknown() { - xxx_messageInfo_ReadResource.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadResource proto.InternalMessageInfo - -type ReadResource_Request struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - CurrentState *DynamicValue `protobuf:"bytes,2,opt,name=current_state,json=currentState,proto3" json:"current_state,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadResource_Request) Reset() { *m = ReadResource_Request{} } -func (m *ReadResource_Request) String() string { return proto.CompactTextString(m) } -func (*ReadResource_Request) ProtoMessage() {} -func (*ReadResource_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{12, 0} -} -func (m *ReadResource_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadResource_Request.Unmarshal(m, b) -} -func (m *ReadResource_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadResource_Request.Marshal(b, m, deterministic) -} -func (dst *ReadResource_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadResource_Request.Merge(dst, src) -} -func (m *ReadResource_Request) XXX_Size() int { - return xxx_messageInfo_ReadResource_Request.Size(m) -} -func (m *ReadResource_Request) XXX_DiscardUnknown() { - xxx_messageInfo_ReadResource_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadResource_Request proto.InternalMessageInfo - -func (m *ReadResource_Request) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *ReadResource_Request) GetCurrentState() *DynamicValue { - if m != nil { - return m.CurrentState - } - return nil -} - -type ReadResource_Response struct { - NewState *DynamicValue `protobuf:"bytes,1,opt,name=new_state,json=newState,proto3" json:"new_state,omitempty"` - Diagnostics []*Diagnostic `protobuf:"bytes,2,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadResource_Response) Reset() { *m = ReadResource_Response{} } -func (m *ReadResource_Response) String() string { return proto.CompactTextString(m) } -func (*ReadResource_Response) ProtoMessage() {} -func (*ReadResource_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{12, 1} -} -func (m *ReadResource_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadResource_Response.Unmarshal(m, b) -} -func (m *ReadResource_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadResource_Response.Marshal(b, m, deterministic) -} -func (dst *ReadResource_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadResource_Response.Merge(dst, src) -} -func (m *ReadResource_Response) XXX_Size() int { - return xxx_messageInfo_ReadResource_Response.Size(m) -} -func (m *ReadResource_Response) XXX_DiscardUnknown() { - xxx_messageInfo_ReadResource_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadResource_Response proto.InternalMessageInfo - -func (m *ReadResource_Response) GetNewState() *DynamicValue { - if m != nil { - return m.NewState - } - return nil -} - -func (m *ReadResource_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type PlanResourceChange struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PlanResourceChange) Reset() { *m = PlanResourceChange{} } -func (m *PlanResourceChange) String() string { return proto.CompactTextString(m) } -func (*PlanResourceChange) ProtoMessage() {} -func (*PlanResourceChange) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{13} -} -func (m *PlanResourceChange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PlanResourceChange.Unmarshal(m, b) -} -func (m *PlanResourceChange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PlanResourceChange.Marshal(b, m, deterministic) -} -func (dst *PlanResourceChange) XXX_Merge(src proto.Message) { - xxx_messageInfo_PlanResourceChange.Merge(dst, src) -} -func (m *PlanResourceChange) XXX_Size() int { - return xxx_messageInfo_PlanResourceChange.Size(m) -} -func (m *PlanResourceChange) XXX_DiscardUnknown() { - xxx_messageInfo_PlanResourceChange.DiscardUnknown(m) -} - -var xxx_messageInfo_PlanResourceChange proto.InternalMessageInfo - -type PlanResourceChange_Request struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - PriorState *DynamicValue `protobuf:"bytes,2,opt,name=prior_state,json=priorState,proto3" json:"prior_state,omitempty"` - ProposedNewState *DynamicValue `protobuf:"bytes,3,opt,name=proposed_new_state,json=proposedNewState,proto3" json:"proposed_new_state,omitempty"` - Config *DynamicValue `protobuf:"bytes,4,opt,name=config,proto3" json:"config,omitempty"` - PriorPrivate []byte `protobuf:"bytes,5,opt,name=prior_private,json=priorPrivate,proto3" json:"prior_private,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PlanResourceChange_Request) Reset() { *m = PlanResourceChange_Request{} } -func (m *PlanResourceChange_Request) String() string { return proto.CompactTextString(m) } -func (*PlanResourceChange_Request) ProtoMessage() {} -func (*PlanResourceChange_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{13, 0} -} -func (m *PlanResourceChange_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PlanResourceChange_Request.Unmarshal(m, b) -} -func (m *PlanResourceChange_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PlanResourceChange_Request.Marshal(b, m, deterministic) -} -func (dst *PlanResourceChange_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_PlanResourceChange_Request.Merge(dst, src) -} -func (m *PlanResourceChange_Request) XXX_Size() int { - return xxx_messageInfo_PlanResourceChange_Request.Size(m) -} -func (m *PlanResourceChange_Request) XXX_DiscardUnknown() { - xxx_messageInfo_PlanResourceChange_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_PlanResourceChange_Request proto.InternalMessageInfo - -func (m *PlanResourceChange_Request) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *PlanResourceChange_Request) GetPriorState() *DynamicValue { - if m != nil { - return m.PriorState - } - return nil -} - -func (m *PlanResourceChange_Request) GetProposedNewState() *DynamicValue { - if m != nil { - return m.ProposedNewState - } - return nil -} - -func (m *PlanResourceChange_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -func (m *PlanResourceChange_Request) GetPriorPrivate() []byte { - if m != nil { - return m.PriorPrivate - } - return nil -} - -type PlanResourceChange_Response struct { - PlannedState *DynamicValue `protobuf:"bytes,1,opt,name=planned_state,json=plannedState,proto3" json:"planned_state,omitempty"` - RequiresReplace []*AttributePath `protobuf:"bytes,2,rep,name=requires_replace,json=requiresReplace,proto3" json:"requires_replace,omitempty"` - PlannedPrivate []byte `protobuf:"bytes,3,opt,name=planned_private,json=plannedPrivate,proto3" json:"planned_private,omitempty"` - Diagnostics []*Diagnostic `protobuf:"bytes,4,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - // This may be set only by the helper/schema "SDK" in the main Terraform - // repository, to request that Terraform Core >=0.12 permit additional - // inconsistencies that can result from the legacy SDK type system - // and its imprecise mapping to the >=0.12 type system. - // The change in behavior implied by this flag makes sense only for the - // specific details of the legacy SDK type system, and are not a general - // mechanism to avoid proper type handling in providers. - // - // ==== DO NOT USE THIS ==== - // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== - // ==== DO NOT USE THIS ==== - LegacyTypeSystem bool `protobuf:"varint,5,opt,name=legacy_type_system,json=legacyTypeSystem,proto3" json:"legacy_type_system,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PlanResourceChange_Response) Reset() { *m = PlanResourceChange_Response{} } -func (m *PlanResourceChange_Response) String() string { return proto.CompactTextString(m) } -func (*PlanResourceChange_Response) ProtoMessage() {} -func (*PlanResourceChange_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{13, 1} -} -func (m *PlanResourceChange_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PlanResourceChange_Response.Unmarshal(m, b) -} -func (m *PlanResourceChange_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PlanResourceChange_Response.Marshal(b, m, deterministic) -} -func (dst *PlanResourceChange_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_PlanResourceChange_Response.Merge(dst, src) -} -func (m *PlanResourceChange_Response) XXX_Size() int { - return xxx_messageInfo_PlanResourceChange_Response.Size(m) -} -func (m *PlanResourceChange_Response) XXX_DiscardUnknown() { - xxx_messageInfo_PlanResourceChange_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_PlanResourceChange_Response proto.InternalMessageInfo - -func (m *PlanResourceChange_Response) GetPlannedState() *DynamicValue { - if m != nil { - return m.PlannedState - } - return nil -} - -func (m *PlanResourceChange_Response) GetRequiresReplace() []*AttributePath { - if m != nil { - return m.RequiresReplace - } - return nil -} - -func (m *PlanResourceChange_Response) GetPlannedPrivate() []byte { - if m != nil { - return m.PlannedPrivate - } - return nil -} - -func (m *PlanResourceChange_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -func (m *PlanResourceChange_Response) GetLegacyTypeSystem() bool { - if m != nil { - return m.LegacyTypeSystem - } - return false -} - -type ApplyResourceChange struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ApplyResourceChange) Reset() { *m = ApplyResourceChange{} } -func (m *ApplyResourceChange) String() string { return proto.CompactTextString(m) } -func (*ApplyResourceChange) ProtoMessage() {} -func (*ApplyResourceChange) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{14} -} -func (m *ApplyResourceChange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ApplyResourceChange.Unmarshal(m, b) -} -func (m *ApplyResourceChange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ApplyResourceChange.Marshal(b, m, deterministic) -} -func (dst *ApplyResourceChange) XXX_Merge(src proto.Message) { - xxx_messageInfo_ApplyResourceChange.Merge(dst, src) -} -func (m *ApplyResourceChange) XXX_Size() int { - return xxx_messageInfo_ApplyResourceChange.Size(m) -} -func (m *ApplyResourceChange) XXX_DiscardUnknown() { - xxx_messageInfo_ApplyResourceChange.DiscardUnknown(m) -} - -var xxx_messageInfo_ApplyResourceChange proto.InternalMessageInfo - -type ApplyResourceChange_Request struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - PriorState *DynamicValue `protobuf:"bytes,2,opt,name=prior_state,json=priorState,proto3" json:"prior_state,omitempty"` - PlannedState *DynamicValue `protobuf:"bytes,3,opt,name=planned_state,json=plannedState,proto3" json:"planned_state,omitempty"` - Config *DynamicValue `protobuf:"bytes,4,opt,name=config,proto3" json:"config,omitempty"` - PlannedPrivate []byte `protobuf:"bytes,5,opt,name=planned_private,json=plannedPrivate,proto3" json:"planned_private,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ApplyResourceChange_Request) Reset() { *m = ApplyResourceChange_Request{} } -func (m *ApplyResourceChange_Request) String() string { return proto.CompactTextString(m) } -func (*ApplyResourceChange_Request) ProtoMessage() {} -func (*ApplyResourceChange_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{14, 0} -} -func (m *ApplyResourceChange_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ApplyResourceChange_Request.Unmarshal(m, b) -} -func (m *ApplyResourceChange_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ApplyResourceChange_Request.Marshal(b, m, deterministic) -} -func (dst *ApplyResourceChange_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_ApplyResourceChange_Request.Merge(dst, src) -} -func (m *ApplyResourceChange_Request) XXX_Size() int { - return xxx_messageInfo_ApplyResourceChange_Request.Size(m) -} -func (m *ApplyResourceChange_Request) XXX_DiscardUnknown() { - xxx_messageInfo_ApplyResourceChange_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_ApplyResourceChange_Request proto.InternalMessageInfo - -func (m *ApplyResourceChange_Request) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *ApplyResourceChange_Request) GetPriorState() *DynamicValue { - if m != nil { - return m.PriorState - } - return nil -} - -func (m *ApplyResourceChange_Request) GetPlannedState() *DynamicValue { - if m != nil { - return m.PlannedState - } - return nil -} - -func (m *ApplyResourceChange_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -func (m *ApplyResourceChange_Request) GetPlannedPrivate() []byte { - if m != nil { - return m.PlannedPrivate - } - return nil -} - -type ApplyResourceChange_Response struct { - NewState *DynamicValue `protobuf:"bytes,1,opt,name=new_state,json=newState,proto3" json:"new_state,omitempty"` - Private []byte `protobuf:"bytes,2,opt,name=private,proto3" json:"private,omitempty"` - Diagnostics []*Diagnostic `protobuf:"bytes,3,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - // This may be set only by the helper/schema "SDK" in the main Terraform - // repository, to request that Terraform Core >=0.12 permit additional - // inconsistencies that can result from the legacy SDK type system - // and its imprecise mapping to the >=0.12 type system. - // The change in behavior implied by this flag makes sense only for the - // specific details of the legacy SDK type system, and are not a general - // mechanism to avoid proper type handling in providers. - // - // ==== DO NOT USE THIS ==== - // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== - // ==== DO NOT USE THIS ==== - LegacyTypeSystem bool `protobuf:"varint,4,opt,name=legacy_type_system,json=legacyTypeSystem,proto3" json:"legacy_type_system,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ApplyResourceChange_Response) Reset() { *m = ApplyResourceChange_Response{} } -func (m *ApplyResourceChange_Response) String() string { return proto.CompactTextString(m) } -func (*ApplyResourceChange_Response) ProtoMessage() {} -func (*ApplyResourceChange_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{14, 1} -} -func (m *ApplyResourceChange_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ApplyResourceChange_Response.Unmarshal(m, b) -} -func (m *ApplyResourceChange_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ApplyResourceChange_Response.Marshal(b, m, deterministic) -} -func (dst *ApplyResourceChange_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_ApplyResourceChange_Response.Merge(dst, src) -} -func (m *ApplyResourceChange_Response) XXX_Size() int { - return xxx_messageInfo_ApplyResourceChange_Response.Size(m) -} -func (m *ApplyResourceChange_Response) XXX_DiscardUnknown() { - xxx_messageInfo_ApplyResourceChange_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_ApplyResourceChange_Response proto.InternalMessageInfo - -func (m *ApplyResourceChange_Response) GetNewState() *DynamicValue { - if m != nil { - return m.NewState - } - return nil -} - -func (m *ApplyResourceChange_Response) GetPrivate() []byte { - if m != nil { - return m.Private - } - return nil -} - -func (m *ApplyResourceChange_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -func (m *ApplyResourceChange_Response) GetLegacyTypeSystem() bool { - if m != nil { - return m.LegacyTypeSystem - } - return false -} - -type ImportResourceState struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ImportResourceState) Reset() { *m = ImportResourceState{} } -func (m *ImportResourceState) String() string { return proto.CompactTextString(m) } -func (*ImportResourceState) ProtoMessage() {} -func (*ImportResourceState) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{15} -} -func (m *ImportResourceState) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ImportResourceState.Unmarshal(m, b) -} -func (m *ImportResourceState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ImportResourceState.Marshal(b, m, deterministic) -} -func (dst *ImportResourceState) XXX_Merge(src proto.Message) { - xxx_messageInfo_ImportResourceState.Merge(dst, src) -} -func (m *ImportResourceState) XXX_Size() int { - return xxx_messageInfo_ImportResourceState.Size(m) -} -func (m *ImportResourceState) XXX_DiscardUnknown() { - xxx_messageInfo_ImportResourceState.DiscardUnknown(m) -} - -var xxx_messageInfo_ImportResourceState proto.InternalMessageInfo - -type ImportResourceState_Request struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ImportResourceState_Request) Reset() { *m = ImportResourceState_Request{} } -func (m *ImportResourceState_Request) String() string { return proto.CompactTextString(m) } -func (*ImportResourceState_Request) ProtoMessage() {} -func (*ImportResourceState_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{15, 0} -} -func (m *ImportResourceState_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ImportResourceState_Request.Unmarshal(m, b) -} -func (m *ImportResourceState_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ImportResourceState_Request.Marshal(b, m, deterministic) -} -func (dst *ImportResourceState_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_ImportResourceState_Request.Merge(dst, src) -} -func (m *ImportResourceState_Request) XXX_Size() int { - return xxx_messageInfo_ImportResourceState_Request.Size(m) -} -func (m *ImportResourceState_Request) XXX_DiscardUnknown() { - xxx_messageInfo_ImportResourceState_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_ImportResourceState_Request proto.InternalMessageInfo - -func (m *ImportResourceState_Request) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *ImportResourceState_Request) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -type ImportResourceState_ImportedResource struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - State *DynamicValue `protobuf:"bytes,2,opt,name=state,proto3" json:"state,omitempty"` - Private []byte `protobuf:"bytes,3,opt,name=private,proto3" json:"private,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ImportResourceState_ImportedResource) Reset() { *m = ImportResourceState_ImportedResource{} } -func (m *ImportResourceState_ImportedResource) String() string { return proto.CompactTextString(m) } -func (*ImportResourceState_ImportedResource) ProtoMessage() {} -func (*ImportResourceState_ImportedResource) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{15, 1} -} -func (m *ImportResourceState_ImportedResource) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ImportResourceState_ImportedResource.Unmarshal(m, b) -} -func (m *ImportResourceState_ImportedResource) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ImportResourceState_ImportedResource.Marshal(b, m, deterministic) -} -func (dst *ImportResourceState_ImportedResource) XXX_Merge(src proto.Message) { - xxx_messageInfo_ImportResourceState_ImportedResource.Merge(dst, src) -} -func (m *ImportResourceState_ImportedResource) XXX_Size() int { - return xxx_messageInfo_ImportResourceState_ImportedResource.Size(m) -} -func (m *ImportResourceState_ImportedResource) XXX_DiscardUnknown() { - xxx_messageInfo_ImportResourceState_ImportedResource.DiscardUnknown(m) -} - -var xxx_messageInfo_ImportResourceState_ImportedResource proto.InternalMessageInfo - -func (m *ImportResourceState_ImportedResource) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *ImportResourceState_ImportedResource) GetState() *DynamicValue { - if m != nil { - return m.State - } - return nil -} - -func (m *ImportResourceState_ImportedResource) GetPrivate() []byte { - if m != nil { - return m.Private - } - return nil -} - -type ImportResourceState_Response struct { - ImportedResources []*ImportResourceState_ImportedResource `protobuf:"bytes,1,rep,name=imported_resources,json=importedResources,proto3" json:"imported_resources,omitempty"` - Diagnostics []*Diagnostic `protobuf:"bytes,2,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ImportResourceState_Response) Reset() { *m = ImportResourceState_Response{} } -func (m *ImportResourceState_Response) String() string { return proto.CompactTextString(m) } -func (*ImportResourceState_Response) ProtoMessage() {} -func (*ImportResourceState_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{15, 2} -} -func (m *ImportResourceState_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ImportResourceState_Response.Unmarshal(m, b) -} -func (m *ImportResourceState_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ImportResourceState_Response.Marshal(b, m, deterministic) -} -func (dst *ImportResourceState_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_ImportResourceState_Response.Merge(dst, src) -} -func (m *ImportResourceState_Response) XXX_Size() int { - return xxx_messageInfo_ImportResourceState_Response.Size(m) -} -func (m *ImportResourceState_Response) XXX_DiscardUnknown() { - xxx_messageInfo_ImportResourceState_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_ImportResourceState_Response proto.InternalMessageInfo - -func (m *ImportResourceState_Response) GetImportedResources() []*ImportResourceState_ImportedResource { - if m != nil { - return m.ImportedResources - } - return nil -} - -func (m *ImportResourceState_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type ReadDataSource struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadDataSource) Reset() { *m = ReadDataSource{} } -func (m *ReadDataSource) String() string { return proto.CompactTextString(m) } -func (*ReadDataSource) ProtoMessage() {} -func (*ReadDataSource) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{16} -} -func (m *ReadDataSource) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadDataSource.Unmarshal(m, b) -} -func (m *ReadDataSource) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadDataSource.Marshal(b, m, deterministic) -} -func (dst *ReadDataSource) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadDataSource.Merge(dst, src) -} -func (m *ReadDataSource) XXX_Size() int { - return xxx_messageInfo_ReadDataSource.Size(m) -} -func (m *ReadDataSource) XXX_DiscardUnknown() { - xxx_messageInfo_ReadDataSource.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadDataSource proto.InternalMessageInfo - -type ReadDataSource_Request struct { - TypeName string `protobuf:"bytes,1,opt,name=type_name,json=typeName,proto3" json:"type_name,omitempty"` - Config *DynamicValue `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadDataSource_Request) Reset() { *m = ReadDataSource_Request{} } -func (m *ReadDataSource_Request) String() string { return proto.CompactTextString(m) } -func (*ReadDataSource_Request) ProtoMessage() {} -func (*ReadDataSource_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{16, 0} -} -func (m *ReadDataSource_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadDataSource_Request.Unmarshal(m, b) -} -func (m *ReadDataSource_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadDataSource_Request.Marshal(b, m, deterministic) -} -func (dst *ReadDataSource_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadDataSource_Request.Merge(dst, src) -} -func (m *ReadDataSource_Request) XXX_Size() int { - return xxx_messageInfo_ReadDataSource_Request.Size(m) -} -func (m *ReadDataSource_Request) XXX_DiscardUnknown() { - xxx_messageInfo_ReadDataSource_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadDataSource_Request proto.InternalMessageInfo - -func (m *ReadDataSource_Request) GetTypeName() string { - if m != nil { - return m.TypeName - } - return "" -} - -func (m *ReadDataSource_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -type ReadDataSource_Response struct { - State *DynamicValue `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"` - Diagnostics []*Diagnostic `protobuf:"bytes,2,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReadDataSource_Response) Reset() { *m = ReadDataSource_Response{} } -func (m *ReadDataSource_Response) String() string { return proto.CompactTextString(m) } -func (*ReadDataSource_Response) ProtoMessage() {} -func (*ReadDataSource_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{16, 1} -} -func (m *ReadDataSource_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReadDataSource_Response.Unmarshal(m, b) -} -func (m *ReadDataSource_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReadDataSource_Response.Marshal(b, m, deterministic) -} -func (dst *ReadDataSource_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReadDataSource_Response.Merge(dst, src) -} -func (m *ReadDataSource_Response) XXX_Size() int { - return xxx_messageInfo_ReadDataSource_Response.Size(m) -} -func (m *ReadDataSource_Response) XXX_DiscardUnknown() { - xxx_messageInfo_ReadDataSource_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_ReadDataSource_Response proto.InternalMessageInfo - -func (m *ReadDataSource_Response) GetState() *DynamicValue { - if m != nil { - return m.State - } - return nil -} - -func (m *ReadDataSource_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type GetProvisionerSchema struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetProvisionerSchema) Reset() { *m = GetProvisionerSchema{} } -func (m *GetProvisionerSchema) String() string { return proto.CompactTextString(m) } -func (*GetProvisionerSchema) ProtoMessage() {} -func (*GetProvisionerSchema) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{17} -} -func (m *GetProvisionerSchema) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetProvisionerSchema.Unmarshal(m, b) -} -func (m *GetProvisionerSchema) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetProvisionerSchema.Marshal(b, m, deterministic) -} -func (dst *GetProvisionerSchema) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetProvisionerSchema.Merge(dst, src) -} -func (m *GetProvisionerSchema) XXX_Size() int { - return xxx_messageInfo_GetProvisionerSchema.Size(m) -} -func (m *GetProvisionerSchema) XXX_DiscardUnknown() { - xxx_messageInfo_GetProvisionerSchema.DiscardUnknown(m) -} - -var xxx_messageInfo_GetProvisionerSchema proto.InternalMessageInfo - -type GetProvisionerSchema_Request struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetProvisionerSchema_Request) Reset() { *m = GetProvisionerSchema_Request{} } -func (m *GetProvisionerSchema_Request) String() string { return proto.CompactTextString(m) } -func (*GetProvisionerSchema_Request) ProtoMessage() {} -func (*GetProvisionerSchema_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{17, 0} -} -func (m *GetProvisionerSchema_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetProvisionerSchema_Request.Unmarshal(m, b) -} -func (m *GetProvisionerSchema_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetProvisionerSchema_Request.Marshal(b, m, deterministic) -} -func (dst *GetProvisionerSchema_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetProvisionerSchema_Request.Merge(dst, src) -} -func (m *GetProvisionerSchema_Request) XXX_Size() int { - return xxx_messageInfo_GetProvisionerSchema_Request.Size(m) -} -func (m *GetProvisionerSchema_Request) XXX_DiscardUnknown() { - xxx_messageInfo_GetProvisionerSchema_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_GetProvisionerSchema_Request proto.InternalMessageInfo - -type GetProvisionerSchema_Response struct { - Provisioner *Schema `protobuf:"bytes,1,opt,name=provisioner,proto3" json:"provisioner,omitempty"` - Diagnostics []*Diagnostic `protobuf:"bytes,2,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetProvisionerSchema_Response) Reset() { *m = GetProvisionerSchema_Response{} } -func (m *GetProvisionerSchema_Response) String() string { return proto.CompactTextString(m) } -func (*GetProvisionerSchema_Response) ProtoMessage() {} -func (*GetProvisionerSchema_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{17, 1} -} -func (m *GetProvisionerSchema_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetProvisionerSchema_Response.Unmarshal(m, b) -} -func (m *GetProvisionerSchema_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetProvisionerSchema_Response.Marshal(b, m, deterministic) -} -func (dst *GetProvisionerSchema_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetProvisionerSchema_Response.Merge(dst, src) -} -func (m *GetProvisionerSchema_Response) XXX_Size() int { - return xxx_messageInfo_GetProvisionerSchema_Response.Size(m) -} -func (m *GetProvisionerSchema_Response) XXX_DiscardUnknown() { - xxx_messageInfo_GetProvisionerSchema_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_GetProvisionerSchema_Response proto.InternalMessageInfo - -func (m *GetProvisionerSchema_Response) GetProvisioner() *Schema { - if m != nil { - return m.Provisioner - } - return nil -} - -func (m *GetProvisionerSchema_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type ValidateProvisionerConfig struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateProvisionerConfig) Reset() { *m = ValidateProvisionerConfig{} } -func (m *ValidateProvisionerConfig) String() string { return proto.CompactTextString(m) } -func (*ValidateProvisionerConfig) ProtoMessage() {} -func (*ValidateProvisionerConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{18} -} -func (m *ValidateProvisionerConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateProvisionerConfig.Unmarshal(m, b) -} -func (m *ValidateProvisionerConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateProvisionerConfig.Marshal(b, m, deterministic) -} -func (dst *ValidateProvisionerConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateProvisionerConfig.Merge(dst, src) -} -func (m *ValidateProvisionerConfig) XXX_Size() int { - return xxx_messageInfo_ValidateProvisionerConfig.Size(m) -} -func (m *ValidateProvisionerConfig) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateProvisionerConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateProvisionerConfig proto.InternalMessageInfo - -type ValidateProvisionerConfig_Request struct { - Config *DynamicValue `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateProvisionerConfig_Request) Reset() { *m = ValidateProvisionerConfig_Request{} } -func (m *ValidateProvisionerConfig_Request) String() string { return proto.CompactTextString(m) } -func (*ValidateProvisionerConfig_Request) ProtoMessage() {} -func (*ValidateProvisionerConfig_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{18, 0} -} -func (m *ValidateProvisionerConfig_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateProvisionerConfig_Request.Unmarshal(m, b) -} -func (m *ValidateProvisionerConfig_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateProvisionerConfig_Request.Marshal(b, m, deterministic) -} -func (dst *ValidateProvisionerConfig_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateProvisionerConfig_Request.Merge(dst, src) -} -func (m *ValidateProvisionerConfig_Request) XXX_Size() int { - return xxx_messageInfo_ValidateProvisionerConfig_Request.Size(m) -} -func (m *ValidateProvisionerConfig_Request) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateProvisionerConfig_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateProvisionerConfig_Request proto.InternalMessageInfo - -func (m *ValidateProvisionerConfig_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -type ValidateProvisionerConfig_Response struct { - Diagnostics []*Diagnostic `protobuf:"bytes,1,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ValidateProvisionerConfig_Response) Reset() { *m = ValidateProvisionerConfig_Response{} } -func (m *ValidateProvisionerConfig_Response) String() string { return proto.CompactTextString(m) } -func (*ValidateProvisionerConfig_Response) ProtoMessage() {} -func (*ValidateProvisionerConfig_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{18, 1} -} -func (m *ValidateProvisionerConfig_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ValidateProvisionerConfig_Response.Unmarshal(m, b) -} -func (m *ValidateProvisionerConfig_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ValidateProvisionerConfig_Response.Marshal(b, m, deterministic) -} -func (dst *ValidateProvisionerConfig_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_ValidateProvisionerConfig_Response.Merge(dst, src) -} -func (m *ValidateProvisionerConfig_Response) XXX_Size() int { - return xxx_messageInfo_ValidateProvisionerConfig_Response.Size(m) -} -func (m *ValidateProvisionerConfig_Response) XXX_DiscardUnknown() { - xxx_messageInfo_ValidateProvisionerConfig_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_ValidateProvisionerConfig_Response proto.InternalMessageInfo - -func (m *ValidateProvisionerConfig_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -type ProvisionResource struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProvisionResource) Reset() { *m = ProvisionResource{} } -func (m *ProvisionResource) String() string { return proto.CompactTextString(m) } -func (*ProvisionResource) ProtoMessage() {} -func (*ProvisionResource) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{19} -} -func (m *ProvisionResource) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProvisionResource.Unmarshal(m, b) -} -func (m *ProvisionResource) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProvisionResource.Marshal(b, m, deterministic) -} -func (dst *ProvisionResource) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProvisionResource.Merge(dst, src) -} -func (m *ProvisionResource) XXX_Size() int { - return xxx_messageInfo_ProvisionResource.Size(m) -} -func (m *ProvisionResource) XXX_DiscardUnknown() { - xxx_messageInfo_ProvisionResource.DiscardUnknown(m) -} - -var xxx_messageInfo_ProvisionResource proto.InternalMessageInfo - -type ProvisionResource_Request struct { - Config *DynamicValue `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` - Connection *DynamicValue `protobuf:"bytes,2,opt,name=connection,proto3" json:"connection,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProvisionResource_Request) Reset() { *m = ProvisionResource_Request{} } -func (m *ProvisionResource_Request) String() string { return proto.CompactTextString(m) } -func (*ProvisionResource_Request) ProtoMessage() {} -func (*ProvisionResource_Request) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{19, 0} -} -func (m *ProvisionResource_Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProvisionResource_Request.Unmarshal(m, b) -} -func (m *ProvisionResource_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProvisionResource_Request.Marshal(b, m, deterministic) -} -func (dst *ProvisionResource_Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProvisionResource_Request.Merge(dst, src) -} -func (m *ProvisionResource_Request) XXX_Size() int { - return xxx_messageInfo_ProvisionResource_Request.Size(m) -} -func (m *ProvisionResource_Request) XXX_DiscardUnknown() { - xxx_messageInfo_ProvisionResource_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_ProvisionResource_Request proto.InternalMessageInfo - -func (m *ProvisionResource_Request) GetConfig() *DynamicValue { - if m != nil { - return m.Config - } - return nil -} - -func (m *ProvisionResource_Request) GetConnection() *DynamicValue { - if m != nil { - return m.Connection - } - return nil -} - -type ProvisionResource_Response struct { - Output string `protobuf:"bytes,1,opt,name=output,proto3" json:"output,omitempty"` - Diagnostics []*Diagnostic `protobuf:"bytes,2,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProvisionResource_Response) Reset() { *m = ProvisionResource_Response{} } -func (m *ProvisionResource_Response) String() string { return proto.CompactTextString(m) } -func (*ProvisionResource_Response) ProtoMessage() {} -func (*ProvisionResource_Response) Descriptor() ([]byte, []int) { - return fileDescriptor_tfplugin5_0417c8e6dca655d3, []int{19, 1} -} -func (m *ProvisionResource_Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProvisionResource_Response.Unmarshal(m, b) -} -func (m *ProvisionResource_Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProvisionResource_Response.Marshal(b, m, deterministic) -} -func (dst *ProvisionResource_Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProvisionResource_Response.Merge(dst, src) -} -func (m *ProvisionResource_Response) XXX_Size() int { - return xxx_messageInfo_ProvisionResource_Response.Size(m) -} -func (m *ProvisionResource_Response) XXX_DiscardUnknown() { - xxx_messageInfo_ProvisionResource_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_ProvisionResource_Response proto.InternalMessageInfo - -func (m *ProvisionResource_Response) GetOutput() string { - if m != nil { - return m.Output - } - return "" -} - -func (m *ProvisionResource_Response) GetDiagnostics() []*Diagnostic { - if m != nil { - return m.Diagnostics - } - return nil -} - -func init() { - proto.RegisterType((*DynamicValue)(nil), "tfplugin5.DynamicValue") - proto.RegisterType((*Diagnostic)(nil), "tfplugin5.Diagnostic") - proto.RegisterType((*AttributePath)(nil), "tfplugin5.AttributePath") - proto.RegisterType((*AttributePath_Step)(nil), "tfplugin5.AttributePath.Step") - proto.RegisterType((*Stop)(nil), "tfplugin5.Stop") - proto.RegisterType((*Stop_Request)(nil), "tfplugin5.Stop.Request") - proto.RegisterType((*Stop_Response)(nil), "tfplugin5.Stop.Response") - proto.RegisterType((*RawState)(nil), "tfplugin5.RawState") - proto.RegisterMapType((map[string]string)(nil), "tfplugin5.RawState.FlatmapEntry") - proto.RegisterType((*Schema)(nil), "tfplugin5.Schema") - proto.RegisterType((*Schema_Block)(nil), "tfplugin5.Schema.Block") - proto.RegisterType((*Schema_Attribute)(nil), "tfplugin5.Schema.Attribute") - proto.RegisterType((*Schema_NestedBlock)(nil), "tfplugin5.Schema.NestedBlock") - proto.RegisterType((*GetProviderSchema)(nil), "tfplugin5.GetProviderSchema") - proto.RegisterType((*GetProviderSchema_Request)(nil), "tfplugin5.GetProviderSchema.Request") - proto.RegisterType((*GetProviderSchema_Response)(nil), "tfplugin5.GetProviderSchema.Response") - proto.RegisterMapType((map[string]*Schema)(nil), "tfplugin5.GetProviderSchema.Response.DataSourceSchemasEntry") - proto.RegisterMapType((map[string]*Schema)(nil), "tfplugin5.GetProviderSchema.Response.ResourceSchemasEntry") - proto.RegisterType((*PrepareProviderConfig)(nil), "tfplugin5.PrepareProviderConfig") - proto.RegisterType((*PrepareProviderConfig_Request)(nil), "tfplugin5.PrepareProviderConfig.Request") - proto.RegisterType((*PrepareProviderConfig_Response)(nil), "tfplugin5.PrepareProviderConfig.Response") - proto.RegisterType((*UpgradeResourceState)(nil), "tfplugin5.UpgradeResourceState") - proto.RegisterType((*UpgradeResourceState_Request)(nil), "tfplugin5.UpgradeResourceState.Request") - proto.RegisterType((*UpgradeResourceState_Response)(nil), "tfplugin5.UpgradeResourceState.Response") - proto.RegisterType((*ValidateResourceTypeConfig)(nil), "tfplugin5.ValidateResourceTypeConfig") - proto.RegisterType((*ValidateResourceTypeConfig_Request)(nil), "tfplugin5.ValidateResourceTypeConfig.Request") - proto.RegisterType((*ValidateResourceTypeConfig_Response)(nil), "tfplugin5.ValidateResourceTypeConfig.Response") - proto.RegisterType((*ValidateDataSourceConfig)(nil), "tfplugin5.ValidateDataSourceConfig") - proto.RegisterType((*ValidateDataSourceConfig_Request)(nil), "tfplugin5.ValidateDataSourceConfig.Request") - proto.RegisterType((*ValidateDataSourceConfig_Response)(nil), "tfplugin5.ValidateDataSourceConfig.Response") - proto.RegisterType((*Configure)(nil), "tfplugin5.Configure") - proto.RegisterType((*Configure_Request)(nil), "tfplugin5.Configure.Request") - proto.RegisterType((*Configure_Response)(nil), "tfplugin5.Configure.Response") - proto.RegisterType((*ReadResource)(nil), "tfplugin5.ReadResource") - proto.RegisterType((*ReadResource_Request)(nil), "tfplugin5.ReadResource.Request") - proto.RegisterType((*ReadResource_Response)(nil), "tfplugin5.ReadResource.Response") - proto.RegisterType((*PlanResourceChange)(nil), "tfplugin5.PlanResourceChange") - proto.RegisterType((*PlanResourceChange_Request)(nil), "tfplugin5.PlanResourceChange.Request") - proto.RegisterType((*PlanResourceChange_Response)(nil), "tfplugin5.PlanResourceChange.Response") - proto.RegisterType((*ApplyResourceChange)(nil), "tfplugin5.ApplyResourceChange") - proto.RegisterType((*ApplyResourceChange_Request)(nil), "tfplugin5.ApplyResourceChange.Request") - proto.RegisterType((*ApplyResourceChange_Response)(nil), "tfplugin5.ApplyResourceChange.Response") - proto.RegisterType((*ImportResourceState)(nil), "tfplugin5.ImportResourceState") - proto.RegisterType((*ImportResourceState_Request)(nil), "tfplugin5.ImportResourceState.Request") - proto.RegisterType((*ImportResourceState_ImportedResource)(nil), "tfplugin5.ImportResourceState.ImportedResource") - proto.RegisterType((*ImportResourceState_Response)(nil), "tfplugin5.ImportResourceState.Response") - proto.RegisterType((*ReadDataSource)(nil), "tfplugin5.ReadDataSource") - proto.RegisterType((*ReadDataSource_Request)(nil), "tfplugin5.ReadDataSource.Request") - proto.RegisterType((*ReadDataSource_Response)(nil), "tfplugin5.ReadDataSource.Response") - proto.RegisterType((*GetProvisionerSchema)(nil), "tfplugin5.GetProvisionerSchema") - proto.RegisterType((*GetProvisionerSchema_Request)(nil), "tfplugin5.GetProvisionerSchema.Request") - proto.RegisterType((*GetProvisionerSchema_Response)(nil), "tfplugin5.GetProvisionerSchema.Response") - proto.RegisterType((*ValidateProvisionerConfig)(nil), "tfplugin5.ValidateProvisionerConfig") - proto.RegisterType((*ValidateProvisionerConfig_Request)(nil), "tfplugin5.ValidateProvisionerConfig.Request") - proto.RegisterType((*ValidateProvisionerConfig_Response)(nil), "tfplugin5.ValidateProvisionerConfig.Response") - proto.RegisterType((*ProvisionResource)(nil), "tfplugin5.ProvisionResource") - proto.RegisterType((*ProvisionResource_Request)(nil), "tfplugin5.ProvisionResource.Request") - proto.RegisterType((*ProvisionResource_Response)(nil), "tfplugin5.ProvisionResource.Response") - proto.RegisterEnum("tfplugin5.Diagnostic_Severity", Diagnostic_Severity_name, Diagnostic_Severity_value) - proto.RegisterEnum("tfplugin5.Schema_NestedBlock_NestingMode", Schema_NestedBlock_NestingMode_name, Schema_NestedBlock_NestingMode_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// ProviderClient is the client API for Provider service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type ProviderClient interface { - // ////// Information about what a provider supports/expects - GetSchema(ctx context.Context, in *GetProviderSchema_Request, opts ...grpc.CallOption) (*GetProviderSchema_Response, error) - PrepareProviderConfig(ctx context.Context, in *PrepareProviderConfig_Request, opts ...grpc.CallOption) (*PrepareProviderConfig_Response, error) - ValidateResourceTypeConfig(ctx context.Context, in *ValidateResourceTypeConfig_Request, opts ...grpc.CallOption) (*ValidateResourceTypeConfig_Response, error) - ValidateDataSourceConfig(ctx context.Context, in *ValidateDataSourceConfig_Request, opts ...grpc.CallOption) (*ValidateDataSourceConfig_Response, error) - UpgradeResourceState(ctx context.Context, in *UpgradeResourceState_Request, opts ...grpc.CallOption) (*UpgradeResourceState_Response, error) - // ////// One-time initialization, called before other functions below - Configure(ctx context.Context, in *Configure_Request, opts ...grpc.CallOption) (*Configure_Response, error) - // ////// Managed Resource Lifecycle - ReadResource(ctx context.Context, in *ReadResource_Request, opts ...grpc.CallOption) (*ReadResource_Response, error) - PlanResourceChange(ctx context.Context, in *PlanResourceChange_Request, opts ...grpc.CallOption) (*PlanResourceChange_Response, error) - ApplyResourceChange(ctx context.Context, in *ApplyResourceChange_Request, opts ...grpc.CallOption) (*ApplyResourceChange_Response, error) - ImportResourceState(ctx context.Context, in *ImportResourceState_Request, opts ...grpc.CallOption) (*ImportResourceState_Response, error) - ReadDataSource(ctx context.Context, in *ReadDataSource_Request, opts ...grpc.CallOption) (*ReadDataSource_Response, error) - // ////// Graceful Shutdown - Stop(ctx context.Context, in *Stop_Request, opts ...grpc.CallOption) (*Stop_Response, error) -} - -type providerClient struct { - cc *grpc.ClientConn -} - -func NewProviderClient(cc *grpc.ClientConn) ProviderClient { - return &providerClient{cc} -} - -func (c *providerClient) GetSchema(ctx context.Context, in *GetProviderSchema_Request, opts ...grpc.CallOption) (*GetProviderSchema_Response, error) { - out := new(GetProviderSchema_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/GetSchema", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) PrepareProviderConfig(ctx context.Context, in *PrepareProviderConfig_Request, opts ...grpc.CallOption) (*PrepareProviderConfig_Response, error) { - out := new(PrepareProviderConfig_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/PrepareProviderConfig", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) ValidateResourceTypeConfig(ctx context.Context, in *ValidateResourceTypeConfig_Request, opts ...grpc.CallOption) (*ValidateResourceTypeConfig_Response, error) { - out := new(ValidateResourceTypeConfig_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/ValidateResourceTypeConfig", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) ValidateDataSourceConfig(ctx context.Context, in *ValidateDataSourceConfig_Request, opts ...grpc.CallOption) (*ValidateDataSourceConfig_Response, error) { - out := new(ValidateDataSourceConfig_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/ValidateDataSourceConfig", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) UpgradeResourceState(ctx context.Context, in *UpgradeResourceState_Request, opts ...grpc.CallOption) (*UpgradeResourceState_Response, error) { - out := new(UpgradeResourceState_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/UpgradeResourceState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) Configure(ctx context.Context, in *Configure_Request, opts ...grpc.CallOption) (*Configure_Response, error) { - out := new(Configure_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/Configure", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) ReadResource(ctx context.Context, in *ReadResource_Request, opts ...grpc.CallOption) (*ReadResource_Response, error) { - out := new(ReadResource_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/ReadResource", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) PlanResourceChange(ctx context.Context, in *PlanResourceChange_Request, opts ...grpc.CallOption) (*PlanResourceChange_Response, error) { - out := new(PlanResourceChange_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/PlanResourceChange", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) ApplyResourceChange(ctx context.Context, in *ApplyResourceChange_Request, opts ...grpc.CallOption) (*ApplyResourceChange_Response, error) { - out := new(ApplyResourceChange_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/ApplyResourceChange", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) ImportResourceState(ctx context.Context, in *ImportResourceState_Request, opts ...grpc.CallOption) (*ImportResourceState_Response, error) { - out := new(ImportResourceState_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/ImportResourceState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) ReadDataSource(ctx context.Context, in *ReadDataSource_Request, opts ...grpc.CallOption) (*ReadDataSource_Response, error) { - out := new(ReadDataSource_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/ReadDataSource", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *providerClient) Stop(ctx context.Context, in *Stop_Request, opts ...grpc.CallOption) (*Stop_Response, error) { - out := new(Stop_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provider/Stop", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// ProviderServer is the server API for Provider service. -type ProviderServer interface { - // ////// Information about what a provider supports/expects - GetSchema(context.Context, *GetProviderSchema_Request) (*GetProviderSchema_Response, error) - PrepareProviderConfig(context.Context, *PrepareProviderConfig_Request) (*PrepareProviderConfig_Response, error) - ValidateResourceTypeConfig(context.Context, *ValidateResourceTypeConfig_Request) (*ValidateResourceTypeConfig_Response, error) - ValidateDataSourceConfig(context.Context, *ValidateDataSourceConfig_Request) (*ValidateDataSourceConfig_Response, error) - UpgradeResourceState(context.Context, *UpgradeResourceState_Request) (*UpgradeResourceState_Response, error) - // ////// One-time initialization, called before other functions below - Configure(context.Context, *Configure_Request) (*Configure_Response, error) - // ////// Managed Resource Lifecycle - ReadResource(context.Context, *ReadResource_Request) (*ReadResource_Response, error) - PlanResourceChange(context.Context, *PlanResourceChange_Request) (*PlanResourceChange_Response, error) - ApplyResourceChange(context.Context, *ApplyResourceChange_Request) (*ApplyResourceChange_Response, error) - ImportResourceState(context.Context, *ImportResourceState_Request) (*ImportResourceState_Response, error) - ReadDataSource(context.Context, *ReadDataSource_Request) (*ReadDataSource_Response, error) - // ////// Graceful Shutdown - Stop(context.Context, *Stop_Request) (*Stop_Response, error) -} - -func RegisterProviderServer(s *grpc.Server, srv ProviderServer) { - s.RegisterService(&_Provider_serviceDesc, srv) -} - -func _Provider_GetSchema_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetProviderSchema_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).GetSchema(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/GetSchema", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).GetSchema(ctx, req.(*GetProviderSchema_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_PrepareProviderConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(PrepareProviderConfig_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).PrepareProviderConfig(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/PrepareProviderConfig", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).PrepareProviderConfig(ctx, req.(*PrepareProviderConfig_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_ValidateResourceTypeConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ValidateResourceTypeConfig_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).ValidateResourceTypeConfig(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/ValidateResourceTypeConfig", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).ValidateResourceTypeConfig(ctx, req.(*ValidateResourceTypeConfig_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_ValidateDataSourceConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ValidateDataSourceConfig_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).ValidateDataSourceConfig(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/ValidateDataSourceConfig", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).ValidateDataSourceConfig(ctx, req.(*ValidateDataSourceConfig_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_UpgradeResourceState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpgradeResourceState_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).UpgradeResourceState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/UpgradeResourceState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).UpgradeResourceState(ctx, req.(*UpgradeResourceState_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_Configure_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Configure_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).Configure(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/Configure", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).Configure(ctx, req.(*Configure_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_ReadResource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ReadResource_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).ReadResource(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/ReadResource", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).ReadResource(ctx, req.(*ReadResource_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_PlanResourceChange_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(PlanResourceChange_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).PlanResourceChange(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/PlanResourceChange", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).PlanResourceChange(ctx, req.(*PlanResourceChange_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_ApplyResourceChange_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ApplyResourceChange_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).ApplyResourceChange(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/ApplyResourceChange", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).ApplyResourceChange(ctx, req.(*ApplyResourceChange_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_ImportResourceState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ImportResourceState_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).ImportResourceState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/ImportResourceState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).ImportResourceState(ctx, req.(*ImportResourceState_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_ReadDataSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ReadDataSource_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).ReadDataSource(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/ReadDataSource", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).ReadDataSource(ctx, req.(*ReadDataSource_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provider_Stop_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Stop_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProviderServer).Stop(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provider/Stop", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProviderServer).Stop(ctx, req.(*Stop_Request)) - } - return interceptor(ctx, in, info, handler) -} - -var _Provider_serviceDesc = grpc.ServiceDesc{ - ServiceName: "tfplugin5.Provider", - HandlerType: (*ProviderServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetSchema", - Handler: _Provider_GetSchema_Handler, - }, - { - MethodName: "PrepareProviderConfig", - Handler: _Provider_PrepareProviderConfig_Handler, - }, - { - MethodName: "ValidateResourceTypeConfig", - Handler: _Provider_ValidateResourceTypeConfig_Handler, - }, - { - MethodName: "ValidateDataSourceConfig", - Handler: _Provider_ValidateDataSourceConfig_Handler, - }, - { - MethodName: "UpgradeResourceState", - Handler: _Provider_UpgradeResourceState_Handler, - }, - { - MethodName: "Configure", - Handler: _Provider_Configure_Handler, - }, - { - MethodName: "ReadResource", - Handler: _Provider_ReadResource_Handler, - }, - { - MethodName: "PlanResourceChange", - Handler: _Provider_PlanResourceChange_Handler, - }, - { - MethodName: "ApplyResourceChange", - Handler: _Provider_ApplyResourceChange_Handler, - }, - { - MethodName: "ImportResourceState", - Handler: _Provider_ImportResourceState_Handler, - }, - { - MethodName: "ReadDataSource", - Handler: _Provider_ReadDataSource_Handler, - }, - { - MethodName: "Stop", - Handler: _Provider_Stop_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "tfplugin5.proto", -} - -// ProvisionerClient is the client API for Provisioner service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type ProvisionerClient interface { - GetSchema(ctx context.Context, in *GetProvisionerSchema_Request, opts ...grpc.CallOption) (*GetProvisionerSchema_Response, error) - ValidateProvisionerConfig(ctx context.Context, in *ValidateProvisionerConfig_Request, opts ...grpc.CallOption) (*ValidateProvisionerConfig_Response, error) - ProvisionResource(ctx context.Context, in *ProvisionResource_Request, opts ...grpc.CallOption) (Provisioner_ProvisionResourceClient, error) - Stop(ctx context.Context, in *Stop_Request, opts ...grpc.CallOption) (*Stop_Response, error) -} - -type provisionerClient struct { - cc *grpc.ClientConn -} - -func NewProvisionerClient(cc *grpc.ClientConn) ProvisionerClient { - return &provisionerClient{cc} -} - -func (c *provisionerClient) GetSchema(ctx context.Context, in *GetProvisionerSchema_Request, opts ...grpc.CallOption) (*GetProvisionerSchema_Response, error) { - out := new(GetProvisionerSchema_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provisioner/GetSchema", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *provisionerClient) ValidateProvisionerConfig(ctx context.Context, in *ValidateProvisionerConfig_Request, opts ...grpc.CallOption) (*ValidateProvisionerConfig_Response, error) { - out := new(ValidateProvisionerConfig_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provisioner/ValidateProvisionerConfig", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *provisionerClient) ProvisionResource(ctx context.Context, in *ProvisionResource_Request, opts ...grpc.CallOption) (Provisioner_ProvisionResourceClient, error) { - stream, err := c.cc.NewStream(ctx, &_Provisioner_serviceDesc.Streams[0], "/tfplugin5.Provisioner/ProvisionResource", opts...) - if err != nil { - return nil, err - } - x := &provisionerProvisionResourceClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Provisioner_ProvisionResourceClient interface { - Recv() (*ProvisionResource_Response, error) - grpc.ClientStream -} - -type provisionerProvisionResourceClient struct { - grpc.ClientStream -} - -func (x *provisionerProvisionResourceClient) Recv() (*ProvisionResource_Response, error) { - m := new(ProvisionResource_Response) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *provisionerClient) Stop(ctx context.Context, in *Stop_Request, opts ...grpc.CallOption) (*Stop_Response, error) { - out := new(Stop_Response) - err := c.cc.Invoke(ctx, "/tfplugin5.Provisioner/Stop", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// ProvisionerServer is the server API for Provisioner service. -type ProvisionerServer interface { - GetSchema(context.Context, *GetProvisionerSchema_Request) (*GetProvisionerSchema_Response, error) - ValidateProvisionerConfig(context.Context, *ValidateProvisionerConfig_Request) (*ValidateProvisionerConfig_Response, error) - ProvisionResource(*ProvisionResource_Request, Provisioner_ProvisionResourceServer) error - Stop(context.Context, *Stop_Request) (*Stop_Response, error) -} - -func RegisterProvisionerServer(s *grpc.Server, srv ProvisionerServer) { - s.RegisterService(&_Provisioner_serviceDesc, srv) -} - -func _Provisioner_GetSchema_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetProvisionerSchema_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProvisionerServer).GetSchema(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provisioner/GetSchema", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProvisionerServer).GetSchema(ctx, req.(*GetProvisionerSchema_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provisioner_ValidateProvisionerConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ValidateProvisionerConfig_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProvisionerServer).ValidateProvisionerConfig(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provisioner/ValidateProvisionerConfig", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProvisionerServer).ValidateProvisionerConfig(ctx, req.(*ValidateProvisionerConfig_Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _Provisioner_ProvisionResource_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(ProvisionResource_Request) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(ProvisionerServer).ProvisionResource(m, &provisionerProvisionResourceServer{stream}) -} - -type Provisioner_ProvisionResourceServer interface { - Send(*ProvisionResource_Response) error - grpc.ServerStream -} - -type provisionerProvisionResourceServer struct { - grpc.ServerStream -} - -func (x *provisionerProvisionResourceServer) Send(m *ProvisionResource_Response) error { - return x.ServerStream.SendMsg(m) -} - -func _Provisioner_Stop_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Stop_Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ProvisionerServer).Stop(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/tfplugin5.Provisioner/Stop", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ProvisionerServer).Stop(ctx, req.(*Stop_Request)) - } - return interceptor(ctx, in, info, handler) -} - -var _Provisioner_serviceDesc = grpc.ServiceDesc{ - ServiceName: "tfplugin5.Provisioner", - HandlerType: (*ProvisionerServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetSchema", - Handler: _Provisioner_GetSchema_Handler, - }, - { - MethodName: "ValidateProvisionerConfig", - Handler: _Provisioner_ValidateProvisionerConfig_Handler, - }, - { - MethodName: "Stop", - Handler: _Provisioner_Stop_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "ProvisionResource", - Handler: _Provisioner_ProvisionResource_Handler, - ServerStreams: true, - }, - }, - Metadata: "tfplugin5.proto", -} - -func init() { proto.RegisterFile("tfplugin5.proto", fileDescriptor_tfplugin5_0417c8e6dca655d3) } - -var fileDescriptor_tfplugin5_0417c8e6dca655d3 = []byte{ - // 1867 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x59, 0xcd, 0x73, 0x1b, 0x49, - 0x15, 0xcf, 0x68, 0x24, 0x5b, 0x7a, 0xf2, 0x87, 0xdc, 0xc9, 0x06, 0x31, 0xbb, 0x0b, 0x46, 0x7c, - 0xd8, 0x5b, 0xbb, 0x51, 0xb6, 0x1c, 0xd8, 0x5d, 0x4c, 0x6a, 0x0b, 0xc7, 0x31, 0x89, 0x8b, 0xac, - 0x31, 0xad, 0x6c, 0x42, 0x15, 0x55, 0xab, 0xea, 0x68, 0xda, 0xca, 0x10, 0x69, 0x66, 0xb6, 0xa7, - 0x65, 0x5b, 0xc5, 0x91, 0x82, 0x33, 0x17, 0x3e, 0xaa, 0x58, 0xb8, 0xf0, 0x2f, 0x70, 0x00, 0x6e, - 0x9c, 0xf8, 0x07, 0xb8, 0x2d, 0x9c, 0x28, 0x8e, 0x14, 0x47, 0xb8, 0x50, 0x45, 0xf5, 0xd7, 0x4c, - 0x4b, 0x1a, 0xd9, 0x13, 0x7b, 0x53, 0xd4, 0xde, 0xa6, 0xfb, 0xfd, 0xfa, 0xbd, 0x5f, 0xbf, 0xf7, - 0xfa, 0xbd, 0x6e, 0x09, 0x56, 0xf9, 0x51, 0x3c, 0x18, 0xf5, 0x83, 0xf0, 0x6b, 0xed, 0x98, 0x45, - 0x3c, 0x42, 0xb5, 0x74, 0xa2, 0x75, 0x1b, 0x96, 0xee, 0x8e, 0x43, 0x32, 0x0c, 0x7a, 0x8f, 0xc8, - 0x60, 0x44, 0x51, 0x13, 0x16, 0x87, 0x49, 0x3f, 0x26, 0xbd, 0x67, 0x4d, 0x67, 0xdd, 0xd9, 0x5c, - 0xc2, 0x66, 0x88, 0x10, 0x94, 0x7f, 0x90, 0x44, 0x61, 0xb3, 0x24, 0xa7, 0xe5, 0x77, 0xeb, 0xef, - 0x0e, 0xc0, 0xdd, 0x80, 0xf4, 0xc3, 0x28, 0xe1, 0x41, 0x0f, 0x6d, 0x43, 0x35, 0xa1, 0xc7, 0x94, - 0x05, 0x7c, 0x2c, 0x57, 0xaf, 0x6c, 0x7d, 0xae, 0x9d, 0xd9, 0xce, 0x80, 0xed, 0x8e, 0x46, 0xe1, - 0x14, 0x2f, 0x0c, 0x27, 0xa3, 0xe1, 0x90, 0xb0, 0xb1, 0xb4, 0x50, 0xc3, 0x66, 0x88, 0xae, 0xc3, - 0x82, 0x4f, 0x39, 0x09, 0x06, 0x4d, 0x57, 0x0a, 0xf4, 0x08, 0xbd, 0x05, 0x35, 0xc2, 0x39, 0x0b, - 0x9e, 0x8c, 0x38, 0x6d, 0x96, 0xd7, 0x9d, 0xcd, 0xfa, 0x56, 0xd3, 0x32, 0xb7, 0x63, 0x64, 0x87, - 0x84, 0x3f, 0xc5, 0x19, 0xb4, 0x75, 0x13, 0xaa, 0xc6, 0x3e, 0xaa, 0xc3, 0xe2, 0xfe, 0xc1, 0xa3, - 0x9d, 0x07, 0xfb, 0x77, 0x1b, 0x57, 0x50, 0x0d, 0x2a, 0x7b, 0x18, 0x7f, 0x07, 0x37, 0x1c, 0x31, - 0xff, 0x78, 0x07, 0x1f, 0xec, 0x1f, 0xdc, 0x6b, 0x94, 0x5a, 0x7f, 0x75, 0x60, 0x79, 0x42, 0x1b, - 0xba, 0x05, 0x95, 0x84, 0xd3, 0x38, 0x69, 0x3a, 0xeb, 0xee, 0x66, 0x7d, 0xeb, 0xd5, 0x79, 0x66, - 0xdb, 0x1d, 0x4e, 0x63, 0xac, 0xb0, 0xde, 0xcf, 0x1c, 0x28, 0x8b, 0x31, 0xda, 0x80, 0x95, 0x94, - 0x4d, 0x37, 0x24, 0x43, 0x2a, 0x9d, 0x55, 0xbb, 0x7f, 0x05, 0x2f, 0xa7, 0xf3, 0x07, 0x64, 0x48, - 0x51, 0x1b, 0x10, 0x1d, 0xd0, 0x21, 0x0d, 0x79, 0xf7, 0x19, 0x1d, 0x77, 0x13, 0xce, 0x82, 0xb0, - 0xaf, 0xdc, 0x73, 0xff, 0x0a, 0x6e, 0x68, 0xd9, 0xb7, 0xe9, 0xb8, 0x23, 0x25, 0x68, 0x13, 0x56, - 0x6d, 0x7c, 0x10, 0x72, 0xe9, 0x32, 0x57, 0x68, 0xce, 0xc0, 0xfb, 0x21, 0xbf, 0x03, 0x22, 0x52, - 0x03, 0xda, 0xe3, 0x11, 0x6b, 0xdd, 0x12, 0xb4, 0xa2, 0xd8, 0xab, 0xc1, 0x22, 0xa6, 0x1f, 0x8e, - 0x68, 0xc2, 0xbd, 0x75, 0xa8, 0x62, 0x9a, 0xc4, 0x51, 0x98, 0x50, 0x74, 0x0d, 0x2a, 0x7b, 0x8c, - 0x45, 0x4c, 0x91, 0xc4, 0x15, 0x2a, 0x06, 0xad, 0x9f, 0x3b, 0x50, 0xc5, 0xe4, 0xa4, 0xc3, 0x09, - 0xa7, 0x69, 0x6a, 0x38, 0x59, 0x6a, 0xa0, 0x6d, 0x58, 0x3c, 0x1a, 0x10, 0x3e, 0x24, 0x71, 0xb3, - 0x24, 0x9d, 0xb4, 0x6e, 0x39, 0xc9, 0xac, 0x6c, 0x7f, 0x4b, 0x41, 0xf6, 0x42, 0xce, 0xc6, 0xd8, - 0x2c, 0xf0, 0xb6, 0x61, 0xc9, 0x16, 0xa0, 0x06, 0xb8, 0xcf, 0xe8, 0x58, 0x13, 0x10, 0x9f, 0x82, - 0xd4, 0xb1, 0xc8, 0x57, 0x9d, 0x2b, 0x6a, 0xb0, 0x5d, 0x7a, 0xc7, 0x69, 0x7d, 0x5c, 0x81, 0x85, - 0x4e, 0xef, 0x29, 0x1d, 0x12, 0x91, 0x52, 0xc7, 0x94, 0x25, 0x81, 0x66, 0xe6, 0x62, 0x33, 0x44, - 0x37, 0xa0, 0xf2, 0x64, 0x10, 0xf5, 0x9e, 0xc9, 0xe5, 0xf5, 0xad, 0xcf, 0x58, 0xd4, 0xd4, 0xda, - 0xf6, 0x1d, 0x21, 0xc6, 0x0a, 0xe5, 0xfd, 0xc6, 0x81, 0x8a, 0x9c, 0x38, 0x43, 0xe5, 0x37, 0x00, - 0xd2, 0xe0, 0x25, 0x7a, 0xcb, 0x2f, 0xcf, 0xea, 0x4d, 0xd3, 0x03, 0x5b, 0x70, 0xf4, 0x2e, 0xd4, - 0xa5, 0xa5, 0x2e, 0x1f, 0xc7, 0x34, 0x69, 0xba, 0x33, 0x59, 0xa5, 0x57, 0x1f, 0xd0, 0x84, 0x53, - 0x5f, 0x71, 0x03, 0xb9, 0xe2, 0xa1, 0x58, 0xe0, 0xfd, 0xd9, 0x81, 0x5a, 0xaa, 0x59, 0x84, 0x23, - 0xcb, 0x2a, 0x2c, 0xbf, 0xc5, 0x9c, 0xd0, 0x6d, 0x4e, 0xaf, 0xf8, 0x46, 0xeb, 0x50, 0xf7, 0x69, - 0xd2, 0x63, 0x41, 0xcc, 0xc5, 0x86, 0xd4, 0xe9, 0xb2, 0xa7, 0x90, 0x07, 0x55, 0x46, 0x3f, 0x1c, - 0x05, 0x8c, 0xfa, 0xf2, 0x84, 0x55, 0x71, 0x3a, 0x16, 0xb2, 0x48, 0xa2, 0xc8, 0xa0, 0x59, 0x51, - 0x32, 0x33, 0x16, 0xb2, 0x5e, 0x34, 0x8c, 0x47, 0x9c, 0xfa, 0xcd, 0x05, 0x25, 0x33, 0x63, 0xf4, - 0x0a, 0xd4, 0x12, 0x1a, 0x26, 0x01, 0x0f, 0x8e, 0x69, 0x73, 0x51, 0x0a, 0xb3, 0x09, 0xef, 0xa3, - 0x12, 0xd4, 0xad, 0x5d, 0xa2, 0x97, 0xa1, 0x26, 0xb8, 0x5a, 0xc7, 0x04, 0x57, 0xc5, 0x84, 0x3c, - 0x1f, 0xcf, 0x17, 0x46, 0xb4, 0x0b, 0x8b, 0x21, 0x4d, 0xb8, 0x38, 0x43, 0xae, 0xac, 0x4e, 0xaf, - 0x9d, 0xe9, 0x61, 0xf9, 0x1d, 0x84, 0xfd, 0xf7, 0x22, 0x9f, 0x62, 0xb3, 0x52, 0x10, 0x1a, 0x06, - 0x61, 0x37, 0xe0, 0x74, 0x98, 0x48, 0x9f, 0xb8, 0xb8, 0x3a, 0x0c, 0xc2, 0x7d, 0x31, 0x96, 0x42, - 0x72, 0xaa, 0x85, 0x15, 0x2d, 0x24, 0xa7, 0x52, 0xd8, 0xba, 0xa3, 0x76, 0xa6, 0x35, 0x4e, 0x96, - 0x1e, 0x80, 0x85, 0xce, 0xfe, 0xc1, 0xbd, 0x07, 0x7b, 0x0d, 0x07, 0x55, 0xa1, 0xfc, 0x60, 0xbf, - 0xf3, 0xb0, 0x51, 0x42, 0x8b, 0xe0, 0x76, 0xf6, 0x1e, 0x36, 0x5c, 0xf1, 0xf1, 0xde, 0xce, 0x61, - 0xa3, 0xdc, 0xfa, 0x65, 0x19, 0xd6, 0xee, 0x51, 0x7e, 0xc8, 0xa2, 0xe3, 0xc0, 0xa7, 0x4c, 0x91, - 0xb6, 0x4f, 0xee, 0xbf, 0x5d, 0xeb, 0xe8, 0xde, 0x80, 0x6a, 0xac, 0x91, 0xd2, 0x77, 0xf5, 0xad, - 0xb5, 0x99, 0x1d, 0xe3, 0x14, 0x82, 0x28, 0x34, 0x18, 0x4d, 0xa2, 0x11, 0xeb, 0xd1, 0x6e, 0x22, - 0x85, 0x26, 0x91, 0xb7, 0xad, 0x65, 0x33, 0xe6, 0xdb, 0xc6, 0x9e, 0xf8, 0x90, 0xab, 0xd5, 0x7c, - 0xa2, 0x4e, 0xf5, 0x2a, 0x9b, 0x9c, 0x45, 0x03, 0xb8, 0xea, 0x13, 0x4e, 0xba, 0x53, 0x96, 0x54, - 0xd2, 0xdf, 0x2e, 0x66, 0xe9, 0x2e, 0xe1, 0xa4, 0x33, 0x6b, 0x6b, 0xcd, 0x9f, 0x9e, 0x47, 0x6f, - 0x43, 0xdd, 0x4f, 0x1b, 0x8f, 0x88, 0x98, 0xb0, 0xf2, 0x52, 0x6e, 0x5b, 0xc2, 0x36, 0xd2, 0x7b, - 0x1f, 0xae, 0xe5, 0xed, 0x27, 0xa7, 0x18, 0x6d, 0xd8, 0xc5, 0x28, 0xd7, 0xc7, 0x59, 0x7d, 0xf2, - 0x1e, 0xc3, 0xf5, 0x7c, 0xf2, 0x97, 0x54, 0xdc, 0xfa, 0xd8, 0x81, 0x97, 0x0e, 0x19, 0x8d, 0x09, - 0xa3, 0xc6, 0x6b, 0xbb, 0x51, 0x78, 0x14, 0xf4, 0xbd, 0xed, 0x34, 0x3d, 0xd0, 0x4d, 0x58, 0xe8, - 0xc9, 0x49, 0x9d, 0x0f, 0xf6, 0x91, 0xb1, 0xef, 0x01, 0x58, 0xc3, 0xbc, 0x1f, 0x3b, 0x56, 0x3e, - 0x7d, 0x13, 0x56, 0x63, 0x65, 0xc1, 0xef, 0x16, 0x53, 0xb3, 0x62, 0xf0, 0x8a, 0xca, 0x74, 0x34, - 0x4a, 0x45, 0xa3, 0xd1, 0xfa, 0x69, 0x09, 0xae, 0xbd, 0x1f, 0xf7, 0x19, 0xf1, 0x69, 0x1a, 0x15, - 0xd1, 0x41, 0x3c, 0x96, 0x6d, 0xee, 0xcc, 0x5a, 0x61, 0x55, 0xee, 0xd2, 0x64, 0xe5, 0x7e, 0x13, - 0x6a, 0x8c, 0x9c, 0x74, 0x13, 0xa1, 0x4e, 0x16, 0x86, 0xfa, 0xd6, 0xd5, 0x9c, 0x5e, 0x85, 0xab, - 0x4c, 0x7f, 0x79, 0x3f, 0xb2, 0x9d, 0xf2, 0x2e, 0xac, 0x8c, 0x14, 0x31, 0x5f, 0xeb, 0x38, 0xc7, - 0x27, 0xcb, 0x06, 0xae, 0x9a, 0xe7, 0x85, 0x5d, 0xf2, 0x47, 0x07, 0xbc, 0x47, 0x64, 0x10, 0xf8, - 0x82, 0x9c, 0xf6, 0x89, 0x68, 0x07, 0x3a, 0xea, 0x8f, 0x0b, 0x3a, 0x26, 0x4b, 0x89, 0x52, 0xb1, - 0x94, 0xd8, 0xb5, 0x36, 0x3f, 0x45, 0xde, 0x29, 0x4c, 0xfe, 0xf7, 0x0e, 0x34, 0x0d, 0xf9, 0xec, - 0x3c, 0x7c, 0x2a, 0xa8, 0xff, 0xc1, 0x81, 0x9a, 0x22, 0x3a, 0x62, 0xd4, 0xeb, 0x67, 0x5c, 0x5f, - 0x87, 0x35, 0x4e, 0x19, 0x23, 0x47, 0x11, 0x1b, 0x76, 0xed, 0x6b, 0x42, 0x0d, 0x37, 0x52, 0xc1, - 0x23, 0x9d, 0x75, 0xff, 0x1f, 0xee, 0xff, 0x72, 0x60, 0x09, 0x53, 0xe2, 0x9b, 0x7c, 0xf1, 0xfc, - 0x82, 0xae, 0xbe, 0x0d, 0xcb, 0xbd, 0x11, 0x63, 0xe2, 0x6a, 0xa9, 0x92, 0xfc, 0x1c, 0xd6, 0x4b, - 0x1a, 0xad, 0x0e, 0xcc, 0xd8, 0xe2, 0xfe, 0x55, 0xa8, 0x85, 0xf4, 0xa4, 0xd8, 0x51, 0xa9, 0x86, - 0xf4, 0xe4, 0x92, 0xa7, 0xe4, 0x77, 0x65, 0x40, 0x87, 0x03, 0x12, 0x9a, 0x1d, 0xef, 0x3e, 0x25, - 0x61, 0x9f, 0x7a, 0xff, 0x75, 0x0a, 0x6e, 0xfc, 0x1d, 0xa8, 0xc7, 0x2c, 0x88, 0x58, 0xb1, 0x6d, - 0x83, 0xc4, 0x2a, 0xca, 0x7b, 0x80, 0x62, 0x16, 0xc5, 0x51, 0x42, 0xfd, 0x6e, 0xb6, 0x63, 0xf7, - 0x6c, 0x05, 0x0d, 0xb3, 0xe4, 0xc0, 0xec, 0x3c, 0x4b, 0x94, 0x72, 0xa1, 0x44, 0x41, 0x5f, 0x84, - 0x65, 0xc5, 0x38, 0x66, 0xc1, 0xb1, 0x30, 0x59, 0x91, 0x77, 0xbe, 0x25, 0x39, 0x79, 0xa8, 0xe6, - 0xbc, 0x5f, 0x97, 0xac, 0x90, 0xdc, 0x86, 0xe5, 0x78, 0x40, 0xc2, 0xb0, 0x68, 0x05, 0x5b, 0xd2, - 0x68, 0x45, 0x70, 0x57, 0x5c, 0x1b, 0xe4, 0xa5, 0x30, 0xe9, 0x32, 0x1a, 0x0f, 0x48, 0x8f, 0xea, - 0xf8, 0xcc, 0x7f, 0x8e, 0xad, 0x9a, 0x15, 0x58, 0x2d, 0x40, 0x1b, 0xb0, 0x6a, 0x28, 0x18, 0xda, - 0xae, 0xa4, 0xbd, 0xa2, 0xa7, 0x35, 0xf1, 0x0b, 0xf7, 0x73, 0xf4, 0x06, 0xa0, 0x01, 0xed, 0x93, - 0xde, 0x58, 0x5e, 0xb2, 0xbb, 0xc9, 0x38, 0xe1, 0x74, 0xa8, 0x6f, 0xae, 0x0d, 0x25, 0x11, 0xd5, - 0xb3, 0x23, 0xe7, 0x5b, 0x7f, 0x71, 0xe1, 0xea, 0x4e, 0x1c, 0x0f, 0xc6, 0x53, 0x79, 0xf3, 0x9f, - 0x17, 0x9f, 0x37, 0x33, 0xd1, 0x70, 0x9f, 0x27, 0x1a, 0xcf, 0x9d, 0x2e, 0x39, 0x9e, 0xaf, 0xe4, - 0x79, 0xde, 0xfb, 0x93, 0x73, 0xe9, 0x53, 0xdc, 0x84, 0x45, 0x63, 0x43, 0x3d, 0x44, 0xcc, 0x70, - 0x3a, 0xac, 0xee, 0x25, 0xc3, 0x5a, 0x9e, 0x13, 0xd6, 0x7f, 0x96, 0xe0, 0xea, 0xfe, 0x30, 0x8e, - 0x18, 0x9f, 0xbc, 0x45, 0xbc, 0x55, 0x30, 0xaa, 0x2b, 0x50, 0x0a, 0x7c, 0xfd, 0xe8, 0x2c, 0x05, - 0xbe, 0x77, 0x0a, 0x0d, 0xa5, 0x8e, 0xa6, 0x25, 0xf5, 0xdc, 0x27, 0x4b, 0xa1, 0x84, 0x50, 0x28, - 0xdb, 0x61, 0xee, 0x84, 0xc3, 0xbc, 0xdf, 0xda, 0xd1, 0xf8, 0x00, 0x50, 0xa0, 0x69, 0x74, 0xcd, - 0x75, 0xdb, 0xb4, 0x85, 0x9b, 0x96, 0x89, 0x9c, 0xad, 0xb7, 0xa7, 0xf9, 0xe3, 0xb5, 0x60, 0x6a, - 0x26, 0xb9, 0x78, 0xf5, 0xfd, 0x9b, 0x03, 0x2b, 0xa2, 0xdf, 0x64, 0x2d, 0xfe, 0xc5, 0x35, 0x77, - 0x36, 0xf1, 0xf2, 0xa9, 0x14, 0x4a, 0x4d, 0xed, 0xe6, 0x0b, 0xef, 0xef, 0x57, 0x0e, 0x5c, 0x33, - 0xcf, 0x14, 0xd1, 0xd6, 0xf3, 0x9e, 0x64, 0xa7, 0x16, 0xaf, 0x5b, 0xa2, 0x2a, 0xa4, 0xd8, 0xf9, - 0x8f, 0x32, 0x1b, 0x75, 0x71, 0x76, 0x1f, 0x39, 0xf0, 0x59, 0x73, 0xc9, 0xb2, 0x28, 0x7e, 0x02, - 0xcf, 0x82, 0x4f, 0xe4, 0x32, 0xf2, 0x0f, 0x07, 0xd6, 0x52, 0x5a, 0xe9, 0x8d, 0x24, 0xb9, 0x38, - 0x2d, 0xf4, 0x36, 0x40, 0x2f, 0x0a, 0x43, 0xda, 0xe3, 0xe6, 0x9e, 0x7f, 0x56, 0xcd, 0xcd, 0xa0, - 0xde, 0xf7, 0xad, 0xfd, 0x5c, 0x87, 0x85, 0x68, 0xc4, 0xe3, 0x11, 0xd7, 0x29, 0xa9, 0x47, 0x17, - 0x0e, 0xc3, 0xd6, 0x2f, 0x6a, 0x50, 0x35, 0x4f, 0x32, 0xf4, 0x3d, 0xa8, 0xdd, 0xa3, 0x5c, 0xff, - 0x42, 0xf5, 0xa5, 0x73, 0x5e, 0xbb, 0x2a, 0x81, 0xbe, 0x5c, 0xe8, 0x4d, 0x8c, 0x06, 0x73, 0xde, - 0x7f, 0x68, 0xd3, 0x5a, 0x9f, 0x8b, 0x48, 0x2d, 0xbd, 0x56, 0x00, 0xa9, 0xad, 0xfd, 0xf0, 0xac, - 0xc7, 0x07, 0xba, 0x61, 0x29, 0x9a, 0x0f, 0x4b, 0xed, 0xb6, 0x8b, 0xc2, 0xb5, 0xf1, 0xd1, 0xfc, - 0xc7, 0x03, 0x7a, 0x3d, 0x47, 0xd7, 0x34, 0x28, 0x35, 0xfc, 0x46, 0x31, 0xb0, 0x36, 0x1b, 0xe4, - 0xbf, 0x41, 0xd1, 0x86, 0xa5, 0x25, 0x0f, 0x90, 0x9a, 0xdb, 0x3c, 0x1f, 0xa8, 0x4d, 0xdd, 0xb7, - 0xde, 0x18, 0xe8, 0x15, 0x6b, 0x59, 0x3a, 0x9b, 0x2a, 0x7d, 0x75, 0x8e, 0x54, 0x6b, 0xfa, 0xee, - 0xe4, 0x8d, 0x1f, 0x7d, 0xde, 0x7e, 0xdb, 0x5a, 0x82, 0x54, 0xdf, 0xfa, 0x7c, 0x80, 0x56, 0xd9, - 0xcb, 0xbb, 0x52, 0x23, 0x3b, 0x4d, 0x67, 0xc5, 0xa9, 0xfa, 0xaf, 0x9c, 0x07, 0xd3, 0x46, 0x8e, - 0x72, 0x2f, 0x60, 0xc8, 0x5e, 0x9e, 0x23, 0x4f, 0xcd, 0x6c, 0x9c, 0x8b, 0xcb, 0xec, 0xe4, 0xb4, - 0xc5, 0x09, 0x3b, 0x79, 0x6d, 0x33, 0xcf, 0x4e, 0x3e, 0x4e, 0xdb, 0x79, 0x3c, 0xdd, 0x09, 0xd1, - 0x17, 0xa6, 0x1c, 0x9d, 0x89, 0x52, 0xed, 0xad, 0xb3, 0x20, 0x5a, 0xf1, 0xd7, 0xd5, 0xef, 0xf7, - 0x68, 0xe2, 0xe7, 0x4f, 0x1e, 0xc5, 0xa9, 0x92, 0xe6, 0xac, 0x40, 0x2d, 0xdd, 0xfa, 0x89, 0x0b, - 0x75, 0xab, 0x31, 0xa0, 0x0f, 0xec, 0xe2, 0xb4, 0x91, 0x53, 0x76, 0xec, 0x1e, 0x97, 0x9b, 0xd5, - 0x73, 0x80, 0x9a, 0xea, 0xe9, 0x19, 0xfd, 0x08, 0xe5, 0x9d, 0xc5, 0x19, 0x54, 0x6a, 0xf4, 0x46, - 0x41, 0xb4, 0xb6, 0xfc, 0x24, 0xa7, 0xd5, 0x4c, 0x94, 0xdf, 0x19, 0x69, 0x6e, 0xf9, 0xcd, 0x43, - 0x29, 0x0b, 0x6f, 0x3a, 0x97, 0x08, 0xc4, 0x93, 0x05, 0xf9, 0xc7, 0xdc, 0xad, 0xff, 0x05, 0x00, - 0x00, 0xff, 0xff, 0xbc, 0x68, 0xf6, 0x08, 0xab, 0x1b, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/terraform/internal/tfplugin5/tfplugin5.proto b/vendor/github.com/hashicorp/terraform/internal/tfplugin5/tfplugin5.proto deleted file mode 100644 index 39c0fe39..00000000 --- a/vendor/github.com/hashicorp/terraform/internal/tfplugin5/tfplugin5.proto +++ /dev/null @@ -1,350 +0,0 @@ -// Terraform Plugin RPC protocol version 5.0 -// -// This file defines version 5.0 of the RPC protocol. To implement a plugin -// against this protocol, copy this definition into your own codebase and -// use protoc to generate stubs for your target language. -// -// This file will be updated in-place in the source Terraform repository for -// any minor versions of protocol 5, but later minor versions will always be -// backwards compatible. Breaking changes, if any are required, will come -// in a subsequent major version with its own separate proto definition. -// -// Note that only the proto files included in a release tag of Terraform are -// official protocol releases. Proto files taken from other commits may include -// incomplete changes or features that did not make it into a final release. -// In all reasonable cases, plugin developers should take the proto file from -// the tag of the most recent release of Terraform, and not from the master -// branch or any other development branch. -// -syntax = "proto3"; - -package tfplugin5; - -// DynamicValue is an opaque encoding of terraform data, with the field name -// indicating the encoding scheme used. -message DynamicValue { - bytes msgpack = 1; - bytes json = 2; -} - -message Diagnostic { - enum Severity { - INVALID = 0; - ERROR = 1; - WARNING = 2; - } - Severity severity = 1; - string summary = 2; - string detail = 3; - AttributePath attribute = 4; -} - -message AttributePath { - message Step { - oneof selector { - // Set "attribute_name" to represent looking up an attribute - // in the current object value. - string attribute_name = 1; - // Set "element_key_*" to represent looking up an element in - // an indexable collection type. - string element_key_string = 2; - int64 element_key_int = 3; - } - } - repeated Step steps = 1; -} - -message Stop { - message Request { - } - message Response { - string Error = 1; - } -} - -// RawState holds the stored state for a resource to be upgraded by the -// provider. It can be in one of two formats, the current json encoded format -// in bytes, or the legacy flatmap format as a map of strings. -message RawState { - bytes json = 1; - map flatmap = 2; -} - -// Schema is the configuration schema for a Resource, Provider, or Provisioner. -message Schema { - message Block { - int64 version = 1; - repeated Attribute attributes = 2; - repeated NestedBlock block_types = 3; - } - - message Attribute { - string name = 1; - bytes type = 2; - string description = 3; - bool required = 4; - bool optional = 5; - bool computed = 6; - bool sensitive = 7; - } - - message NestedBlock { - enum NestingMode { - INVALID = 0; - SINGLE = 1; - LIST = 2; - SET = 3; - MAP = 4; - } - - string type_name = 1; - Block block = 2; - NestingMode nesting = 3; - int64 min_items = 4; - int64 max_items = 5; - } - - // The version of the schema. - // Schemas are versioned, so that providers can upgrade a saved resource - // state when the schema is changed. - int64 version = 1; - - // Block is the top level configuration block for this schema. - Block block = 2; -} - -service Provider { - //////// Information about what a provider supports/expects - rpc GetSchema(GetProviderSchema.Request) returns (GetProviderSchema.Response); - rpc PrepareProviderConfig(PrepareProviderConfig.Request) returns (PrepareProviderConfig.Response); - rpc ValidateResourceTypeConfig(ValidateResourceTypeConfig.Request) returns (ValidateResourceTypeConfig.Response); - rpc ValidateDataSourceConfig(ValidateDataSourceConfig.Request) returns (ValidateDataSourceConfig.Response); - rpc UpgradeResourceState(UpgradeResourceState.Request) returns (UpgradeResourceState.Response); - - //////// One-time initialization, called before other functions below - rpc Configure(Configure.Request) returns (Configure.Response); - - //////// Managed Resource Lifecycle - rpc ReadResource(ReadResource.Request) returns (ReadResource.Response); - rpc PlanResourceChange(PlanResourceChange.Request) returns (PlanResourceChange.Response); - rpc ApplyResourceChange(ApplyResourceChange.Request) returns (ApplyResourceChange.Response); - rpc ImportResourceState(ImportResourceState.Request) returns (ImportResourceState.Response); - - rpc ReadDataSource(ReadDataSource.Request) returns (ReadDataSource.Response); - - //////// Graceful Shutdown - rpc Stop(Stop.Request) returns (Stop.Response); -} - -message GetProviderSchema { - message Request { - } - message Response { - Schema provider = 1; - map resource_schemas = 2; - map data_source_schemas = 3; - repeated Diagnostic diagnostics = 4; - } -} - -message PrepareProviderConfig { - message Request { - DynamicValue config = 1; - } - message Response { - DynamicValue prepared_config = 1; - repeated Diagnostic diagnostics = 2; - } -} - -message UpgradeResourceState { - message Request { - string type_name = 1; - - // version is the schema_version number recorded in the state file - int64 version = 2; - - // raw_state is the raw states as stored for the resource. Core does - // not have access to the schema of prior_version, so it's the - // provider's responsibility to interpret this value using the - // appropriate older schema. The raw_state will be the json encoded - // state, or a legacy flat-mapped format. - RawState raw_state = 3; - } - message Response { - // new_state is a msgpack-encoded data structure that, when interpreted with - // the _current_ schema for this resource type, is functionally equivalent to - // that which was given in prior_state_raw. - DynamicValue upgraded_state = 1; - - // diagnostics describes any errors encountered during migration that could not - // be safely resolved, and warnings about any possibly-risky assumptions made - // in the upgrade process. - repeated Diagnostic diagnostics = 2; - } -} - -message ValidateResourceTypeConfig { - message Request { - string type_name = 1; - DynamicValue config = 2; - } - message Response { - repeated Diagnostic diagnostics = 1; - } -} - -message ValidateDataSourceConfig { - message Request { - string type_name = 1; - DynamicValue config = 2; - } - message Response { - repeated Diagnostic diagnostics = 1; - } -} - -message Configure { - message Request { - string terraform_version = 1; - DynamicValue config = 2; - } - message Response { - repeated Diagnostic diagnostics = 1; - } -} - -message ReadResource { - message Request { - string type_name = 1; - DynamicValue current_state = 2; - } - message Response { - DynamicValue new_state = 1; - repeated Diagnostic diagnostics = 2; - } -} - -message PlanResourceChange { - message Request { - string type_name = 1; - DynamicValue prior_state = 2; - DynamicValue proposed_new_state = 3; - DynamicValue config = 4; - bytes prior_private = 5; - } - - message Response { - DynamicValue planned_state = 1; - repeated AttributePath requires_replace = 2; - bytes planned_private = 3; - repeated Diagnostic diagnostics = 4; - - - // This may be set only by the helper/schema "SDK" in the main Terraform - // repository, to request that Terraform Core >=0.12 permit additional - // inconsistencies that can result from the legacy SDK type system - // and its imprecise mapping to the >=0.12 type system. - // The change in behavior implied by this flag makes sense only for the - // specific details of the legacy SDK type system, and are not a general - // mechanism to avoid proper type handling in providers. - // - // ==== DO NOT USE THIS ==== - // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== - // ==== DO NOT USE THIS ==== - bool legacy_type_system = 5; - } -} - -message ApplyResourceChange { - message Request { - string type_name = 1; - DynamicValue prior_state = 2; - DynamicValue planned_state = 3; - DynamicValue config = 4; - bytes planned_private = 5; - } - message Response { - DynamicValue new_state = 1; - bytes private = 2; - repeated Diagnostic diagnostics = 3; - - // This may be set only by the helper/schema "SDK" in the main Terraform - // repository, to request that Terraform Core >=0.12 permit additional - // inconsistencies that can result from the legacy SDK type system - // and its imprecise mapping to the >=0.12 type system. - // The change in behavior implied by this flag makes sense only for the - // specific details of the legacy SDK type system, and are not a general - // mechanism to avoid proper type handling in providers. - // - // ==== DO NOT USE THIS ==== - // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== - // ==== DO NOT USE THIS ==== - bool legacy_type_system = 4; - } -} - -message ImportResourceState { - message Request { - string type_name = 1; - string id = 2; - } - - message ImportedResource { - string type_name = 1; - DynamicValue state = 2; - bytes private = 3; - } - - message Response { - repeated ImportedResource imported_resources = 1; - repeated Diagnostic diagnostics = 2; - } -} - -message ReadDataSource { - message Request { - string type_name = 1; - DynamicValue config = 2; - } - message Response { - DynamicValue state = 1; - repeated Diagnostic diagnostics = 2; - } -} - -service Provisioner { - rpc GetSchema(GetProvisionerSchema.Request) returns (GetProvisionerSchema.Response); - rpc ValidateProvisionerConfig(ValidateProvisionerConfig.Request) returns (ValidateProvisionerConfig.Response); - rpc ProvisionResource(ProvisionResource.Request) returns (stream ProvisionResource.Response); - rpc Stop(Stop.Request) returns (Stop.Response); -} - -message GetProvisionerSchema { - message Request { - } - message Response { - Schema provisioner = 1; - repeated Diagnostic diagnostics = 2; - } -} - -message ValidateProvisionerConfig { - message Request { - DynamicValue config = 1; - } - message Response { - repeated Diagnostic diagnostics = 1; - } -} - -message ProvisionResource { - message Request { - DynamicValue config = 1; - DynamicValue connection = 2; - } - message Response { - string output = 1; - repeated Diagnostic diagnostics = 2; - } -} diff --git a/vendor/github.com/hashicorp/terraform/lang/data.go b/vendor/github.com/hashicorp/terraform/lang/data.go deleted file mode 100644 index 80313d6c..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/data.go +++ /dev/null @@ -1,33 +0,0 @@ -package lang - -import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// Data is an interface whose implementations can provide cty.Value -// representations of objects identified by referenceable addresses from -// the addrs package. -// -// This interface will grow each time a new type of reference is added, and so -// implementations outside of the Terraform codebases are not advised. -// -// Each method returns a suitable value and optionally some diagnostics. If the -// returned diagnostics contains errors then the type of the returned value is -// used to construct an unknown value of the same type which is then used in -// place of the requested object so that type checking can still proceed. In -// cases where it's not possible to even determine a suitable result type, -// cty.DynamicVal is returned along with errors describing the problem. -type Data interface { - StaticValidateReferences(refs []*addrs.Reference, self addrs.Referenceable) tfdiags.Diagnostics - - GetCountAttr(addrs.CountAttr, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetResourceInstance(addrs.ResourceInstance, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetLocalValue(addrs.LocalValue, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetModuleInstance(addrs.ModuleCallInstance, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetModuleInstanceOutput(addrs.ModuleCallOutput, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetPathAttr(addrs.PathAttr, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetTerraformAttr(addrs.TerraformAttr, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetInputVariable(addrs.InputVariable, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/doc.go b/vendor/github.com/hashicorp/terraform/lang/doc.go deleted file mode 100644 index af5c5cac..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package lang deals with the runtime aspects of Terraform's configuration -// language, with concerns such as expression evaluation. It is closely related -// to sibling package "configs", which is responsible for configuration -// parsing and static validation. -package lang diff --git a/vendor/github.com/hashicorp/terraform/lang/eval.go b/vendor/github.com/hashicorp/terraform/lang/eval.go deleted file mode 100644 index b5aaa858..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/eval.go +++ /dev/null @@ -1,470 +0,0 @@ -package lang - -import ( - "fmt" - "log" - "strconv" - - "github.com/hashicorp/terraform/addrs" - - "github.com/hashicorp/hcl2/ext/dynblock" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcldec" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// ExpandBlock expands any "dynamic" blocks present in the given body. The -// result is a body with those blocks expanded, ready to be evaluated with -// EvalBlock. -// -// If the returned diagnostics contains errors then the result may be -// incomplete or invalid. -func (s *Scope) ExpandBlock(body hcl.Body, schema *configschema.Block) (hcl.Body, tfdiags.Diagnostics) { - spec := schema.DecoderSpec() - - traversals := dynblock.ForEachVariablesHCLDec(body, spec) - refs, diags := References(traversals) - - ctx, ctxDiags := s.EvalContext(refs) - diags = diags.Append(ctxDiags) - - return dynblock.Expand(body, ctx), diags -} - -// EvalBlock evaluates the given body using the given block schema and returns -// a cty object value representing its contents. The type of the result conforms -// to the implied type of the given schema. -// -// This function does not automatically expand "dynamic" blocks within the -// body. If that is desired, first call the ExpandBlock method to obtain -// an expanded body to pass to this method. -// -// If the returned diagnostics contains errors then the result may be -// incomplete or invalid. -func (s *Scope) EvalBlock(body hcl.Body, schema *configschema.Block) (cty.Value, tfdiags.Diagnostics) { - spec := schema.DecoderSpec() - - traversals := hcldec.Variables(body, spec) - refs, diags := References(traversals) - - ctx, ctxDiags := s.EvalContext(refs) - diags = diags.Append(ctxDiags) - if diags.HasErrors() { - // We'll stop early if we found problems in the references, because - // it's likely evaluation will produce redundant copies of the same errors. - return cty.UnknownVal(schema.ImpliedType()), diags - } - - val, evalDiags := hcldec.Decode(body, spec, ctx) - diags = diags.Append(evalDiags) - - return val, diags -} - -// EvalExpr evaluates a single expression in the receiving context and returns -// the resulting value. The value will be converted to the given type before -// it is returned if possible, or else an error diagnostic will be produced -// describing the conversion error. -// -// Pass an expected type of cty.DynamicPseudoType to skip automatic conversion -// and just obtain the returned value directly. -// -// If the returned diagnostics contains errors then the result may be -// incomplete, but will always be of the requested type. -func (s *Scope) EvalExpr(expr hcl.Expression, wantType cty.Type) (cty.Value, tfdiags.Diagnostics) { - refs, diags := ReferencesInExpr(expr) - - ctx, ctxDiags := s.EvalContext(refs) - diags = diags.Append(ctxDiags) - if diags.HasErrors() { - // We'll stop early if we found problems in the references, because - // it's likely evaluation will produce redundant copies of the same errors. - return cty.UnknownVal(wantType), diags - } - - val, evalDiags := expr.Value(ctx) - diags = diags.Append(evalDiags) - - if wantType != cty.DynamicPseudoType { - var convErr error - val, convErr = convert.Convert(val, wantType) - if convErr != nil { - val = cty.UnknownVal(wantType) - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect value type", - Detail: fmt.Sprintf("Invalid expression value: %s.", tfdiags.FormatError(convErr)), - Subject: expr.Range().Ptr(), - }) - } - } - - return val, diags -} - -// EvalReference evaluates the given reference in the receiving scope and -// returns the resulting value. The value will be converted to the given type before -// it is returned if possible, or else an error diagnostic will be produced -// describing the conversion error. -// -// Pass an expected type of cty.DynamicPseudoType to skip automatic conversion -// and just obtain the returned value directly. -// -// If the returned diagnostics contains errors then the result may be -// incomplete, but will always be of the requested type. -func (s *Scope) EvalReference(ref *addrs.Reference, wantType cty.Type) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // We cheat a bit here and just build an EvalContext for our requested - // reference with the "self" address overridden, and then pull the "self" - // result out of it to return. - ctx, ctxDiags := s.evalContext([]*addrs.Reference{ref}, ref.Subject) - diags = diags.Append(ctxDiags) - val := ctx.Variables["self"] - if val == cty.NilVal { - val = cty.DynamicVal - } - - var convErr error - val, convErr = convert.Convert(val, wantType) - if convErr != nil { - val = cty.UnknownVal(wantType) - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect value type", - Detail: fmt.Sprintf("Invalid expression value: %s.", tfdiags.FormatError(convErr)), - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - } - - return val, diags -} - -// EvalContext constructs a HCL expression evaluation context whose variable -// scope contains sufficient values to satisfy the given set of references. -// -// Most callers should prefer to use the evaluation helper methods that -// this type offers, but this is here for less common situations where the -// caller will handle the evaluation calls itself. -func (s *Scope) EvalContext(refs []*addrs.Reference) (*hcl.EvalContext, tfdiags.Diagnostics) { - return s.evalContext(refs, s.SelfAddr) -} - -func (s *Scope) evalContext(refs []*addrs.Reference, selfAddr addrs.Referenceable) (*hcl.EvalContext, tfdiags.Diagnostics) { - if s == nil { - panic("attempt to construct EvalContext for nil Scope") - } - - var diags tfdiags.Diagnostics - vals := make(map[string]cty.Value) - funcs := s.Functions() - ctx := &hcl.EvalContext{ - Variables: vals, - Functions: funcs, - } - - if len(refs) == 0 { - // Easy path for common case where there are no references at all. - return ctx, diags - } - - // First we'll do static validation of the references. This catches things - // early that might otherwise not get caught due to unknown values being - // present in the scope during planning. - if staticDiags := s.Data.StaticValidateReferences(refs, selfAddr); staticDiags.HasErrors() { - diags = diags.Append(staticDiags) - return ctx, diags - } - - // The reference set we are given has not been de-duped, and so there can - // be redundant requests in it for two reasons: - // - The same item is referenced multiple times - // - Both an item and that item's container are separately referenced. - // We will still visit every reference here and ask our data source for - // it, since that allows us to gather a full set of any errors and - // warnings, but once we've gathered all the data we'll then skip anything - // that's redundant in the process of populating our values map. - dataResources := map[string]map[string]map[addrs.InstanceKey]cty.Value{} - managedResources := map[string]map[string]map[addrs.InstanceKey]cty.Value{} - wholeModules := map[string]map[addrs.InstanceKey]cty.Value{} - moduleOutputs := map[string]map[addrs.InstanceKey]map[string]cty.Value{} - inputVariables := map[string]cty.Value{} - localValues := map[string]cty.Value{} - pathAttrs := map[string]cty.Value{} - terraformAttrs := map[string]cty.Value{} - countAttrs := map[string]cty.Value{} - var self cty.Value - - for _, ref := range refs { - rng := ref.SourceRange - isSelf := false - - rawSubj := ref.Subject - if rawSubj == addrs.Self { - if selfAddr == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "self" reference`, - // This detail message mentions some current practice that - // this codepath doesn't really "know about". If the "self" - // object starts being supported in more contexts later then - // we'll need to adjust this message. - Detail: `The "self" object is not available in this context. This object can be used only in resource provisioner and connection blocks.`, - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - continue - } - - // Treat "self" as an alias for the configured self address. - rawSubj = selfAddr - isSelf = true - - if rawSubj == addrs.Self { - // Programming error: the self address cannot alias itself. - panic("scope SelfAddr attempting to alias itself") - } - } - - // This type switch must cover all of the "Referenceable" implementations - // in package addrs. - switch subj := rawSubj.(type) { - - case addrs.ResourceInstance: - var into map[string]map[string]map[addrs.InstanceKey]cty.Value - switch subj.Resource.Mode { - case addrs.ManagedResourceMode: - into = managedResources - case addrs.DataResourceMode: - into = dataResources - default: - panic(fmt.Errorf("unsupported ResourceMode %s", subj.Resource.Mode)) - } - - val, valDiags := normalizeRefValue(s.Data.GetResourceInstance(subj, rng)) - diags = diags.Append(valDiags) - - r := subj.Resource - if into[r.Type] == nil { - into[r.Type] = make(map[string]map[addrs.InstanceKey]cty.Value) - } - if into[r.Type][r.Name] == nil { - into[r.Type][r.Name] = make(map[addrs.InstanceKey]cty.Value) - } - into[r.Type][r.Name][subj.Key] = val - if isSelf { - self = val - } - - case addrs.ModuleCallInstance: - val, valDiags := normalizeRefValue(s.Data.GetModuleInstance(subj, rng)) - diags = diags.Append(valDiags) - - if wholeModules[subj.Call.Name] == nil { - wholeModules[subj.Call.Name] = make(map[addrs.InstanceKey]cty.Value) - } - wholeModules[subj.Call.Name][subj.Key] = val - if isSelf { - self = val - } - - case addrs.ModuleCallOutput: - val, valDiags := normalizeRefValue(s.Data.GetModuleInstanceOutput(subj, rng)) - diags = diags.Append(valDiags) - - callName := subj.Call.Call.Name - callKey := subj.Call.Key - if moduleOutputs[callName] == nil { - moduleOutputs[callName] = make(map[addrs.InstanceKey]map[string]cty.Value) - } - if moduleOutputs[callName][callKey] == nil { - moduleOutputs[callName][callKey] = make(map[string]cty.Value) - } - moduleOutputs[callName][callKey][subj.Name] = val - if isSelf { - self = val - } - - case addrs.InputVariable: - val, valDiags := normalizeRefValue(s.Data.GetInputVariable(subj, rng)) - diags = diags.Append(valDiags) - inputVariables[subj.Name] = val - if isSelf { - self = val - } - - case addrs.LocalValue: - val, valDiags := normalizeRefValue(s.Data.GetLocalValue(subj, rng)) - diags = diags.Append(valDiags) - localValues[subj.Name] = val - if isSelf { - self = val - } - - case addrs.PathAttr: - val, valDiags := normalizeRefValue(s.Data.GetPathAttr(subj, rng)) - diags = diags.Append(valDiags) - pathAttrs[subj.Name] = val - if isSelf { - self = val - } - - case addrs.TerraformAttr: - val, valDiags := normalizeRefValue(s.Data.GetTerraformAttr(subj, rng)) - diags = diags.Append(valDiags) - terraformAttrs[subj.Name] = val - if isSelf { - self = val - } - - case addrs.CountAttr: - val, valDiags := normalizeRefValue(s.Data.GetCountAttr(subj, rng)) - diags = diags.Append(valDiags) - countAttrs[subj.Name] = val - if isSelf { - self = val - } - - default: - // Should never happen - panic(fmt.Errorf("Scope.buildEvalContext cannot handle address type %T", rawSubj)) - } - } - - for k, v := range buildResourceObjects(managedResources) { - vals[k] = v - } - vals["data"] = cty.ObjectVal(buildResourceObjects(dataResources)) - vals["module"] = cty.ObjectVal(buildModuleObjects(wholeModules, moduleOutputs)) - vals["var"] = cty.ObjectVal(inputVariables) - vals["local"] = cty.ObjectVal(localValues) - vals["path"] = cty.ObjectVal(pathAttrs) - vals["terraform"] = cty.ObjectVal(terraformAttrs) - vals["count"] = cty.ObjectVal(countAttrs) - if self != cty.NilVal { - vals["self"] = self - } - - return ctx, diags -} - -func buildResourceObjects(resources map[string]map[string]map[addrs.InstanceKey]cty.Value) map[string]cty.Value { - vals := make(map[string]cty.Value) - for typeName, names := range resources { - nameVals := make(map[string]cty.Value) - for name, keys := range names { - nameVals[name] = buildInstanceObjects(keys) - } - vals[typeName] = cty.ObjectVal(nameVals) - } - return vals -} - -func buildModuleObjects(wholeModules map[string]map[addrs.InstanceKey]cty.Value, moduleOutputs map[string]map[addrs.InstanceKey]map[string]cty.Value) map[string]cty.Value { - vals := make(map[string]cty.Value) - - for name, keys := range wholeModules { - vals[name] = buildInstanceObjects(keys) - } - - for name, keys := range moduleOutputs { - if _, exists := wholeModules[name]; exists { - // If we also have a whole module value for this name then we'll - // skip this since the individual outputs are embedded in that result. - continue - } - - // The shape of this collection isn't compatible with buildInstanceObjects, - // but rather than replicating most of the buildInstanceObjects logic - // here we'll instead first transform the structure to be what that - // function expects and then use it. This is a little wasteful, but - // we do not expect this these maps to be large and so the extra work - // here should not hurt too much. - flattened := make(map[addrs.InstanceKey]cty.Value, len(keys)) - for k, vals := range keys { - flattened[k] = cty.ObjectVal(vals) - } - vals[name] = buildInstanceObjects(flattened) - } - - return vals -} - -func buildInstanceObjects(keys map[addrs.InstanceKey]cty.Value) cty.Value { - if val, exists := keys[addrs.NoKey]; exists { - // If present, a "no key" value supersedes all other values, - // since they should be embedded inside it. - return val - } - - // If we only have individual values then we need to construct - // either a list or a map, depending on what sort of keys we - // have. - haveInt := false - haveString := false - maxInt := 0 - - for k := range keys { - switch tk := k.(type) { - case addrs.IntKey: - haveInt = true - if int(tk) > maxInt { - maxInt = int(tk) - } - case addrs.StringKey: - haveString = true - } - } - - // We should either have ints or strings and not both, but - // if we have both then we'll prefer strings and let the - // language interpreter try to convert the int keys into - // strings in a map. - switch { - case haveString: - vals := make(map[string]cty.Value) - for k, v := range keys { - switch tk := k.(type) { - case addrs.StringKey: - vals[string(tk)] = v - case addrs.IntKey: - sk := strconv.Itoa(int(tk)) - vals[sk] = v - } - } - return cty.ObjectVal(vals) - case haveInt: - // We'll make a tuple that is long enough for our maximum - // index value. It doesn't matter if we end up shorter than - // the number of instances because if length(...) were - // being evaluated we would've got a NoKey reference and - // thus not ended up in this codepath at all. - vals := make([]cty.Value, maxInt+1) - for i := range vals { - if v, exists := keys[addrs.IntKey(i)]; exists { - vals[i] = v - } else { - // Just a placeholder, since nothing will access this anyway - vals[i] = cty.DynamicVal - } - } - return cty.TupleVal(vals) - default: - // Should never happen because there are no other key types. - log.Printf("[ERROR] strange makeInstanceObjects call with no supported key types") - return cty.EmptyObjectVal - } -} - -func normalizeRefValue(val cty.Value, diags tfdiags.Diagnostics) (cty.Value, tfdiags.Diagnostics) { - if diags.HasErrors() { - // If there are errors then we will force an unknown result so that - // we can still evaluate and catch type errors but we'll avoid - // producing redundant re-statements of the same errors we've already - // dealt with here. - return cty.UnknownVal(val.Type()), diags - } - return val, diags -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/cidr.go b/vendor/github.com/hashicorp/terraform/lang/funcs/cidr.go deleted file mode 100644 index 6ce8aa9f..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/cidr.go +++ /dev/null @@ -1,129 +0,0 @@ -package funcs - -import ( - "fmt" - "net" - - "github.com/apparentlymart/go-cidr/cidr" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/gocty" -) - -// CidrHostFunc contructs a function that calculates a full host IP address -// within a given IP network address prefix. -var CidrHostFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "prefix", - Type: cty.String, - }, - { - Name: "hostnum", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var hostNum int - if err := gocty.FromCtyValue(args[1], &hostNum); err != nil { - return cty.UnknownVal(cty.String), err - } - _, network, err := net.ParseCIDR(args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) - } - - ip, err := cidr.Host(network, hostNum) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(ip.String()), nil - }, -}) - -// CidrNetmaskFunc contructs a function that converts an IPv4 address prefix given -// in CIDR notation into a subnet mask address. -var CidrNetmaskFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "prefix", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - _, network, err := net.ParseCIDR(args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) - } - - return cty.StringVal(net.IP(network.Mask).String()), nil - }, -}) - -// CidrSubnetFunc contructs a function that calculates a subnet address within -// a given IP network address prefix. -var CidrSubnetFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "prefix", - Type: cty.String, - }, - { - Name: "newbits", - Type: cty.Number, - }, - { - Name: "netnum", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var newbits int - if err := gocty.FromCtyValue(args[1], &newbits); err != nil { - return cty.UnknownVal(cty.String), err - } - var netnum int - if err := gocty.FromCtyValue(args[2], &netnum); err != nil { - return cty.UnknownVal(cty.String), err - } - - _, network, err := net.ParseCIDR(args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) - } - - // For portability with 32-bit systems where the subnet number - // will be a 32-bit int, we only allow extension of 32 bits in - // one call even if we're running on a 64-bit machine. - // (Of course, this is significant only for IPv6.) - if newbits > 32 { - return cty.UnknownVal(cty.String), fmt.Errorf("may not extend prefix by more than 32 bits") - } - - newNetwork, err := cidr.Subnet(network, newbits, netnum) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(newNetwork.String()), nil - }, -}) - -// CidrHost calculates a full host IP address within a given IP network address prefix. -func CidrHost(prefix, hostnum cty.Value) (cty.Value, error) { - return CidrHostFunc.Call([]cty.Value{prefix, hostnum}) -} - -// CidrNetmask converts an IPv4 address prefix given in CIDR notation into a subnet mask address. -func CidrNetmask(prefix cty.Value) (cty.Value, error) { - return CidrNetmaskFunc.Call([]cty.Value{prefix}) -} - -// CidrSubnet calculates a subnet address within a given IP network address prefix. -func CidrSubnet(prefix, newbits, netnum cty.Value) (cty.Value, error) { - return CidrSubnetFunc.Call([]cty.Value{prefix, newbits, netnum}) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/collection.go b/vendor/github.com/hashicorp/terraform/lang/funcs/collection.go deleted file mode 100644 index f01ab66c..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/collection.go +++ /dev/null @@ -1,1320 +0,0 @@ -package funcs - -import ( - "fmt" - "sort" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/function/stdlib" - "github.com/zclconf/go-cty/cty/gocty" -) - -var ElementFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.DynamicPseudoType, - }, - { - Name: "index", - Type: cty.Number, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - list := args[0] - listTy := list.Type() - switch { - case listTy.IsListType(): - return listTy.ElementType(), nil - case listTy.IsTupleType(): - if !args[1].IsKnown() { - // If the index isn't known yet then we can't predict the - // result type since each tuple element can have its own type. - return cty.DynamicPseudoType, nil - } - - etys := listTy.TupleElementTypes() - var index int - err := gocty.FromCtyValue(args[1], &index) - if err != nil { - // e.g. fractional number where whole number is required - return cty.DynamicPseudoType, fmt.Errorf("invalid index: %s", err) - } - if len(etys) == 0 { - return cty.DynamicPseudoType, fmt.Errorf("cannot use element function with an empty list") - } - index = index % len(etys) - return etys[index], nil - default: - return cty.DynamicPseudoType, fmt.Errorf("cannot read elements from %s", listTy.FriendlyName()) - } - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - var index int - err := gocty.FromCtyValue(args[1], &index) - if err != nil { - // can't happen because we checked this in the Type function above - return cty.DynamicVal, fmt.Errorf("invalid index: %s", err) - } - - if !args[0].IsKnown() { - return cty.UnknownVal(retType), nil - } - - l := args[0].LengthInt() - if l == 0 { - return cty.DynamicVal, fmt.Errorf("cannot use element function with an empty list") - } - index = index % l - - // We did all the necessary type checks in the type function above, - // so this is guaranteed not to fail. - return args[0].Index(cty.NumberIntVal(int64(index))), nil - }, -}) - -var LengthFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "value", - Type: cty.DynamicPseudoType, - AllowDynamicType: true, - AllowUnknown: true, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - collTy := args[0].Type() - switch { - case collTy == cty.String || collTy.IsTupleType() || collTy.IsObjectType() || collTy.IsListType() || collTy.IsMapType() || collTy.IsSetType() || collTy == cty.DynamicPseudoType: - return cty.Number, nil - default: - return cty.Number, fmt.Errorf("argument must be a string, a collection type, or a structural type") - } - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - coll := args[0] - collTy := args[0].Type() - switch { - case collTy == cty.DynamicPseudoType: - return cty.UnknownVal(cty.Number), nil - case collTy.IsTupleType(): - l := len(collTy.TupleElementTypes()) - return cty.NumberIntVal(int64(l)), nil - case collTy.IsObjectType(): - l := len(collTy.AttributeTypes()) - return cty.NumberIntVal(int64(l)), nil - case collTy == cty.String: - // We'll delegate to the cty stdlib strlen function here, because - // it deals with all of the complexities of tokenizing unicode - // grapheme clusters. - return stdlib.Strlen(coll) - case collTy.IsListType() || collTy.IsSetType() || collTy.IsMapType(): - return coll.Length(), nil - default: - // Should never happen, because of the checks in our Type func above - return cty.UnknownVal(cty.Number), fmt.Errorf("impossible value type for length(...)") - } - }, -}) - -// CoalesceListFunc contructs a function that takes any number of list arguments -// and returns the first one that isn't empty. -var CoalesceListFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "vals", - Type: cty.List(cty.DynamicPseudoType), - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - if len(args) == 0 { - return cty.NilType, fmt.Errorf("at least one argument is required") - } - - argTypes := make([]cty.Type, len(args)) - - for i, arg := range args { - argTypes[i] = arg.Type() - } - - retType, _ := convert.UnifyUnsafe(argTypes) - if retType == cty.NilType { - return cty.NilType, fmt.Errorf("all arguments must have the same type") - } - - return retType, nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - - vals := make([]cty.Value, 0, len(args)) - for _, arg := range args { - if !arg.IsKnown() { - // If we run into an unknown list at some point, we can't - // predict the final result yet. (If there's a known, non-empty - // arg before this then we won't get here.) - return cty.UnknownVal(retType), nil - } - - // We already know this will succeed because of the checks in our Type func above - arg, _ = convert.Convert(arg, retType) - - it := arg.ElementIterator() - for it.Next() { - _, v := it.Element() - vals = append(vals, v) - } - - if len(vals) > 0 { - return cty.ListVal(vals), nil - } - } - - return cty.NilVal, fmt.Errorf("no non-null arguments") - }, -}) - -// CompactFunc contructs a function that takes a list of strings and returns a new list -// with any empty string elements removed. -var CompactFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.String), - }, - }, - Type: function.StaticReturnType(cty.List(cty.String)), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - listVal := args[0] - if !listVal.IsWhollyKnown() { - // If some of the element values aren't known yet then we - // can't yet return a compacted list - return cty.UnknownVal(retType), nil - } - - var outputList []cty.Value - - for it := listVal.ElementIterator(); it.Next(); { - _, v := it.Element() - if v.AsString() == "" { - continue - } - outputList = append(outputList, v) - } - - if len(outputList) == 0 { - return cty.ListValEmpty(cty.String), nil - } - - return cty.ListVal(outputList), nil - }, -}) - -// ContainsFunc contructs a function that determines whether a given list contains -// a given single value as one of its elements. -var ContainsFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.DynamicPseudoType), - }, - { - Name: "value", - Type: cty.DynamicPseudoType, - }, - }, - Type: function.StaticReturnType(cty.Bool), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - - _, err = Index(args[0], args[1]) - if err != nil { - return cty.False, nil - } - - return cty.True, nil - }, -}) - -// IndexFunc contructs a function that finds the element index for a given value in a list. -var IndexFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.DynamicPseudoType, - }, - { - Name: "value", - Type: cty.DynamicPseudoType, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - if !(args[0].Type().IsListType() || args[0].Type().IsTupleType()) { - return cty.NilVal, fmt.Errorf("argument must be a list or tuple") - } - - if !args[0].IsKnown() { - return cty.UnknownVal(cty.Number), nil - } - - if args[0].LengthInt() == 0 { // Easy path - return cty.NilVal, fmt.Errorf("cannot search an empty list") - } - - for it := args[0].ElementIterator(); it.Next(); { - i, v := it.Element() - eq, err := stdlib.Equal(v, args[1]) - if err != nil { - return cty.NilVal, err - } - if !eq.IsKnown() { - return cty.UnknownVal(cty.Number), nil - } - if eq.True() { - return i, nil - } - } - return cty.NilVal, fmt.Errorf("item not found") - - }, -}) - -// DistinctFunc contructs a function that takes a list and returns a new list -// with any duplicate elements removed. -var DistinctFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.DynamicPseudoType), - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - return args[0].Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - listVal := args[0] - - if !listVal.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - var list []cty.Value - - for it := listVal.ElementIterator(); it.Next(); { - _, v := it.Element() - list, err = appendIfMissing(list, v) - if err != nil { - return cty.NilVal, err - } - } - - return cty.ListVal(list), nil - }, -}) - -// ChunklistFunc contructs a function that splits a single list into fixed-size chunks, -// returning a list of lists. -var ChunklistFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.DynamicPseudoType), - }, - { - Name: "size", - Type: cty.Number, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - return cty.List(args[0].Type()), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - listVal := args[0] - if !listVal.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - - var size int - err = gocty.FromCtyValue(args[1], &size) - if err != nil { - return cty.NilVal, fmt.Errorf("invalid index: %s", err) - } - - if size < 0 { - return cty.NilVal, fmt.Errorf("the size argument must be positive") - } - - output := make([]cty.Value, 0) - - // if size is 0, returns a list made of the initial list - if size == 0 { - output = append(output, listVal) - return cty.ListVal(output), nil - } - - chunk := make([]cty.Value, 0) - - l := args[0].LengthInt() - i := 0 - - for it := listVal.ElementIterator(); it.Next(); { - _, v := it.Element() - chunk = append(chunk, v) - - // Chunk when index isn't 0, or when reaching the values's length - if (i+1)%size == 0 || (i+1) == l { - output = append(output, cty.ListVal(chunk)) - chunk = make([]cty.Value, 0) - } - i++ - } - - return cty.ListVal(output), nil - }, -}) - -// FlattenFunc contructs a function that takes a list and replaces any elements -// that are lists with a flattened sequence of the list contents. -var FlattenFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.DynamicPseudoType), - }, - }, - Type: function.StaticReturnType(cty.List(cty.DynamicPseudoType)), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - inputList := args[0] - if !inputList.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - - if inputList.LengthInt() == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - outputList := make([]cty.Value, 0) - - return cty.ListVal(flattener(outputList, inputList)), nil - }, -}) - -// Flatten until it's not a cty.List -func flattener(finalList []cty.Value, flattenList cty.Value) []cty.Value { - - for it := flattenList.ElementIterator(); it.Next(); { - _, val := it.Element() - - if val.Type().IsListType() { - finalList = flattener(finalList, val) - } else { - finalList = append(finalList, val) - } - } - return finalList -} - -// KeysFunc contructs a function that takes a map and returns a sorted list of the map keys. -var KeysFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "inputMap", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - ty := args[0].Type() - switch { - case ty.IsMapType(): - return cty.List(cty.String), nil - case ty.IsObjectType(): - atys := ty.AttributeTypes() - if len(atys) == 0 { - return cty.EmptyTuple, nil - } - // All of our result elements will be strings, and atys just - // decides how many there are. - etys := make([]cty.Type, len(atys)) - for i := range etys { - etys[i] = cty.String - } - return cty.Tuple(etys), nil - default: - return cty.DynamicPseudoType, function.NewArgErrorf(0, "must have map or object type") - } - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - m := args[0] - var keys []cty.Value - - switch { - case m.Type().IsObjectType(): - // In this case we allow unknown values so we must work only with - // the attribute _types_, not with the value itself. - var names []string - for name := range m.Type().AttributeTypes() { - names = append(names, name) - } - sort.Strings(names) // same ordering guaranteed by cty's ElementIterator - if len(names) == 0 { - return cty.EmptyTupleVal, nil - } - keys = make([]cty.Value, len(names)) - for i, name := range names { - keys[i] = cty.StringVal(name) - } - return cty.TupleVal(keys), nil - default: - if !m.IsKnown() { - return cty.UnknownVal(retType), nil - } - - // cty guarantees that ElementIterator will iterate in lexicographical - // order by key. - for it := args[0].ElementIterator(); it.Next(); { - k, _ := it.Element() - keys = append(keys, k) - } - if len(keys) == 0 { - return cty.ListValEmpty(cty.String), nil - } - return cty.ListVal(keys), nil - } - }, -}) - -// ListFunc contructs a function that takes an arbitrary number of arguments -// and returns a list containing those values in the same order. -// -// This function is deprecated in Terraform v0.12 -var ListFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "vals", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - if len(args) == 0 { - return cty.NilType, fmt.Errorf("at least one argument is required") - } - - argTypes := make([]cty.Type, len(args)) - - for i, arg := range args { - argTypes[i] = arg.Type() - } - - retType, _ := convert.UnifyUnsafe(argTypes) - if retType == cty.NilType { - return cty.NilType, fmt.Errorf("all arguments must have the same type") - } - - return cty.List(retType), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - newList := make([]cty.Value, 0, len(args)) - - for _, arg := range args { - // We already know this will succeed because of the checks in our Type func above - arg, _ = convert.Convert(arg, retType.ElementType()) - newList = append(newList, arg) - } - - return cty.ListVal(newList), nil - }, -}) - -// LookupFunc contructs a function that performs dynamic lookups of map types. -var LookupFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "inputMap", - Type: cty.DynamicPseudoType, - }, - { - Name: "key", - Type: cty.String, - }, - }, - VarParam: &function.Parameter{ - Name: "default", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - if len(args) < 1 || len(args) > 3 { - return cty.NilType, fmt.Errorf("lookup() takes two or three arguments, got %d", len(args)) - } - - ty := args[0].Type() - - switch { - case ty.IsObjectType(): - if !args[1].IsKnown() { - return cty.DynamicPseudoType, nil - } - - key := args[1].AsString() - if ty.HasAttribute(key) { - return args[0].GetAttr(key).Type(), nil - } else if len(args) == 3 { - // if the key isn't found but a default is provided, - // return the default type - return args[2].Type(), nil - } - return cty.DynamicPseudoType, function.NewArgErrorf(0, "the given object has no attribute %q", key) - case ty.IsMapType(): - return ty.ElementType(), nil - default: - return cty.NilType, function.NewArgErrorf(0, "lookup() requires a map as the first argument") - } - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var defaultVal cty.Value - defaultValueSet := false - - if len(args) == 3 { - defaultVal = args[2] - defaultValueSet = true - } - - mapVar := args[0] - lookupKey := args[1].AsString() - - if !mapVar.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - - if mapVar.Type().IsObjectType() { - if mapVar.Type().HasAttribute(lookupKey) { - return mapVar.GetAttr(lookupKey), nil - } - } else if mapVar.HasIndex(cty.StringVal(lookupKey)) == cty.True { - v := mapVar.Index(cty.StringVal(lookupKey)) - if ty := v.Type(); !ty.Equals(cty.NilType) { - switch { - case ty.Equals(cty.String): - return cty.StringVal(v.AsString()), nil - case ty.Equals(cty.Number): - return cty.NumberVal(v.AsBigFloat()), nil - default: - return cty.NilVal, fmt.Errorf("lookup() can only be used with flat lists") - } - } - } - - if defaultValueSet { - defaultVal, err = convert.Convert(defaultVal, retType) - if err != nil { - return cty.NilVal, err - } - return defaultVal, nil - } - - return cty.UnknownVal(cty.DynamicPseudoType), fmt.Errorf( - "lookup failed to find '%s'", lookupKey) - }, -}) - -// MapFunc contructs a function that takes an even number of arguments and -// returns a map whose elements are constructed from consecutive pairs of arguments. -// -// This function is deprecated in Terraform v0.12 -var MapFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "vals", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - if len(args) < 2 || len(args)%2 != 0 { - return cty.NilType, fmt.Errorf("map requires an even number of two or more arguments, got %d", len(args)) - } - - argTypes := make([]cty.Type, len(args)/2) - index := 0 - - for i := 0; i < len(args); i += 2 { - argTypes[index] = args[i+1].Type() - index++ - } - - valType, _ := convert.UnifyUnsafe(argTypes) - if valType == cty.NilType { - return cty.NilType, fmt.Errorf("all arguments must have the same type") - } - - return cty.Map(valType), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - for _, arg := range args { - if !arg.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - } - - outputMap := make(map[string]cty.Value) - - for i := 0; i < len(args); i += 2 { - - key := args[i].AsString() - - err := gocty.FromCtyValue(args[i], &key) - if err != nil { - return cty.NilVal, err - } - - val := args[i+1] - - var variable cty.Value - err = gocty.FromCtyValue(val, &variable) - if err != nil { - return cty.NilVal, err - } - - // We already know this will succeed because of the checks in our Type func above - variable, _ = convert.Convert(variable, retType.ElementType()) - - // Check for duplicate keys - if _, ok := outputMap[key]; ok { - return cty.NilVal, fmt.Errorf("argument %d is a duplicate key: %q", i+1, key) - } - outputMap[key] = variable - } - - return cty.MapVal(outputMap), nil - }, -}) - -// MatchkeysFunc contructs a function that constructs a new list by taking a -// subset of elements from one list whose indexes match the corresponding -// indexes of values in another list. -var MatchkeysFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "values", - Type: cty.List(cty.DynamicPseudoType), - }, - { - Name: "keys", - Type: cty.List(cty.DynamicPseudoType), - }, - { - Name: "searchset", - Type: cty.List(cty.DynamicPseudoType), - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - if !args[1].Type().Equals(args[2].Type()) { - return cty.NilType, fmt.Errorf("lists must be of the same type") - } - - return args[0].Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - if !args[0].IsKnown() { - return cty.UnknownVal(cty.List(retType.ElementType())), nil - } - - if args[0].LengthInt() != args[1].LengthInt() { - return cty.ListValEmpty(retType.ElementType()), fmt.Errorf("length of keys and values should be equal") - } - - output := make([]cty.Value, 0) - - values := args[0] - keys := args[1] - searchset := args[2] - - // if searchset is empty, return an empty list. - if searchset.LengthInt() == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - - if !values.IsWhollyKnown() || !keys.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - - i := 0 - for it := keys.ElementIterator(); it.Next(); { - _, key := it.Element() - for iter := searchset.ElementIterator(); iter.Next(); { - _, search := iter.Element() - eq, err := stdlib.Equal(key, search) - if err != nil { - return cty.NilVal, err - } - if !eq.IsKnown() { - return cty.ListValEmpty(retType.ElementType()), nil - } - if eq.True() { - v := values.Index(cty.NumberIntVal(int64(i))) - output = append(output, v) - break - } - } - i++ - } - - // if we haven't matched any key, then output is an empty list. - if len(output) == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - return cty.ListVal(output), nil - }, -}) - -// MergeFunc contructs a function that takes an arbitrary number of maps and -// returns a single map that contains a merged set of elements from all of the maps. -// -// If more than one given map defines the same key then the one that is later in -// the argument sequence takes precedence. -var MergeFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "maps", - Type: cty.DynamicPseudoType, - AllowDynamicType: true, - AllowNull: true, - }, - Type: function.StaticReturnType(cty.DynamicPseudoType), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - outputMap := make(map[string]cty.Value) - - for _, arg := range args { - if !arg.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - if !arg.Type().IsObjectType() && !arg.Type().IsMapType() { - return cty.NilVal, fmt.Errorf("arguments must be maps or objects, got %#v", arg.Type().FriendlyName()) - } - for it := arg.ElementIterator(); it.Next(); { - k, v := it.Element() - outputMap[k.AsString()] = v - } - } - return cty.ObjectVal(outputMap), nil - }, -}) - -// SetProductFunc calculates the cartesian product of two or more sets or -// sequences. If the arguments are all lists then the result is a list of tuples, -// preserving the ordering of all of the input lists. Otherwise the result is a -// set of tuples. -var SetProductFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "sets", - Type: cty.DynamicPseudoType, - }, - Type: func(args []cty.Value) (retType cty.Type, err error) { - if len(args) < 2 { - return cty.NilType, fmt.Errorf("at least two arguments are required") - } - - listCount := 0 - elemTys := make([]cty.Type, len(args)) - for i, arg := range args { - aty := arg.Type() - switch { - case aty.IsSetType(): - elemTys[i] = aty.ElementType() - case aty.IsListType(): - elemTys[i] = aty.ElementType() - listCount++ - case aty.IsTupleType(): - // We can accept a tuple type only if there's some common type - // that all of its elements can be converted to. - allEtys := aty.TupleElementTypes() - if len(allEtys) == 0 { - elemTys[i] = cty.DynamicPseudoType - listCount++ - break - } - ety, _ := convert.UnifyUnsafe(allEtys) - if ety == cty.NilType { - return cty.NilType, function.NewArgErrorf(i, "all elements must be of the same type") - } - elemTys[i] = ety - listCount++ - default: - return cty.NilType, function.NewArgErrorf(i, "a set or a list is required") - } - } - - if listCount == len(args) { - return cty.List(cty.Tuple(elemTys)), nil - } - return cty.Set(cty.Tuple(elemTys)), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - ety := retType.ElementType() - - total := 1 - for _, arg := range args { - // Because of our type checking function, we are guaranteed that - // all of the arguments are known, non-null values of types that - // support LengthInt. - total *= arg.LengthInt() - } - - if total == 0 { - // If any of the arguments was an empty collection then our result - // is also an empty collection, which we'll short-circuit here. - if retType.IsListType() { - return cty.ListValEmpty(ety), nil - } - return cty.SetValEmpty(ety), nil - } - - subEtys := ety.TupleElementTypes() - product := make([][]cty.Value, total) - - b := make([]cty.Value, total*len(args)) - n := make([]int, len(args)) - s := 0 - argVals := make([][]cty.Value, len(args)) - for i, arg := range args { - argVals[i] = arg.AsValueSlice() - } - - for i := range product { - e := s + len(args) - pi := b[s:e] - product[i] = pi - s = e - - for j, n := range n { - val := argVals[j][n] - ty := subEtys[j] - if !val.Type().Equals(ty) { - var err error - val, err = convert.Convert(val, ty) - if err != nil { - // Should never happen since we checked this in our - // type-checking function. - return cty.NilVal, fmt.Errorf("failed to convert argVals[%d][%d] to %s; this is a bug in Terraform", j, n, ty.FriendlyName()) - } - } - pi[j] = val - } - - for j := len(n) - 1; j >= 0; j-- { - n[j]++ - if n[j] < len(argVals[j]) { - break - } - n[j] = 0 - } - } - - productVals := make([]cty.Value, total) - for i, vals := range product { - productVals[i] = cty.TupleVal(vals) - } - - if retType.IsListType() { - return cty.ListVal(productVals), nil - } - return cty.SetVal(productVals), nil - }, -}) - -// SliceFunc contructs a function that extracts some consecutive elements -// from within a list. -var SliceFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.DynamicPseudoType), - }, - { - Name: "startIndex", - Type: cty.Number, - }, - { - Name: "endIndex", - Type: cty.Number, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - return args[0].Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - inputList := args[0] - if !inputList.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - var startIndex, endIndex int - - if err = gocty.FromCtyValue(args[1], &startIndex); err != nil { - return cty.NilVal, fmt.Errorf("invalid start index: %s", err) - } - if err = gocty.FromCtyValue(args[2], &endIndex); err != nil { - return cty.NilVal, fmt.Errorf("invalid start index: %s", err) - } - - if startIndex < 0 { - return cty.NilVal, fmt.Errorf("from index must be >= 0") - } - if endIndex > inputList.LengthInt() { - return cty.NilVal, fmt.Errorf("to index must be <= length of the input list") - } - if startIndex > endIndex { - return cty.NilVal, fmt.Errorf("from index must be <= to index") - } - - var outputList []cty.Value - - i := 0 - for it := inputList.ElementIterator(); it.Next(); { - _, v := it.Element() - if i >= startIndex && i < endIndex { - outputList = append(outputList, v) - } - i++ - } - - if len(outputList) == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - return cty.ListVal(outputList), nil - }, -}) - -// TransposeFunc contructs a function that takes a map of lists of strings and -// swaps the keys and values to produce a new map of lists of strings. -var TransposeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "values", - Type: cty.Map(cty.List(cty.String)), - }, - }, - Type: function.StaticReturnType(cty.Map(cty.List(cty.String))), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - inputMap := args[0] - if !inputMap.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - - outputMap := make(map[string]cty.Value) - tmpMap := make(map[string][]string) - - for it := inputMap.ElementIterator(); it.Next(); { - inKey, inVal := it.Element() - for iter := inVal.ElementIterator(); iter.Next(); { - _, val := iter.Element() - if !val.Type().Equals(cty.String) { - return cty.MapValEmpty(cty.List(cty.String)), fmt.Errorf("input must be a map of lists of strings") - } - - outKey := val.AsString() - if _, ok := tmpMap[outKey]; !ok { - tmpMap[outKey] = make([]string, 0) - } - outVal := tmpMap[outKey] - outVal = append(outVal, inKey.AsString()) - sort.Strings(outVal) - tmpMap[outKey] = outVal - } - } - - for outKey, outVal := range tmpMap { - values := make([]cty.Value, 0) - for _, v := range outVal { - values = append(values, cty.StringVal(v)) - } - outputMap[outKey] = cty.ListVal(values) - } - - return cty.MapVal(outputMap), nil - }, -}) - -// ValuesFunc contructs a function that returns a list of the map values, -// in the order of the sorted keys. -var ValuesFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "values", - Type: cty.DynamicPseudoType, - }, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - ty := args[0].Type() - if ty.IsMapType() { - return cty.List(ty.ElementType()), nil - } else if ty.IsObjectType() { - // The result is a tuple type with all of the same types as our - // object type's attributes, sorted in lexicographical order by the - // keys. (This matches the sort order guaranteed by ElementIterator - // on a cty object value.) - atys := ty.AttributeTypes() - if len(atys) == 0 { - return cty.EmptyTuple, nil - } - attrNames := make([]string, 0, len(atys)) - for name := range atys { - attrNames = append(attrNames, name) - } - sort.Strings(attrNames) - - tys := make([]cty.Type, len(attrNames)) - for i, name := range attrNames { - tys[i] = atys[name] - } - return cty.Tuple(tys), nil - } - return cty.NilType, fmt.Errorf("values() requires a map as the first argument") - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - mapVar := args[0] - - // We can just iterate the map/object value here because cty guarantees - // that these types always iterate in key lexicographical order. - var values []cty.Value - for it := mapVar.ElementIterator(); it.Next(); { - _, val := it.Element() - values = append(values, val) - } - - if retType.IsTupleType() { - return cty.TupleVal(values), nil - } - if len(values) == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - return cty.ListVal(values), nil - }, -}) - -// ZipmapFunc contructs a function that constructs a map from a list of keys -// and a corresponding list of values. -var ZipmapFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "keys", - Type: cty.List(cty.String), - }, - { - Name: "values", - Type: cty.DynamicPseudoType, - }, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - keys := args[0] - values := args[1] - valuesTy := values.Type() - - switch { - case valuesTy.IsListType(): - return cty.Map(values.Type().ElementType()), nil - case valuesTy.IsTupleType(): - if !keys.IsWhollyKnown() { - // Since zipmap with a tuple produces an object, we need to know - // all of the key names before we can predict our result type. - return cty.DynamicPseudoType, nil - } - - keysRaw := keys.AsValueSlice() - valueTypesRaw := valuesTy.TupleElementTypes() - if len(keysRaw) != len(valueTypesRaw) { - return cty.NilType, fmt.Errorf("number of keys (%d) does not match number of values (%d)", len(keysRaw), len(valueTypesRaw)) - } - atys := make(map[string]cty.Type, len(valueTypesRaw)) - for i, keyVal := range keysRaw { - if keyVal.IsNull() { - return cty.NilType, fmt.Errorf("keys list has null value at index %d", i) - } - key := keyVal.AsString() - atys[key] = valueTypesRaw[i] - } - return cty.Object(atys), nil - - default: - return cty.NilType, fmt.Errorf("values argument must be a list or tuple value") - } - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - keys := args[0] - values := args[1] - - if !keys.IsWhollyKnown() { - // Unknown map keys and object attributes are not supported, so - // our entire result must be unknown in this case. - return cty.UnknownVal(retType), nil - } - - // both keys and values are guaranteed to be shallowly-known here, - // because our declared params above don't allow unknown or null values. - if keys.LengthInt() != values.LengthInt() { - return cty.NilVal, fmt.Errorf("number of keys (%d) does not match number of values (%d)", keys.LengthInt(), values.LengthInt()) - } - - output := make(map[string]cty.Value) - - i := 0 - for it := keys.ElementIterator(); it.Next(); { - _, v := it.Element() - val := values.Index(cty.NumberIntVal(int64(i))) - output[v.AsString()] = val - i++ - } - - switch { - case retType.IsMapType(): - if len(output) == 0 { - return cty.MapValEmpty(retType.ElementType()), nil - } - return cty.MapVal(output), nil - case retType.IsObjectType(): - return cty.ObjectVal(output), nil - default: - // Should never happen because the type-check function should've - // caught any other case. - return cty.NilVal, fmt.Errorf("internally selected incorrect result type %s (this is a bug)", retType.FriendlyName()) - } - }, -}) - -// helper function to add an element to a list, if it does not already exist -func appendIfMissing(slice []cty.Value, element cty.Value) ([]cty.Value, error) { - for _, ele := range slice { - eq, err := stdlib.Equal(ele, element) - if err != nil { - return slice, err - } - if eq.True() { - return slice, nil - } - } - return append(slice, element), nil -} - -// Element returns a single element from a given list at the given index. If -// index is greater than the length of the list then it is wrapped modulo -// the list length. -func Element(list, index cty.Value) (cty.Value, error) { - return ElementFunc.Call([]cty.Value{list, index}) -} - -// Length returns the number of elements in the given collection or number of -// Unicode characters in the given string. -func Length(collection cty.Value) (cty.Value, error) { - return LengthFunc.Call([]cty.Value{collection}) -} - -// CoalesceList takes any number of list arguments and returns the first one that isn't empty. -func CoalesceList(args ...cty.Value) (cty.Value, error) { - return CoalesceListFunc.Call(args) -} - -// Compact takes a list of strings and returns a new list -// with any empty string elements removed. -func Compact(list cty.Value) (cty.Value, error) { - return CompactFunc.Call([]cty.Value{list}) -} - -// Contains determines whether a given list contains a given single value -// as one of its elements. -func Contains(list, value cty.Value) (cty.Value, error) { - return ContainsFunc.Call([]cty.Value{list, value}) -} - -// Index finds the element index for a given value in a list. -func Index(list, value cty.Value) (cty.Value, error) { - return IndexFunc.Call([]cty.Value{list, value}) -} - -// Distinct takes a list and returns a new list with any duplicate elements removed. -func Distinct(list cty.Value) (cty.Value, error) { - return DistinctFunc.Call([]cty.Value{list}) -} - -// Chunklist splits a single list into fixed-size chunks, returning a list of lists. -func Chunklist(list, size cty.Value) (cty.Value, error) { - return ChunklistFunc.Call([]cty.Value{list, size}) -} - -// Flatten takes a list and replaces any elements that are lists with a flattened -// sequence of the list contents. -func Flatten(list cty.Value) (cty.Value, error) { - return FlattenFunc.Call([]cty.Value{list}) -} - -// Keys takes a map and returns a sorted list of the map keys. -func Keys(inputMap cty.Value) (cty.Value, error) { - return KeysFunc.Call([]cty.Value{inputMap}) -} - -// List takes any number of list arguments and returns a list containing those -// values in the same order. -func List(args ...cty.Value) (cty.Value, error) { - return ListFunc.Call(args) -} - -// Lookup performs a dynamic lookup into a map. -// There are two required arguments, map and key, plus an optional default, -// which is a value to return if no key is found in map. -func Lookup(args ...cty.Value) (cty.Value, error) { - return LookupFunc.Call(args) -} - -// Map takes an even number of arguments and returns a map whose elements are constructed -// from consecutive pairs of arguments. -func Map(args ...cty.Value) (cty.Value, error) { - return MapFunc.Call(args) -} - -// Matchkeys constructs a new list by taking a subset of elements from one list -// whose indexes match the corresponding indexes of values in another list. -func Matchkeys(values, keys, searchset cty.Value) (cty.Value, error) { - return MatchkeysFunc.Call([]cty.Value{values, keys, searchset}) -} - -// Merge takes an arbitrary number of maps and returns a single map that contains -// a merged set of elements from all of the maps. -// -// If more than one given map defines the same key then the one that is later in -// the argument sequence takes precedence. -func Merge(maps ...cty.Value) (cty.Value, error) { - return MergeFunc.Call(maps) -} - -// SetProduct computes the cartesian product of sets or sequences. -func SetProduct(sets ...cty.Value) (cty.Value, error) { - return SetProductFunc.Call(sets) -} - -// Slice extracts some consecutive elements from within a list. -func Slice(list, start, end cty.Value) (cty.Value, error) { - return SliceFunc.Call([]cty.Value{list, start, end}) -} - -// Transpose takes a map of lists of strings and swaps the keys and values to -// produce a new map of lists of strings. -func Transpose(values cty.Value) (cty.Value, error) { - return TransposeFunc.Call([]cty.Value{values}) -} - -// Values returns a list of the map values, in the order of the sorted keys. -// This function only works on flat maps. -func Values(values cty.Value) (cty.Value, error) { - return ValuesFunc.Call([]cty.Value{values}) -} - -// Zipmap constructs a map from a list of keys and a corresponding list of values. -func Zipmap(keys, values cty.Value) (cty.Value, error) { - return ZipmapFunc.Call([]cty.Value{keys, values}) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/conversion.go b/vendor/github.com/hashicorp/terraform/lang/funcs/conversion.go deleted file mode 100644 index 83f85979..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/conversion.go +++ /dev/null @@ -1,87 +0,0 @@ -package funcs - -import ( - "strconv" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/function" -) - -// MakeToFunc constructs a "to..." function, like "tostring", which converts -// its argument to a specific type or type kind. -// -// The given type wantTy can be any type constraint that cty's "convert" package -// would accept. In particular, this means that you can pass -// cty.List(cty.DynamicPseudoType) to mean "list of any single type", which -// will then cause cty to attempt to unify all of the element types when given -// a tuple. -func MakeToFunc(wantTy cty.Type) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "v", - // We use DynamicPseudoType rather than wantTy here so that - // all values will pass through the function API verbatim and - // we can handle the conversion logic within the Type and - // Impl functions. This allows us to customize the error - // messages to be more appropriate for an explicit type - // conversion, whereas the cty function system produces - // messages aimed at _implicit_ type conversions. - Type: cty.DynamicPseudoType, - AllowNull: true, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - gotTy := args[0].Type() - if gotTy.Equals(wantTy) { - return wantTy, nil - } - conv := convert.GetConversionUnsafe(args[0].Type(), wantTy) - if conv == nil { - // We'll use some specialized errors for some trickier cases, - // but most we can handle in a simple way. - switch { - case gotTy.IsTupleType() && wantTy.IsTupleType(): - return cty.NilType, function.NewArgErrorf(0, "incompatible tuple type for conversion: %s", convert.MismatchMessage(gotTy, wantTy)) - case gotTy.IsObjectType() && wantTy.IsObjectType(): - return cty.NilType, function.NewArgErrorf(0, "incompatible object type for conversion: %s", convert.MismatchMessage(gotTy, wantTy)) - default: - return cty.NilType, function.NewArgErrorf(0, "cannot convert %s to %s", gotTy.FriendlyName(), wantTy.FriendlyNameForConstraint()) - } - } - // If a conversion is available then everything is fine. - return wantTy, nil - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - // We didn't set "AllowUnknown" on our argument, so it is guaranteed - // to be known here but may still be null. - ret, err := convert.Convert(args[0], retType) - if err != nil { - // Because we used GetConversionUnsafe above, conversion can - // still potentially fail in here. For example, if the user - // asks to convert the string "a" to bool then we'll - // optimistically permit it during type checking but fail here - // once we note that the value isn't either "true" or "false". - gotTy := args[0].Type() - switch { - case gotTy == cty.String && wantTy == cty.Bool: - what := "string" - if !args[0].IsNull() { - what = strconv.Quote(args[0].AsString()) - } - return cty.NilVal, function.NewArgErrorf(0, `cannot convert %s to bool; only the strings "true" or "false" are allowed`, what) - case gotTy == cty.String && wantTy == cty.Number: - what := "string" - if !args[0].IsNull() { - what = strconv.Quote(args[0].AsString()) - } - return cty.NilVal, function.NewArgErrorf(0, `cannot convert %s to number; given string must be a decimal representation of a number`, what) - default: - return cty.NilVal, function.NewArgErrorf(0, "cannot convert %s to %s", gotTy.FriendlyName(), wantTy.FriendlyNameForConstraint()) - } - } - return ret, nil - }, - }) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/crypto.go b/vendor/github.com/hashicorp/terraform/lang/funcs/crypto.go deleted file mode 100644 index 5d17a1d0..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/crypto.go +++ /dev/null @@ -1,285 +0,0 @@ -package funcs - -import ( - "crypto/md5" - "crypto/rsa" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "crypto/x509" - "encoding/base64" - "encoding/hex" - "encoding/pem" - "fmt" - "hash" - - uuid "github.com/hashicorp/go-uuid" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/gocty" - "golang.org/x/crypto/bcrypt" -) - -var UUIDFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - result, err := uuid.GenerateUUID() - if err != nil { - return cty.UnknownVal(cty.String), err - } - return cty.StringVal(result), nil - }, -}) - -// Base64Sha256Func constructs a function that computes the SHA256 hash of a given string -// and encodes it with Base64. -var Base64Sha256Func = makeStringHashFunction(sha256.New, base64.StdEncoding.EncodeToString) - -// MakeFileBase64Sha256Func constructs a function that is like Base64Sha256Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileBase64Sha256Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha512.New, base64.StdEncoding.EncodeToString) -} - -// Base64Sha512Func constructs a function that computes the SHA256 hash of a given string -// and encodes it with Base64. -var Base64Sha512Func = makeStringHashFunction(sha512.New, base64.StdEncoding.EncodeToString) - -// MakeFileBase64Sha512Func constructs a function that is like Base64Sha512Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileBase64Sha512Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha512.New, base64.StdEncoding.EncodeToString) -} - -// BcryptFunc constructs a function that computes a hash of the given string using the Blowfish cipher. -var BcryptFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - VarParam: &function.Parameter{ - Name: "cost", - Type: cty.Number, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - defaultCost := 10 - - if len(args) > 1 { - var val int - if err := gocty.FromCtyValue(args[1], &val); err != nil { - return cty.UnknownVal(cty.String), err - } - defaultCost = val - } - - if len(args) > 2 { - return cty.UnknownVal(cty.String), fmt.Errorf("bcrypt() takes no more than two arguments") - } - - input := args[0].AsString() - out, err := bcrypt.GenerateFromPassword([]byte(input), defaultCost) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("error occured generating password %s", err.Error()) - } - - return cty.StringVal(string(out)), nil - }, -}) - -// Md5Func constructs a function that computes the MD5 hash of a given string and encodes it with hexadecimal digits. -var Md5Func = makeStringHashFunction(md5.New, hex.EncodeToString) - -// MakeFileMd5Func constructs a function that is like Md5Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileMd5Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, md5.New, hex.EncodeToString) -} - -// RsaDecryptFunc constructs a function that decrypts an RSA-encrypted ciphertext. -var RsaDecryptFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "ciphertext", - Type: cty.String, - }, - { - Name: "privatekey", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - s := args[0].AsString() - key := args[1].AsString() - - b, err := base64.StdEncoding.DecodeString(s) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode input %q: cipher text must be base64-encoded", s) - } - - block, _ := pem.Decode([]byte(key)) - if block == nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to parse key: no key found") - } - if block.Headers["Proc-Type"] == "4,ENCRYPTED" { - return cty.UnknownVal(cty.String), fmt.Errorf( - "failed to parse key: password protected keys are not supported. Please decrypt the key prior to use", - ) - } - - x509Key, err := x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - out, err := rsa.DecryptPKCS1v15(nil, x509Key, b) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(string(out)), nil - }, -}) - -// Sha1Func contructs a function that computes the SHA1 hash of a given string -// and encodes it with hexadecimal digits. -var Sha1Func = makeStringHashFunction(sha1.New, hex.EncodeToString) - -// MakeFileSha1Func constructs a function that is like Sha1Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileSha1Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha1.New, hex.EncodeToString) -} - -// Sha256Func contructs a function that computes the SHA256 hash of a given string -// and encodes it with hexadecimal digits. -var Sha256Func = makeStringHashFunction(sha256.New, hex.EncodeToString) - -// MakeFileSha256Func constructs a function that is like Sha256Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileSha256Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha256.New, hex.EncodeToString) -} - -// Sha512Func contructs a function that computes the SHA512 hash of a given string -// and encodes it with hexadecimal digits. -var Sha512Func = makeStringHashFunction(sha512.New, hex.EncodeToString) - -// MakeFileSha512Func constructs a function that is like Sha512Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileSha512Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha512.New, hex.EncodeToString) -} - -func makeStringHashFunction(hf func() hash.Hash, enc func([]byte) string) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - s := args[0].AsString() - h := hf() - h.Write([]byte(s)) - rv := enc(h.Sum(nil)) - return cty.StringVal(rv), nil - }, - }) -} - -func makeFileHashFunction(baseDir string, hf func() hash.Hash, enc func([]byte) string) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - path := args[0].AsString() - src, err := readFileBytes(baseDir, path) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - h := hf() - h.Write(src) - rv := enc(h.Sum(nil)) - return cty.StringVal(rv), nil - }, - }) -} - -// UUID generates and returns a Type-4 UUID in the standard hexadecimal string -// format. -// -// This is not a pure function: it will generate a different result for each -// call. It must therefore be registered as an impure function in the function -// table in the "lang" package. -func UUID() (cty.Value, error) { - return UUIDFunc.Call(nil) -} - -// Base64Sha256 computes the SHA256 hash of a given string and encodes it with -// Base64. -// -// The given string is first encoded as UTF-8 and then the SHA256 algorithm is applied -// as defined in RFC 4634. The raw hash is then encoded with Base64 before returning. -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. -func Base64Sha256(str cty.Value) (cty.Value, error) { - return Base64Sha256Func.Call([]cty.Value{str}) -} - -// Base64Sha512 computes the SHA512 hash of a given string and encodes it with -// Base64. -// -// The given string is first encoded as UTF-8 and then the SHA256 algorithm is applied -// as defined in RFC 4634. The raw hash is then encoded with Base64 before returning. -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4 -func Base64Sha512(str cty.Value) (cty.Value, error) { - return Base64Sha512Func.Call([]cty.Value{str}) -} - -// Bcrypt computes a hash of the given string using the Blowfish cipher, -// returning a string in the Modular Crypt Format -// usually expected in the shadow password file on many Unix systems. -func Bcrypt(str cty.Value, cost ...cty.Value) (cty.Value, error) { - args := make([]cty.Value, len(cost)+1) - args[0] = str - copy(args[1:], cost) - return BcryptFunc.Call(args) -} - -// Md5 computes the MD5 hash of a given string and encodes it with hexadecimal digits. -func Md5(str cty.Value) (cty.Value, error) { - return Md5Func.Call([]cty.Value{str}) -} - -// RsaDecrypt decrypts an RSA-encrypted ciphertext, returning the corresponding -// cleartext. -func RsaDecrypt(ciphertext, privatekey cty.Value) (cty.Value, error) { - return RsaDecryptFunc.Call([]cty.Value{ciphertext, privatekey}) -} - -// Sha1 computes the SHA1 hash of a given string and encodes it with hexadecimal digits. -func Sha1(str cty.Value) (cty.Value, error) { - return Sha1Func.Call([]cty.Value{str}) -} - -// Sha256 computes the SHA256 hash of a given string and encodes it with hexadecimal digits. -func Sha256(str cty.Value) (cty.Value, error) { - return Sha256Func.Call([]cty.Value{str}) -} - -// Sha512 computes the SHA512 hash of a given string and encodes it with hexadecimal digits. -func Sha512(str cty.Value) (cty.Value, error) { - return Sha512Func.Call([]cty.Value{str}) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/datetime.go b/vendor/github.com/hashicorp/terraform/lang/funcs/datetime.go deleted file mode 100644 index 5dae1987..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/datetime.go +++ /dev/null @@ -1,70 +0,0 @@ -package funcs - -import ( - "time" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" -) - -// TimestampFunc constructs a function that returns a string representation of the current date and time. -var TimestampFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(time.Now().UTC().Format(time.RFC3339)), nil - }, -}) - -// TimeAddFunc constructs a function that adds a duration to a timestamp, returning a new timestamp. -var TimeAddFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "timestamp", - Type: cty.String, - }, - { - Name: "duration", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - ts, err := time.Parse(time.RFC3339, args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), err - } - duration, err := time.ParseDuration(args[1].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(ts.Add(duration).Format(time.RFC3339)), nil - }, -}) - -// Timestamp returns a string representation of the current date and time. -// -// In the Terraform language, timestamps are conventionally represented as -// strings using RFC 3339 "Date and Time format" syntax, and so timestamp -// returns a string in this format. -func Timestamp() (cty.Value, error) { - return TimestampFunc.Call([]cty.Value{}) -} - -// TimeAdd adds a duration to a timestamp, returning a new timestamp. -// -// In the Terraform language, timestamps are conventionally represented as -// strings using RFC 3339 "Date and Time format" syntax. Timeadd requires -// the timestamp argument to be a string conforming to this syntax. -// -// `duration` is a string representation of a time difference, consisting of -// sequences of number and unit pairs, like `"1.5h"` or `1h30m`. The accepted -// units are `ns`, `us` (or `µs`), `"ms"`, `"s"`, `"m"`, and `"h"`. The first -// number may be negative to indicate a negative duration, like `"-2h5m"`. -// -// The result is a string, also in RFC 3339 format, representing the result -// of adding the given direction to the given timestamp. -func TimeAdd(timestamp cty.Value, duration cty.Value) (cty.Value, error) { - return TimeAddFunc.Call([]cty.Value{timestamp, duration}) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/encoding.go b/vendor/github.com/hashicorp/terraform/lang/funcs/encoding.go deleted file mode 100644 index af93f08d..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/encoding.go +++ /dev/null @@ -1,140 +0,0 @@ -package funcs - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "log" - "net/url" - "unicode/utf8" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" -) - -// Base64DecodeFunc constructs a function that decodes a string containing a base64 sequence. -var Base64DecodeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - s := args[0].AsString() - sDec, err := base64.StdEncoding.DecodeString(s) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode base64 data '%s'", s) - } - if !utf8.Valid([]byte(sDec)) { - log.Printf("[DEBUG] the result of decoding the the provided string is not valid UTF-8: %s", sDec) - return cty.UnknownVal(cty.String), fmt.Errorf("the result of decoding the the provided string is not valid UTF-8") - } - return cty.StringVal(string(sDec)), nil - }, -}) - -// Base64EncodeFunc constructs a function that encodes a string to a base64 sequence. -var Base64EncodeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(base64.StdEncoding.EncodeToString([]byte(args[0].AsString()))), nil - }, -}) - -// Base64GzipFunc constructs a function that compresses a string with gzip and then encodes the result in -// Base64 encoding. -var Base64GzipFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - s := args[0].AsString() - - var b bytes.Buffer - gz := gzip.NewWriter(&b) - if _, err := gz.Write([]byte(s)); err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to write gzip raw data: '%s'", s) - } - if err := gz.Flush(); err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to flush gzip writer: '%s'", s) - } - if err := gz.Close(); err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to close gzip writer: '%s'", s) - } - return cty.StringVal(base64.StdEncoding.EncodeToString(b.Bytes())), nil - }, -}) - -// URLEncodeFunc constructs a function that applies URL encoding to a given string. -var URLEncodeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(url.QueryEscape(args[0].AsString())), nil - }, -}) - -// Base64Decode decodes a string containing a base64 sequence. -// -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. -// -// Strings in the Terraform language are sequences of unicode characters rather -// than bytes, so this function will also interpret the resulting bytes as -// UTF-8. If the bytes after Base64 decoding are _not_ valid UTF-8, this function -// produces an error. -func Base64Decode(str cty.Value) (cty.Value, error) { - return Base64DecodeFunc.Call([]cty.Value{str}) -} - -// Base64Encode applies Base64 encoding to a string. -// -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. -// -// Strings in the Terraform language are sequences of unicode characters rather -// than bytes, so this function will first encode the characters from the string -// as UTF-8, and then apply Base64 encoding to the result. -func Base64Encode(str cty.Value) (cty.Value, error) { - return Base64EncodeFunc.Call([]cty.Value{str}) -} - -// Base64Gzip compresses a string with gzip and then encodes the result in -// Base64 encoding. -// -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. -// -// Strings in the Terraform language are sequences of unicode characters rather -// than bytes, so this function will first encode the characters from the string -// as UTF-8, then apply gzip compression, and then finally apply Base64 encoding. -func Base64Gzip(str cty.Value) (cty.Value, error) { - return Base64GzipFunc.Call([]cty.Value{str}) -} - -// URLEncode applies URL encoding to a given string. -// -// This function identifies characters in the given string that would have a -// special meaning when included as a query string argument in a URL and -// escapes them using RFC 3986 "percent encoding". -// -// If the given string contains non-ASCII characters, these are first encoded as -// UTF-8 and then percent encoding is applied separately to each UTF-8 byte. -func URLEncode(str cty.Value) (cty.Value, error) { - return URLEncodeFunc.Call([]cty.Value{str}) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/filesystem.go b/vendor/github.com/hashicorp/terraform/lang/funcs/filesystem.go deleted file mode 100644 index 617b891b..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/filesystem.go +++ /dev/null @@ -1,345 +0,0 @@ -package funcs - -import ( - "encoding/base64" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "unicode/utf8" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - homedir "github.com/mitchellh/go-homedir" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" -) - -// MakeFileFunc constructs a function that takes a file path and returns the -// contents of that file, either directly as a string (where valid UTF-8 is -// required) or as a string containing base64 bytes. -func MakeFileFunc(baseDir string, encBase64 bool) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - path := args[0].AsString() - src, err := readFileBytes(baseDir, path) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - switch { - case encBase64: - enc := base64.StdEncoding.EncodeToString(src) - return cty.StringVal(enc), nil - default: - if !utf8.Valid(src) { - return cty.UnknownVal(cty.String), fmt.Errorf("contents of %s are not valid UTF-8; to read arbitrary bytes, use the filebase64 function instead", path) - } - return cty.StringVal(string(src)), nil - } - }, - }) -} - -// MakeTemplateFileFunc constructs a function that takes a file path and -// an arbitrary object of named values and attempts to render the referenced -// file as a template using HCL template syntax. -// -// The template itself may recursively call other functions so a callback -// must be provided to get access to those functions. The template cannot, -// however, access any variables defined in the scope: it is restricted only to -// those variables provided in the second function argument, to ensure that all -// dependencies on other graph nodes can be seen before executing this function. -// -// As a special exception, a referenced template file may not recursively call -// the templatefile function, since that would risk the same file being -// included into itself indefinitely. -func MakeTemplateFileFunc(baseDir string, funcsCb func() map[string]function.Function) function.Function { - - params := []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - { - Name: "vars", - Type: cty.DynamicPseudoType, - }, - } - - loadTmpl := func(fn string) (hcl.Expression, error) { - // We re-use File here to ensure the same filename interpretation - // as it does, along with its other safety checks. - tmplVal, err := File(baseDir, cty.StringVal(fn)) - if err != nil { - return nil, err - } - - expr, diags := hclsyntax.ParseTemplate([]byte(tmplVal.AsString()), fn, hcl.Pos{Line: 1, Column: 1}) - if diags.HasErrors() { - return nil, diags - } - - return expr, nil - } - - renderTmpl := func(expr hcl.Expression, varsVal cty.Value) (cty.Value, error) { - if varsTy := varsVal.Type(); !(varsTy.IsMapType() || varsTy.IsObjectType()) { - return cty.DynamicVal, function.NewArgErrorf(2, "invalid vars value: must be a map") // or an object, but we don't strongly distinguish these most of the time - } - - ctx := &hcl.EvalContext{ - Variables: varsVal.AsValueMap(), - } - - // We'll pre-check references in the template here so we can give a - // more specialized error message than HCL would by default, so it's - // clearer that this problem is coming from a templatefile call. - for _, traversal := range expr.Variables() { - root := traversal.RootName() - if _, ok := ctx.Variables[root]; !ok { - return cty.DynamicVal, function.NewArgErrorf(2, "vars map does not contain key %q, referenced at %s", root, traversal[0].SourceRange()) - } - } - - givenFuncs := funcsCb() // this callback indirection is to avoid chicken/egg problems - funcs := make(map[string]function.Function, len(givenFuncs)) - for name, fn := range givenFuncs { - if name == "templatefile" { - // We stub this one out to prevent recursive calls. - funcs[name] = function.New(&function.Spec{ - Params: params, - Type: func(args []cty.Value) (cty.Type, error) { - return cty.NilType, fmt.Errorf("cannot recursively call templatefile from inside templatefile call") - }, - }) - continue - } - funcs[name] = fn - } - ctx.Functions = funcs - - val, diags := expr.Value(ctx) - if diags.HasErrors() { - return cty.DynamicVal, diags - } - return val, nil - } - - return function.New(&function.Spec{ - Params: params, - Type: func(args []cty.Value) (cty.Type, error) { - if !(args[0].IsKnown() && args[1].IsKnown()) { - return cty.DynamicPseudoType, nil - } - - // We'll render our template now to see what result type it produces. - // A template consisting only of a single interpolation an potentially - // return any type. - expr, err := loadTmpl(args[0].AsString()) - if err != nil { - return cty.DynamicPseudoType, err - } - - // This is safe even if args[1] contains unknowns because the HCL - // template renderer itself knows how to short-circuit those. - val, err := renderTmpl(expr, args[1]) - return val.Type(), err - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - expr, err := loadTmpl(args[0].AsString()) - if err != nil { - return cty.DynamicVal, err - } - return renderTmpl(expr, args[1]) - }, - }) - -} - -// MakeFileExistsFunc constructs a function that takes a path -// and determines whether a file exists at that path -func MakeFileExistsFunc(baseDir string) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.Bool), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - path := args[0].AsString() - path, err := homedir.Expand(path) - if err != nil { - return cty.UnknownVal(cty.Bool), fmt.Errorf("failed to expand ~: %s", err) - } - - if !filepath.IsAbs(path) { - path = filepath.Join(baseDir, path) - } - - // Ensure that the path is canonical for the host OS - path = filepath.Clean(path) - - fi, err := os.Stat(path) - if err != nil { - if os.IsNotExist(err) { - return cty.False, nil - } - return cty.UnknownVal(cty.Bool), fmt.Errorf("failed to stat %s", path) - } - - if fi.Mode().IsRegular() { - return cty.True, nil - } - - return cty.False, fmt.Errorf("%s is not a regular file, but %q", - path, fi.Mode().String()) - }, - }) -} - -// BasenameFunc constructs a function that takes a string containing a filesystem path -// and removes all except the last portion from it. -var BasenameFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(filepath.Base(args[0].AsString())), nil - }, -}) - -// DirnameFunc constructs a function that takes a string containing a filesystem path -// and removes the last portion from it. -var DirnameFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(filepath.Dir(args[0].AsString())), nil - }, -}) - -// PathExpandFunc constructs a function that expands a leading ~ character to the current user's home directory. -var PathExpandFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - - homePath, err := homedir.Expand(args[0].AsString()) - return cty.StringVal(homePath), err - }, -}) - -func readFileBytes(baseDir, path string) ([]byte, error) { - path, err := homedir.Expand(path) - if err != nil { - return nil, fmt.Errorf("failed to expand ~: %s", err) - } - - if !filepath.IsAbs(path) { - path = filepath.Join(baseDir, path) - } - - // Ensure that the path is canonical for the host OS - path = filepath.Clean(path) - - src, err := ioutil.ReadFile(path) - if err != nil { - // ReadFile does not return Terraform-user-friendly error - // messages, so we'll provide our own. - if os.IsNotExist(err) { - return nil, fmt.Errorf("no file exists at %s", path) - } - return nil, fmt.Errorf("failed to read %s", path) - } - - return src, nil -} - -// File reads the contents of the file at the given path. -// -// The file must contain valid UTF-8 bytes, or this function will return an error. -// -// The underlying function implementation works relative to a particular base -// directory, so this wrapper takes a base directory string and uses it to -// construct the underlying function before calling it. -func File(baseDir string, path cty.Value) (cty.Value, error) { - fn := MakeFileFunc(baseDir, false) - return fn.Call([]cty.Value{path}) -} - -// FileExists determines whether a file exists at the given path. -// -// The underlying function implementation works relative to a particular base -// directory, so this wrapper takes a base directory string and uses it to -// construct the underlying function before calling it. -func FileExists(baseDir string, path cty.Value) (cty.Value, error) { - fn := MakeFileExistsFunc(baseDir) - return fn.Call([]cty.Value{path}) -} - -// FileBase64 reads the contents of the file at the given path. -// -// The bytes from the file are encoded as base64 before returning. -// -// The underlying function implementation works relative to a particular base -// directory, so this wrapper takes a base directory string and uses it to -// construct the underlying function before calling it. -func FileBase64(baseDir string, path cty.Value) (cty.Value, error) { - fn := MakeFileFunc(baseDir, true) - return fn.Call([]cty.Value{path}) -} - -// Basename takes a string containing a filesystem path and removes all except the last portion from it. -// -// The underlying function implementation works only with the path string and does not access the filesystem itself. -// It is therefore unable to take into account filesystem features such as symlinks. -// -// If the path is empty then the result is ".", representing the current working directory. -func Basename(path cty.Value) (cty.Value, error) { - return BasenameFunc.Call([]cty.Value{path}) -} - -// Dirname takes a string containing a filesystem path and removes the last portion from it. -// -// The underlying function implementation works only with the path string and does not access the filesystem itself. -// It is therefore unable to take into account filesystem features such as symlinks. -// -// If the path is empty then the result is ".", representing the current working directory. -func Dirname(path cty.Value) (cty.Value, error) { - return DirnameFunc.Call([]cty.Value{path}) -} - -// Pathexpand takes a string that might begin with a `~` segment, and if so it replaces that segment with -// the current user's home directory path. -// -// The underlying function implementation works only with the path string and does not access the filesystem itself. -// It is therefore unable to take into account filesystem features such as symlinks. -// -// If the leading segment in the path is not `~` then the given path is returned unmodified. -func Pathexpand(path cty.Value) (cty.Value, error) { - return PathExpandFunc.Call([]cty.Value{path}) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/number.go b/vendor/github.com/hashicorp/terraform/lang/funcs/number.go deleted file mode 100644 index 15cfe718..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/number.go +++ /dev/null @@ -1,155 +0,0 @@ -package funcs - -import ( - "math" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/gocty" -) - -// CeilFunc contructs a function that returns the closest whole number greater -// than or equal to the given value. -var CeilFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var val float64 - if err := gocty.FromCtyValue(args[0], &val); err != nil { - return cty.UnknownVal(cty.String), err - } - return cty.NumberIntVal(int64(math.Ceil(val))), nil - }, -}) - -// FloorFunc contructs a function that returns the closest whole number lesser -// than or equal to the given value. -var FloorFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var val float64 - if err := gocty.FromCtyValue(args[0], &val); err != nil { - return cty.UnknownVal(cty.String), err - } - return cty.NumberIntVal(int64(math.Floor(val))), nil - }, -}) - -// LogFunc contructs a function that returns the logarithm of a given number in a given base. -var LogFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - { - Name: "base", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var num float64 - if err := gocty.FromCtyValue(args[0], &num); err != nil { - return cty.UnknownVal(cty.String), err - } - - var base float64 - if err := gocty.FromCtyValue(args[1], &base); err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.NumberFloatVal(math.Log(num) / math.Log(base)), nil - }, -}) - -// PowFunc contructs a function that returns the logarithm of a given number in a given base. -var PowFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - { - Name: "power", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var num float64 - if err := gocty.FromCtyValue(args[0], &num); err != nil { - return cty.UnknownVal(cty.String), err - } - - var power float64 - if err := gocty.FromCtyValue(args[1], &power); err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.NumberFloatVal(math.Pow(num, power)), nil - }, -}) - -// SignumFunc contructs a function that returns the closest whole number greater -// than or equal to the given value. -var SignumFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var num int - if err := gocty.FromCtyValue(args[0], &num); err != nil { - return cty.UnknownVal(cty.String), err - } - switch { - case num < 0: - return cty.NumberIntVal(-1), nil - case num > 0: - return cty.NumberIntVal(+1), nil - default: - return cty.NumberIntVal(0), nil - } - }, -}) - -// Ceil returns the closest whole number greater than or equal to the given value. -func Ceil(num cty.Value) (cty.Value, error) { - return CeilFunc.Call([]cty.Value{num}) -} - -// Floor returns the closest whole number lesser than or equal to the given value. -func Floor(num cty.Value) (cty.Value, error) { - return FloorFunc.Call([]cty.Value{num}) -} - -// Log returns returns the logarithm of a given number in a given base. -func Log(num, base cty.Value) (cty.Value, error) { - return LogFunc.Call([]cty.Value{num, base}) -} - -// Pow returns the logarithm of a given number in a given base. -func Pow(num, power cty.Value) (cty.Value, error) { - return PowFunc.Call([]cty.Value{num, power}) -} - -// Signum determines the sign of a number, returning a number between -1 and -// 1 to represent the sign. -func Signum(num cty.Value) (cty.Value, error) { - return SignumFunc.Call([]cty.Value{num}) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/funcs/string.go b/vendor/github.com/hashicorp/terraform/lang/funcs/string.go deleted file mode 100644 index c9ddf19e..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/funcs/string.go +++ /dev/null @@ -1,280 +0,0 @@ -package funcs - -import ( - "fmt" - "regexp" - "sort" - "strings" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/gocty" -) - -var JoinFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "separator", - Type: cty.String, - }, - }, - VarParam: &function.Parameter{ - Name: "lists", - Type: cty.List(cty.String), - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - sep := args[0].AsString() - listVals := args[1:] - if len(listVals) < 1 { - return cty.UnknownVal(cty.String), fmt.Errorf("at least one list is required") - } - - l := 0 - for _, list := range listVals { - if !list.IsWhollyKnown() { - return cty.UnknownVal(cty.String), nil - } - l += list.LengthInt() - } - - items := make([]string, 0, l) - for ai, list := range listVals { - ei := 0 - for it := list.ElementIterator(); it.Next(); { - _, val := it.Element() - if val.IsNull() { - if len(listVals) > 1 { - return cty.UnknownVal(cty.String), function.NewArgErrorf(ai+1, "element %d of list %d is null; cannot concatenate null values", ei, ai+1) - } - return cty.UnknownVal(cty.String), function.NewArgErrorf(ai+1, "element %d is null; cannot concatenate null values", ei) - } - items = append(items, val.AsString()) - ei++ - } - } - - return cty.StringVal(strings.Join(items, sep)), nil - }, -}) - -var SortFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.String), - }, - }, - Type: function.StaticReturnType(cty.List(cty.String)), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - listVal := args[0] - - if !listVal.IsWhollyKnown() { - // If some of the element values aren't known yet then we - // can't yet preduct the order of the result. - return cty.UnknownVal(retType), nil - } - if listVal.LengthInt() == 0 { // Easy path - return listVal, nil - } - - list := make([]string, 0, listVal.LengthInt()) - for it := listVal.ElementIterator(); it.Next(); { - iv, v := it.Element() - if v.IsNull() { - return cty.UnknownVal(retType), fmt.Errorf("given list element %s is null; a null string cannot be sorted", iv.AsBigFloat().String()) - } - list = append(list, v.AsString()) - } - - sort.Strings(list) - retVals := make([]cty.Value, len(list)) - for i, s := range list { - retVals[i] = cty.StringVal(s) - } - return cty.ListVal(retVals), nil - }, -}) - -var SplitFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "separator", - Type: cty.String, - }, - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.List(cty.String)), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - sep := args[0].AsString() - str := args[1].AsString() - elems := strings.Split(str, sep) - elemVals := make([]cty.Value, len(elems)) - for i, s := range elems { - elemVals[i] = cty.StringVal(s) - } - if len(elemVals) == 0 { - return cty.ListValEmpty(cty.String), nil - } - return cty.ListVal(elemVals), nil - }, -}) - -// ChompFunc constructions a function that removes newline characters at the end of a string. -var ChompFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - newlines := regexp.MustCompile(`(?:\r\n?|\n)*\z`) - return cty.StringVal(newlines.ReplaceAllString(args[0].AsString(), "")), nil - }, -}) - -// IndentFunc constructions a function that adds a given number of spaces to the -// beginnings of all but the first line in a given multi-line string. -var IndentFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "spaces", - Type: cty.Number, - }, - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var spaces int - if err := gocty.FromCtyValue(args[0], &spaces); err != nil { - return cty.UnknownVal(cty.String), err - } - data := args[1].AsString() - pad := strings.Repeat(" ", spaces) - return cty.StringVal(strings.Replace(data, "\n", "\n"+pad, -1)), nil - }, -}) - -// ReplaceFunc constructions a function that searches a given string for another -// given substring, and replaces each occurence with a given replacement string. -var ReplaceFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - { - Name: "substr", - Type: cty.String, - }, - { - Name: "replace", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - str := args[0].AsString() - substr := args[1].AsString() - replace := args[2].AsString() - - // We search/replace using a regexp if the string is surrounded - // in forward slashes. - if len(substr) > 1 && substr[0] == '/' && substr[len(substr)-1] == '/' { - re, err := regexp.Compile(substr[1 : len(substr)-1]) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(re.ReplaceAllString(str, replace)), nil - } - - return cty.StringVal(strings.Replace(str, substr, replace, -1)), nil - }, -}) - -// TitleFunc constructions a function that converts the first letter of each word -// in the given string to uppercase. -var TitleFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - return cty.StringVal(strings.Title(args[0].AsString())), nil - }, -}) - -// TrimSpaceFunc constructions a function that removes any space characters from -// the start and end of the given string. -var TrimSpaceFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - return cty.StringVal(strings.TrimSpace(args[0].AsString())), nil - }, -}) - -// Join concatenates together the string elements of one or more lists with a -// given separator. -func Join(sep cty.Value, lists ...cty.Value) (cty.Value, error) { - args := make([]cty.Value, len(lists)+1) - args[0] = sep - copy(args[1:], lists) - return JoinFunc.Call(args) -} - -// Sort re-orders the elements of a given list of strings so that they are -// in ascending lexicographical order. -func Sort(list cty.Value) (cty.Value, error) { - return SortFunc.Call([]cty.Value{list}) -} - -// Split divides a given string by a given separator, returning a list of -// strings containing the characters between the separator sequences. -func Split(sep, str cty.Value) (cty.Value, error) { - return SplitFunc.Call([]cty.Value{sep, str}) -} - -// Chomp removes newline characters at the end of a string. -func Chomp(str cty.Value) (cty.Value, error) { - return ChompFunc.Call([]cty.Value{str}) -} - -// Indent adds a given number of spaces to the beginnings of all but the first -// line in a given multi-line string. -func Indent(spaces, str cty.Value) (cty.Value, error) { - return IndentFunc.Call([]cty.Value{spaces, str}) -} - -// Replace searches a given string for another given substring, -// and replaces all occurences with a given replacement string. -func Replace(str, substr, replace cty.Value) (cty.Value, error) { - return ReplaceFunc.Call([]cty.Value{str, substr, replace}) -} - -// Title converts the first letter of each word in the given string to uppercase. -func Title(str cty.Value) (cty.Value, error) { - return TitleFunc.Call([]cty.Value{str}) -} - -// TrimSpace removes any space characters from the start and end of the given string. -func TrimSpace(str cty.Value) (cty.Value, error) { - return TrimSpaceFunc.Call([]cty.Value{str}) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/functions.go b/vendor/github.com/hashicorp/terraform/lang/functions.go deleted file mode 100644 index bf1b746a..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/functions.go +++ /dev/null @@ -1,146 +0,0 @@ -package lang - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/function/stdlib" - - "github.com/hashicorp/terraform/lang/funcs" -) - -var impureFunctions = []string{ - "bcrypt", - "timestamp", - "uuid", -} - -// Functions returns the set of functions that should be used to when evaluating -// expressions in the receiving scope. -func (s *Scope) Functions() map[string]function.Function { - s.funcsLock.Lock() - if s.funcs == nil { - // Some of our functions are just directly the cty stdlib functions. - // Others are implemented in the subdirectory "funcs" here in this - // repository. New functions should generally start out their lives - // in the "funcs" directory and potentially graduate to cty stdlib - // later if the functionality seems to be something domain-agnostic - // that would be useful to all applications using cty functions. - - s.funcs = map[string]function.Function{ - "abs": stdlib.AbsoluteFunc, - "basename": funcs.BasenameFunc, - "base64decode": funcs.Base64DecodeFunc, - "base64encode": funcs.Base64EncodeFunc, - "base64gzip": funcs.Base64GzipFunc, - "base64sha256": funcs.Base64Sha256Func, - "base64sha512": funcs.Base64Sha512Func, - "bcrypt": funcs.BcryptFunc, - "ceil": funcs.CeilFunc, - "chomp": funcs.ChompFunc, - "cidrhost": funcs.CidrHostFunc, - "cidrnetmask": funcs.CidrNetmaskFunc, - "cidrsubnet": funcs.CidrSubnetFunc, - "coalesce": stdlib.CoalesceFunc, - "coalescelist": funcs.CoalesceListFunc, - "compact": funcs.CompactFunc, - "concat": stdlib.ConcatFunc, - "contains": funcs.ContainsFunc, - "csvdecode": stdlib.CSVDecodeFunc, - "dirname": funcs.DirnameFunc, - "distinct": funcs.DistinctFunc, - "element": funcs.ElementFunc, - "chunklist": funcs.ChunklistFunc, - "file": funcs.MakeFileFunc(s.BaseDir, false), - "fileexists": funcs.MakeFileExistsFunc(s.BaseDir), - "filebase64": funcs.MakeFileFunc(s.BaseDir, true), - "filebase64sha256": funcs.MakeFileBase64Sha256Func(s.BaseDir), - "filebase64sha512": funcs.MakeFileBase64Sha512Func(s.BaseDir), - "filemd5": funcs.MakeFileMd5Func(s.BaseDir), - "filesha1": funcs.MakeFileSha1Func(s.BaseDir), - "filesha256": funcs.MakeFileSha256Func(s.BaseDir), - "filesha512": funcs.MakeFileSha512Func(s.BaseDir), - "flatten": funcs.FlattenFunc, - "floor": funcs.FloorFunc, - "format": stdlib.FormatFunc, - "formatdate": stdlib.FormatDateFunc, - "formatlist": stdlib.FormatListFunc, - "indent": funcs.IndentFunc, - "index": funcs.IndexFunc, - "join": funcs.JoinFunc, - "jsondecode": stdlib.JSONDecodeFunc, - "jsonencode": stdlib.JSONEncodeFunc, - "keys": funcs.KeysFunc, - "length": funcs.LengthFunc, - "list": funcs.ListFunc, - "log": funcs.LogFunc, - "lookup": funcs.LookupFunc, - "lower": stdlib.LowerFunc, - "map": funcs.MapFunc, - "matchkeys": funcs.MatchkeysFunc, - "max": stdlib.MaxFunc, - "md5": funcs.Md5Func, - "merge": funcs.MergeFunc, - "min": stdlib.MinFunc, - "pathexpand": funcs.PathExpandFunc, - "pow": funcs.PowFunc, - "replace": funcs.ReplaceFunc, - "rsadecrypt": funcs.RsaDecryptFunc, - "sethaselement": stdlib.SetHasElementFunc, - "setintersection": stdlib.SetIntersectionFunc, - "setproduct": funcs.SetProductFunc, - "setunion": stdlib.SetUnionFunc, - "sha1": funcs.Sha1Func, - "sha256": funcs.Sha256Func, - "sha512": funcs.Sha512Func, - "signum": funcs.SignumFunc, - "slice": funcs.SliceFunc, - "sort": funcs.SortFunc, - "split": funcs.SplitFunc, - "substr": stdlib.SubstrFunc, - "timestamp": funcs.TimestampFunc, - "timeadd": funcs.TimeAddFunc, - "title": funcs.TitleFunc, - "tostring": funcs.MakeToFunc(cty.String), - "tonumber": funcs.MakeToFunc(cty.Number), - "tobool": funcs.MakeToFunc(cty.Bool), - "toset": funcs.MakeToFunc(cty.Set(cty.DynamicPseudoType)), - "tolist": funcs.MakeToFunc(cty.List(cty.DynamicPseudoType)), - "tomap": funcs.MakeToFunc(cty.Map(cty.DynamicPseudoType)), - "transpose": funcs.TransposeFunc, - "trimspace": funcs.TrimSpaceFunc, - "upper": stdlib.UpperFunc, - "urlencode": funcs.URLEncodeFunc, - "uuid": funcs.UUIDFunc, - "values": funcs.ValuesFunc, - "zipmap": funcs.ZipmapFunc, - } - - s.funcs["templatefile"] = funcs.MakeTemplateFileFunc(s.BaseDir, func() map[string]function.Function { - // The templatefile function prevents recursive calls to itself - // by copying this map and overwriting the "templatefile" entry. - return s.funcs - }) - - if s.PureOnly { - // Force our few impure functions to return unknown so that we - // can defer evaluating them until a later pass. - for _, name := range impureFunctions { - s.funcs[name] = function.Unpredictable(s.funcs[name]) - } - } - } - s.funcsLock.Unlock() - - return s.funcs -} - -var unimplFunc = function.New(&function.Spec{ - Type: func([]cty.Value) (cty.Type, error) { - return cty.DynamicPseudoType, fmt.Errorf("function not yet implemented") - }, - Impl: func([]cty.Value, cty.Type) (cty.Value, error) { - return cty.DynamicVal, fmt.Errorf("function not yet implemented") - }, -}) diff --git a/vendor/github.com/hashicorp/terraform/lang/references.go b/vendor/github.com/hashicorp/terraform/lang/references.go deleted file mode 100644 index 69dd0d82..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/references.go +++ /dev/null @@ -1,68 +0,0 @@ -package lang - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcldec" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/tfdiags" -) - -// References finds all of the references in the given set of traversals, -// returning diagnostics if any of the traversals cannot be interpreted as a -// reference. -// -// This function does not do any de-duplication of references, since references -// have source location information embedded in them and so any invalid -// references that are duplicated should have errors reported for each -// occurence. -// -// If the returned diagnostics contains errors then the result may be -// incomplete or invalid. Otherwise, the returned slice has one reference per -// given traversal, though it is not guaranteed that the references will -// appear in the same order as the given traversals. -func References(traversals []hcl.Traversal) ([]*addrs.Reference, tfdiags.Diagnostics) { - if len(traversals) == 0 { - return nil, nil - } - - var diags tfdiags.Diagnostics - refs := make([]*addrs.Reference, 0, len(traversals)) - - for _, traversal := range traversals { - ref, refDiags := addrs.ParseRef(traversal) - diags = diags.Append(refDiags) - if ref == nil { - continue - } - refs = append(refs, ref) - } - - return refs, diags -} - -// ReferencesInBlock is a helper wrapper around References that first searches -// the given body for traversals, before converting those traversals to -// references. -// -// A block schema must be provided so that this function can determine where in -// the body variables are expected. -func ReferencesInBlock(body hcl.Body, schema *configschema.Block) ([]*addrs.Reference, tfdiags.Diagnostics) { - if body == nil { - return nil, nil - } - spec := schema.DecoderSpec() - traversals := hcldec.Variables(body, spec) - return References(traversals) -} - -// ReferencesInExpr is a helper wrapper around References that first searches -// the given expression for traversals, before converting those traversals -// to references. -func ReferencesInExpr(expr hcl.Expression) ([]*addrs.Reference, tfdiags.Diagnostics) { - if expr == nil { - return nil, nil - } - traversals := expr.Variables() - return References(traversals) -} diff --git a/vendor/github.com/hashicorp/terraform/lang/scope.go b/vendor/github.com/hashicorp/terraform/lang/scope.go deleted file mode 100644 index 98fca6ba..00000000 --- a/vendor/github.com/hashicorp/terraform/lang/scope.go +++ /dev/null @@ -1,34 +0,0 @@ -package lang - -import ( - "sync" - - "github.com/zclconf/go-cty/cty/function" - - "github.com/hashicorp/terraform/addrs" -) - -// Scope is the main type in this package, allowing dynamic evaluation of -// blocks and expressions based on some contextual information that informs -// which variables and functions will be available. -type Scope struct { - // Data is used to resolve references in expressions. - Data Data - - // SelfAddr is the address that the "self" object should be an alias of, - // or nil if the "self" object should not be available at all. - SelfAddr addrs.Referenceable - - // BaseDir is the base directory used by any interpolation functions that - // accept filesystem paths as arguments. - BaseDir string - - // PureOnly can be set to true to request that any non-pure functions - // produce unknown value results rather than actually executing. This is - // important during a plan phase to avoid generating results that could - // then differ during apply. - PureOnly bool - - funcs map[string]function.Function - funcsLock sync.Mutex -} diff --git a/vendor/github.com/hashicorp/terraform/plans/action.go b/vendor/github.com/hashicorp/terraform/plans/action.go deleted file mode 100644 index c3e6a32a..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/action.go +++ /dev/null @@ -1,22 +0,0 @@ -package plans - -type Action rune - -const ( - NoOp Action = 0 - Create Action = '+' - Read Action = '←' - Update Action = '~' - DeleteThenCreate Action = '∓' - CreateThenDelete Action = '±' - Delete Action = '-' -) - -//go:generate stringer -type Action - -// IsReplace returns true if the action is one of the two actions that -// represents replacing an existing object with a new object: -// DeleteThenCreate or CreateThenDelete. -func (a Action) IsReplace() bool { - return a == DeleteThenCreate || a == CreateThenDelete -} diff --git a/vendor/github.com/hashicorp/terraform/plans/action_string.go b/vendor/github.com/hashicorp/terraform/plans/action_string.go deleted file mode 100644 index c79465a2..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/action_string.go +++ /dev/null @@ -1,36 +0,0 @@ -// Code generated by "stringer -type Action"; DO NOT EDIT. - -package plans - -import "strconv" - -const ( - _Action_name_0 = "NoOp" - _Action_name_1 = "Create" - _Action_name_2 = "Delete" - _Action_name_3 = "Update" - _Action_name_4 = "CreateThenDelete" - _Action_name_5 = "Read" - _Action_name_6 = "DeleteThenCreate" -) - -func (i Action) String() string { - switch { - case i == 0: - return _Action_name_0 - case i == 43: - return _Action_name_1 - case i == 45: - return _Action_name_2 - case i == 126: - return _Action_name_3 - case i == 177: - return _Action_name_4 - case i == 8592: - return _Action_name_5 - case i == 8723: - return _Action_name_6 - default: - return "Action(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform/plans/changes.go b/vendor/github.com/hashicorp/terraform/plans/changes.go deleted file mode 100644 index d7e0dcdb..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/changes.go +++ /dev/null @@ -1,308 +0,0 @@ -package plans - -import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/states" - "github.com/zclconf/go-cty/cty" -) - -// Changes describes various actions that Terraform will attempt to take if -// the corresponding plan is applied. -// -// A Changes object can be rendered into a visual diff (by the caller, using -// code in another package) for display to the user. -type Changes struct { - // Resources tracks planned changes to resource instance objects. - Resources []*ResourceInstanceChangeSrc - - // Outputs tracks planned changes output values. - // - // Note that although an in-memory plan contains planned changes for - // outputs throughout the configuration, a plan serialized - // to disk retains only the root outputs because they are - // externally-visible, while other outputs are implementation details and - // can be easily re-calculated during the apply phase. Therefore only root - // module outputs will survive a round-trip through a plan file. - Outputs []*OutputChangeSrc -} - -// NewChanges returns a valid Changes object that describes no changes. -func NewChanges() *Changes { - return &Changes{} -} - -func (c *Changes) Empty() bool { - for _, res := range c.Resources { - if res.Action != NoOp { - return false - } - } - return true -} - -// ResourceInstance returns the planned change for the current object of the -// resource instance of the given address, if any. Returns nil if no change is -// planned. -func (c *Changes) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstanceChangeSrc { - addrStr := addr.String() - for _, rc := range c.Resources { - if rc.Addr.String() == addrStr && rc.DeposedKey == states.NotDeposed { - return rc - } - } - - return nil -} - -// ResourceInstanceDeposed returns the plan change of a deposed object of -// the resource instance of the given address, if any. Returns nil if no change -// is planned. -func (c *Changes) ResourceInstanceDeposed(addr addrs.AbsResourceInstance, key states.DeposedKey) *ResourceInstanceChangeSrc { - addrStr := addr.String() - for _, rc := range c.Resources { - if rc.Addr.String() == addrStr && rc.DeposedKey == key { - return rc - } - } - - return nil -} - -// OutputValue returns the planned change for the output value with the -// given address, if any. Returns nil if no change is planned. -func (c *Changes) OutputValue(addr addrs.AbsOutputValue) *OutputChangeSrc { - addrStr := addr.String() - for _, oc := range c.Outputs { - if oc.Addr.String() == addrStr { - return oc - } - } - - return nil -} - -// SyncWrapper returns a wrapper object around the receiver that can be used -// to make certain changes to the receiver in a concurrency-safe way, as long -// as all callers share the same wrapper object. -func (c *Changes) SyncWrapper() *ChangesSync { - return &ChangesSync{ - changes: c, - } -} - -// ResourceInstanceChange describes a change to a particular resource instance -// object. -type ResourceInstanceChange struct { - // Addr is the absolute address of the resource instance that the change - // will apply to. - Addr addrs.AbsResourceInstance - - // DeposedKey is the identifier for a deposed object associated with the - // given instance, or states.NotDeposed if this change applies to the - // current object. - // - // A Replace change for a resource with create_before_destroy set will - // create a new DeposedKey temporarily during replacement. In that case, - // DeposedKey in the plan is always states.NotDeposed, representing that - // the current object is being replaced with the deposed. - DeposedKey states.DeposedKey - - // Provider is the address of the provider configuration that was used - // to plan this change, and thus the configuration that must also be - // used to apply it. - ProviderAddr addrs.AbsProviderConfig - - // Change is an embedded description of the change. - Change - - // RequiredReplace is a set of paths that caused the change action to be - // Replace rather than Update. Always nil if the change action is not - // Replace. - // - // This is retained only for UI-plan-rendering purposes and so it does not - // currently survive a round-trip through a saved plan file. - RequiredReplace cty.PathSet - - // Private allows a provider to stash any extra data that is opaque to - // Terraform that relates to this change. Terraform will save this - // byte-for-byte and return it to the provider in the apply call. - Private []byte -} - -// Encode produces a variant of the reciever that has its change values -// serialized so it can be written to a plan file. Pass the implied type of the -// corresponding resource type schema for correct operation. -func (rc *ResourceInstanceChange) Encode(ty cty.Type) (*ResourceInstanceChangeSrc, error) { - cs, err := rc.Change.Encode(ty) - if err != nil { - return nil, err - } - return &ResourceInstanceChangeSrc{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - ProviderAddr: rc.ProviderAddr, - ChangeSrc: *cs, - RequiredReplace: rc.RequiredReplace, - Private: rc.Private, - }, err -} - -// Simplify will, where possible, produce a change with a simpler action than -// the receiever given a flag indicating whether the caller is dealing with -// a normal apply or a destroy. This flag deals with the fact that Terraform -// Core uses a specialized graph node type for destroying; only that -// specialized node should set "destroying" to true. -// -// The following table shows the simplification behavior: -// -// Action Destroying? New Action -// --------+-------------+----------- -// Create true NoOp -// Delete false NoOp -// Replace true Delete -// Replace false Create -// -// For any combination not in the above table, the Simplify just returns the -// receiver as-is. -func (rc *ResourceInstanceChange) Simplify(destroying bool) *ResourceInstanceChange { - if destroying { - switch rc.Action { - case Delete: - // We'll fall out and just return rc verbatim, then. - case CreateThenDelete, DeleteThenCreate: - return &ResourceInstanceChange{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - Private: rc.Private, - ProviderAddr: rc.ProviderAddr, - Change: Change{ - Action: Delete, - Before: rc.Before, - After: cty.NullVal(rc.Before.Type()), - }, - } - default: - return &ResourceInstanceChange{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - Private: rc.Private, - ProviderAddr: rc.ProviderAddr, - Change: Change{ - Action: NoOp, - Before: rc.Before, - After: rc.Before, - }, - } - } - } else { - switch rc.Action { - case Delete: - return &ResourceInstanceChange{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - Private: rc.Private, - ProviderAddr: rc.ProviderAddr, - Change: Change{ - Action: NoOp, - Before: rc.Before, - After: rc.Before, - }, - } - case CreateThenDelete, DeleteThenCreate: - return &ResourceInstanceChange{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - Private: rc.Private, - ProviderAddr: rc.ProviderAddr, - Change: Change{ - Action: Create, - Before: cty.NullVal(rc.After.Type()), - After: rc.After, - }, - } - } - } - - // If we fall out here then our change is already simple enough. - return rc -} - -// OutputChange describes a change to an output value. -type OutputChange struct { - // Addr is the absolute address of the output value that the change - // will apply to. - Addr addrs.AbsOutputValue - - // Change is an embedded description of the change. - // - // For output value changes, the type constraint for the DynamicValue - // instances is always cty.DynamicPseudoType. - Change - - // Sensitive, if true, indicates that either the old or new value in the - // change is sensitive and so a rendered version of the plan in the UI - // should elide the actual values while still indicating the action of the - // change. - Sensitive bool -} - -// Encode produces a variant of the reciever that has its change values -// serialized so it can be written to a plan file. -func (oc *OutputChange) Encode() (*OutputChangeSrc, error) { - cs, err := oc.Change.Encode(cty.DynamicPseudoType) - if err != nil { - return nil, err - } - return &OutputChangeSrc{ - Addr: oc.Addr, - ChangeSrc: *cs, - Sensitive: oc.Sensitive, - }, err -} - -// Change describes a single change with a given action. -type Change struct { - // Action defines what kind of change is being made. - Action Action - - // Interpretation of Before and After depend on Action: - // - // NoOp Before and After are the same, unchanged value - // Create Before is nil, and After is the expected value after create. - // Read Before is any prior value (nil if no prior), and After is the - // value that was or will be read. - // Update Before is the value prior to update, and After is the expected - // value after update. - // Replace As with Update. - // Delete Before is the value prior to delete, and After is always nil. - // - // Unknown values may appear anywhere within the Before and After values, - // either as the values themselves or as nested elements within known - // collections/structures. - Before, After cty.Value -} - -// Encode produces a variant of the reciever that has its change values -// serialized so it can be written to a plan file. Pass the type constraint -// that the values are expected to conform to; to properly decode the values -// later an identical type constraint must be provided at that time. -// -// Where a Change is embedded in some other struct, it's generally better -// to call the corresponding Encode method of that struct rather than working -// directly with its embedded Change. -func (c *Change) Encode(ty cty.Type) (*ChangeSrc, error) { - beforeDV, err := NewDynamicValue(c.Before, ty) - if err != nil { - return nil, err - } - afterDV, err := NewDynamicValue(c.After, ty) - if err != nil { - return nil, err - } - - return &ChangeSrc{ - Action: c.Action, - Before: beforeDV, - After: afterDV, - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform/plans/changes_src.go b/vendor/github.com/hashicorp/terraform/plans/changes_src.go deleted file mode 100644 index 90153ea7..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/changes_src.go +++ /dev/null @@ -1,190 +0,0 @@ -package plans - -import ( - "fmt" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/states" - "github.com/zclconf/go-cty/cty" -) - -// ResourceInstanceChangeSrc is a not-yet-decoded ResourceInstanceChange. -// Pass the associated resource type's schema type to method Decode to -// obtain a ResourceInstancChange. -type ResourceInstanceChangeSrc struct { - // Addr is the absolute address of the resource instance that the change - // will apply to. - Addr addrs.AbsResourceInstance - - // DeposedKey is the identifier for a deposed object associated with the - // given instance, or states.NotDeposed if this change applies to the - // current object. - // - // A Replace change for a resource with create_before_destroy set will - // create a new DeposedKey temporarily during replacement. In that case, - // DeposedKey in the plan is always states.NotDeposed, representing that - // the current object is being replaced with the deposed. - DeposedKey states.DeposedKey - - // Provider is the address of the provider configuration that was used - // to plan this change, and thus the configuration that must also be - // used to apply it. - ProviderAddr addrs.AbsProviderConfig - - // ChangeSrc is an embedded description of the not-yet-decoded change. - ChangeSrc - - // RequiredReplace is a set of paths that caused the change action to be - // Replace rather than Update. Always nil if the change action is not - // Replace. - // - // This is retained only for UI-plan-rendering purposes and so it does not - // currently survive a round-trip through a saved plan file. - RequiredReplace cty.PathSet - - // Private allows a provider to stash any extra data that is opaque to - // Terraform that relates to this change. Terraform will save this - // byte-for-byte and return it to the provider in the apply call. - Private []byte -} - -// Decode unmarshals the raw representation of the instance object being -// changed. Pass the implied type of the corresponding resource type schema -// for correct operation. -func (rcs *ResourceInstanceChangeSrc) Decode(ty cty.Type) (*ResourceInstanceChange, error) { - change, err := rcs.ChangeSrc.Decode(ty) - if err != nil { - return nil, err - } - return &ResourceInstanceChange{ - Addr: rcs.Addr, - DeposedKey: rcs.DeposedKey, - ProviderAddr: rcs.ProviderAddr, - Change: *change, - RequiredReplace: rcs.RequiredReplace, - Private: rcs.Private, - }, nil -} - -// DeepCopy creates a copy of the receiver where any pointers to nested mutable -// values are also copied, thus ensuring that future mutations of the receiver -// will not affect the copy. -// -// Some types used within a resource change are immutable by convention even -// though the Go language allows them to be mutated, such as the types from -// the addrs package. These are _not_ copied by this method, under the -// assumption that callers will behave themselves. -func (rcs *ResourceInstanceChangeSrc) DeepCopy() *ResourceInstanceChangeSrc { - if rcs == nil { - return nil - } - ret := *rcs - - ret.RequiredReplace = cty.NewPathSet(ret.RequiredReplace.List()...) - - if len(ret.Private) != 0 { - private := make([]byte, len(ret.Private)) - copy(private, ret.Private) - ret.Private = private - } - - ret.ChangeSrc.Before = ret.ChangeSrc.Before.Copy() - ret.ChangeSrc.After = ret.ChangeSrc.After.Copy() - - return &ret -} - -// OutputChangeSrc describes a change to an output value. -type OutputChangeSrc struct { - // Addr is the absolute address of the output value that the change - // will apply to. - Addr addrs.AbsOutputValue - - // ChangeSrc is an embedded description of the not-yet-decoded change. - // - // For output value changes, the type constraint for the DynamicValue - // instances is always cty.DynamicPseudoType. - ChangeSrc - - // Sensitive, if true, indicates that either the old or new value in the - // change is sensitive and so a rendered version of the plan in the UI - // should elide the actual values while still indicating the action of the - // change. - Sensitive bool -} - -// Decode unmarshals the raw representation of the output value being -// changed. -func (ocs *OutputChangeSrc) Decode() (*OutputChange, error) { - change, err := ocs.ChangeSrc.Decode(cty.DynamicPseudoType) - if err != nil { - return nil, err - } - return &OutputChange{ - Addr: ocs.Addr, - Change: *change, - Sensitive: ocs.Sensitive, - }, nil -} - -// DeepCopy creates a copy of the receiver where any pointers to nested mutable -// values are also copied, thus ensuring that future mutations of the receiver -// will not affect the copy. -// -// Some types used within a resource change are immutable by convention even -// though the Go language allows them to be mutated, such as the types from -// the addrs package. These are _not_ copied by this method, under the -// assumption that callers will behave themselves. -func (ocs *OutputChangeSrc) DeepCopy() *OutputChangeSrc { - if ocs == nil { - return nil - } - ret := *ocs - - ret.ChangeSrc.Before = ret.ChangeSrc.Before.Copy() - ret.ChangeSrc.After = ret.ChangeSrc.After.Copy() - - return &ret -} - -// ChangeSrc is a not-yet-decoded Change. -type ChangeSrc struct { - // Action defines what kind of change is being made. - Action Action - - // Before and After correspond to the fields of the same name in Change, - // but have not yet been decoded from the serialized value used for - // storage. - Before, After DynamicValue -} - -// Decode unmarshals the raw representations of the before and after values -// to produce a Change object. Pass the type constraint that the result must -// conform to. -// -// Where a ChangeSrc is embedded in some other struct, it's generally better -// to call the corresponding Decode method of that struct rather than working -// directly with its embedded Change. -func (cs *ChangeSrc) Decode(ty cty.Type) (*Change, error) { - var err error - before := cty.NullVal(ty) - after := cty.NullVal(ty) - - if len(cs.Before) > 0 { - before, err = cs.Before.Decode(ty) - if err != nil { - return nil, fmt.Errorf("error decoding 'before' value: %s", err) - } - } - if len(cs.After) > 0 { - after, err = cs.After.Decode(ty) - if err != nil { - return nil, fmt.Errorf("error decoding 'after' value: %s", err) - } - } - return &Change{ - Action: cs.Action, - Before: before, - After: after, - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform/plans/changes_state.go b/vendor/github.com/hashicorp/terraform/plans/changes_state.go deleted file mode 100644 index 543e6c2b..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/changes_state.go +++ /dev/null @@ -1,15 +0,0 @@ -package plans - -import ( - "github.com/hashicorp/terraform/states" -) - -// PlannedState merges the set of changes described by the receiver into the -// given prior state to produce the planned result state. -// -// The result is an approximation of the state as it would exist after -// applying these changes, omitting any values that cannot be determined until -// the changes are actually applied. -func (c *Changes) PlannedState(prior *states.State) (*states.State, error) { - panic("Changes.PlannedState not yet implemented") -} diff --git a/vendor/github.com/hashicorp/terraform/plans/changes_sync.go b/vendor/github.com/hashicorp/terraform/plans/changes_sync.go deleted file mode 100644 index 6b4ff98f..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/changes_sync.go +++ /dev/null @@ -1,144 +0,0 @@ -package plans - -import ( - "fmt" - "sync" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/states" -) - -// ChangesSync is a wrapper around a Changes that provides a concurrency-safe -// interface to insert new changes and retrieve copies of existing changes. -// -// Each ChangesSync is independent of all others, so all concurrent writers -// to a particular Changes must share a single ChangesSync. Behavior is -// undefined if any other caller makes changes to the underlying Changes -// object or its nested objects concurrently with any of the methods of a -// particular ChangesSync. -type ChangesSync struct { - lock sync.Mutex - changes *Changes -} - -// AppendResourceInstanceChange records the given resource instance change in -// the set of planned resource changes. -// -// The caller must ensure that there are no concurrent writes to the given -// change while this method is running, but it is safe to resume mutating -// it after this method returns without affecting the saved change. -func (cs *ChangesSync) AppendResourceInstanceChange(changeSrc *ResourceInstanceChangeSrc) { - if cs == nil { - panic("AppendResourceInstanceChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - s := changeSrc.DeepCopy() - cs.changes.Resources = append(cs.changes.Resources, s) -} - -// GetResourceInstanceChange searches the set of resource instance changes for -// one matching the given address and generation, returning it if it exists. -// -// If no such change exists, nil is returned. -// -// The returned object is a deep copy of the change recorded in the plan, so -// callers may mutate it although it's generally better (less confusing) to -// treat planned changes as immutable after they've been initially constructed. -func (cs *ChangesSync) GetResourceInstanceChange(addr addrs.AbsResourceInstance, gen states.Generation) *ResourceInstanceChangeSrc { - if cs == nil { - panic("GetResourceInstanceChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - if gen == states.CurrentGen { - return cs.changes.ResourceInstance(addr).DeepCopy() - } - if dk, ok := gen.(states.DeposedKey); ok { - return cs.changes.ResourceInstanceDeposed(addr, dk).DeepCopy() - } - panic(fmt.Sprintf("unsupported generation value %#v", gen)) -} - -// RemoveResourceInstanceChange searches the set of resource instance changes -// for one matching the given address and generation, and removes it from the -// set if it exists. -func (cs *ChangesSync) RemoveResourceInstanceChange(addr addrs.AbsResourceInstance, gen states.Generation) { - if cs == nil { - panic("RemoveResourceInstanceChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - dk := states.NotDeposed - if realDK, ok := gen.(states.DeposedKey); ok { - dk = realDK - } - - addrStr := addr.String() - for i, r := range cs.changes.Resources { - if r.Addr.String() != addrStr || r.DeposedKey != dk { - continue - } - copy(cs.changes.Resources[i:], cs.changes.Resources[i+1:]) - cs.changes.Resources = cs.changes.Resources[:len(cs.changes.Resources)-1] - return - } -} - -// AppendOutputChange records the given output value change in the set of -// planned value changes. -// -// The caller must ensure that there are no concurrent writes to the given -// change while this method is running, but it is safe to resume mutating -// it after this method returns without affecting the saved change. -func (cs *ChangesSync) AppendOutputChange(changeSrc *OutputChangeSrc) { - if cs == nil { - panic("AppendOutputChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - s := changeSrc.DeepCopy() - cs.changes.Outputs = append(cs.changes.Outputs, s) -} - -// GetOutputChange searches the set of output value changes for one matching -// the given address, returning it if it exists. -// -// If no such change exists, nil is returned. -// -// The returned object is a deep copy of the change recorded in the plan, so -// callers may mutate it although it's generally better (less confusing) to -// treat planned changes as immutable after they've been initially constructed. -func (cs *ChangesSync) GetOutputChange(addr addrs.AbsOutputValue) *OutputChangeSrc { - if cs == nil { - panic("GetOutputChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - return cs.changes.OutputValue(addr) -} - -// RemoveOutputChange searches the set of output value changes for one matching -// the given address, and removes it from the set if it exists. -func (cs *ChangesSync) RemoveOutputChange(addr addrs.AbsOutputValue) { - if cs == nil { - panic("RemoveOutputChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - addrStr := addr.String() - for i, o := range cs.changes.Outputs { - if o.Addr.String() != addrStr { - continue - } - copy(cs.changes.Outputs[i:], cs.changes.Outputs[i+1:]) - cs.changes.Outputs = cs.changes.Outputs[:len(cs.changes.Outputs)-1] - return - } -} diff --git a/vendor/github.com/hashicorp/terraform/plans/doc.go b/vendor/github.com/hashicorp/terraform/plans/doc.go deleted file mode 100644 index 01ca3892..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package plans contains the types that are used to represent Terraform plans. -// -// A plan describes a set of changes that Terraform will make to update remote -// objects to match with changes to the configuration. -package plans diff --git a/vendor/github.com/hashicorp/terraform/plans/dynamic_value.go b/vendor/github.com/hashicorp/terraform/plans/dynamic_value.go deleted file mode 100644 index 51fbb24c..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/dynamic_value.go +++ /dev/null @@ -1,96 +0,0 @@ -package plans - -import ( - "github.com/zclconf/go-cty/cty" - ctymsgpack "github.com/zclconf/go-cty/cty/msgpack" -) - -// DynamicValue is the representation in the plan of a value whose type cannot -// be determined at compile time, such as because it comes from a schema -// defined in a plugin. -// -// This type is used as an indirection so that the overall plan structure can -// be decoded without schema available, and then the dynamic values accessed -// at a later time once the appropriate schema has been determined. -// -// Internally, DynamicValue is a serialized version of a cty.Value created -// against a particular type constraint. Callers should not access directly -// the serialized form, whose format may change in future. Values of this -// type must always be created by calling NewDynamicValue. -// -// The zero value of DynamicValue is nil, and represents the absense of a -// value within the Go type system. This is distinct from a cty.NullVal -// result, which represents the absense of a value within the cty type system. -type DynamicValue []byte - -// NewDynamicValue creates a DynamicValue by serializing the given value -// against the given type constraint. The value must conform to the type -// constraint, or the result is undefined. -// -// If the value to be encoded has no predefined schema (for example, for -// module output values and input variables), set the type constraint to -// cty.DynamicPseudoType in order to save type information as part of the -// value, and then also pass cty.DynamicPseudoType to method Decode to recover -// the original value. -// -// cty.NilVal can be used to represent the absense of a value, but callers -// must be careful to distinguish values that are absent at the Go layer -// (cty.NilVal) vs. values that are absent at the cty layer (cty.NullVal -// results). -func NewDynamicValue(val cty.Value, ty cty.Type) (DynamicValue, error) { - // If we're given cty.NilVal (the zero value of cty.Value, which is - // distinct from a typed null value created by cty.NullVal) then we'll - // assume the caller is trying to represent the _absense_ of a value, - // and so we'll return a nil DynamicValue. - if val == cty.NilVal { - return DynamicValue(nil), nil - } - - // Currently our internal encoding is msgpack, via ctymsgpack. - buf, err := ctymsgpack.Marshal(val, ty) - if err != nil { - return nil, err - } - - return DynamicValue(buf), nil -} - -// Decode retrieves the effective value from the receiever by interpreting the -// serialized form against the given type constraint. For correct results, -// the type constraint must match (or be consistent with) the one that was -// used to create the receiver. -// -// A nil DynamicValue decodes to cty.NilVal, which is not a valid value and -// instead represents the absense of a value. -func (v DynamicValue) Decode(ty cty.Type) (cty.Value, error) { - if v == nil { - return cty.NilVal, nil - } - - return ctymsgpack.Unmarshal([]byte(v), ty) -} - -// ImpliedType returns the type implied by the serialized structure of the -// receiving value. -// -// This will not necessarily be exactly the type that was given when the -// value was encoded, and in particular must not be used for values that -// were encoded with their static type given as cty.DynamicPseudoType. -// It is however safe to use this method for values that were encoded using -// their runtime type as the conforming type, with the result being -// semantically equivalent but with all lists and sets represented as tuples, -// and maps as objects, due to ambiguities of the serialization. -func (v DynamicValue) ImpliedType() (cty.Type, error) { - return ctymsgpack.ImpliedType([]byte(v)) -} - -// Copy produces a copy of the receiver with a distinct backing array. -func (v DynamicValue) Copy() DynamicValue { - if v == nil { - return nil - } - - ret := make(DynamicValue, len(v)) - copy(ret, v) - return ret -} diff --git a/vendor/github.com/hashicorp/terraform/plans/objchange/all_null.go b/vendor/github.com/hashicorp/terraform/plans/objchange/all_null.go deleted file mode 100644 index b1acb253..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/objchange/all_null.go +++ /dev/null @@ -1,68 +0,0 @@ -package objchange - -import ( - "fmt" - - "github.com/hashicorp/terraform/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// AllAttributesNull constructs a non-null cty.Value of the object type implied -// by the given schema that has all of its leaf attributes set to null and all -// of its nested block collections set to zero-length. -// -// This simulates what would result from decoding an empty configuration block -// with the given schema, except that it does not produce errors -func AllAttributesNull(schema *configschema.Block) cty.Value { - vals := make(map[string]cty.Value) - ty := schema.ImpliedType() - - for name := range schema.Attributes { - aty := ty.AttributeType(name) - vals[name] = cty.NullVal(aty) - } - - for name, blockS := range schema.BlockTypes { - aty := ty.AttributeType(name) - - switch blockS.Nesting { - case configschema.NestingSingle: - // NestingSingle behaves like an object attribute, which decodes - // as null when it's not present in configuration. - vals[name] = cty.NullVal(aty) - default: - // All other nesting types decode as "empty" when not present, but - // empty values take different forms depending on the type. - switch { - case aty.IsListType(): - vals[name] = cty.ListValEmpty(aty.ElementType()) - case aty.IsSetType(): - vals[name] = cty.SetValEmpty(aty.ElementType()) - case aty.IsMapType(): - vals[name] = cty.MapValEmpty(aty.ElementType()) - case aty.Equals(cty.DynamicPseudoType): - // We use DynamicPseudoType in situations where there's a - // nested attribute of DynamicPseudoType, since the schema - // system cannot predict the final type until it knows exactly - // how many elements there will be. However, since we're - // trying to behave as if there are _no_ elements, we know - // we're producing either an empty tuple or empty object - // and just need to distinguish these two cases. - switch blockS.Nesting { - case configschema.NestingList: - vals[name] = cty.EmptyTupleVal - case configschema.NestingMap: - vals[name] = cty.EmptyObjectVal - } - } - } - - // By the time we get down here we should always have set a value. - // If not, that suggests a missing case in the above switches. - if _, ok := vals[name]; !ok { - panic(fmt.Sprintf("failed to create empty value for nested block %q", name)) - } - } - - return cty.ObjectVal(vals) -} diff --git a/vendor/github.com/hashicorp/terraform/plans/objchange/compatible.go b/vendor/github.com/hashicorp/terraform/plans/objchange/compatible.go deleted file mode 100644 index fa1fd032..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/objchange/compatible.go +++ /dev/null @@ -1,376 +0,0 @@ -package objchange - -import ( - "fmt" - "strconv" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform/configs/configschema" -) - -// AssertObjectCompatible checks whether the given "actual" value is a valid -// completion of the possibly-partially-unknown "planned" value. -// -// This means that any known leaf value in "planned" must be equal to the -// corresponding value in "actual", and various other similar constraints. -// -// Any inconsistencies are reported by returning a non-zero number of errors. -// These errors are usually (but not necessarily) cty.PathError values -// referring to a particular nested value within the "actual" value. -// -// The two values must have types that conform to the given schema's implied -// type, or this function will panic. -func AssertObjectCompatible(schema *configschema.Block, planned, actual cty.Value) []error { - return assertObjectCompatible(schema, planned, actual, nil) -} - -func assertObjectCompatible(schema *configschema.Block, planned, actual cty.Value, path cty.Path) []error { - var errs []error - if planned.IsNull() && !actual.IsNull() { - errs = append(errs, path.NewErrorf("was absent, but now present")) - return errs - } - if actual.IsNull() && !planned.IsNull() { - errs = append(errs, path.NewErrorf("was present, but now absent")) - return errs - } - if planned.IsNull() { - // No further checks possible if both values are null - return errs - } - - for name, attrS := range schema.Attributes { - plannedV := planned.GetAttr(name) - actualV := actual.GetAttr(name) - - path := append(path, cty.GetAttrStep{Name: name}) - moreErrs := assertValueCompatible(plannedV, actualV, path) - if attrS.Sensitive { - if len(moreErrs) > 0 { - // Use a vague placeholder message instead, to avoid disclosing - // sensitive information. - errs = append(errs, path.NewErrorf("inconsistent values for sensitive attribute")) - } - } else { - errs = append(errs, moreErrs...) - } - } - for name, blockS := range schema.BlockTypes { - plannedV := planned.GetAttr(name) - actualV := actual.GetAttr(name) - - // As a special case, we permit a "planned" block with exactly one - // element where all of the "leaf" values are unknown, since that's - // what HCL's dynamic block extension generates if the for_each - // expression is itself unknown and thus it cannot predict how many - // child blocks will get created. - switch blockS.Nesting { - case configschema.NestingSingle: - if allLeafValuesUnknown(plannedV) && !plannedV.IsNull() { - return errs - } - case configschema.NestingList, configschema.NestingMap, configschema.NestingSet: - if plannedV.IsKnown() && !plannedV.IsNull() && plannedV.LengthInt() == 1 { - elemVs := plannedV.AsValueSlice() - if allLeafValuesUnknown(elemVs[0]) { - return errs - } - } - default: - panic(fmt.Sprintf("unsupported nesting mode %s", blockS.Nesting)) - } - - path := append(path, cty.GetAttrStep{Name: name}) - switch blockS.Nesting { - case configschema.NestingSingle: - moreErrs := assertObjectCompatible(&blockS.Block, plannedV, actualV, path) - errs = append(errs, moreErrs...) - case configschema.NestingList: - // A NestingList might either be a list or a tuple, depending on - // whether there are dynamically-typed attributes inside. However, - // both support a similar-enough API that we can treat them the - // same for our purposes here. - if !plannedV.IsKnown() || plannedV.IsNull() || actualV.IsNull() { - continue - } - - plannedL := plannedV.LengthInt() - actualL := actualV.LengthInt() - if plannedL != actualL { - errs = append(errs, path.NewErrorf("block count changed from %d to %d", plannedL, actualL)) - continue - } - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - if !actualV.HasIndex(idx).True() { - continue - } - actualEV := actualV.Index(idx) - moreErrs := assertObjectCompatible(&blockS.Block, plannedEV, actualEV, append(path, cty.IndexStep{Key: idx})) - errs = append(errs, moreErrs...) - } - case configschema.NestingMap: - // A NestingMap might either be a map or an object, depending on - // whether there are dynamically-typed attributes inside, but - // that's decided statically and so both values will have the same - // kind. - if plannedV.Type().IsObjectType() { - plannedAtys := plannedV.Type().AttributeTypes() - actualAtys := actualV.Type().AttributeTypes() - for k := range plannedAtys { - if _, ok := actualAtys[k]; !ok { - errs = append(errs, path.NewErrorf("block key %q has vanished", k)) - continue - } - - plannedEV := plannedV.GetAttr(k) - actualEV := actualV.GetAttr(k) - moreErrs := assertObjectCompatible(&blockS.Block, plannedEV, actualEV, append(path, cty.GetAttrStep{Name: k})) - errs = append(errs, moreErrs...) - } - for k := range actualAtys { - if _, ok := plannedAtys[k]; !ok { - errs = append(errs, path.NewErrorf("new block key %q has appeared", k)) - continue - } - } - } else { - if !plannedV.IsKnown() || plannedV.IsNull() || actualV.IsNull() { - continue - } - plannedL := plannedV.LengthInt() - actualL := actualV.LengthInt() - if plannedL != actualL { - errs = append(errs, path.NewErrorf("block count changed from %d to %d", plannedL, actualL)) - continue - } - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - if !actualV.HasIndex(idx).True() { - continue - } - actualEV := actualV.Index(idx) - moreErrs := assertObjectCompatible(&blockS.Block, plannedEV, actualEV, append(path, cty.IndexStep{Key: idx})) - errs = append(errs, moreErrs...) - } - } - case configschema.NestingSet: - if !plannedV.IsKnown() || !actualV.IsKnown() || plannedV.IsNull() || actualV.IsNull() { - continue - } - - setErrs := assertSetValuesCompatible(plannedV, actualV, path, func(plannedEV, actualEV cty.Value) bool { - errs := assertObjectCompatible(&blockS.Block, plannedEV, actualEV, append(path, cty.IndexStep{Key: actualEV})) - return len(errs) == 0 - }) - errs = append(errs, setErrs...) - - // There can be fewer elements in a set after its elements are all - // known (values that turn out to be equal will coalesce) but the - // number of elements must never get larger. - plannedL := plannedV.LengthInt() - actualL := actualV.LengthInt() - if plannedL < actualL { - errs = append(errs, path.NewErrorf("block set length changed from %d to %d", plannedL, actualL)) - } - default: - panic(fmt.Sprintf("unsupported nesting mode %s", blockS.Nesting)) - } - } - return errs -} - -func assertValueCompatible(planned, actual cty.Value, path cty.Path) []error { - // NOTE: We don't normally use the GoString rendering of cty.Value in - // user-facing error messages as a rule, but we make an exception - // for this function because we expect the user to pass this message on - // verbatim to the provider development team and so more detail is better. - - var errs []error - if planned.Type() == cty.DynamicPseudoType { - // Anything goes, then - return errs - } - if problems := planned.Type().TestConformance(actual.Type()); len(problems) > 0 { - errs = append(errs, path.NewErrorf("wrong final value type: %s", convert.MismatchMessage(actual.Type(), planned.Type()))) - // If the types don't match then we can't do any other comparisons, - // so we bail early. - return errs - } - - if !planned.IsKnown() { - // We didn't know what were going to end up with during plan, so - // anything goes during apply. - return errs - } - - if actual.IsNull() { - if planned.IsNull() { - return nil - } - errs = append(errs, path.NewErrorf("was %#v, but now null", planned)) - return errs - } - if planned.IsNull() { - errs = append(errs, path.NewErrorf("was null, but now %#v", actual)) - return errs - } - - ty := planned.Type() - switch { - - case !actual.IsKnown(): - errs = append(errs, path.NewErrorf("was known, but now unknown")) - - case ty.IsPrimitiveType(): - if !actual.Equals(planned).True() { - errs = append(errs, path.NewErrorf("was %#v, but now %#v", planned, actual)) - } - - case ty.IsListType() || ty.IsMapType() || ty.IsTupleType(): - for it := planned.ElementIterator(); it.Next(); { - k, plannedV := it.Element() - if !actual.HasIndex(k).True() { - errs = append(errs, path.NewErrorf("element %s has vanished", indexStrForErrors(k))) - continue - } - - actualV := actual.Index(k) - moreErrs := assertValueCompatible(plannedV, actualV, append(path, cty.IndexStep{Key: k})) - errs = append(errs, moreErrs...) - } - - for it := actual.ElementIterator(); it.Next(); { - k, _ := it.Element() - if !planned.HasIndex(k).True() { - errs = append(errs, path.NewErrorf("new element %s has appeared", indexStrForErrors(k))) - } - } - - case ty.IsObjectType(): - atys := ty.AttributeTypes() - for name := range atys { - // Because we already tested that the two values have the same type, - // we can assume that the same attributes are present in both and - // focus just on testing their values. - plannedV := planned.GetAttr(name) - actualV := actual.GetAttr(name) - moreErrs := assertValueCompatible(plannedV, actualV, append(path, cty.GetAttrStep{Name: name})) - errs = append(errs, moreErrs...) - } - - case ty.IsSetType(): - // We can't really do anything useful for sets here because changing - // an unknown element to known changes the identity of the element, and - // so we can't correlate them properly. However, we will at least check - // to ensure that the number of elements is consistent, along with - // the general type-match checks we ran earlier in this function. - if planned.IsKnown() && !planned.IsNull() && !actual.IsNull() { - - setErrs := assertSetValuesCompatible(planned, actual, path, func(plannedV, actualV cty.Value) bool { - errs := assertValueCompatible(plannedV, actualV, append(path, cty.IndexStep{Key: actualV})) - return len(errs) == 0 - }) - errs = append(errs, setErrs...) - - // There can be fewer elements in a set after its elements are all - // known (values that turn out to be equal will coalesce) but the - // number of elements must never get larger. - - plannedL := planned.LengthInt() - actualL := actual.LengthInt() - if plannedL < actualL { - errs = append(errs, path.NewErrorf("length changed from %d to %d", plannedL, actualL)) - } - } - } - - return errs -} - -func indexStrForErrors(v cty.Value) string { - switch v.Type() { - case cty.Number: - return v.AsBigFloat().Text('f', -1) - case cty.String: - return strconv.Quote(v.AsString()) - default: - // Should be impossible, since no other index types are allowed! - return fmt.Sprintf("%#v", v) - } -} - -func allLeafValuesUnknown(v cty.Value) bool { - seenKnownValue := false - cty.Walk(v, func(path cty.Path, cv cty.Value) (bool, error) { - if cv.IsNull() { - seenKnownValue = true - } - if cv.Type().IsPrimitiveType() && cv.IsKnown() { - seenKnownValue = true - } - return true, nil - }) - return !seenKnownValue -} - -// assertSetValuesCompatible checks that each of the elements in a can -// be correlated with at least one equivalent element in b and vice-versa, -// using the given correlation function. -// -// This allows the number of elements in the sets to change as long as all -// elements in both sets can be correlated, making this function safe to use -// with sets that may contain unknown values as long as the unknown case is -// addressed in some reasonable way in the callback function. -// -// The callback always recieves values from set a as its first argument and -// values from set b in its second argument, so it is safe to use with -// non-commutative functions. -// -// As with assertValueCompatible, we assume that the target audience of error -// messages here is a provider developer (via a bug report from a user) and so -// we intentionally violate our usual rule of keeping cty implementation -// details out of error messages. -func assertSetValuesCompatible(planned, actual cty.Value, path cty.Path, f func(aVal, bVal cty.Value) bool) []error { - a := planned - b := actual - - // Our methodology here is a little tricky, to deal with the fact that - // it's impossible to directly correlate two non-equal set elements because - // they don't have identities separate from their values. - // The approach is to count the number of equivalent elements each element - // of a has in b and vice-versa, and then return true only if each element - // in both sets has at least one equivalent. - as := a.AsValueSlice() - bs := b.AsValueSlice() - aeqs := make([]bool, len(as)) - beqs := make([]bool, len(bs)) - for ai, av := range as { - for bi, bv := range bs { - if f(av, bv) { - aeqs[ai] = true - beqs[bi] = true - } - } - } - - var errs []error - for i, eq := range aeqs { - if !eq { - errs = append(errs, path.NewErrorf("planned set element %#v does not correlate with any element in actual", as[i])) - } - } - if len(errs) > 0 { - // Exit early since otherwise we're likely to generate duplicate - // error messages from the other perspective in the subsequent loop. - return errs - } - for i, eq := range beqs { - if !eq { - errs = append(errs, path.NewErrorf("actual set element %#v does not correlate with any element in plan", bs[i])) - } - } - return errs -} diff --git a/vendor/github.com/hashicorp/terraform/plans/objchange/doc.go b/vendor/github.com/hashicorp/terraform/plans/objchange/doc.go deleted file mode 100644 index 2c18a010..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/objchange/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package objchange deals with the business logic of taking a prior state -// value and a config value and producing a proposed new merged value, along -// with other related rules in this domain. -package objchange diff --git a/vendor/github.com/hashicorp/terraform/plans/objchange/lcs.go b/vendor/github.com/hashicorp/terraform/plans/objchange/lcs.go deleted file mode 100644 index cbfefddd..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/objchange/lcs.go +++ /dev/null @@ -1,104 +0,0 @@ -package objchange - -import ( - "github.com/zclconf/go-cty/cty" -) - -// LongestCommonSubsequence finds a sequence of values that are common to both -// x and y, with the same relative ordering as in both collections. This result -// is useful as a first step towards computing a diff showing added/removed -// elements in a sequence. -// -// The approached used here is a "naive" one, assuming that both xs and ys will -// generally be small in most reasonable Terraform configurations. For larger -// lists the time/space usage may be sub-optimal. -// -// A pair of lists may have multiple longest common subsequences. In that -// case, the one selected by this function is undefined. -func LongestCommonSubsequence(xs, ys []cty.Value) []cty.Value { - if len(xs) == 0 || len(ys) == 0 { - return make([]cty.Value, 0) - } - - c := make([]int, len(xs)*len(ys)) - eqs := make([]bool, len(xs)*len(ys)) - w := len(xs) - - for y := 0; y < len(ys); y++ { - for x := 0; x < len(xs); x++ { - eqV := xs[x].Equals(ys[y]) - eq := false - if eqV.IsKnown() && eqV.True() { - eq = true - eqs[(w*y)+x] = true // equality tests can be expensive, so cache it - } - if eq { - // Sequence gets one longer than for the cell at top left, - // since we'd append a new item to the sequence here. - if x == 0 || y == 0 { - c[(w*y)+x] = 1 - } else { - c[(w*y)+x] = c[(w*(y-1))+(x-1)] + 1 - } - } else { - // We follow the longest of the sequence above and the sequence - // to the left of us in the matrix. - l := 0 - u := 0 - if x > 0 { - l = c[(w*y)+(x-1)] - } - if y > 0 { - u = c[(w*(y-1))+x] - } - if l > u { - c[(w*y)+x] = l - } else { - c[(w*y)+x] = u - } - } - } - } - - // The bottom right cell tells us how long our longest sequence will be - seq := make([]cty.Value, c[len(c)-1]) - - // Now we will walk back from the bottom right cell, finding again all - // of the equal pairs to construct our sequence. - x := len(xs) - 1 - y := len(ys) - 1 - i := len(seq) - 1 - - for x > -1 && y > -1 { - if eqs[(w*y)+x] { - // Add the value to our result list and then walk diagonally - // up and to the left. - seq[i] = xs[x] - x-- - y-- - i-- - } else { - // Take the path with the greatest sequence length in the matrix. - l := 0 - u := 0 - if x > 0 { - l = c[(w*y)+(x-1)] - } - if y > 0 { - u = c[(w*(y-1))+x] - } - if l > u { - x-- - } else { - y-- - } - } - } - - if i > -1 { - // should never happen if the matrix was constructed properly - panic("not enough elements in sequence") - } - - return seq -} diff --git a/vendor/github.com/hashicorp/terraform/plans/objchange/objchange.go b/vendor/github.com/hashicorp/terraform/plans/objchange/objchange.go deleted file mode 100644 index 15565a40..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/objchange/objchange.go +++ /dev/null @@ -1,383 +0,0 @@ -package objchange - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/configs/configschema" -) - -// ProposedNewObject constructs a proposed new object value by combining the -// computed attribute values from "prior" with the configured attribute values -// from "config". -// -// Both value must conform to the given schema's implied type, or this function -// will panic. -// -// The prior value must be wholly known, but the config value may be unknown -// or have nested unknown values. -// -// The merging of the two objects includes the attributes of any nested blocks, -// which will be correlated in a manner appropriate for their nesting mode. -// Note in particular that the correlation for blocks backed by sets is a -// heuristic based on matching non-computed attribute values and so it may -// produce strange results with more "extreme" cases, such as a nested set -// block where _all_ attributes are computed. -func ProposedNewObject(schema *configschema.Block, prior, config cty.Value) cty.Value { - if prior.IsNull() { - // In this case, we will construct a synthetic prior value that is - // similar to the result of decoding an empty configuration block, - // which simplifies our handling of the top-level attributes/blocks - // below by giving us one non-null level of object to pull values from. - prior = AllAttributesNull(schema) - } - return proposedNewObject(schema, prior, config) -} - -// PlannedDataResourceObject is similar to ProposedNewObject but tailored for -// planning data resources in particular. Specifically, it replaces the values -// of any Computed attributes not set in the configuration with an unknown -// value, which serves as a placeholder for a value to be filled in by the -// provider when the data resource is finally read. -// -// Data resources are different because the planning of them is handled -// entirely within Terraform Core and not subject to customization by the -// provider. This function is, in effect, producing an equivalent result to -// passing the ProposedNewObject result into a provider's PlanResourceChange -// function, assuming a fixed implementation of PlanResourceChange that just -// fills in unknown values as needed. -func PlannedDataResourceObject(schema *configschema.Block, config cty.Value) cty.Value { - // Our trick here is to run the ProposedNewObject logic with an - // entirely-unknown prior value. Because of cty's unknown short-circuit - // behavior, any operation on prior returns another unknown, and so - // unknown values propagate into all of the parts of the resulting value - // that would normally be filled in by preserving the prior state. - prior := cty.UnknownVal(schema.ImpliedType()) - return proposedNewObject(schema, prior, config) -} - -func proposedNewObject(schema *configschema.Block, prior, config cty.Value) cty.Value { - if config.IsNull() || !config.IsKnown() { - // This is a weird situation, but we'll allow it anyway to free - // callers from needing to specifically check for these cases. - return prior - } - if (!prior.Type().IsObjectType()) || (!config.Type().IsObjectType()) { - panic("ProposedNewObject only supports object-typed values") - } - - // From this point onwards, we can assume that both values are non-null - // object types, and that the config value itself is known (though it - // may contain nested values that are unknown.) - - newAttrs := map[string]cty.Value{} - for name, attr := range schema.Attributes { - priorV := prior.GetAttr(name) - configV := config.GetAttr(name) - var newV cty.Value - switch { - case attr.Computed && attr.Optional: - // This is the trickiest scenario: we want to keep the prior value - // if the config isn't overriding it. Note that due to some - // ambiguity here, setting an optional+computed attribute from - // config and then later switching the config to null in a - // subsequent change causes the initial config value to be "sticky" - // unless the provider specifically overrides it during its own - // plan customization step. - if configV.IsNull() { - newV = priorV - } else { - newV = configV - } - case attr.Computed: - // configV will always be null in this case, by definition. - // priorV may also be null, but that's okay. - newV = priorV - default: - // For non-computed attributes, we always take the config value, - // even if it is null. If it's _required_ then null values - // should've been caught during an earlier validation step, and - // so we don't really care about that here. - newV = configV - } - newAttrs[name] = newV - } - - // Merging nested blocks is a little more complex, since we need to - // correlate blocks between both objects and then recursively propose - // a new object for each. The correlation logic depends on the nesting - // mode for each block type. - for name, blockType := range schema.BlockTypes { - priorV := prior.GetAttr(name) - configV := config.GetAttr(name) - var newV cty.Value - switch blockType.Nesting { - - case configschema.NestingSingle: - newV = ProposedNewObject(&blockType.Block, priorV, configV) - - case configschema.NestingList: - // Nested blocks are correlated by index. - configVLen := 0 - if configV.IsKnown() && !configV.IsNull() { - configVLen = configV.LengthInt() - } - if configVLen > 0 { - newVals := make([]cty.Value, 0, configVLen) - for it := configV.ElementIterator(); it.Next(); { - idx, configEV := it.Element() - if priorV.IsKnown() && (priorV.IsNull() || !priorV.HasIndex(idx).True()) { - // If there is no corresponding prior element then - // we just take the config value as-is. - newVals = append(newVals, configEV) - continue - } - priorEV := priorV.Index(idx) - - newEV := ProposedNewObject(&blockType.Block, priorEV, configEV) - newVals = append(newVals, newEV) - } - // Despite the name, a NestingList might also be a tuple, if - // its nested schema contains dynamically-typed attributes. - if configV.Type().IsTupleType() { - newV = cty.TupleVal(newVals) - } else { - newV = cty.ListVal(newVals) - } - } else { - // Despite the name, a NestingList might also be a tuple, if - // its nested schema contains dynamically-typed attributes. - if configV.Type().IsTupleType() { - newV = cty.EmptyTupleVal - } else { - newV = cty.ListValEmpty(blockType.ImpliedType()) - } - } - - case configschema.NestingMap: - // Despite the name, a NestingMap may produce either a map or - // object value, depending on whether the nested schema contains - // dynamically-typed attributes. - if configV.Type().IsObjectType() { - // Nested blocks are correlated by key. - configVLen := 0 - if configV.IsKnown() && !configV.IsNull() { - configVLen = configV.LengthInt() - } - if configVLen > 0 { - newVals := make(map[string]cty.Value, configVLen) - atys := configV.Type().AttributeTypes() - for name := range atys { - configEV := configV.GetAttr(name) - if !priorV.Type().HasAttribute(name) { - // If there is no corresponding prior element then - // we just take the config value as-is. - newVals[name] = configEV - continue - } - priorEV := priorV.GetAttr(name) - - newEV := ProposedNewObject(&blockType.Block, priorEV, configEV) - newVals[name] = newEV - } - // Although we call the nesting mode "map", we actually use - // object values so that elements might have different types - // in case of dynamically-typed attributes. - newV = cty.ObjectVal(newVals) - } else { - newV = cty.EmptyObjectVal - } - } else { - configVLen := 0 - if configV.IsKnown() && !configV.IsNull() { - configVLen = configV.LengthInt() - } - if configVLen > 0 { - newVals := make(map[string]cty.Value, configVLen) - for it := configV.ElementIterator(); it.Next(); { - idx, configEV := it.Element() - k := idx.AsString() - if priorV.IsKnown() && (priorV.IsNull() || !priorV.HasIndex(idx).True()) { - // If there is no corresponding prior element then - // we just take the config value as-is. - newVals[k] = configEV - continue - } - priorEV := priorV.Index(idx) - - newEV := ProposedNewObject(&blockType.Block, priorEV, configEV) - newVals[k] = newEV - } - newV = cty.MapVal(newVals) - } else { - newV = cty.MapValEmpty(blockType.ImpliedType()) - } - } - - case configschema.NestingSet: - if !configV.Type().IsSetType() { - panic("configschema.NestingSet value is not a set as expected") - } - - // Nested blocks are correlated by comparing the element values - // after eliminating all of the computed attributes. In practice, - // this means that any config change produces an entirely new - // nested object, and we only propagate prior computed values - // if the non-computed attribute values are identical. - var cmpVals [][2]cty.Value - if priorV.IsKnown() && !priorV.IsNull() { - cmpVals = setElementCompareValues(&blockType.Block, priorV, false) - } - configVLen := 0 - if configV.IsKnown() && !configV.IsNull() { - configVLen = configV.LengthInt() - } - if configVLen > 0 { - used := make([]bool, len(cmpVals)) // track used elements in case multiple have the same compare value - newVals := make([]cty.Value, 0, configVLen) - for it := configV.ElementIterator(); it.Next(); { - _, configEV := it.Element() - var priorEV cty.Value - for i, cmp := range cmpVals { - if used[i] { - continue - } - if cmp[1].RawEquals(configEV) { - priorEV = cmp[0] - used[i] = true // we can't use this value on a future iteration - break - } - } - if priorEV == cty.NilVal { - priorEV = cty.NullVal(blockType.ImpliedType()) - } - - newEV := ProposedNewObject(&blockType.Block, priorEV, configEV) - newVals = append(newVals, newEV) - } - newV = cty.SetVal(newVals) - } else { - newV = cty.SetValEmpty(blockType.Block.ImpliedType()) - } - - default: - // Should never happen, since the above cases are comprehensive. - panic(fmt.Sprintf("unsupported block nesting mode %s", blockType.Nesting)) - } - - newAttrs[name] = newV - } - - return cty.ObjectVal(newAttrs) -} - -// setElementCompareValues takes a known, non-null value of a cty.Set type and -// returns a table -- constructed of two-element arrays -- that maps original -// set element values to corresponding values that have all of the computed -// values removed, making them suitable for comparison with values obtained -// from configuration. The element type of the set must conform to the implied -// type of the given schema, or this function will panic. -// -// In the resulting slice, the zeroth element of each array is the original -// value and the one-indexed element is the corresponding "compare value". -// -// This is intended to help correlate prior elements with configured elements -// in ProposedNewObject. The result is a heuristic rather than an exact science, -// since e.g. two separate elements may reduce to the same value through this -// process. The caller must therefore be ready to deal with duplicates. -func setElementCompareValues(schema *configschema.Block, set cty.Value, isConfig bool) [][2]cty.Value { - ret := make([][2]cty.Value, 0, set.LengthInt()) - for it := set.ElementIterator(); it.Next(); { - _, ev := it.Element() - ret = append(ret, [2]cty.Value{ev, setElementCompareValue(schema, ev, isConfig)}) - } - return ret -} - -// setElementCompareValue creates a new value that has all of the same -// non-computed attribute values as the one given but has all computed -// attribute values forced to null. -// -// If isConfig is true then non-null Optional+Computed attribute values will -// be preserved. Otherwise, they will also be set to null. -// -// The input value must conform to the schema's implied type, and the return -// value is guaranteed to conform to it. -func setElementCompareValue(schema *configschema.Block, v cty.Value, isConfig bool) cty.Value { - if v.IsNull() || !v.IsKnown() { - return v - } - - attrs := map[string]cty.Value{} - for name, attr := range schema.Attributes { - switch { - case attr.Computed && attr.Optional: - if isConfig { - attrs[name] = v.GetAttr(name) - } else { - attrs[name] = cty.NullVal(attr.Type) - } - case attr.Computed: - attrs[name] = cty.NullVal(attr.Type) - default: - attrs[name] = v.GetAttr(name) - } - } - - for name, blockType := range schema.BlockTypes { - switch blockType.Nesting { - - case configschema.NestingSingle: - attrs[name] = setElementCompareValue(&blockType.Block, v.GetAttr(name), isConfig) - - case configschema.NestingList, configschema.NestingSet: - cv := v.GetAttr(name) - if cv.IsNull() || !cv.IsKnown() { - attrs[name] = cv - continue - } - if l := cv.LengthInt(); l > 0 { - elems := make([]cty.Value, 0, l) - for it := cv.ElementIterator(); it.Next(); { - _, ev := it.Element() - elems = append(elems, setElementCompareValue(&blockType.Block, ev, isConfig)) - } - if blockType.Nesting == configschema.NestingSet { - // SetValEmpty would panic if given elements that are not - // all of the same type, but that's guaranteed not to - // happen here because our input value was _already_ a - // set and we've not changed the types of any elements here. - attrs[name] = cty.SetVal(elems) - } else { - attrs[name] = cty.TupleVal(elems) - } - } else { - if blockType.Nesting == configschema.NestingSet { - attrs[name] = cty.SetValEmpty(blockType.Block.ImpliedType()) - } else { - attrs[name] = cty.EmptyTupleVal - } - } - - case configschema.NestingMap: - cv := v.GetAttr(name) - if cv.IsNull() || !cv.IsKnown() { - attrs[name] = cv - continue - } - elems := make(map[string]cty.Value) - for it := cv.ElementIterator(); it.Next(); { - kv, ev := it.Element() - elems[kv.AsString()] = setElementCompareValue(&blockType.Block, ev, isConfig) - } - attrs[name] = cty.ObjectVal(elems) - - default: - // Should never happen, since the above cases are comprehensive. - panic(fmt.Sprintf("unsupported block nesting mode %s", blockType.Nesting)) - } - } - - return cty.ObjectVal(attrs) -} diff --git a/vendor/github.com/hashicorp/terraform/plans/objchange/plan_valid.go b/vendor/github.com/hashicorp/terraform/plans/objchange/plan_valid.go deleted file mode 100644 index 308c47f5..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/objchange/plan_valid.go +++ /dev/null @@ -1,267 +0,0 @@ -package objchange - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/configs/configschema" -) - -// AssertPlanValid checks checks whether a planned new state returned by a -// provider's PlanResourceChange method is suitable to achieve a change -// from priorState to config. It returns a slice with nonzero length if -// any problems are detected. Because problems here indicate bugs in the -// provider that generated the plannedState, they are written with provider -// developers as an audience, rather than end-users. -// -// All of the given values must have the same type and must conform to the -// implied type of the given schema, or this function may panic or produce -// garbage results. -// -// During planning, a provider may only make changes to attributes that are -// null (unset) in the configuration and are marked as "computed" in the -// resource type schema, in order to insert any default values the provider -// may know about. If the default value cannot be determined until apply time, -// the provider can return an unknown value. Providers are forbidden from -// planning a change that disagrees with any non-null argument in the -// configuration. -// -// As a special exception, providers _are_ allowed to provide attribute values -// conflicting with configuration if and only if the planned value exactly -// matches the corresponding attribute value in the prior state. The provider -// can use this to signal that the new value is functionally equivalent to -// the old and thus no change is required. -func AssertPlanValid(schema *configschema.Block, priorState, config, plannedState cty.Value) []error { - return assertPlanValid(schema, priorState, config, plannedState, nil) -} - -func assertPlanValid(schema *configschema.Block, priorState, config, plannedState cty.Value, path cty.Path) []error { - var errs []error - if plannedState.IsNull() && !config.IsNull() { - errs = append(errs, path.NewErrorf("planned for absense but config wants existence")) - return errs - } - if config.IsNull() && !plannedState.IsNull() { - errs = append(errs, path.NewErrorf("planned for existence but config wants absense")) - return errs - } - if plannedState.IsNull() { - // No further checks possible if the planned value is null - return errs - } - - impTy := schema.ImpliedType() - - for name, attrS := range schema.Attributes { - plannedV := plannedState.GetAttr(name) - configV := config.GetAttr(name) - priorV := cty.NullVal(attrS.Type) - if !priorState.IsNull() { - priorV = priorState.GetAttr(name) - } - - path := append(path, cty.GetAttrStep{Name: name}) - moreErrs := assertPlannedValueValid(attrS, priorV, configV, plannedV, path) - errs = append(errs, moreErrs...) - } - for name, blockS := range schema.BlockTypes { - path := append(path, cty.GetAttrStep{Name: name}) - plannedV := plannedState.GetAttr(name) - configV := config.GetAttr(name) - priorV := cty.NullVal(impTy.AttributeType(name)) - if !priorState.IsNull() { - priorV = priorState.GetAttr(name) - } - if plannedV.RawEquals(configV) { - // Easy path: nothing has changed at all - continue - } - if !plannedV.IsKnown() { - errs = append(errs, path.NewErrorf("attribute representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - - switch blockS.Nesting { - case configschema.NestingSingle: - moreErrs := assertPlanValid(&blockS.Block, priorV, configV, plannedV, path) - errs = append(errs, moreErrs...) - case configschema.NestingList: - // A NestingList might either be a list or a tuple, depending on - // whether there are dynamically-typed attributes inside. However, - // both support a similar-enough API that we can treat them the - // same for our purposes here. - if plannedV.IsNull() { - errs = append(errs, path.NewErrorf("attribute representing a list of nested blocks must be empty to indicate no blocks, not null")) - continue - } - - plannedL := plannedV.LengthInt() - configL := configV.LengthInt() - if plannedL != configL { - errs = append(errs, path.NewErrorf("block count in plan (%d) disagrees with count in config (%d)", plannedL, configL)) - continue - } - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - path := append(path, cty.IndexStep{Key: idx}) - if !plannedEV.IsKnown() { - errs = append(errs, path.NewErrorf("element representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - if !configV.HasIndex(idx).True() { - continue // should never happen since we checked the lengths above - } - configEV := configV.Index(idx) - priorEV := cty.NullVal(blockS.ImpliedType()) - if !priorV.IsNull() && priorV.HasIndex(idx).True() { - priorEV = priorV.Index(idx) - } - - moreErrs := assertPlanValid(&blockS.Block, priorEV, configEV, plannedEV, path) - errs = append(errs, moreErrs...) - } - case configschema.NestingMap: - if plannedV.IsNull() { - errs = append(errs, path.NewErrorf("attribute representing a map of nested blocks must be empty to indicate no blocks, not null")) - continue - } - - // A NestingMap might either be a map or an object, depending on - // whether there are dynamically-typed attributes inside, but - // that's decided statically and so all values will have the same - // kind. - if plannedV.Type().IsObjectType() { - plannedAtys := plannedV.Type().AttributeTypes() - configAtys := configV.Type().AttributeTypes() - for k := range plannedAtys { - if _, ok := configAtys[k]; !ok { - errs = append(errs, path.NewErrorf("block key %q from plan is not present in config", k)) - continue - } - path := append(path, cty.GetAttrStep{Name: k}) - - plannedEV := plannedV.GetAttr(k) - if !plannedEV.IsKnown() { - errs = append(errs, path.NewErrorf("element representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - configEV := configV.GetAttr(k) - priorEV := cty.NullVal(blockS.ImpliedType()) - if !priorV.IsNull() && priorV.Type().HasAttribute(k) { - priorEV = priorV.GetAttr(k) - } - moreErrs := assertPlanValid(&blockS.Block, priorEV, configEV, plannedEV, path) - errs = append(errs, moreErrs...) - } - for k := range configAtys { - if _, ok := plannedAtys[k]; !ok { - errs = append(errs, path.NewErrorf("block key %q from config is not present in plan", k)) - continue - } - } - } else { - plannedL := plannedV.LengthInt() - configL := configV.LengthInt() - if plannedL != configL { - errs = append(errs, path.NewErrorf("block count in plan (%d) disagrees with count in config (%d)", plannedL, configL)) - continue - } - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - path := append(path, cty.IndexStep{Key: idx}) - if !plannedEV.IsKnown() { - errs = append(errs, path.NewErrorf("element representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - k := idx.AsString() - if !configV.HasIndex(idx).True() { - errs = append(errs, path.NewErrorf("block key %q from plan is not present in config", k)) - continue - } - configEV := configV.Index(idx) - priorEV := cty.NullVal(blockS.ImpliedType()) - if !priorV.IsNull() && priorV.HasIndex(idx).True() { - priorEV = priorV.GetAttr(k) - } - moreErrs := assertPlanValid(&blockS.Block, priorEV, configEV, plannedEV, path) - errs = append(errs, moreErrs...) - } - for it := configV.ElementIterator(); it.Next(); { - idx, _ := it.Element() - if !plannedV.HasIndex(idx).True() { - errs = append(errs, path.NewErrorf("block key %q from config is not present in plan", idx.AsString())) - continue - } - } - } - case configschema.NestingSet: - if plannedV.IsNull() { - errs = append(errs, path.NewErrorf("attribute representing a set of nested blocks must be empty to indicate no blocks, not null")) - continue - } - - // Because set elements have no identifier with which to correlate - // them, we can't robustly validate the plan for a nested block - // backed by a set, and so unfortunately we need to just trust the - // provider to do the right thing. :( - // - // (In principle we could correlate elements by matching the - // subset of attributes explicitly set in config, except for the - // special diff suppression rule which allows for there to be a - // planned value that is constructed by mixing part of a prior - // value with part of a config value, creating an entirely new - // element that is not present in either prior nor config.) - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - path := append(path, cty.IndexStep{Key: idx}) - if !plannedEV.IsKnown() { - errs = append(errs, path.NewErrorf("element representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - } - - default: - panic(fmt.Sprintf("unsupported nesting mode %s", blockS.Nesting)) - } - } - - return errs -} - -func assertPlannedValueValid(attrS *configschema.Attribute, priorV, configV, plannedV cty.Value, path cty.Path) []error { - var errs []error - if plannedV.RawEquals(configV) { - // This is the easy path: provider didn't change anything at all. - return errs - } - if plannedV.RawEquals(priorV) && !priorV.IsNull() { - // Also pretty easy: there is a prior value and the provider has - // returned it unchanged. This indicates that configV and plannedV - // are functionally equivalent and so the provider wishes to disregard - // the configuration value in favor of the prior. - return errs - } - if attrS.Computed && configV.IsNull() { - // The provider is allowed to change the value of any computed - // attribute that isn't explicitly set in the config. - return errs - } - - // If none of the above conditions match, the provider has made an invalid - // change to this attribute. - if priorV.IsNull() { - if attrS.Sensitive { - errs = append(errs, path.NewErrorf("sensitive planned value does not match config value")) - } else { - errs = append(errs, path.NewErrorf("planned value %#v does not match config value %#v", plannedV, configV)) - } - return errs - } - if attrS.Sensitive { - errs = append(errs, path.NewErrorf("sensitive planned value does not match config value nor prior value")) - } else { - errs = append(errs, path.NewErrorf("planned value %#v does not match config value %#v nor prior value %#v", plannedV, configV, priorV)) - } - return errs -} diff --git a/vendor/github.com/hashicorp/terraform/plans/plan.go b/vendor/github.com/hashicorp/terraform/plans/plan.go deleted file mode 100644 index 5a3e4548..00000000 --- a/vendor/github.com/hashicorp/terraform/plans/plan.go +++ /dev/null @@ -1,92 +0,0 @@ -package plans - -import ( - "sort" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// Plan is the top-level type representing a planned set of changes. -// -// A plan is a summary of the set of changes required to move from a current -// state to a goal state derived from configuration. The described changes -// are not applied directly, but contain an approximation of the final -// result that will be completed during apply by resolving any values that -// cannot be predicted. -// -// A plan must always be accompanied by the state and configuration it was -// built from, since the plan does not itself include all of the information -// required to make the changes indicated. -type Plan struct { - VariableValues map[string]DynamicValue - Changes *Changes - TargetAddrs []addrs.Targetable - ProviderSHA256s map[string][]byte - Backend Backend -} - -// Backend represents the backend-related configuration and other data as it -// existed when a plan was created. -type Backend struct { - // Type is the type of backend that the plan will apply against. - Type string - - // Config is the configuration of the backend, whose schema is decided by - // the backend Type. - Config DynamicValue - - // Workspace is the name of the workspace that was active when the plan - // was created. It is illegal to apply a plan created for one workspace - // to the state of another workspace. - // (This constraint is already enforced by the statefile lineage mechanism, - // but storing this explicitly allows us to return a better error message - // in the situation where the user has the wrong workspace selected.) - Workspace string -} - -func NewBackend(typeName string, config cty.Value, configSchema *configschema.Block, workspaceName string) (*Backend, error) { - dv, err := NewDynamicValue(config, configSchema.ImpliedType()) - if err != nil { - return nil, err - } - - return &Backend{ - Type: typeName, - Config: dv, - Workspace: workspaceName, - }, nil -} - -// ProviderAddrs returns a list of all of the provider configuration addresses -// referenced throughout the receiving plan. -// -// The result is de-duplicated so that each distinct address appears only once. -func (p *Plan) ProviderAddrs() []addrs.AbsProviderConfig { - if p == nil || p.Changes == nil { - return nil - } - - m := map[string]addrs.AbsProviderConfig{} - for _, rc := range p.Changes.Resources { - m[rc.ProviderAddr.String()] = rc.ProviderAddr - } - if len(m) == 0 { - return nil - } - - // This is mainly just so we'll get stable results for testing purposes. - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - - ret := make([]addrs.AbsProviderConfig, len(keys)) - for i, key := range keys { - ret[i] = m[key] - } - - return ret -} diff --git a/vendor/github.com/hashicorp/terraform/plugin/client.go b/vendor/github.com/hashicorp/terraform/plugin/client.go index 0eab5385..7e2f4fec 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/client.go +++ b/vendor/github.com/hashicorp/terraform/plugin/client.go @@ -19,13 +19,11 @@ func ClientConfig(m discovery.PluginMeta) *plugin.ClientConfig { }) return &plugin.ClientConfig{ - Cmd: exec.Command(m.Path), - HandshakeConfig: Handshake, - VersionedPlugins: VersionedPlugins, - Managed: true, - Logger: logger, - AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC}, - AutoMTLS: true, + Cmd: exec.Command(m.Path), + HandshakeConfig: Handshake, + Managed: true, + Plugins: PluginMap, + Logger: logger, } } diff --git a/vendor/github.com/hashicorp/terraform/plugin/convert/diagnostics.go b/vendor/github.com/hashicorp/terraform/plugin/convert/diagnostics.go deleted file mode 100644 index 51cb2fe2..00000000 --- a/vendor/github.com/hashicorp/terraform/plugin/convert/diagnostics.go +++ /dev/null @@ -1,132 +0,0 @@ -package convert - -import ( - proto "github.com/hashicorp/terraform/internal/tfplugin5" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// WarnsAndErrorsToProto converts the warnings and errors return by the legacy -// provider to protobuf diagnostics. -func WarnsAndErrsToProto(warns []string, errs []error) (diags []*proto.Diagnostic) { - for _, w := range warns { - diags = AppendProtoDiag(diags, w) - } - - for _, e := range errs { - diags = AppendProtoDiag(diags, e) - } - - return diags -} - -// AppendProtoDiag appends a new diagnostic from a warning string or an error. -// This panics if d is not a string or error. -func AppendProtoDiag(diags []*proto.Diagnostic, d interface{}) []*proto.Diagnostic { - switch d := d.(type) { - case cty.PathError: - ap := PathToAttributePath(d.Path) - diags = append(diags, &proto.Diagnostic{ - Severity: proto.Diagnostic_ERROR, - Summary: d.Error(), - Attribute: ap, - }) - case error: - diags = append(diags, &proto.Diagnostic{ - Severity: proto.Diagnostic_ERROR, - Summary: d.Error(), - }) - case string: - diags = append(diags, &proto.Diagnostic{ - Severity: proto.Diagnostic_WARNING, - Summary: d, - }) - case *proto.Diagnostic: - diags = append(diags, d) - case []*proto.Diagnostic: - diags = append(diags, d...) - } - return diags -} - -// ProtoToDiagnostics converts a list of proto.Diagnostics to a tf.Diagnostics. -func ProtoToDiagnostics(ds []*proto.Diagnostic) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - for _, d := range ds { - var severity tfdiags.Severity - - switch d.Severity { - case proto.Diagnostic_ERROR: - severity = tfdiags.Error - case proto.Diagnostic_WARNING: - severity = tfdiags.Warning - } - - var newDiag tfdiags.Diagnostic - - // if there's an attribute path, we need to create a AttributeValue diagnostic - if d.Attribute != nil { - path := AttributePathToPath(d.Attribute) - newDiag = tfdiags.AttributeValue(severity, d.Summary, d.Detail, path) - } else { - newDiag = tfdiags.WholeContainingBody(severity, d.Summary, d.Detail) - } - - diags = diags.Append(newDiag) - } - - return diags -} - -// AttributePathToPath takes the proto encoded path and converts it to a cty.Path -func AttributePathToPath(ap *proto.AttributePath) cty.Path { - var p cty.Path - for _, step := range ap.Steps { - switch selector := step.Selector.(type) { - case *proto.AttributePath_Step_AttributeName: - p = p.GetAttr(selector.AttributeName) - case *proto.AttributePath_Step_ElementKeyString: - p = p.Index(cty.StringVal(selector.ElementKeyString)) - case *proto.AttributePath_Step_ElementKeyInt: - p = p.Index(cty.NumberIntVal(selector.ElementKeyInt)) - } - } - return p -} - -// AttributePathToPath takes a cty.Path and converts it to a proto-encoded path. -func PathToAttributePath(p cty.Path) *proto.AttributePath { - ap := &proto.AttributePath{} - for _, step := range p { - switch selector := step.(type) { - case cty.GetAttrStep: - ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_AttributeName{ - AttributeName: selector.Name, - }, - }) - case cty.IndexStep: - key := selector.Key - switch key.Type() { - case cty.String: - ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_ElementKeyString{ - ElementKeyString: key.AsString(), - }, - }) - case cty.Number: - v, _ := key.AsBigFloat().Int64() - ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_ElementKeyInt{ - ElementKeyInt: v, - }, - }) - default: - // We'll bail early if we encounter anything else, and just - // return the valid prefix. - return ap - } - } - } - return ap -} diff --git a/vendor/github.com/hashicorp/terraform/plugin/convert/schema.go b/vendor/github.com/hashicorp/terraform/plugin/convert/schema.go deleted file mode 100644 index db879b54..00000000 --- a/vendor/github.com/hashicorp/terraform/plugin/convert/schema.go +++ /dev/null @@ -1,122 +0,0 @@ -package convert - -import ( - "encoding/json" - "reflect" - "sort" - - "github.com/hashicorp/terraform/configs/configschema" - proto "github.com/hashicorp/terraform/internal/tfplugin5" - "github.com/hashicorp/terraform/providers" -) - -// ConfigSchemaToProto takes a *configschema.Block and converts it to a -// proto.Schema_Block for a grpc response. -func ConfigSchemaToProto(b *configschema.Block) *proto.Schema_Block { - block := &proto.Schema_Block{} - - for _, name := range sortedKeys(b.Attributes) { - a := b.Attributes[name] - attr := &proto.Schema_Attribute{ - Name: name, - Description: a.Description, - Optional: a.Optional, - Computed: a.Computed, - Required: a.Required, - Sensitive: a.Sensitive, - } - - ty, err := json.Marshal(a.Type) - if err != nil { - panic(err) - } - - attr.Type = ty - - block.Attributes = append(block.Attributes, attr) - } - - for _, name := range sortedKeys(b.BlockTypes) { - b := b.BlockTypes[name] - block.BlockTypes = append(block.BlockTypes, protoSchemaNestedBlock(name, b)) - } - - return block -} - -func protoSchemaNestedBlock(name string, b *configschema.NestedBlock) *proto.Schema_NestedBlock { - return &proto.Schema_NestedBlock{ - TypeName: name, - Block: ConfigSchemaToProto(&b.Block), - Nesting: proto.Schema_NestedBlock_NestingMode(b.Nesting), - MinItems: int64(b.MinItems), - MaxItems: int64(b.MaxItems), - } -} - -// ProtoToProviderSchema takes a proto.Schema and converts it to a providers.Schema. -func ProtoToProviderSchema(s *proto.Schema) providers.Schema { - return providers.Schema{ - Version: s.Version, - Block: ProtoToConfigSchema(s.Block), - } -} - -// ProtoToConfigSchema takes the GetSchcema_Block from a grpc response and converts it -// to a terraform *configschema.Block. -func ProtoToConfigSchema(b *proto.Schema_Block) *configschema.Block { - block := &configschema.Block{ - Attributes: make(map[string]*configschema.Attribute), - BlockTypes: make(map[string]*configschema.NestedBlock), - } - - for _, a := range b.Attributes { - attr := &configschema.Attribute{ - Description: a.Description, - Required: a.Required, - Optional: a.Optional, - Computed: a.Computed, - Sensitive: a.Sensitive, - } - - if err := json.Unmarshal(a.Type, &attr.Type); err != nil { - panic(err) - } - - block.Attributes[a.Name] = attr - } - - for _, b := range b.BlockTypes { - block.BlockTypes[b.TypeName] = schemaNestedBlock(b) - } - - return block -} - -func schemaNestedBlock(b *proto.Schema_NestedBlock) *configschema.NestedBlock { - nb := &configschema.NestedBlock{ - Nesting: configschema.NestingMode(b.Nesting), - MinItems: int(b.MinItems), - MaxItems: int(b.MaxItems), - } - - nested := ProtoToConfigSchema(b.Block) - nb.Block = *nested - return nb -} - -// sortedKeys returns the lexically sorted keys from the given map. This is -// used to make schema conversions are deterministic. This panics if map keys -// are not a string. -func sortedKeys(m interface{}) []string { - v := reflect.ValueOf(m) - keys := make([]string, v.Len()) - - mapKeys := v.MapKeys() - for i, k := range mapKeys { - keys[i] = k.Interface().(string) - } - - sort.Strings(keys) - return keys -} diff --git a/vendor/github.com/hashicorp/terraform/plugin/discovery/error.go b/vendor/github.com/hashicorp/terraform/plugin/discovery/error.go index 6ca8b60a..df855a76 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/discovery/error.go +++ b/vendor/github.com/hashicorp/terraform/plugin/discovery/error.go @@ -22,19 +22,9 @@ const ErrorNoSuitableVersion = Error("no suitable version is available") // version of Terraform. const ErrorNoVersionCompatible = Error("no available version is compatible with this version of Terraform") -// ErrorVersionIncompatible indicates that all of the versions within the -// constraints are not compatible with the current version of Terrafrom, though -// there does exist a version outside of the constaints that is compatible. -const ErrorVersionIncompatible = Error("incompatible provider version") - // ErrorNoSuchProvider indicates that no provider exists with a name given const ErrorNoSuchProvider = Error("no provider exists with the given name") -// ErrorNoVersionCompatibleWithPlatform indicates that all of the available -// versions that otherwise met constraints are not compatible with the -// requested platform -const ErrorNoVersionCompatibleWithPlatform = Error("no available version is compatible for the requested platform") - func (err Error) Error() string { return string(err) } diff --git a/vendor/github.com/hashicorp/terraform/plugin/discovery/get.go b/vendor/github.com/hashicorp/terraform/plugin/discovery/get.go index e0700701..815640f1 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/discovery/get.go +++ b/vendor/github.com/hashicorp/terraform/plugin/discovery/get.go @@ -13,32 +13,28 @@ import ( "strconv" "strings" - "github.com/hashicorp/errwrap" + "golang.org/x/net/html" + getter "github.com/hashicorp/go-getter" multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/httpclient" - "github.com/hashicorp/terraform/registry" - "github.com/hashicorp/terraform/registry/regsrc" - "github.com/hashicorp/terraform/registry/response" - "github.com/hashicorp/terraform/svchost/disco" - tfversion "github.com/hashicorp/terraform/version" "github.com/mitchellh/cli" ) -// Releases are located by querying the terraform registry. +// Releases are located by parsing the html listing from releases.hashicorp.com. +// +// The URL for releases follows the pattern: +// https://releases.hashicorp.com/terraform-provider-name//terraform-provider-name___. +// +// The plugin protocol version will be saved with the release and returned in +// the header X-TERRAFORM_PROTOCOL_VERSION. const protocolVersionHeader = "x-terraform-protocol-version" -const gpgVerificationError = `GPG signature verification error: -Terraform was unable to verify the GPG signature of the downloaded provider -files using the keys downloaded from the Terraform Registry. This may mean that -the publisher of the provider removed the key it was signed with, or that the -distributed files were changed after this version was released.` +var releaseHost = "https://releases.hashicorp.com" var httpClient *http.Client -var errVersionNotFound = errors.New("version not found") - func init() { httpClient = httpclient.New() @@ -83,13 +79,6 @@ type ProviderInstaller struct { SkipVerify bool Ui cli.Ui // Ui for output - - // Services is a required *disco.Disco, which may have services and - // credentials pre-loaded. - Services *disco.Disco - - // registry client - registry *registry.Client } // Get is part of an implementation of type Installer, and attempts to download @@ -112,139 +101,95 @@ type ProviderInstaller struct { // be presented alongside context about what is being installed, and thus the // error messages do not redundantly include such information. func (i *ProviderInstaller) Get(provider string, req Constraints) (PluginMeta, error) { - // a little bit of initialization. - if i.OS == "" { - i.OS = runtime.GOOS - } - if i.Arch == "" { - i.Arch = runtime.GOARCH - } - if i.registry == nil { - i.registry = registry.NewClient(i.Services, nil) - } - - // get a full listing of versions for the requested provider - allVersions, err := i.listProviderVersions(provider) - + versions, err := i.listProviderVersions(provider) // TODO: return multiple errors - if err != nil { - if registry.IsServiceNotProvided(err) { - return PluginMeta{}, err - } - return PluginMeta{}, ErrorNoSuchProvider - } - if len(allVersions.Versions) == 0 { - return PluginMeta{}, ErrorNoSuitableVersion - } - providerSource := allVersions.ID - - // Filter the list of plugin versions to those which meet the version constraints - versions := allowedVersions(allVersions, req) - if len(versions) == 0 { - return PluginMeta{}, ErrorNoSuitableVersion - } - - // sort them newest to oldest. The newest version wins! - response.ProviderVersionCollection(versions).Sort() - - // if the chosen provider version does not support the requested platform, - // filter the list of acceptable versions to those that support that platform - if err := i.checkPlatformCompatibility(versions[0]); err != nil { - versions = i.platformCompatibleVersions(versions) - if len(versions) == 0 { - return PluginMeta{}, ErrorNoVersionCompatibleWithPlatform - } - } - - // we now have a winning platform-compatible version - versionMeta := versions[0] - v := VersionStr(versionMeta.Version).MustParse() - - // check protocol compatibility - if err := i.checkPluginProtocol(versionMeta); err != nil { - closestMatch, err := i.findClosestProtocolCompatibleVersion(allVersions.Versions) - if err != nil { - // No operation here if we can't find a version with compatible protocol - return PluginMeta{}, err - } - - // Prompt version suggestion to UI based on closest protocol match - var errMsg string - closestVersion := VersionStr(closestMatch.Version).MustParse() - if v.NewerThan(closestVersion) { - errMsg = providerProtocolTooNew - } else { - errMsg = providerProtocolTooOld - } - - constraintStr := req.String() - if constraintStr == "" { - constraintStr = "(any version)" - } - - return PluginMeta{}, errwrap.Wrap(ErrorVersionIncompatible, fmt.Errorf(fmt.Sprintf( - errMsg, provider, v.String(), tfversion.String(), - closestVersion.String(), closestVersion.MinorUpgradeConstraintStr(), constraintStr))) - } - - downloadURLs, err := i.listProviderDownloadURLs(providerSource, versionMeta.Version) - providerURL := downloadURLs.DownloadURL - - if !i.SkipVerify { - sha256, err := i.getProviderChecksum(downloadURLs) - if err != nil { - return PluginMeta{}, err - } - - // add the checksum parameter for go-getter to verify the download for us. - if sha256 != "" { - providerURL = providerURL + "?checksum=sha256:" + sha256 - } - } - - printedProviderName := fmt.Sprintf("%s (%s)", provider, providerSource) - i.Ui.Info(fmt.Sprintf("- Downloading plugin for provider %q (%s)...", printedProviderName, versionMeta.Version)) - log.Printf("[DEBUG] getting provider %q version %q", printedProviderName, versionMeta.Version) - err = i.install(provider, v, providerURL) if err != nil { return PluginMeta{}, err } - // Find what we just installed - // (This is weird, because go-getter doesn't directly return - // information about what was extracted, and we just extracted - // the archive directly into a shared dir here.) - log.Printf("[DEBUG] looking for the %s %s plugin we just installed", provider, versionMeta.Version) - metas := FindPlugins("provider", []string{i.Dir}) - log.Printf("[DEBUG] all plugins found %#v", metas) - metas, _ = metas.ValidateVersions() - metas = metas.WithName(provider).WithVersion(v) - log.Printf("[DEBUG] filtered plugins %#v", metas) - if metas.Count() == 0 { - // This should never happen. Suggests that the release archive - // contains an executable file whose name doesn't match the - // expected convention. - return PluginMeta{}, fmt.Errorf( - "failed to find installed plugin version %s; this is a bug in Terraform and should be reported", - versionMeta.Version, - ) + if len(versions) == 0 { + return PluginMeta{}, ErrorNoSuitableVersion } - if metas.Count() > 1 { - // This should also never happen, and suggests that a - // particular version was re-released with a different - // executable filename. We consider releases as immutable, so - // this is an error. - return PluginMeta{}, fmt.Errorf( - "multiple plugins installed for version %s; this is a bug in Terraform and should be reported", - versionMeta.Version, - ) + versions = allowedVersions(versions, req) + if len(versions) == 0 { + return PluginMeta{}, ErrorNoSuitableVersion } - // By now we know we have exactly one meta, and so "Newest" will - // return that one. - return metas.Newest(), nil + // sort them newest to oldest + Versions(versions).Sort() + // Ensure that our installation directory exists + err = os.MkdirAll(i.Dir, os.ModePerm) + if err != nil { + return PluginMeta{}, fmt.Errorf("failed to create plugin dir %s: %s", i.Dir, err) + } + + // take the first matching plugin we find + for _, v := range versions { + url := i.providerURL(provider, v.String()) + + if !i.SkipVerify { + sha256, err := i.getProviderChecksum(provider, v.String()) + if err != nil { + return PluginMeta{}, err + } + + // add the checksum parameter for go-getter to verify the download for us. + if sha256 != "" { + url = url + "?checksum=sha256:" + sha256 + } + } + + log.Printf("[DEBUG] fetching provider info for %s version %s", provider, v) + if checkPlugin(url, i.PluginProtocolVersion) { + i.Ui.Info(fmt.Sprintf("- Downloading plugin for provider %q (%s)...", provider, v.String())) + log.Printf("[DEBUG] getting provider %q version %q", provider, v) + err := i.install(provider, v, url) + if err != nil { + return PluginMeta{}, err + } + + // Find what we just installed + // (This is weird, because go-getter doesn't directly return + // information about what was extracted, and we just extracted + // the archive directly into a shared dir here.) + log.Printf("[DEBUG] looking for the %s %s plugin we just installed", provider, v) + metas := FindPlugins("provider", []string{i.Dir}) + log.Printf("[DEBUG] all plugins found %#v", metas) + metas, _ = metas.ValidateVersions() + metas = metas.WithName(provider).WithVersion(v) + log.Printf("[DEBUG] filtered plugins %#v", metas) + if metas.Count() == 0 { + // This should never happen. Suggests that the release archive + // contains an executable file whose name doesn't match the + // expected convention. + return PluginMeta{}, fmt.Errorf( + "failed to find installed plugin version %s; this is a bug in Terraform and should be reported", + v, + ) + } + + if metas.Count() > 1 { + // This should also never happen, and suggests that a + // particular version was re-released with a different + // executable filename. We consider releases as immutable, so + // this is an error. + return PluginMeta{}, fmt.Errorf( + "multiple plugins installed for version %s; this is a bug in Terraform and should be reported", + v, + ) + } + + // By now we know we have exactly one meta, and so "Newest" will + // return that one. + return metas.Newest(), nil + } + + log.Printf("[INFO] incompatible ProtocolVersion for %s version %s", provider, v) + } + + return PluginMeta{}, ErrorNoVersionCompatible } func (i *ProviderInstaller) install(provider string, version Version, url string) error { @@ -335,6 +280,7 @@ func (i *ProviderInstaller) install(provider string, version Version, url string return err } } + return nil } @@ -370,194 +316,184 @@ func (i *ProviderInstaller) PurgeUnused(used map[string]PluginMeta) (PluginMetaS return removed, errs } -func (i *ProviderInstaller) getProviderChecksum(urls *response.TerraformProviderPlatformLocation) (string, error) { - // Get SHA256SUMS file. - shasums, err := getFile(urls.ShasumsURL) - if err != nil { - return "", fmt.Errorf("error fetching checksums: %s", err) - } - - // Get SHA256SUMS.sig file. - signature, err := getFile(urls.ShasumsSignatureURL) - if err != nil { - return "", fmt.Errorf("error fetching checksums signature: %s", err) - } - - // Verify GPG signature. - asciiArmor := urls.SigningKeys.GPGASCIIArmor() - signer, err := verifySig(shasums, signature, asciiArmor) - if err != nil { - log.Printf("[ERROR] error verifying signature: %s", err) - return "", fmt.Errorf(gpgVerificationError) - } - - // Display identity for GPG key which succeeded verifying the signature. - // This could also be used to display to the user with i.Ui.Info(). - identities := []string{} - for k := range signer.Identities { - identities = append(identities, k) - } - identity := strings.Join(identities, ", ") - log.Printf("[DEBUG] verified GPG signature with key from %s", identity) - - // Extract checksum for this os/arch platform binary. - return checksumForFile(shasums, urls.Filename), nil +// Plugins are referred to by the short name, but all URLs and files will use +// the full name prefixed with terraform-- +func (i *ProviderInstaller) providerName(name string) string { + return "terraform-provider-" + name } -// list all versions available for the named provider -func (i *ProviderInstaller) listProviderVersions(name string) (*response.TerraformProviderVersions, error) { - provider := regsrc.NewTerraformProvider(name, i.OS, i.Arch) - versions, err := i.registry.TerraformProviderVersions(provider) - return versions, err +func (i *ProviderInstaller) providerFileName(name, version string) string { + os := i.OS + arch := i.Arch + if os == "" { + os = runtime.GOOS + } + if arch == "" { + arch = runtime.GOARCH + } + return fmt.Sprintf("%s_%s_%s_%s.zip", i.providerName(name), version, os, arch) } -func (i *ProviderInstaller) listProviderDownloadURLs(name, version string) (*response.TerraformProviderPlatformLocation, error) { - urls, err := i.registry.TerraformProviderLocation(regsrc.NewTerraformProvider(name, i.OS, i.Arch), version) - if urls == nil { - return nil, fmt.Errorf("No download urls found for provider %s", name) - } - return urls, err +// providerVersionsURL returns the path to the released versions directory for the provider: +// https://releases.hashicorp.com/terraform-provider-name/ +func (i *ProviderInstaller) providerVersionsURL(name string) string { + return releaseHost + "/" + i.providerName(name) + "/" } -// findClosestProtocolCompatibleVersion searches for the provider version with the closest protocol match. -// Prerelease versions are filtered. -func (i *ProviderInstaller) findClosestProtocolCompatibleVersion(versions []*response.TerraformProviderVersion) (*response.TerraformProviderVersion, error) { - // Loop through all the provider versions to find the earliest and latest - // versions that match the installer protocol to then select the closest of the two - var latest, earliest *response.TerraformProviderVersion - for _, version := range versions { - // Prereleases are filtered and will not be suggested - v, err := VersionStr(version.Version).Parse() - if err != nil || v.IsPrerelease() { - continue - } +// providerURL returns the full path to the provider file, using the current OS +// and ARCH: +// .../terraform-provider-name_/terraform-provider-name___. +func (i *ProviderInstaller) providerURL(name, version string) string { + return fmt.Sprintf("%s%s/%s", i.providerVersionsURL(name), version, i.providerFileName(name, version)) +} - if err := i.checkPluginProtocol(version); err == nil { - if earliest == nil { - // Found the first provider version with compatible protocol - earliest = version - } - // Update the latest protocol compatible version - latest = version - } - } - if earliest == nil { - // No compatible protocol was found for any version - return nil, ErrorNoVersionCompatible - } +func (i *ProviderInstaller) providerChecksumURL(name, version string) string { + fileName := fmt.Sprintf("%s_%s_SHA256SUMS", i.providerName(name), version) + u := fmt.Sprintf("%s%s/%s", i.providerVersionsURL(name), version, fileName) + return u +} - // Convert protocols to comparable types - protoString := strconv.Itoa(int(i.PluginProtocolVersion)) - protocolVersion, err := VersionStr(protoString).Parse() +func (i *ProviderInstaller) getProviderChecksum(name, version string) (string, error) { + checksums, err := getPluginSHA256SUMs(i.providerChecksumURL(name, version)) if err != nil { - return nil, fmt.Errorf("invalid plugin protocol version: %q", i.PluginProtocolVersion) + return "", err } - earliestVersionProtocol, err := VersionStr(earliest.Protocols[0]).Parse() + return checksumForFile(checksums, i.providerFileName(name, version)), nil +} + +// Return the plugin version by making a HEAD request to the provided url. +// If the header is not present, we assume the latest version will be +// compatible, and leave the check for discovery or execution. +func checkPlugin(url string, pluginProtocolVersion uint) bool { + resp, err := httpClient.Head(url) if err != nil { + log.Printf("[ERROR] error fetching plugin headers: %s", err) + return false + } + + if resp.StatusCode != http.StatusOK { + log.Println("[ERROR] non-200 status fetching plugin headers:", resp.Status) + return false + } + + proto := resp.Header.Get(protocolVersionHeader) + if proto == "" { + // The header isn't present, but we don't make this error fatal since + // the latest version will probably work. + log.Printf("[WARN] missing %s from: %s", protocolVersionHeader, url) + return true + } + + protoVersion, err := strconv.Atoi(proto) + if err != nil { + log.Printf("[ERROR] invalid ProtocolVersion: %s", proto) + return false + } + + return protoVersion == int(pluginProtocolVersion) +} + +// list the version available for the named plugin +func (i *ProviderInstaller) listProviderVersions(name string) ([]Version, error) { + versions, err := listPluginVersions(i.providerVersionsURL(name)) + if err != nil { + // listPluginVersions returns a verbose error message indicating + // what was being accessed and what failed return nil, err } - - // Compare installer protocol version with the first protocol listed of the earliest match - // [A, B] where A is assumed the earliest compatible major version of the protocol pair - if protocolVersion.NewerThan(earliestVersionProtocol) { - // Provider protocols are too old, the closest version is the earliest compatible version - return earliest, nil - } - - // Provider protocols are too new, the closest version is the latest compatible version - return latest, nil + return versions, nil } -func (i *ProviderInstaller) checkPluginProtocol(versionMeta *response.TerraformProviderVersion) error { - // TODO: should this be a different error? We should probably differentiate between - // no compatible versions and no protocol versions listed at all - if len(versionMeta.Protocols) == 0 { - return fmt.Errorf("no plugin protocol versions listed") - } - - protoString := strconv.Itoa(int(i.PluginProtocolVersion)) - protocolVersion, err := VersionStr(protoString).Parse() - if err != nil { - return fmt.Errorf("invalid plugin protocol version: %q", i.PluginProtocolVersion) - } - protocolConstraint, err := protocolVersion.MinorUpgradeConstraintStr().Parse() - if err != nil { - // This should not fail if the preceding function succeeded. - return fmt.Errorf("invalid plugin protocol version: %q", protocolVersion.String()) - } - - for _, p := range versionMeta.Protocols { - proPro, err := VersionStr(p).Parse() - if err != nil { - // invalid protocol reported by the registry. Move along. - log.Printf("[WARN] invalid provider protocol version %q found in the registry", versionMeta.Version) - continue - } - // success! - if protocolConstraint.Allows(proPro) { - return nil - } - } - - return ErrorNoVersionCompatible -} - -// REVIEWER QUESTION (again): this ends up swallowing a bunch of errors from -// checkPluginProtocol. Do they need to be percolated up better, or would -// debug messages would suffice in these situations? -func (i *ProviderInstaller) findPlatformCompatibleVersion(versions []*response.TerraformProviderVersion) (*response.TerraformProviderVersion, error) { - for _, version := range versions { - if err := i.checkPlatformCompatibility(version); err == nil { - return version, nil - } - } - - return nil, ErrorNoVersionCompatibleWithPlatform -} - -// platformCompatibleVersions returns a list of provider versions that are -// compatible with the requested platform. -func (i *ProviderInstaller) platformCompatibleVersions(versions []*response.TerraformProviderVersion) []*response.TerraformProviderVersion { - var v []*response.TerraformProviderVersion - for _, version := range versions { - if err := i.checkPlatformCompatibility(version); err == nil { - v = append(v, version) - } - } - return v -} - -func (i *ProviderInstaller) checkPlatformCompatibility(versionMeta *response.TerraformProviderVersion) error { - if len(versionMeta.Platforms) == 0 { - return fmt.Errorf("no supported provider platforms listed") - } - for _, p := range versionMeta.Platforms { - if p.Arch == i.Arch && p.OS == i.OS { - return nil - } - } - return fmt.Errorf("version %s does not support the requested platform %s_%s", versionMeta.Version, i.OS, i.Arch) -} +var errVersionNotFound = errors.New("version not found") // take the list of available versions for a plugin, and filter out those that // don't fit the constraints. -func allowedVersions(available *response.TerraformProviderVersions, required Constraints) []*response.TerraformProviderVersion { - var allowed []*response.TerraformProviderVersion +func allowedVersions(available []Version, required Constraints) []Version { + var allowed []Version - for _, v := range available.Versions { - version, err := VersionStr(v.Version).Parse() - if err != nil { - log.Printf("[WARN] invalid version found for %q: %s", available.ID, err) - continue - } - if required.Allows(version) { + for _, v := range available { + if required.Allows(v) { allowed = append(allowed, v) } } + return allowed } +// return a list of the plugin versions at the given URL +func listPluginVersions(url string) ([]Version, error) { + resp, err := httpClient.Get(url) + if err != nil { + // http library produces a verbose error message that includes the + // URL being accessed, etc. + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := ioutil.ReadAll(resp.Body) + log.Printf("[ERROR] failed to fetch plugin versions from %s\n%s\n%s", url, resp.Status, body) + + switch resp.StatusCode { + case http.StatusNotFound, http.StatusForbidden: + // These are treated as indicative of the given name not being + // a valid provider name at all. + return nil, ErrorNoSuchProvider + + default: + // All other errors are assumed to be operational problems. + return nil, fmt.Errorf("error accessing %s: %s", url, resp.Status) + } + + } + + body, err := html.Parse(resp.Body) + if err != nil { + log.Fatal(err) + } + + names := []string{} + + // all we need to do is list links on the directory listing page that look like plugins + var f func(*html.Node) + f = func(n *html.Node) { + if n.Type == html.ElementNode && n.Data == "a" { + c := n.FirstChild + if c != nil && c.Type == html.TextNode && strings.HasPrefix(c.Data, "terraform-") { + names = append(names, c.Data) + return + } + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + f(c) + } + } + f(body) + + return versionsFromNames(names), nil +} + +// parse the list of directory names into a sorted list of available versions +func versionsFromNames(names []string) []Version { + var versions []Version + for _, name := range names { + parts := strings.SplitN(name, "_", 2) + if len(parts) == 2 && parts[1] != "" { + v, err := VersionStr(parts[1]).Parse() + if err != nil { + // filter invalid versions scraped from the page + log.Printf("[WARN] invalid version found for %q: %s", name, err) + continue + } + + versions = append(versions, v) + } + } + + return versions +} + func checksumForFile(sums []byte, name string) string { for _, line := range strings.Split(string(sums), "\n") { parts := strings.Fields(line) @@ -568,6 +504,27 @@ func checksumForFile(sums []byte, name string) string { return "" } +// fetch the SHA256SUMS file provided, and verify its signature. +func getPluginSHA256SUMs(sumsURL string) ([]byte, error) { + sigURL := sumsURL + ".sig" + + sums, err := getFile(sumsURL) + if err != nil { + return nil, fmt.Errorf("error fetching checksums: %s", err) + } + + sig, err := getFile(sigURL) + if err != nil { + return nil, fmt.Errorf("error fetching checksums signature: %s", err) + } + + if err := verifySig(sums, sig); err != nil { + return nil, err + } + + return sums, nil +} + func getFile(url string) ([]byte, error) { resp, err := httpClient.Get(url) if err != nil { @@ -586,41 +543,6 @@ func getFile(url string) ([]byte, error) { return data, nil } -// providerProtocolTooOld is a message sent to the CLI UI if the provider's -// supported protocol versions are too old for the user's version of terraform, -// but an older version of the provider is compatible. -const providerProtocolTooOld = ` -[reset][bold][red]Provider %q v%s is not compatible with Terraform %s.[reset][red] - -Provider version %s is the earliest compatible version. Select it with -the following version constraint: - - version = %q - -Terraform checked all of the plugin versions matching the given constraint: - %s - -Consult the documentation for this provider for more information on -compatibility between provider and Terraform versions. -` - -// providerProtocolTooNew is a message sent to the CLI UI if the provider's -// supported protocol versions are too new for the user's version of terraform, -// and the user could either upgrade terraform or choose an older version of the -// provider -const providerProtocolTooNew = ` -[reset][bold][red]Provider %q v%s is not compatible with Terraform %s.[reset][red] - -Provider version %s is the latest compatible version. Select it with -the following constraint: - - version = %q - -Terraform checked all of the plugin versions matching the given constraint: - %s - -Consult the documentation for this provider for more information on -compatibility between provider and Terraform versions. - -Alternatively, upgrade to the latest version of Terraform for compatibility with newer provider releases. -` +func GetReleaseHost() string { + return releaseHost +} diff --git a/vendor/github.com/hashicorp/terraform/plugin/discovery/requirements.go b/vendor/github.com/hashicorp/terraform/plugin/discovery/requirements.go index 0466ab25..75430fdd 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/discovery/requirements.go +++ b/vendor/github.com/hashicorp/terraform/plugin/discovery/requirements.go @@ -4,12 +4,6 @@ import ( "bytes" ) -// PluginInstallProtocolVersion is the protocol version TF-core -// supports to communicate with servers, and is used to resolve -// plugin discovery with terraform registry, in addition to -// any specified plugin version constraints -const PluginInstallProtocolVersion = 5 - // PluginRequirements describes a set of plugins (assumed to be of a consistent // kind) that are required to exist and have versions within the given // corresponding sets. diff --git a/vendor/github.com/hashicorp/terraform/plugin/discovery/signature.go b/vendor/github.com/hashicorp/terraform/plugin/discovery/signature.go index 4e941aec..b6686a5d 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/discovery/signature.go +++ b/vendor/github.com/hashicorp/terraform/plugin/discovery/signature.go @@ -10,11 +10,44 @@ import ( // Verify the data using the provided openpgp detached signature and the // embedded hashicorp public key. -func verifySig(data, sig []byte, armor string) (*openpgp.Entity, error) { - el, err := openpgp.ReadArmoredKeyRing(strings.NewReader(armor)) +func verifySig(data, sig []byte) error { + el, err := openpgp.ReadArmoredKeyRing(strings.NewReader(hashiPublicKey)) if err != nil { log.Fatal(err) } - return openpgp.CheckDetachedSignature(el, bytes.NewReader(data), bytes.NewReader(sig)) + _, err = openpgp.CheckDetachedSignature(el, bytes.NewReader(data), bytes.NewReader(sig)) + return err } + +// this is the public key that signs the checksums file for releases. +const hashiPublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- +Version: GnuPG v1 + +mQENBFMORM0BCADBRyKO1MhCirazOSVwcfTr1xUxjPvfxD3hjUwHtjsOy/bT6p9f +W2mRPfwnq2JB5As+paL3UGDsSRDnK9KAxQb0NNF4+eVhr/EJ18s3wwXXDMjpIifq +fIm2WyH3G+aRLTLPIpscUNKDyxFOUbsmgXAmJ46Re1fn8uKxKRHbfa39aeuEYWFA +3drdL1WoUngvED7f+RnKBK2G6ZEpO+LDovQk19xGjiMTtPJrjMjZJ3QXqPvx5wca +KSZLr4lMTuoTI/ZXyZy5bD4tShiZz6KcyX27cD70q2iRcEZ0poLKHyEIDAi3TM5k +SwbbWBFd5RNPOR0qzrb/0p9ksKK48IIfH2FvABEBAAG0K0hhc2hpQ29ycCBTZWN1 +cml0eSA8c2VjdXJpdHlAaGFzaGljb3JwLmNvbT6JATgEEwECACIFAlMORM0CGwMG +CwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEFGFLYc0j/xMyWIIAIPhcVqiQ59n +Jc07gjUX0SWBJAxEG1lKxfzS4Xp+57h2xxTpdotGQ1fZwsihaIqow337YHQI3q0i +SqV534Ms+j/tU7X8sq11xFJIeEVG8PASRCwmryUwghFKPlHETQ8jJ+Y8+1asRydi +psP3B/5Mjhqv/uOK+Vy3zAyIpyDOMtIpOVfjSpCplVRdtSTFWBu9Em7j5I2HMn1w +sJZnJgXKpybpibGiiTtmnFLOwibmprSu04rsnP4ncdC2XRD4wIjoyA+4PKgX3sCO +klEzKryWYBmLkJOMDdo52LttP3279s7XrkLEE7ia0fXa2c12EQ0f0DQ1tGUvyVEW +WmJVccm5bq25AQ0EUw5EzQEIANaPUY04/g7AmYkOMjaCZ6iTp9hB5Rsj/4ee/ln9 +wArzRO9+3eejLWh53FoN1rO+su7tiXJA5YAzVy6tuolrqjM8DBztPxdLBbEi4V+j +2tK0dATdBQBHEh3OJApO2UBtcjaZBT31zrG9K55D+CrcgIVEHAKY8Cb4kLBkb5wM +skn+DrASKU0BNIV1qRsxfiUdQHZfSqtp004nrql1lbFMLFEuiY8FZrkkQ9qduixo +mTT6f34/oiY+Jam3zCK7RDN/OjuWheIPGj/Qbx9JuNiwgX6yRj7OE1tjUx6d8g9y +0H1fmLJbb3WZZbuuGFnK6qrE3bGeY8+AWaJAZ37wpWh1p0cAEQEAAYkBHwQYAQIA +CQUCUw5EzQIbDAAKCRBRhS2HNI/8TJntCAClU7TOO/X053eKF1jqNW4A1qpxctVc +z8eTcY8Om5O4f6a/rfxfNFKn9Qyja/OG1xWNobETy7MiMXYjaa8uUx5iFy6kMVaP +0BXJ59NLZjMARGw6lVTYDTIvzqqqwLxgliSDfSnqUhubGwvykANPO+93BBx89MRG +unNoYGXtPlhNFrAsB1VR8+EyKLv2HQtGCPSFBhrjuzH3gxGibNDDdFQLxxuJWepJ +EK1UbTS4ms0NgZ2Uknqn1WRU1Ki7rE4sTy68iZtWpKQXZEJa0IGnuI2sSINGcXCJ +oEIgXTMyCILo34Fa/C6VCm2WBgz9zZO8/rHIiQm1J5zqz0DrDwKBUM9C +=LYpS +-----END PGP PUBLIC KEY BLOCK-----` diff --git a/vendor/github.com/hashicorp/terraform/plugin/discovery/version.go b/vendor/github.com/hashicorp/terraform/plugin/discovery/version.go index 4311d510..8fad58d6 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/discovery/version.go +++ b/vendor/github.com/hashicorp/terraform/plugin/discovery/version.go @@ -55,11 +55,6 @@ func (v Version) Equal(other Version) bool { return v.raw.Equal(other.raw) } -// IsPrerelease determines if version is a prerelease -func (v Version) IsPrerelease() bool { - return v.raw.Prerelease() != "" -} - // MinorUpgradeConstraintStr returns a ConstraintStr that would permit // minor upgrades relative to the receiving version. func (v Version) MinorUpgradeConstraintStr() ConstraintStr { diff --git a/vendor/github.com/hashicorp/terraform/plugin/discovery/version_set.go b/vendor/github.com/hashicorp/terraform/plugin/discovery/version_set.go index de02f5ec..0aefd759 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/discovery/version_set.go +++ b/vendor/github.com/hashicorp/terraform/plugin/discovery/version_set.go @@ -36,11 +36,6 @@ type Constraints struct { raw version.Constraints } -// NewConstraints creates a Constraints based on a version.Constraints. -func NewConstraints(c version.Constraints) Constraints { - return Constraints{c} -} - // AllVersions is a Constraints containing all versions var AllVersions Constraints diff --git a/vendor/github.com/hashicorp/terraform/plugin/grpc_provider.go b/vendor/github.com/hashicorp/terraform/plugin/grpc_provider.go deleted file mode 100644 index 26e84e9e..00000000 --- a/vendor/github.com/hashicorp/terraform/plugin/grpc_provider.go +++ /dev/null @@ -1,558 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "io" - "log" - "sync" - - "github.com/zclconf/go-cty/cty" - - plugin "github.com/hashicorp/go-plugin" - proto "github.com/hashicorp/terraform/internal/tfplugin5" - "github.com/hashicorp/terraform/plugin/convert" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/version" - "github.com/zclconf/go-cty/cty/msgpack" - "google.golang.org/grpc" -) - -// GRPCProviderPlugin implements plugin.GRPCPlugin for the go-plugin package. -type GRPCProviderPlugin struct { - plugin.Plugin - GRPCProvider func() proto.ProviderServer -} - -func (p *GRPCProviderPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { - return &GRPCProvider{ - client: proto.NewProviderClient(c), - ctx: ctx, - }, nil -} - -func (p *GRPCProviderPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error { - proto.RegisterProviderServer(s, p.GRPCProvider()) - return nil -} - -// GRPCProvider handles the client, or core side of the plugin rpc connection. -// The GRPCProvider methods are mostly a translation layer between the -// terraform provioders types and the grpc proto types, directly converting -// between the two. -type GRPCProvider struct { - // PluginClient provides a reference to the plugin.Client which controls the plugin process. - // This allows the GRPCProvider a way to shutdown the plugin process. - PluginClient *plugin.Client - - // TestListener contains a net.Conn to close when the GRPCProvider is being - // used in an end to end test of a provider. - TestListener io.Closer - - // Proto client use to make the grpc service calls. - client proto.ProviderClient - - // this context is created by the plugin package, and is canceled when the - // plugin process ends. - ctx context.Context - - // schema stores the schema for this provider. This is used to properly - // serialize the state for requests. - mu sync.Mutex - schemas providers.GetSchemaResponse -} - -// getSchema is used internally to get the saved provider schema. The schema -// should have already been fetched from the provider, but we have to -// synchronize access to avoid being called concurrently with GetSchema. -func (p *GRPCProvider) getSchema() providers.GetSchemaResponse { - p.mu.Lock() - // unlock inline in case GetSchema needs to be called - if p.schemas.Provider.Block != nil { - p.mu.Unlock() - return p.schemas - } - p.mu.Unlock() - - // the schema should have been fetched already, but give it another shot - // just in case things are being called out of order. This may happen for - // tests. - schemas := p.GetSchema() - if schemas.Diagnostics.HasErrors() { - panic(schemas.Diagnostics.Err()) - } - - return schemas -} - -// getResourceSchema is a helper to extract the schema for a resource, and -// panics if the schema is not available. -func (p *GRPCProvider) getResourceSchema(name string) providers.Schema { - schema := p.getSchema() - resSchema, ok := schema.ResourceTypes[name] - if !ok { - panic("unknown resource type " + name) - } - return resSchema -} - -// gettDatasourceSchema is a helper to extract the schema for a datasource, and -// panics if that schema is not available. -func (p *GRPCProvider) getDatasourceSchema(name string) providers.Schema { - schema := p.getSchema() - dataSchema, ok := schema.DataSources[name] - if !ok { - panic("unknown data source " + name) - } - return dataSchema -} - -func (p *GRPCProvider) GetSchema() (resp providers.GetSchemaResponse) { - log.Printf("[TRACE] GRPCProvider: GetSchema") - p.mu.Lock() - defer p.mu.Unlock() - - if p.schemas.Provider.Block != nil { - return p.schemas - } - - resp.ResourceTypes = make(map[string]providers.Schema) - resp.DataSources = make(map[string]providers.Schema) - - protoResp, err := p.client.GetSchema(p.ctx, new(proto.GetProviderSchema_Request)) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - if protoResp.Provider == nil { - resp.Diagnostics = resp.Diagnostics.Append(errors.New("missing provider schema")) - return resp - } - - resp.Provider = convert.ProtoToProviderSchema(protoResp.Provider) - - for name, res := range protoResp.ResourceSchemas { - resp.ResourceTypes[name] = convert.ProtoToProviderSchema(res) - } - - for name, data := range protoResp.DataSourceSchemas { - resp.DataSources[name] = convert.ProtoToProviderSchema(data) - } - - p.schemas = resp - - return resp -} - -func (p *GRPCProvider) PrepareProviderConfig(r providers.PrepareProviderConfigRequest) (resp providers.PrepareProviderConfigResponse) { - log.Printf("[TRACE] GRPCProvider: PrepareProviderConfig") - - schema := p.getSchema() - ty := schema.Provider.Block.ImpliedType() - - mp, err := msgpack.Marshal(r.Config, ty) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.PrepareProviderConfig_Request{ - Config: &proto.DynamicValue{Msgpack: mp}, - } - - protoResp, err := p.client.PrepareProviderConfig(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - config := cty.NullVal(ty) - if protoResp.PreparedConfig != nil { - config, err = msgpack.Unmarshal(protoResp.PreparedConfig.Msgpack, ty) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.PreparedConfig = config - - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvider) ValidateResourceTypeConfig(r providers.ValidateResourceTypeConfigRequest) (resp providers.ValidateResourceTypeConfigResponse) { - log.Printf("[TRACE] GRPCProvider: ValidateResourceTypeConfig") - - resourceSchema := p.getResourceSchema(r.TypeName) - - mp, err := msgpack.Marshal(r.Config, resourceSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ValidateResourceTypeConfig_Request{ - TypeName: r.TypeName, - Config: &proto.DynamicValue{Msgpack: mp}, - } - - protoResp, err := p.client.ValidateResourceTypeConfig(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvider) ValidateDataSourceConfig(r providers.ValidateDataSourceConfigRequest) (resp providers.ValidateDataSourceConfigResponse) { - log.Printf("[TRACE] GRPCProvider: ValidateDataSourceConfig") - - dataSchema := p.getDatasourceSchema(r.TypeName) - - mp, err := msgpack.Marshal(r.Config, dataSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ValidateDataSourceConfig_Request{ - TypeName: r.TypeName, - Config: &proto.DynamicValue{Msgpack: mp}, - } - - protoResp, err := p.client.ValidateDataSourceConfig(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvider) UpgradeResourceState(r providers.UpgradeResourceStateRequest) (resp providers.UpgradeResourceStateResponse) { - log.Printf("[TRACE] GRPCProvider: UpgradeResourceState") - - resSchema := p.getResourceSchema(r.TypeName) - - protoReq := &proto.UpgradeResourceState_Request{ - TypeName: r.TypeName, - Version: int64(r.Version), - RawState: &proto.RawState{ - Json: r.RawStateJSON, - Flatmap: r.RawStateFlatmap, - }, - } - - protoResp, err := p.client.UpgradeResourceState(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - state := cty.NullVal(resSchema.Block.ImpliedType()) - if protoResp.UpgradedState != nil { - state, err = msgpack.Unmarshal(protoResp.UpgradedState.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - - resp.UpgradedState = state - return resp -} - -func (p *GRPCProvider) Configure(r providers.ConfigureRequest) (resp providers.ConfigureResponse) { - log.Printf("[TRACE] GRPCProvider: Configure") - - schema := p.getSchema() - - var mp []byte - - // we don't have anything to marshal if there's no config - mp, err := msgpack.Marshal(r.Config, schema.Provider.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.Configure_Request{ - TerraformVersion: version.Version, - Config: &proto.DynamicValue{ - Msgpack: mp, - }, - } - - protoResp, err := p.client.Configure(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvider) Stop() error { - log.Printf("[TRACE] GRPCProvider: Stop") - - resp, err := p.client.Stop(p.ctx, new(proto.Stop_Request)) - if err != nil { - return err - } - - if resp.Error != "" { - return errors.New(resp.Error) - } - return nil -} - -func (p *GRPCProvider) ReadResource(r providers.ReadResourceRequest) (resp providers.ReadResourceResponse) { - log.Printf("[TRACE] GRPCProvider: ReadResource") - - resSchema := p.getResourceSchema(r.TypeName) - - mp, err := msgpack.Marshal(r.PriorState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ReadResource_Request{ - TypeName: r.TypeName, - CurrentState: &proto.DynamicValue{Msgpack: mp}, - } - - protoResp, err := p.client.ReadResource(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - state := cty.NullVal(resSchema.Block.ImpliedType()) - if protoResp.NewState != nil { - state, err = msgpack.Unmarshal(protoResp.NewState.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.NewState = state - - return resp -} - -func (p *GRPCProvider) PlanResourceChange(r providers.PlanResourceChangeRequest) (resp providers.PlanResourceChangeResponse) { - log.Printf("[TRACE] GRPCProvider: PlanResourceChange") - - resSchema := p.getResourceSchema(r.TypeName) - - priorMP, err := msgpack.Marshal(r.PriorState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - configMP, err := msgpack.Marshal(r.Config, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - propMP, err := msgpack.Marshal(r.ProposedNewState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.PlanResourceChange_Request{ - TypeName: r.TypeName, - PriorState: &proto.DynamicValue{Msgpack: priorMP}, - Config: &proto.DynamicValue{Msgpack: configMP}, - ProposedNewState: &proto.DynamicValue{Msgpack: propMP}, - PriorPrivate: r.PriorPrivate, - } - - protoResp, err := p.client.PlanResourceChange(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - state := cty.NullVal(resSchema.Block.ImpliedType()) - if protoResp.PlannedState != nil { - state, err = msgpack.Unmarshal(protoResp.PlannedState.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.PlannedState = state - - for _, p := range protoResp.RequiresReplace { - resp.RequiresReplace = append(resp.RequiresReplace, convert.AttributePathToPath(p)) - } - - resp.PlannedPrivate = protoResp.PlannedPrivate - - resp.LegacyTypeSystem = protoResp.LegacyTypeSystem - - return resp -} - -func (p *GRPCProvider) ApplyResourceChange(r providers.ApplyResourceChangeRequest) (resp providers.ApplyResourceChangeResponse) { - log.Printf("[TRACE] GRPCProvider: ApplyResourceChange") - - resSchema := p.getResourceSchema(r.TypeName) - - priorMP, err := msgpack.Marshal(r.PriorState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - plannedMP, err := msgpack.Marshal(r.PlannedState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - configMP, err := msgpack.Marshal(r.Config, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ApplyResourceChange_Request{ - TypeName: r.TypeName, - PriorState: &proto.DynamicValue{Msgpack: priorMP}, - PlannedState: &proto.DynamicValue{Msgpack: plannedMP}, - Config: &proto.DynamicValue{Msgpack: configMP}, - PlannedPrivate: r.PlannedPrivate, - } - - protoResp, err := p.client.ApplyResourceChange(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - resp.Private = protoResp.Private - - state := cty.NullVal(resSchema.Block.ImpliedType()) - if protoResp.NewState != nil { - state, err = msgpack.Unmarshal(protoResp.NewState.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.NewState = state - - resp.LegacyTypeSystem = protoResp.LegacyTypeSystem - - return resp -} - -func (p *GRPCProvider) ImportResourceState(r providers.ImportResourceStateRequest) (resp providers.ImportResourceStateResponse) { - log.Printf("[TRACE] GRPCProvider: ImportResourceState") - - protoReq := &proto.ImportResourceState_Request{ - TypeName: r.TypeName, - Id: r.ID, - } - - protoResp, err := p.client.ImportResourceState(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - for _, imported := range protoResp.ImportedResources { - resource := providers.ImportedResource{ - TypeName: imported.TypeName, - Private: imported.Private, - } - - resSchema := p.getResourceSchema(resource.TypeName) - state := cty.NullVal(resSchema.Block.ImpliedType()) - if imported.State != nil { - state, err = msgpack.Unmarshal(imported.State.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resource.State = state - resp.ImportedResources = append(resp.ImportedResources, resource) - } - - return resp -} - -func (p *GRPCProvider) ReadDataSource(r providers.ReadDataSourceRequest) (resp providers.ReadDataSourceResponse) { - log.Printf("[TRACE] GRPCProvider: ReadDataSource") - - dataSchema := p.getDatasourceSchema(r.TypeName) - - config, err := msgpack.Marshal(r.Config, dataSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ReadDataSource_Request{ - TypeName: r.TypeName, - Config: &proto.DynamicValue{ - Msgpack: config, - }, - } - - protoResp, err := p.client.ReadDataSource(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - state := cty.NullVal(dataSchema.Block.ImpliedType()) - if protoResp.State != nil { - state, err = msgpack.Unmarshal(protoResp.State.Msgpack, dataSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.State = state - - return resp -} - -// closing the grpc connection is final, and terraform will call it at the end of every phase. -func (p *GRPCProvider) Close() error { - log.Printf("[TRACE] GRPCProvider: Close") - - // close the remote listener if we're running within a test - if p.TestListener != nil { - p.TestListener.Close() - } - - // Check this since it's not automatically inserted during plugin creation. - // It's currently only inserted by the command package, because that is - // where the factory is built and is the only point with access to the - // plugin.Client. - if p.PluginClient == nil { - log.Println("[DEBUG] provider has no plugin.Client") - return nil - } - - p.PluginClient.Kill() - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/plugin/grpc_provisioner.go b/vendor/github.com/hashicorp/terraform/plugin/grpc_provisioner.go deleted file mode 100644 index 136c88d6..00000000 --- a/vendor/github.com/hashicorp/terraform/plugin/grpc_provisioner.go +++ /dev/null @@ -1,178 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "io" - "log" - "sync" - - plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/terraform/configs/configschema" - proto "github.com/hashicorp/terraform/internal/tfplugin5" - "github.com/hashicorp/terraform/plugin/convert" - "github.com/hashicorp/terraform/provisioners" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/msgpack" - "google.golang.org/grpc" -) - -// GRPCProvisionerPlugin is the plugin.GRPCPlugin implementation. -type GRPCProvisionerPlugin struct { - plugin.Plugin - GRPCProvisioner func() proto.ProvisionerServer -} - -func (p *GRPCProvisionerPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { - return &GRPCProvisioner{ - client: proto.NewProvisionerClient(c), - ctx: ctx, - }, nil -} - -func (p *GRPCProvisionerPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error { - proto.RegisterProvisionerServer(s, p.GRPCProvisioner()) - return nil -} - -// provisioners.Interface grpc implementation -type GRPCProvisioner struct { - // PluginClient provides a reference to the plugin.Client which controls the plugin process. - // This allows the GRPCProvider a way to shutdown the plugin process. - PluginClient *plugin.Client - - client proto.ProvisionerClient - ctx context.Context - - // Cache the schema since we need it for serialization in each method call. - mu sync.Mutex - schema *configschema.Block -} - -func (p *GRPCProvisioner) GetSchema() (resp provisioners.GetSchemaResponse) { - p.mu.Lock() - defer p.mu.Unlock() - - if p.schema != nil { - return provisioners.GetSchemaResponse{ - Provisioner: p.schema, - } - } - - protoResp, err := p.client.GetSchema(p.ctx, new(proto.GetProvisionerSchema_Request)) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - if protoResp.Provisioner == nil { - resp.Diagnostics = resp.Diagnostics.Append(errors.New("missing provisioner schema")) - return resp - } - - resp.Provisioner = convert.ProtoToConfigSchema(protoResp.Provisioner.Block) - - p.schema = resp.Provisioner - - return resp -} - -func (p *GRPCProvisioner) ValidateProvisionerConfig(r provisioners.ValidateProvisionerConfigRequest) (resp provisioners.ValidateProvisionerConfigResponse) { - schema := p.GetSchema() - if schema.Diagnostics.HasErrors() { - resp.Diagnostics = resp.Diagnostics.Append(schema.Diagnostics) - return resp - } - - mp, err := msgpack.Marshal(r.Config, schema.Provisioner.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ValidateProvisionerConfig_Request{ - Config: &proto.DynamicValue{Msgpack: mp}, - } - protoResp, err := p.client.ValidateProvisionerConfig(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvisioner) ProvisionResource(r provisioners.ProvisionResourceRequest) (resp provisioners.ProvisionResourceResponse) { - schema := p.GetSchema() - if schema.Diagnostics.HasErrors() { - resp.Diagnostics = resp.Diagnostics.Append(schema.Diagnostics) - return resp - } - - mp, err := msgpack.Marshal(r.Config, schema.Provisioner.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - // connection is always assumed to be a simple string map - connMP, err := msgpack.Marshal(r.Connection, cty.Map(cty.String)) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ProvisionResource_Request{ - Config: &proto.DynamicValue{Msgpack: mp}, - Connection: &proto.DynamicValue{Msgpack: connMP}, - } - - outputClient, err := p.client.ProvisionResource(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - for { - rcv, err := outputClient.Recv() - if rcv != nil { - r.UIOutput.Output(rcv.Output) - } - if err != nil { - if err != io.EOF { - resp.Diagnostics = resp.Diagnostics.Append(err) - } - break - } - - if len(rcv.Diagnostics) > 0 { - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(rcv.Diagnostics)) - break - } - } - - return resp -} - -func (p *GRPCProvisioner) Stop() error { - protoResp, err := p.client.Stop(p.ctx, &proto.Stop_Request{}) - if err != nil { - return err - } - if protoResp.Error != "" { - return errors.New(protoResp.Error) - } - return nil -} - -func (p *GRPCProvisioner) Close() error { - // check this since it's not automatically inserted during plugin creation - if p.PluginClient == nil { - log.Println("[DEBUG] provider has no plugin.Client") - return nil - } - - p.PluginClient.Kill() - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/plugin/plugin.go b/vendor/github.com/hashicorp/terraform/plugin/plugin.go index e4fb5776..00fa7b29 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/plugin.go +++ b/vendor/github.com/hashicorp/terraform/plugin/plugin.go @@ -6,9 +6,8 @@ import ( // See serve.go for serving plugins -var VersionedPlugins = map[int]plugin.PluginSet{ - 5: { - "provider": &GRPCProviderPlugin{}, - "provisioner": &GRPCProvisionerPlugin{}, - }, +// PluginMap should be used by clients for the map of plugins. +var PluginMap = map[string]plugin.Plugin{ + "provider": &ResourceProviderPlugin{}, + "provisioner": &ResourceProvisionerPlugin{}, } diff --git a/vendor/github.com/hashicorp/terraform/plugin/resource_provider.go b/vendor/github.com/hashicorp/terraform/plugin/resource_provider.go index 459661a5..d6a433c4 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/resource_provider.go +++ b/vendor/github.com/hashicorp/terraform/plugin/resource_provider.go @@ -9,14 +9,11 @@ import ( // ResourceProviderPlugin is the plugin.Plugin implementation. type ResourceProviderPlugin struct { - ResourceProvider func() terraform.ResourceProvider + F func() terraform.ResourceProvider } func (p *ResourceProviderPlugin) Server(b *plugin.MuxBroker) (interface{}, error) { - return &ResourceProviderServer{ - Broker: b, - Provider: p.ResourceProvider(), - }, nil + return &ResourceProviderServer{Broker: b, Provider: p.F()}, nil } func (p *ResourceProviderPlugin) Client( diff --git a/vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go b/vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go index f0cc341f..8fce9d8a 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go @@ -4,20 +4,16 @@ import ( "net/rpc" "github.com/hashicorp/go-plugin" - "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/terraform" ) // ResourceProvisionerPlugin is the plugin.Plugin implementation. type ResourceProvisionerPlugin struct { - ResourceProvisioner func() terraform.ResourceProvisioner + F func() terraform.ResourceProvisioner } func (p *ResourceProvisionerPlugin) Server(b *plugin.MuxBroker) (interface{}, error) { - return &ResourceProvisionerServer{ - Broker: b, - Provisioner: p.ResourceProvisioner(), - }, nil + return &ResourceProvisionerServer{Broker: b, Provisioner: p.F()}, nil } func (p *ResourceProvisionerPlugin) Client( @@ -32,11 +28,6 @@ type ResourceProvisioner struct { Client *rpc.Client } -func (p *ResourceProvisioner) GetConfigSchema() (*configschema.Block, error) { - panic("not implemented") - return nil, nil -} - func (p *ResourceProvisioner) Validate(c *terraform.ResourceConfig) ([]string, []error) { var resp ResourceProvisionerValidateResponse args := ResourceProvisionerValidateArgs{ diff --git a/vendor/github.com/hashicorp/terraform/plugin/serve.go b/vendor/github.com/hashicorp/terraform/plugin/serve.go index 8d056c59..2028a613 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/serve.go +++ b/vendor/github.com/hashicorp/terraform/plugin/serve.go @@ -2,23 +2,14 @@ package plugin import ( "github.com/hashicorp/go-plugin" - grpcplugin "github.com/hashicorp/terraform/helper/plugin" - proto "github.com/hashicorp/terraform/internal/tfplugin5" "github.com/hashicorp/terraform/terraform" ) +// The constants below are the names of the plugins that can be dispensed +// from the plugin server. const ( - // The constants below are the names of the plugins that can be dispensed - // from the plugin server. ProviderPluginName = "provider" ProvisionerPluginName = "provisioner" - - // DefaultProtocolVersion is the protocol version assumed for legacy clients that don't specify - // a particular version during their handshake. This is the version used when Terraform 0.10 - // and 0.11 launch plugins that were built with support for both versions 4 and 5, and must - // stay unchanged at 4 until we intentionally build plugins that are not compatible with 0.10 and - // 0.11. - DefaultProtocolVersion = 4 ) // Handshake is the HandshakeConfig used to configure clients and servers. @@ -28,7 +19,7 @@ var Handshake = plugin.HandshakeConfig{ // one or the other that makes it so that they can't safely communicate. // This could be adding a new interface value, it could be how // helper/schema computes diffs, etc. - ProtocolVersion: DefaultProtocolVersion, + ProtocolVersion: 4, // The magic cookie values should NEVER be changed. MagicCookieKey: "TF_PLUGIN_MAGIC_COOKIE", @@ -37,85 +28,27 @@ var Handshake = plugin.HandshakeConfig{ type ProviderFunc func() terraform.ResourceProvider type ProvisionerFunc func() terraform.ResourceProvisioner -type GRPCProviderFunc func() proto.ProviderServer -type GRPCProvisionerFunc func() proto.ProvisionerServer // ServeOpts are the configurations to serve a plugin. type ServeOpts struct { ProviderFunc ProviderFunc ProvisionerFunc ProvisionerFunc - - // Wrapped versions of the above plugins will automatically shimmed and - // added to the GRPC functions when possible. - GRPCProviderFunc GRPCProviderFunc - GRPCProvisionerFunc GRPCProvisionerFunc } // Serve serves a plugin. This function never returns and should be the final // function called in the main function of the plugin. func Serve(opts *ServeOpts) { - // since the plugins may not yet be aware of the new protocol, we - // automatically wrap the plugins in the grpc shims. - if opts.GRPCProviderFunc == nil && opts.ProviderFunc != nil { - provider := grpcplugin.NewGRPCProviderServerShim(opts.ProviderFunc()) - // this is almost always going to be a *schema.Provider, but check that - // we got back a valid provider just in case. - if provider != nil { - opts.GRPCProviderFunc = func() proto.ProviderServer { - return provider - } - } - } - if opts.GRPCProvisionerFunc == nil && opts.ProvisionerFunc != nil { - provisioner := grpcplugin.NewGRPCProvisionerServerShim(opts.ProvisionerFunc()) - if provisioner != nil { - opts.GRPCProvisionerFunc = func() proto.ProvisionerServer { - return provisioner - } - } - } - plugin.Serve(&plugin.ServeConfig{ - HandshakeConfig: Handshake, - VersionedPlugins: pluginSet(opts), - GRPCServer: plugin.DefaultGRPCServer, + HandshakeConfig: Handshake, + Plugins: pluginMap(opts), }) } -// pluginMap returns the legacy map[string]plugin.Plugin to use for configuring -// a plugin server or client. -func legacyPluginMap(opts *ServeOpts) map[string]plugin.Plugin { +// pluginMap returns the map[string]plugin.Plugin to use for configuring a plugin +// server or client. +func pluginMap(opts *ServeOpts) map[string]plugin.Plugin { return map[string]plugin.Plugin{ - "provider": &ResourceProviderPlugin{ - ResourceProvider: opts.ProviderFunc, - }, - "provisioner": &ResourceProvisionerPlugin{ - ResourceProvisioner: opts.ProvisionerFunc, - }, + "provider": &ResourceProviderPlugin{F: opts.ProviderFunc}, + "provisioner": &ResourceProvisionerPlugin{F: opts.ProvisionerFunc}, } } - -func pluginSet(opts *ServeOpts) map[int]plugin.PluginSet { - // Set the legacy netrpc plugins at version 4. - // The oldest version is returned in when executed by a legacy go-plugin - // client. - plugins := map[int]plugin.PluginSet{ - 4: legacyPluginMap(opts), - } - - // add the new protocol versions if they're configured - if opts.GRPCProviderFunc != nil || opts.GRPCProvisionerFunc != nil { - plugins[5] = plugin.PluginSet{} - if opts.GRPCProviderFunc != nil { - plugins[5]["provider"] = &GRPCProviderPlugin{ - GRPCProvider: opts.GRPCProviderFunc, - } - } - if opts.GRPCProvisionerFunc != nil { - plugins[5]["provisioner"] = &GRPCProvisionerPlugin{ - GRPCProvisioner: opts.GRPCProvisionerFunc, - } - } - } - return plugins -} diff --git a/vendor/github.com/hashicorp/terraform/providers/addressed_types.go b/vendor/github.com/hashicorp/terraform/providers/addressed_types.go deleted file mode 100644 index 7ed523f1..00000000 --- a/vendor/github.com/hashicorp/terraform/providers/addressed_types.go +++ /dev/null @@ -1,47 +0,0 @@ -package providers - -import ( - "sort" - - "github.com/hashicorp/terraform/addrs" -) - -// AddressedTypes is a helper that extracts all of the distinct provider -// types from the given list of relative provider configuration addresses. -func AddressedTypes(providerAddrs []addrs.ProviderConfig) []string { - if len(providerAddrs) == 0 { - return nil - } - m := map[string]struct{}{} - for _, addr := range providerAddrs { - m[addr.Type] = struct{}{} - } - - names := make([]string, 0, len(m)) - for typeName := range m { - names = append(names, typeName) - } - - sort.Strings(names) // Stable result for tests - return names -} - -// AddressedTypesAbs is a helper that extracts all of the distinct provider -// types from the given list of absolute provider configuration addresses. -func AddressedTypesAbs(providerAddrs []addrs.AbsProviderConfig) []string { - if len(providerAddrs) == 0 { - return nil - } - m := map[string]struct{}{} - for _, addr := range providerAddrs { - m[addr.ProviderConfig.Type] = struct{}{} - } - - names := make([]string, 0, len(m)) - for typeName := range m { - names = append(names, typeName) - } - - sort.Strings(names) // Stable result for tests - return names -} diff --git a/vendor/github.com/hashicorp/terraform/providers/doc.go b/vendor/github.com/hashicorp/terraform/providers/doc.go deleted file mode 100644 index 39aa1de6..00000000 --- a/vendor/github.com/hashicorp/terraform/providers/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package providers contains the interface and primary types required to -// implement a Terraform resource provider. -package providers diff --git a/vendor/github.com/hashicorp/terraform/providers/provider.go b/vendor/github.com/hashicorp/terraform/providers/provider.go deleted file mode 100644 index 1aa08c27..00000000 --- a/vendor/github.com/hashicorp/terraform/providers/provider.go +++ /dev/null @@ -1,351 +0,0 @@ -package providers - -import ( - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" -) - -// Interface represents the set of methods required for a complete resource -// provider plugin. -type Interface interface { - // GetSchema returns the complete schema for the provider. - GetSchema() GetSchemaResponse - - // PrepareProviderConfig allows the provider to validate the configuration - // values, and set or override any values with defaults. - PrepareProviderConfig(PrepareProviderConfigRequest) PrepareProviderConfigResponse - - // ValidateResourceTypeConfig allows the provider to validate the resource - // configuration values. - ValidateResourceTypeConfig(ValidateResourceTypeConfigRequest) ValidateResourceTypeConfigResponse - - // ValidateDataSource allows the provider to validate the data source - // configuration values. - ValidateDataSourceConfig(ValidateDataSourceConfigRequest) ValidateDataSourceConfigResponse - - // UpgradeResourceState is called when the state loader encounters an - // instance state whose schema version is less than the one reported by the - // currently-used version of the corresponding provider, and the upgraded - // result is used for any further processing. - UpgradeResourceState(UpgradeResourceStateRequest) UpgradeResourceStateResponse - - // Configure configures and initialized the provider. - Configure(ConfigureRequest) ConfigureResponse - - // Stop is called when the provider should halt any in-flight actions. - // - // Stop should not block waiting for in-flight actions to complete. It - // should take any action it wants and return immediately acknowledging it - // has received the stop request. Terraform will not make any further API - // calls to the provider after Stop is called. - // - // The error returned, if non-nil, is assumed to mean that signaling the - // stop somehow failed and that the user should expect potentially waiting - // a longer period of time. - Stop() error - - // ReadResource refreshes a resource and returns its current state. - ReadResource(ReadResourceRequest) ReadResourceResponse - - // PlanResourceChange takes the current state and proposed state of a - // resource, and returns the planned final state. - PlanResourceChange(PlanResourceChangeRequest) PlanResourceChangeResponse - - // ApplyResourceChange takes the planned state for a resource, which may - // yet contain unknown computed values, and applies the changes returning - // the final state. - ApplyResourceChange(ApplyResourceChangeRequest) ApplyResourceChangeResponse - - // ImportResourceState requests that the given resource be imported. - ImportResourceState(ImportResourceStateRequest) ImportResourceStateResponse - - // ReadDataSource returns the data source's current state. - ReadDataSource(ReadDataSourceRequest) ReadDataSourceResponse - - // Close shuts down the plugin process if applicable. - Close() error -} - -type GetSchemaResponse struct { - // Provider is the schema for the provider itself. - Provider Schema - - // ResourceTypes map the resource type name to that type's schema. - ResourceTypes map[string]Schema - - // DataSources maps the data source name to that data source's schema. - DataSources map[string]Schema - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -// Schema pairs a provider or resource schema with that schema's version. -// This is used to be able to upgrade the schema in UpgradeResourceState. -type Schema struct { - Version int64 - Block *configschema.Block -} - -type PrepareProviderConfigRequest struct { - // Config is the raw configuration value for the provider. - Config cty.Value -} - -type PrepareProviderConfigResponse struct { - // PreparedConfig is the configuration as prepared by the provider. - PreparedConfig cty.Value - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ValidateResourceTypeConfigRequest struct { - // TypeName is the name of the resource type to validate. - TypeName string - - // Config is the configuration value to validate, which may contain unknown - // values. - Config cty.Value -} - -type ValidateResourceTypeConfigResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ValidateDataSourceConfigRequest struct { - // TypeName is the name of the data source type to validate. - TypeName string - - // Config is the configuration value to validate, which may contain unknown - // values. - Config cty.Value -} - -type ValidateDataSourceConfigResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type UpgradeResourceStateRequest struct { - // TypeName is the name of the resource type being upgraded - TypeName string - - // Version is version of the schema that created the current state. - Version int64 - - // RawStateJSON and RawStateFlatmap contiain the state that needs to be - // upgraded to match the current schema version. Because the schema is - // unknown, this contains only the raw data as stored in the state. - // RawStateJSON is the current json state encoding. - // RawStateFlatmap is the legacy flatmap encoding. - // Only on of these fields may be set for the upgrade request. - RawStateJSON []byte - RawStateFlatmap map[string]string -} - -type UpgradeResourceStateResponse struct { - // UpgradedState is the newly upgraded resource state. - UpgradedState cty.Value - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ConfigureRequest struct { - // Terraform version is the version string from the running instance of - // terraform. Providers can use TerraformVersion to verify compatibility, - // and to store for informational purposes. - TerraformVersion string - - // Config is the complete configuration value for the provider. - Config cty.Value -} - -type ConfigureResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ReadResourceRequest struct { - // TypeName is the name of the resource type being read. - TypeName string - - // PriorState contains the previously saved state value for this resource. - PriorState cty.Value -} - -type ReadResourceResponse struct { - // NewState contains the current state of the resource. - NewState cty.Value - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type PlanResourceChangeRequest struct { - // TypeName is the name of the resource type to plan. - TypeName string - - // PriorState is the previously saved state value for this resource. - PriorState cty.Value - - // ProposedNewState is the expected state after the new configuration is - // applied. This is created by directly applying the configuration to the - // PriorState. The provider is then responsible for applying any further - // changes required to create the proposed final state. - ProposedNewState cty.Value - - // Config is the resource configuration, before being merged with the - // PriorState. Any value not explicitly set in the configuration will be - // null. Config is supplied for reference, but Provider implementations - // should prefer the ProposedNewState in most circumstances. - Config cty.Value - - // PriorPrivate is the previously saved private data returned from the - // provider during the last apply. - PriorPrivate []byte -} - -type PlanResourceChangeResponse struct { - // PlannedState is the expected state of the resource once the current - // configuration is applied. - PlannedState cty.Value - - // RequiresReplace is the list of thee attributes that are requiring - // resource replacement. - RequiresReplace []cty.Path - - // PlannedPrivate is an opaque blob that is not interpreted by terraform - // core. This will be saved and relayed back to the provider during - // ApplyResourceChange. - PlannedPrivate []byte - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics - - // LegacyTypeSystem is set only if the provider is using the legacy SDK - // whose type system cannot be precisely mapped into the Terraform type - // system. We use this to bypass certain consistency checks that would - // otherwise fail due to this imprecise mapping. No other provider or SDK - // implementation is permitted to set this. - LegacyTypeSystem bool -} - -type ApplyResourceChangeRequest struct { - // TypeName is the name of the resource type being applied. - TypeName string - - // PriorState is the current state of resource. - PriorState cty.Value - - // Planned state is the state returned from PlanResourceChange, and should - // represent the new state, minus any remaining computed attributes. - PlannedState cty.Value - - // Config is the resource configuration, before being merged with the - // PriorState. Any value not explicitly set in the configuration will be - // null. Config is supplied for reference, but Provider implementations - // should prefer the PlannedState in most circumstances. - Config cty.Value - - // PlannedPrivate is the same value as returned by PlanResourceChange. - PlannedPrivate []byte -} - -type ApplyResourceChangeResponse struct { - // NewState is the new complete state after applying the planned change. - // In the event of an error, NewState should represent the most recent - // known state of the resource, if it exists. - NewState cty.Value - - // Private is an opaque blob that will be stored in state along with the - // resource. It is intended only for interpretation by the provider itself. - Private []byte - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics - - // LegacyTypeSystem is set only if the provider is using the legacy SDK - // whose type system cannot be precisely mapped into the Terraform type - // system. We use this to bypass certain consistency checks that would - // otherwise fail due to this imprecise mapping. No other provider or SDK - // implementation is permitted to set this. - LegacyTypeSystem bool -} - -type ImportResourceStateRequest struct { - // TypeName is the name of the resource type to be imported. - TypeName string - - // ID is a string with which the provider can identify the resource to be - // imported. - ID string -} - -type ImportResourceStateResponse struct { - // ImportedResources contains one or more state values related to the - // imported resource. It is not required that these be complete, only that - // there is enough identifying information for the provider to successfully - // update the states in ReadResource. - ImportedResources []ImportedResource - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -// ImportedResource represents an object being imported into Terraform with the -// help of a provider. An ImportedObject is a RemoteObject that has been read -// by the provider's import handler but hasn't yet been committed to state. -type ImportedResource struct { - // TypeName is the name of the resource type associated with the - // returned state. It's possible for providers to import multiple related - // types with a single import request. - TypeName string - - // State is the state of the remote object being imported. This may not be - // complete, but must contain enough information to uniquely identify the - // resource. - State cty.Value - - // Private is an opaque blob that will be stored in state along with the - // resource. It is intended only for interpretation by the provider itself. - Private []byte -} - -// AsInstanceObject converts the receiving ImportedObject into a -// ResourceInstanceObject that has status ObjectReady. -// -// The returned object does not know its own resource type, so the caller must -// retain the ResourceType value from the source object if this information is -// needed. -// -// The returned object also has no dependency addresses, but the caller may -// freely modify the direct fields of the returned object without affecting -// the receiver. -func (ir ImportedResource) AsInstanceObject() *states.ResourceInstanceObject { - return &states.ResourceInstanceObject{ - Status: states.ObjectReady, - Value: ir.State, - Private: ir.Private, - } -} - -type ReadDataSourceRequest struct { - // TypeName is the name of the data source type to Read. - TypeName string - - // Config is the complete configuration for the requested data source. - Config cty.Value -} - -type ReadDataSourceResponse struct { - // State is the current state of the requested data source. - State cty.Value - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} diff --git a/vendor/github.com/hashicorp/terraform/providers/resolver.go b/vendor/github.com/hashicorp/terraform/providers/resolver.go deleted file mode 100644 index 4de8e0ac..00000000 --- a/vendor/github.com/hashicorp/terraform/providers/resolver.go +++ /dev/null @@ -1,112 +0,0 @@ -package providers - -import ( - "fmt" - - "github.com/hashicorp/terraform/plugin/discovery" -) - -// Resolver is an interface implemented by objects that are able to resolve -// a given set of resource provider version constraints into Factory -// callbacks. -type Resolver interface { - // Given a constraint map, return a Factory for each requested provider. - // If some or all of the constraints cannot be satisfied, return a non-nil - // slice of errors describing the problems. - ResolveProviders(reqd discovery.PluginRequirements) (map[string]Factory, []error) -} - -// ResolverFunc wraps a callback function and turns it into a Resolver -// implementation, for convenience in situations where a function and its -// associated closure are sufficient as a resolver implementation. -type ResolverFunc func(reqd discovery.PluginRequirements) (map[string]Factory, []error) - -// ResolveProviders implements Resolver by calling the -// wrapped function. -func (f ResolverFunc) ResolveProviders(reqd discovery.PluginRequirements) (map[string]Factory, []error) { - return f(reqd) -} - -// ResolverFixed returns a Resolver that has a fixed set of provider factories -// provided by the caller. The returned resolver ignores version constraints -// entirely and just returns the given factory for each requested provider -// name. -// -// This function is primarily used in tests, to provide mock providers or -// in-process providers under test. -func ResolverFixed(factories map[string]Factory) Resolver { - return ResolverFunc(func(reqd discovery.PluginRequirements) (map[string]Factory, []error) { - ret := make(map[string]Factory, len(reqd)) - var errs []error - for name := range reqd { - if factory, exists := factories[name]; exists { - ret[name] = factory - } else { - errs = append(errs, fmt.Errorf("provider %q is not available", name)) - } - } - return ret, errs - }) -} - -// Factory is a function type that creates a new instance of a resource -// provider, or returns an error if that is impossible. -type Factory func() (Interface, error) - -// FactoryFixed is a helper that creates a Factory that just returns some given -// single provider. -// -// Unlike usual factories, the exact same instance is returned for each call -// to the factory and so this must be used in only specialized situations where -// the caller can take care to either not mutate the given provider at all -// or to mutate it in ways that will not cause unexpected behavior for others -// holding the same reference. -func FactoryFixed(p Interface) Factory { - return func() (Interface, error) { - return p, nil - } -} - -// ProviderHasResource is a helper that requests schema from the given provider -// and checks if it has a resource type of the given name. -// -// This function is more expensive than it may first appear since it must -// retrieve the entire schema from the underlying provider, and so it should -// be used sparingly and especially not in tight loops. -// -// Since retrieving the provider may fail (e.g. if the provider is accessed -// over an RPC channel that has operational problems), this function will -// return false if the schema cannot be retrieved, under the assumption that -// a subsequent call to do anything with the resource type would fail -// anyway. -func ProviderHasResource(provider Interface, typeName string) bool { - resp := provider.GetSchema() - if resp.Diagnostics.HasErrors() { - return false - } - - _, exists := resp.ResourceTypes[typeName] - return exists -} - -// ProviderHasDataSource is a helper that requests schema from the given -// provider and checks if it has a data source of the given name. -// -// This function is more expensive than it may first appear since it must -// retrieve the entire schema from the underlying provider, and so it should -// be used sparingly and especially not in tight loops. -// -// Since retrieving the provider may fail (e.g. if the provider is accessed -// over an RPC channel that has operational problems), this function will -// return false if the schema cannot be retrieved, under the assumption that -// a subsequent call to do anything with the data source would fail -// anyway. -func ProviderHasDataSource(provider Interface, dataSourceName string) bool { - resp := provider.GetSchema() - if resp.Diagnostics.HasErrors() { - return false - } - - _, exists := resp.DataSources[dataSourceName] - return exists -} diff --git a/vendor/github.com/hashicorp/terraform/provisioners/doc.go b/vendor/github.com/hashicorp/terraform/provisioners/doc.go deleted file mode 100644 index b03ba9a1..00000000 --- a/vendor/github.com/hashicorp/terraform/provisioners/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package provisioners contains the interface and primary types to implement a -// Terraform resource provisioner. -package provisioners diff --git a/vendor/github.com/hashicorp/terraform/provisioners/factory.go b/vendor/github.com/hashicorp/terraform/provisioners/factory.go deleted file mode 100644 index 590b97a8..00000000 --- a/vendor/github.com/hashicorp/terraform/provisioners/factory.go +++ /dev/null @@ -1,19 +0,0 @@ -package provisioners - -// Factory is a function type that creates a new instance of a resource -// provisioner, or returns an error if that is impossible. -type Factory func() (Interface, error) - -// FactoryFixed is a helper that creates a Factory that just returns some given -// single provisioner. -// -// Unlike usual factories, the exact same instance is returned for each call -// to the factory and so this must be used in only specialized situations where -// the caller can take care to either not mutate the given provider at all -// or to mutate it in ways that will not cause unexpected behavior for others -// holding the same reference. -func FactoryFixed(p Interface) Factory { - return func() (Interface, error) { - return p, nil - } -} diff --git a/vendor/github.com/hashicorp/terraform/provisioners/provisioner.go b/vendor/github.com/hashicorp/terraform/provisioners/provisioner.go deleted file mode 100644 index e53c8848..00000000 --- a/vendor/github.com/hashicorp/terraform/provisioners/provisioner.go +++ /dev/null @@ -1,82 +0,0 @@ -package provisioners - -import ( - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// Interface is the set of methods required for a resource provisioner plugin. -type Interface interface { - // GetSchema returns the schema for the provisioner configuration. - GetSchema() GetSchemaResponse - - // ValidateProvisionerConfig allows the provisioner to validate the - // configuration values. - ValidateProvisionerConfig(ValidateProvisionerConfigRequest) ValidateProvisionerConfigResponse - - // ProvisionResource runs the provisioner with provided configuration. - // ProvisionResource blocks until the execution is complete. - // If the returned diagnostics contain any errors, the resource will be - // left in a tainted state. - ProvisionResource(ProvisionResourceRequest) ProvisionResourceResponse - - // Stop is called to interrupt the provisioner. - // - // Stop should not block waiting for in-flight actions to complete. It - // should take any action it wants and return immediately acknowledging it - // has received the stop request. Terraform will not make any further API - // calls to the provisioner after Stop is called. - // - // The error returned, if non-nil, is assumed to mean that signaling the - // stop somehow failed and that the user should expect potentially waiting - // a longer period of time. - Stop() error - - // Close shuts down the plugin process if applicable. - Close() error -} - -type GetSchemaResponse struct { - // Provisioner contains the schema for this provisioner. - Provisioner *configschema.Block - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -// UIOutput provides the Output method for resource provisioner -// plugins to write any output to the UI. -// -// Provisioners may call the Output method multiple times while Apply is in -// progress. It is invalid to call Output after Apply returns. -type UIOutput interface { - Output(string) -} - -type ValidateProvisionerConfigRequest struct { - // Config is the complete configuration to be used for the provisioner. - Config cty.Value -} - -type ValidateProvisionerConfigResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ProvisionResourceRequest struct { - // Config is the complete provisioner configuration. - Config cty.Value - - // Connection contains any information required to access the resource - // instance. - Connection cty.Value - - // UIOutput is used to return output during the Apply operation. - UIOutput UIOutput -} - -type ProvisionResourceResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} diff --git a/vendor/github.com/hashicorp/terraform/registry/client.go b/vendor/github.com/hashicorp/terraform/registry/client.go index 0b90790d..8e31a6a3 100644 --- a/vendor/github.com/hashicorp/terraform/registry/client.go +++ b/vendor/github.com/hashicorp/terraform/registry/client.go @@ -20,11 +20,10 @@ import ( ) const ( - xTerraformGet = "X-Terraform-Get" - xTerraformVersion = "X-Terraform-Version" - requestTimeout = 10 * time.Second - modulesServiceID = "modules.v1" - providersServiceID = "providers.v1" + xTerraformGet = "X-Terraform-Get" + xTerraformVersion = "X-Terraform-Version" + requestTimeout = 10 * time.Second + serviceID = "modules.v1" ) var tfVersion = version.String() @@ -58,28 +57,28 @@ func NewClient(services *disco.Disco, client *http.Client) *Client { } } -// Discover queries the host, and returns the url for the registry. -func (c *Client) Discover(host svchost.Hostname, serviceID string) (*url.URL, error) { - service, err := c.services.DiscoverServiceURL(host, serviceID) - if err != nil { - return nil, err +// Discover qeuries the host, and returns the url for the registry. +func (c *Client) Discover(host svchost.Hostname) *url.URL { + service := c.services.DiscoverServiceURL(host, serviceID) + if service == nil { + return nil } if !strings.HasSuffix(service.Path, "/") { service.Path += "/" } - return service, nil + return service } -// ModuleVersions queries the registry for a module, and returns the available versions. -func (c *Client) ModuleVersions(module *regsrc.Module) (*response.ModuleVersions, error) { +// Versions queries the registry for a module, and returns the available versions. +func (c *Client) Versions(module *regsrc.Module) (*response.ModuleVersions, error) { host, err := module.SvcHost() if err != nil { return nil, err } - service, err := c.Discover(host, modulesServiceID) - if err != nil { - return nil, err + service := c.Discover(host) + if service == nil { + return nil, fmt.Errorf("host %s does not provide Terraform modules", host) } p, err := url.Parse(path.Join(module.Module(), "versions")) @@ -142,17 +141,17 @@ func (c *Client) addRequestCreds(host svchost.Hostname, req *http.Request) { } } -// ModuleLocation find the download location for a specific version module. +// Location find the download location for a specific version module. // This returns a string, because the final location may contain special go-getter syntax. -func (c *Client) ModuleLocation(module *regsrc.Module, version string) (string, error) { +func (c *Client) Location(module *regsrc.Module, version string) (string, error) { host, err := module.SvcHost() if err != nil { return "", err } - service, err := c.Discover(host, modulesServiceID) - if err != nil { - return "", err + service := c.Discover(host) + if service == nil { + return "", fmt.Errorf("host %s does not provide Terraform modules", host.ForDisplay()) } var p *url.URL @@ -226,118 +225,3 @@ func (c *Client) ModuleLocation(module *regsrc.Module, version string) (string, return location, nil } - -// TerraformProviderVersions queries the registry for a provider, and returns the available versions. -func (c *Client) TerraformProviderVersions(provider *regsrc.TerraformProvider) (*response.TerraformProviderVersions, error) { - host, err := provider.SvcHost() - if err != nil { - return nil, err - } - - service, err := c.Discover(host, providersServiceID) - if err != nil { - return nil, err - } - - p, err := url.Parse(path.Join(provider.TerraformProvider(), "versions")) - if err != nil { - return nil, err - } - - service = service.ResolveReference(p) - - log.Printf("[DEBUG] fetching provider versions from %q", service) - - req, err := http.NewRequest("GET", service.String(), nil) - if err != nil { - return nil, err - } - - c.addRequestCreds(host, req) - req.Header.Set(xTerraformVersion, tfVersion) - - resp, err := c.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - switch resp.StatusCode { - case http.StatusOK: - // OK - case http.StatusNotFound: - return nil, &errProviderNotFound{addr: provider} - default: - return nil, fmt.Errorf("error looking up provider versions: %s", resp.Status) - } - - var versions response.TerraformProviderVersions - - dec := json.NewDecoder(resp.Body) - if err := dec.Decode(&versions); err != nil { - return nil, err - } - - return &versions, nil -} - -// TerraformProviderLocation queries the registry for a provider download metadata -func (c *Client) TerraformProviderLocation(provider *regsrc.TerraformProvider, version string) (*response.TerraformProviderPlatformLocation, error) { - host, err := provider.SvcHost() - if err != nil { - return nil, err - } - - service, err := c.Discover(host, providersServiceID) - if err != nil { - return nil, err - } - - p, err := url.Parse(path.Join( - provider.TerraformProvider(), - version, - "download", - provider.OS, - provider.Arch, - )) - if err != nil { - return nil, err - } - - service = service.ResolveReference(p) - - log.Printf("[DEBUG] fetching provider location from %q", service) - - req, err := http.NewRequest("GET", service.String(), nil) - if err != nil { - return nil, err - } - - c.addRequestCreds(host, req) - req.Header.Set(xTerraformVersion, tfVersion) - - resp, err := c.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var loc response.TerraformProviderPlatformLocation - - dec := json.NewDecoder(resp.Body) - if err := dec.Decode(&loc); err != nil { - return nil, err - } - - switch resp.StatusCode { - case http.StatusOK, http.StatusNoContent: - // OK - case http.StatusNotFound: - return nil, fmt.Errorf("provider %q version %q not found", provider.TerraformProvider(), version) - default: - // anything else is an error: - return nil, fmt.Errorf("error getting download location for %q: %s", provider.TerraformProvider(), resp.Status) - } - - return &loc, nil -} diff --git a/vendor/github.com/hashicorp/terraform/registry/errors.go b/vendor/github.com/hashicorp/terraform/registry/errors.go index cdde4822..b8dcd31e 100644 --- a/vendor/github.com/hashicorp/terraform/registry/errors.go +++ b/vendor/github.com/hashicorp/terraform/registry/errors.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/hashicorp/terraform/registry/regsrc" - "github.com/hashicorp/terraform/svchost/disco" ) type errModuleNotFound struct { @@ -22,27 +21,3 @@ func IsModuleNotFound(err error) bool { _, ok := err.(*errModuleNotFound) return ok } - -type errProviderNotFound struct { - addr *regsrc.TerraformProvider -} - -func (e *errProviderNotFound) Error() string { - return fmt.Sprintf("provider %s not found", e.addr) -} - -// IsProviderNotFound returns true only if the given error is a "provider not found" -// error. This allows callers to recognize this particular error condition -// as distinct from operational errors such as poor network connectivity. -func IsProviderNotFound(err error) bool { - _, ok := err.(*errProviderNotFound) - return ok -} - -// IsServiceNotProvided returns true only if the given error is a "service not provided" -// error. This allows callers to recognize this particular error condition -// as distinct from operational errors such as poor network connectivity. -func IsServiceNotProvided(err error) bool { - _, ok := err.(*disco.ErrServiceNotProvided) - return ok -} diff --git a/vendor/github.com/hashicorp/terraform/registry/regsrc/terraform_provider.go b/vendor/github.com/hashicorp/terraform/registry/regsrc/terraform_provider.go deleted file mode 100644 index 58dedee5..00000000 --- a/vendor/github.com/hashicorp/terraform/registry/regsrc/terraform_provider.go +++ /dev/null @@ -1,60 +0,0 @@ -package regsrc - -import ( - "fmt" - "runtime" - "strings" - - "github.com/hashicorp/terraform/svchost" -) - -var ( - // DefaultProviderNamespace represents the namespace for canonical - // HashiCorp-controlled providers. - DefaultProviderNamespace = "-" -) - -// TerraformProvider describes a Terraform Registry Provider source. -type TerraformProvider struct { - RawHost *FriendlyHost - RawNamespace string - RawName string - OS string - Arch string -} - -// NewTerraformProvider constructs a new provider source. -func NewTerraformProvider(name, os, arch string) *TerraformProvider { - if os == "" { - os = runtime.GOOS - } - if arch == "" { - arch = runtime.GOARCH - } - - // separate namespace if included - namespace := DefaultProviderNamespace - if names := strings.SplitN(name, "/", 2); len(names) == 2 { - namespace, name = names[0], names[1] - } - p := &TerraformProvider{ - RawHost: PublicRegistryHost, - RawNamespace: namespace, - RawName: name, - OS: os, - Arch: arch, - } - - return p -} - -// Provider returns just the registry ID of the provider -func (p *TerraformProvider) TerraformProvider() string { - return fmt.Sprintf("%s/%s", p.RawNamespace, p.RawName) -} - -// SvcHost returns the svchost.Hostname for this provider. The -// default PublicRegistryHost is returned. -func (p *TerraformProvider) SvcHost() (svchost.Hostname, error) { - return svchost.ForComparison(PublicRegistryHost.Raw) -} diff --git a/vendor/github.com/hashicorp/terraform/registry/response/provider.go b/vendor/github.com/hashicorp/terraform/registry/response/provider.go deleted file mode 100644 index 5e8bae35..00000000 --- a/vendor/github.com/hashicorp/terraform/registry/response/provider.go +++ /dev/null @@ -1,36 +0,0 @@ -package response - -import ( - "time" -) - -// Provider is the response structure with the data for a single provider -// version. This is just the metadata. A full provider response will be -// ProviderDetail. -type Provider struct { - ID string `json:"id"` - - //--------------------------------------------------------------- - // Metadata about the overall provider. - - Owner string `json:"owner"` - Namespace string `json:"namespace"` - Name string `json:"name"` - Version string `json:"version"` - Description string `json:"description"` - Source string `json:"source"` - PublishedAt time.Time `json:"published_at"` - Downloads int `json:"downloads"` -} - -// ProviderDetail represents a Provider with full detail. -type ProviderDetail struct { - Provider - - //--------------------------------------------------------------- - // The fields below are only set when requesting this specific - // module. They are available to easily know all available versions - // without multiple API calls. - - Versions []string `json:"versions"` // All versions -} diff --git a/vendor/github.com/hashicorp/terraform/registry/response/provider_list.go b/vendor/github.com/hashicorp/terraform/registry/response/provider_list.go deleted file mode 100644 index 1dc7d237..00000000 --- a/vendor/github.com/hashicorp/terraform/registry/response/provider_list.go +++ /dev/null @@ -1,7 +0,0 @@ -package response - -// ProviderList is the response structure for a pageable list of providers. -type ProviderList struct { - Meta PaginationMeta `json:"meta"` - Providers []*Provider `json:"providers"` -} diff --git a/vendor/github.com/hashicorp/terraform/registry/response/terraform_provider.go b/vendor/github.com/hashicorp/terraform/registry/response/terraform_provider.go deleted file mode 100644 index 08d382a4..00000000 --- a/vendor/github.com/hashicorp/terraform/registry/response/terraform_provider.go +++ /dev/null @@ -1,95 +0,0 @@ -package response - -import ( - "sort" - "strings" - - version "github.com/hashicorp/go-version" -) - -// TerraformProvider is the response structure for all required information for -// Terraform to choose a download URL. It must include all versions and all -// platforms for Terraform to perform version and os/arch constraint matching -// locally. -type TerraformProvider struct { - ID string `json:"id"` - Verified bool `json:"verified"` - - Versions []*TerraformProviderVersion `json:"versions"` -} - -// TerraformProviderVersion is the Terraform-specific response structure for a -// provider version. -type TerraformProviderVersion struct { - Version string `json:"version"` - Protocols []string `json:"protocols"` - - Platforms []*TerraformProviderPlatform `json:"platforms"` -} - -// TerraformProviderVersions is the Terraform-specific response structure for an -// array of provider versions -type TerraformProviderVersions struct { - ID string `json:"id"` - Versions []*TerraformProviderVersion `json:"versions"` -} - -// TerraformProviderPlatform is the Terraform-specific response structure for a -// provider platform. -type TerraformProviderPlatform struct { - OS string `json:"os"` - Arch string `json:"arch"` -} - -// TerraformProviderPlatformLocation is the Terraform-specific response -// structure for a provider platform with all details required to perform a -// download. -type TerraformProviderPlatformLocation struct { - Protocols []string `json:"protocols"` - OS string `json:"os"` - Arch string `json:"arch"` - Filename string `json:"filename"` - DownloadURL string `json:"download_url"` - ShasumsURL string `json:"shasums_url"` - ShasumsSignatureURL string `json:"shasums_signature_url"` - Shasum string `json:"shasum"` - - SigningKeys SigningKeyList `json:"signing_keys"` -} - -// SigningKeyList is the response structure for a list of signing keys. -type SigningKeyList struct { - GPGKeys []*GPGKey `json:"gpg_public_keys"` -} - -// GPGKey is the response structure for a GPG key. -type GPGKey struct { - ASCIIArmor string `json:"ascii_armor"` - Source string `json:"source"` - SourceURL *string `json:"source_url"` -} - -// Collection type for TerraformProviderVersion -type ProviderVersionCollection []*TerraformProviderVersion - -// GPGASCIIArmor returns an ASCII-armor-formatted string for all of the gpg -// keys in the response. -func (signingKeys *SigningKeyList) GPGASCIIArmor() string { - keys := []string{} - - for _, gpgKey := range signingKeys.GPGKeys { - keys = append(keys, gpgKey.ASCIIArmor) - } - - return strings.Join(keys, "\n") -} - -// Sort sorts versions from newest to oldest. -func (v ProviderVersionCollection) Sort() { - sort.Slice(v, func(i, j int) bool { - versionA, _ := version.NewVersion(v[i].Version) - versionB, _ := version.NewVersion(v[j].Version) - - return versionA.GreaterThan(versionB) - }) -} diff --git a/vendor/github.com/hashicorp/terraform/states/doc.go b/vendor/github.com/hashicorp/terraform/states/doc.go deleted file mode 100644 index 7dd74ac7..00000000 --- a/vendor/github.com/hashicorp/terraform/states/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package states contains the types that are used to represent Terraform -// states. -package states diff --git a/vendor/github.com/hashicorp/terraform/states/eachmode_string.go b/vendor/github.com/hashicorp/terraform/states/eachmode_string.go deleted file mode 100644 index 6de61802..00000000 --- a/vendor/github.com/hashicorp/terraform/states/eachmode_string.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by "stringer -type EachMode"; DO NOT EDIT. - -package states - -import "strconv" - -const ( - _EachMode_name_0 = "NoEach" - _EachMode_name_1 = "EachListEachMap" -) - -var ( - _EachMode_index_1 = [...]uint8{0, 8, 15} -) - -func (i EachMode) String() string { - switch { - case i == 0: - return _EachMode_name_0 - case 76 <= i && i <= 77: - i -= 76 - return _EachMode_name_1[_EachMode_index_1[i]:_EachMode_index_1[i+1]] - default: - return "EachMode(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform/states/instance_generation.go b/vendor/github.com/hashicorp/terraform/states/instance_generation.go deleted file mode 100644 index 617ad4ea..00000000 --- a/vendor/github.com/hashicorp/terraform/states/instance_generation.go +++ /dev/null @@ -1,24 +0,0 @@ -package states - -// Generation is used to represent multiple objects in a succession of objects -// represented by a single resource instance address. A resource instance can -// have multiple generations over its lifetime due to object replacement -// (when a change can't be applied without destroying and re-creating), and -// multiple generations can exist at the same time when create_before_destroy -// is used. -// -// A Generation value can either be the value of the variable "CurrentGen" or -// a value of type DeposedKey. Generation values can be compared for equality -// using "==" and used as map keys. The zero value of Generation (nil) is not -// a valid generation and must not be used. -type Generation interface { - generation() -} - -// CurrentGen is the Generation representing the currently-active object for -// a resource instance. -var CurrentGen Generation - -type currentGen struct{} - -func (g currentGen) generation() {} diff --git a/vendor/github.com/hashicorp/terraform/states/instance_object.go b/vendor/github.com/hashicorp/terraform/states/instance_object.go deleted file mode 100644 index b45bfa6a..00000000 --- a/vendor/github.com/hashicorp/terraform/states/instance_object.go +++ /dev/null @@ -1,120 +0,0 @@ -package states - -import ( - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform/addrs" -) - -// ResourceInstanceObject is the local representation of a specific remote -// object associated with a resource instance. In practice not all remote -// objects are actually remote in the sense of being accessed over the network, -// but this is the most common case. -// -// It is not valid to mutate a ResourceInstanceObject once it has been created. -// Instead, create a new object and replace the existing one. -type ResourceInstanceObject struct { - // Value is the object-typed value representing the remote object within - // Terraform. - Value cty.Value - - // Internal is an opaque value set by the provider when this object was - // last created or updated. Terraform Core does not use this value in - // any way and it is not exposed anywhere in the user interface, so - // a provider can use it for retaining any necessary private state. - Private []byte - - // Status represents the "readiness" of the object as of the last time - // it was updated. - Status ObjectStatus - - // Dependencies is a set of other addresses in the same module which - // this instance depended on when the given attributes were evaluated. - // This is used to construct the dependency relationships for an object - // whose configuration is no longer available, such as if it has been - // removed from configuration altogether, or is now deposed. - Dependencies []addrs.Referenceable -} - -// ObjectStatus represents the status of a RemoteObject. -type ObjectStatus rune - -//go:generate stringer -type ObjectStatus - -const ( - // ObjectReady is an object status for an object that is ready to use. - ObjectReady ObjectStatus = 'R' - - // ObjectTainted is an object status representing an object that is in - // an unrecoverable bad state due to a partial failure during a create, - // update, or delete operation. Since it cannot be moved into the - // ObjectRead state, a tainted object must be replaced. - ObjectTainted ObjectStatus = 'T' - - // ObjectPlanned is a special object status used only for the transient - // placeholder objects we place into state during the refresh and plan - // walks to stand in for objects that will be created during apply. - // - // Any object of this status must have a corresponding change recorded - // in the current plan, whose value must then be used in preference to - // the value stored in state when evaluating expressions. A planned - // object stored in state will be incomplete if any of its attributes are - // not yet known, and the plan must be consulted in order to "see" those - // unknown values, because the state is not able to represent them. - ObjectPlanned ObjectStatus = 'P' -) - -// Encode marshals the value within the receiver to produce a -// ResourceInstanceObjectSrc ready to be written to a state file. -// -// The given type must be the implied type of the resource type schema, and -// the given value must conform to it. It is important to pass the schema -// type and not the object's own type so that dynamically-typed attributes -// will be stored correctly. The caller must also provide the version number -// of the schema that the given type was derived from, which will be recorded -// in the source object so it can be used to detect when schema migration is -// required on read. -// -// The returned object may share internal references with the receiver and -// so the caller must not mutate the receiver any further once once this -// method is called. -func (o *ResourceInstanceObject) Encode(ty cty.Type, schemaVersion uint64) (*ResourceInstanceObjectSrc, error) { - // Our state serialization can't represent unknown values, so we convert - // them to nulls here. This is lossy, but nobody should be writing unknown - // values here and expecting to get them out again later. - // - // We get unknown values here while we're building out a "planned state" - // during the plan phase, but the value stored in the plan takes precedence - // for expression evaluation. The apply step should never produce unknown - // values, but if it does it's the responsibility of the caller to detect - // and raise an error about that. - val := cty.UnknownAsNull(o.Value) - - src, err := ctyjson.Marshal(val, ty) - if err != nil { - return nil, err - } - - return &ResourceInstanceObjectSrc{ - SchemaVersion: schemaVersion, - AttrsJSON: src, - Private: o.Private, - Status: o.Status, - Dependencies: o.Dependencies, - }, nil -} - -// AsTainted returns a deep copy of the receiver with the status updated to -// ObjectTainted. -func (o *ResourceInstanceObject) AsTainted() *ResourceInstanceObject { - if o == nil { - // A nil object can't be tainted, but we'll allow this anyway to - // avoid a crash, since we presumably intend to eventually record - // the object has having been deleted anyway. - return nil - } - ret := o.DeepCopy() - ret.Status = ObjectTainted - return ret -} diff --git a/vendor/github.com/hashicorp/terraform/states/instance_object_src.go b/vendor/github.com/hashicorp/terraform/states/instance_object_src.go deleted file mode 100644 index 6cb3c27e..00000000 --- a/vendor/github.com/hashicorp/terraform/states/instance_object_src.go +++ /dev/null @@ -1,113 +0,0 @@ -package states - -import ( - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/config/hcl2shim" -) - -// ResourceInstanceObjectSrc is a not-fully-decoded version of -// ResourceInstanceObject. Decoding of it can be completed by first handling -// any schema migration steps to get to the latest schema version and then -// calling method Decode with the implied type of the latest schema. -type ResourceInstanceObjectSrc struct { - // SchemaVersion is the resource-type-specific schema version number that - // was current when either AttrsJSON or AttrsFlat was encoded. Migration - // steps are required if this is less than the current version number - // reported by the corresponding provider. - SchemaVersion uint64 - - // AttrsJSON is a JSON-encoded representation of the object attributes, - // encoding the value (of the object type implied by the associated resource - // type schema) that represents this remote object in Terraform Language - // expressions, and is compared with configuration when producing a diff. - // - // This is retained in JSON format here because it may require preprocessing - // before decoding if, for example, the stored attributes are for an older - // schema version which the provider must upgrade before use. If the - // version is current, it is valid to simply decode this using the - // type implied by the current schema, without the need for the provider - // to perform an upgrade first. - // - // When writing a ResourceInstanceObject into the state, AttrsJSON should - // always be conformant to the current schema version and the current - // schema version should be recorded in the SchemaVersion field. - AttrsJSON []byte - - // AttrsFlat is a legacy form of attributes used in older state file - // formats, and in the new state format for objects that haven't yet been - // upgraded. This attribute is mutually exclusive with Attrs: for any - // ResourceInstanceObject, only one of these attributes may be populated - // and the other must be nil. - // - // An instance object with this field populated should be upgraded to use - // Attrs at the earliest opportunity, since this legacy flatmap-based - // format will be phased out over time. AttrsFlat should not be used when - // writing new or updated objects to state; instead, callers must follow - // the recommendations in the AttrsJSON documentation above. - AttrsFlat map[string]string - - // These fields all correspond to the fields of the same name on - // ResourceInstanceObject. - Private []byte - Status ObjectStatus - Dependencies []addrs.Referenceable -} - -// Decode unmarshals the raw representation of the object attributes. Pass the -// implied type of the corresponding resource type schema for correct operation. -// -// Before calling Decode, the caller must check that the SchemaVersion field -// exactly equals the version number of the schema whose implied type is being -// passed, or else the result is undefined. -// -// The returned object may share internal references with the receiver and -// so the caller must not mutate the receiver any further once once this -// method is called. -func (os *ResourceInstanceObjectSrc) Decode(ty cty.Type) (*ResourceInstanceObject, error) { - var val cty.Value - var err error - if os.AttrsFlat != nil { - // Legacy mode. We'll do our best to unpick this from the flatmap. - val, err = hcl2shim.HCL2ValueFromFlatmap(os.AttrsFlat, ty) - if err != nil { - return nil, err - } - } else { - val, err = ctyjson.Unmarshal(os.AttrsJSON, ty) - if err != nil { - return nil, err - } - } - - return &ResourceInstanceObject{ - Value: val, - Status: os.Status, - Dependencies: os.Dependencies, - Private: os.Private, - }, nil -} - -// CompleteUpgrade creates a new ResourceInstanceObjectSrc by copying the -// metadata from the receiver and writing in the given new schema version -// and attribute value that are presumed to have resulted from upgrading -// from an older schema version. -func (os *ResourceInstanceObjectSrc) CompleteUpgrade(newAttrs cty.Value, newType cty.Type, newSchemaVersion uint64) (*ResourceInstanceObjectSrc, error) { - new := os.DeepCopy() - new.AttrsFlat = nil // We always use JSON after an upgrade, even if the source used flatmap - - // This is the same principle as ResourceInstanceObject.Encode, but - // avoiding a decode/re-encode cycle because we don't have type info - // available for the "old" attributes. - newAttrs = cty.UnknownAsNull(newAttrs) - src, err := ctyjson.Marshal(newAttrs, newType) - if err != nil { - return nil, err - } - - new.AttrsJSON = src - new.SchemaVersion = newSchemaVersion - return new, nil -} diff --git a/vendor/github.com/hashicorp/terraform/states/module.go b/vendor/github.com/hashicorp/terraform/states/module.go deleted file mode 100644 index d89e7878..00000000 --- a/vendor/github.com/hashicorp/terraform/states/module.go +++ /dev/null @@ -1,285 +0,0 @@ -package states - -import ( - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" -) - -// Module is a container for the states of objects within a particular module. -type Module struct { - Addr addrs.ModuleInstance - - // Resources contains the state for each resource. The keys in this map are - // an implementation detail and must not be used by outside callers. - Resources map[string]*Resource - - // OutputValues contains the state for each output value. The keys in this - // map are output value names. - OutputValues map[string]*OutputValue - - // LocalValues contains the value for each named output value. The keys - // in this map are local value names. - LocalValues map[string]cty.Value -} - -// NewModule constructs an empty module state for the given module address. -func NewModule(addr addrs.ModuleInstance) *Module { - return &Module{ - Addr: addr, - Resources: map[string]*Resource{}, - OutputValues: map[string]*OutputValue{}, - LocalValues: map[string]cty.Value{}, - } -} - -// Resource returns the state for the resource with the given address within -// the receiving module state, or nil if the requested resource is not tracked -// in the state. -func (ms *Module) Resource(addr addrs.Resource) *Resource { - return ms.Resources[addr.String()] -} - -// ResourceInstance returns the state for the resource instance with the given -// address within the receiving module state, or nil if the requested instance -// is not tracked in the state. -func (ms *Module) ResourceInstance(addr addrs.ResourceInstance) *ResourceInstance { - rs := ms.Resource(addr.Resource) - if rs == nil { - return nil - } - return rs.Instance(addr.Key) -} - -// SetResourceMeta updates the resource-level metadata for the resource -// with the given address, creating the resource state for it if it doesn't -// already exist. -func (ms *Module) SetResourceMeta(addr addrs.Resource, eachMode EachMode, provider addrs.AbsProviderConfig) { - rs := ms.Resource(addr) - if rs == nil { - rs = &Resource{ - Addr: addr, - Instances: map[addrs.InstanceKey]*ResourceInstance{}, - } - ms.Resources[addr.String()] = rs - } - - rs.EachMode = eachMode - rs.ProviderConfig = provider -} - -// RemoveResource removes the entire state for the given resource, taking with -// it any instances associated with the resource. This should generally be -// called only for resource objects whose instances have all been destroyed. -func (ms *Module) RemoveResource(addr addrs.Resource) { - delete(ms.Resources, addr.String()) -} - -// SetResourceInstanceCurrent saves the given instance object as the current -// generation of the resource instance with the given address, simulataneously -// updating the recorded provider configuration address, dependencies, and -// resource EachMode. -// -// Any existing current instance object for the given resource is overwritten. -// Set obj to nil to remove the primary generation object altogether. If there -// are no deposed objects then the instance will be removed altogether. -// -// The provider address and "each mode" are resource-wide settings and so they -// are updated for all other instances of the same resource as a side-effect of -// this call. -func (ms *Module) SetResourceInstanceCurrent(addr addrs.ResourceInstance, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) - - rs := ms.Resource(addr.Resource) - is := rs.EnsureInstance(addr.Key) - - is.Current = obj - - if !is.HasObjects() { - // If we have no objects at all then we'll clean up. - delete(rs.Instances, addr.Key) - } - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - // Also clean up if we only expect to have one instance anyway - // and there are none. We leave the resource behind if an each mode - // is active because an empty list or map of instances is a valid state. - delete(ms.Resources, addr.Resource.String()) - } -} - -// SetResourceInstanceDeposed saves the given instance object as a deposed -// generation of the resource instance with the given address and deposed key. -// -// Call this method only for pre-existing deposed objects that already have -// a known DeposedKey. For example, this method is useful if reloading objects -// that were persisted to a state file. To mark the current object as deposed, -// use DeposeResourceInstanceObject instead. -// -// The resource that contains the given instance must already exist in the -// state, or this method will panic. Use Resource to check first if its -// presence is not already guaranteed. -// -// Any existing current instance object for the given resource and deposed key -// is overwritten. Set obj to nil to remove the deposed object altogether. If -// the instance is left with no objects after this operation then it will -// be removed from its containing resource altogether. -func (ms *Module) SetResourceInstanceDeposed(addr addrs.ResourceInstance, key DeposedKey, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) - - rs := ms.Resource(addr.Resource) - is := rs.EnsureInstance(addr.Key) - if obj != nil { - is.Deposed[key] = obj - } else { - delete(is.Deposed, key) - } - - if !is.HasObjects() { - // If we have no objects at all then we'll clean up. - delete(rs.Instances, addr.Key) - } - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - // Also clean up if we only expect to have one instance anyway - // and there are none. We leave the resource behind if an each mode - // is active because an empty list or map of instances is a valid state. - delete(ms.Resources, addr.Resource.String()) - } -} - -// ForgetResourceInstanceAll removes the record of all objects associated with -// the specified resource instance, if present. If not present, this is a no-op. -func (ms *Module) ForgetResourceInstanceAll(addr addrs.ResourceInstance) { - rs := ms.Resource(addr.Resource) - if rs == nil { - return - } - delete(rs.Instances, addr.Key) - - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - // Also clean up if we only expect to have one instance anyway - // and there are none. We leave the resource behind if an each mode - // is active because an empty list or map of instances is a valid state. - delete(ms.Resources, addr.Resource.String()) - } -} - -// ForgetResourceInstanceDeposed removes the record of the deposed object with -// the given address and key, if present. If not present, this is a no-op. -func (ms *Module) ForgetResourceInstanceDeposed(addr addrs.ResourceInstance, key DeposedKey) { - rs := ms.Resource(addr.Resource) - if rs == nil { - return - } - is := rs.Instance(addr.Key) - if is == nil { - return - } - delete(is.Deposed, key) - - if !is.HasObjects() { - // If we have no objects at all then we'll clean up. - delete(rs.Instances, addr.Key) - } - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - // Also clean up if we only expect to have one instance anyway - // and there are none. We leave the resource behind if an each mode - // is active because an empty list or map of instances is a valid state. - delete(ms.Resources, addr.Resource.String()) - } -} - -// deposeResourceInstanceObject is the real implementation of -// SyncState.DeposeResourceInstanceObject. -func (ms *Module) deposeResourceInstanceObject(addr addrs.ResourceInstance, forceKey DeposedKey) DeposedKey { - is := ms.ResourceInstance(addr) - if is == nil { - return NotDeposed - } - return is.deposeCurrentObject(forceKey) -} - -// maybeRestoreResourceInstanceDeposed is the real implementation of -// SyncState.MaybeRestoreResourceInstanceDeposed. -func (ms *Module) maybeRestoreResourceInstanceDeposed(addr addrs.ResourceInstance, key DeposedKey) bool { - rs := ms.Resource(addr.Resource) - if rs == nil { - return false - } - is := rs.Instance(addr.Key) - if is == nil { - return false - } - if is.Current != nil { - return false - } - if len(is.Deposed) == 0 { - return false - } - is.Current = is.Deposed[key] - delete(is.Deposed, key) - return true -} - -// SetOutputValue writes an output value into the state, overwriting any -// existing value of the same name. -func (ms *Module) SetOutputValue(name string, value cty.Value, sensitive bool) *OutputValue { - os := &OutputValue{ - Value: value, - Sensitive: sensitive, - } - ms.OutputValues[name] = os - return os -} - -// RemoveOutputValue removes the output value of the given name from the state, -// if it exists. This method is a no-op if there is no value of the given -// name. -func (ms *Module) RemoveOutputValue(name string) { - delete(ms.OutputValues, name) -} - -// SetLocalValue writes a local value into the state, overwriting any -// existing value of the same name. -func (ms *Module) SetLocalValue(name string, value cty.Value) { - ms.LocalValues[name] = value -} - -// RemoveLocalValue removes the local value of the given name from the state, -// if it exists. This method is a no-op if there is no value of the given -// name. -func (ms *Module) RemoveLocalValue(name string) { - delete(ms.LocalValues, name) -} - -// PruneResourceHusks is a specialized method that will remove any Resource -// objects that do not contain any instances, even if they have an EachMode. -// -// You probably shouldn't call this! See the method of the same name on -// type State for more information on what this is for and the rare situations -// where it is safe to use. -func (ms *Module) PruneResourceHusks() { - for _, rs := range ms.Resources { - if len(rs.Instances) == 0 { - ms.RemoveResource(rs.Addr) - } - } -} - -// empty returns true if the receving module state is contributing nothing -// to the state. In other words, it returns true if the module could be -// removed from the state altogether without changing the meaning of the state. -// -// In practice a module containing no objects is the same as a non-existent -// module, and so we can opportunistically clean up once a module becomes -// empty on the assumption that it will be re-added if needed later. -func (ms *Module) empty() bool { - if ms == nil { - return true - } - - // This must be updated to cover any new collections added to Module - // in future. - return (len(ms.Resources) == 0 && - len(ms.OutputValues) == 0 && - len(ms.LocalValues) == 0) -} diff --git a/vendor/github.com/hashicorp/terraform/states/objectstatus_string.go b/vendor/github.com/hashicorp/terraform/states/objectstatus_string.go deleted file mode 100644 index cd6d1284..00000000 --- a/vendor/github.com/hashicorp/terraform/states/objectstatus_string.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by "stringer -type ObjectStatus"; DO NOT EDIT. - -package states - -import "strconv" - -const ( - _ObjectStatus_name_0 = "ObjectPlanned" - _ObjectStatus_name_1 = "ObjectReady" - _ObjectStatus_name_2 = "ObjectTainted" -) - -func (i ObjectStatus) String() string { - switch { - case i == 80: - return _ObjectStatus_name_0 - case i == 82: - return _ObjectStatus_name_1 - case i == 84: - return _ObjectStatus_name_2 - default: - return "ObjectStatus(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform/states/output_value.go b/vendor/github.com/hashicorp/terraform/states/output_value.go deleted file mode 100644 index d232b76d..00000000 --- a/vendor/github.com/hashicorp/terraform/states/output_value.go +++ /dev/null @@ -1,14 +0,0 @@ -package states - -import ( - "github.com/zclconf/go-cty/cty" -) - -// OutputValue represents the state of a particular output value. -// -// It is not valid to mutate an OutputValue object once it has been created. -// Instead, create an entirely new OutputValue to replace the previous one. -type OutputValue struct { - Value cty.Value - Sensitive bool -} diff --git a/vendor/github.com/hashicorp/terraform/states/resource.go b/vendor/github.com/hashicorp/terraform/states/resource.go deleted file mode 100644 index e2a2b858..00000000 --- a/vendor/github.com/hashicorp/terraform/states/resource.go +++ /dev/null @@ -1,239 +0,0 @@ -package states - -import ( - "fmt" - "math/rand" - "time" - - "github.com/hashicorp/terraform/addrs" -) - -// Resource represents the state of a resource. -type Resource struct { - // Addr is the module-relative address for the resource this state object - // belongs to. - Addr addrs.Resource - - // EachMode is the multi-instance mode currently in use for this resource, - // or NoEach if this is a single-instance resource. This dictates what - // type of value is returned when accessing this resource via expressions - // in the Terraform language. - EachMode EachMode - - // Instances contains the potentially-multiple instances associated with - // this resource. This map can contain a mixture of different key types, - // but only the ones of InstanceKeyType are considered current. - Instances map[addrs.InstanceKey]*ResourceInstance - - // ProviderConfig is the absolute address for the provider configuration that - // most recently managed this resource. This is used to connect a resource - // with a provider configuration when the resource configuration block is - // not available, such as if it has been removed from configuration - // altogether. - ProviderConfig addrs.AbsProviderConfig -} - -// Instance returns the state for the instance with the given key, or nil -// if no such instance is tracked within the state. -func (rs *Resource) Instance(key addrs.InstanceKey) *ResourceInstance { - return rs.Instances[key] -} - -// EnsureInstance returns the state for the instance with the given key, -// creating a new empty state for it if one doesn't already exist. -// -// Because this may create and save a new state, it is considered to be -// a write operation. -func (rs *Resource) EnsureInstance(key addrs.InstanceKey) *ResourceInstance { - ret := rs.Instance(key) - if ret == nil { - ret = NewResourceInstance() - rs.Instances[key] = ret - } - return ret -} - -// ResourceInstance represents the state of a particular instance of a resource. -type ResourceInstance struct { - // Current, if non-nil, is the remote object that is currently represented - // by the corresponding resource instance. - Current *ResourceInstanceObjectSrc - - // Deposed, if len > 0, contains any remote objects that were previously - // represented by the corresponding resource instance but have been - // replaced and are pending destruction due to the create_before_destroy - // lifecycle mode. - Deposed map[DeposedKey]*ResourceInstanceObjectSrc -} - -// NewResourceInstance constructs and returns a new ResourceInstance, ready to -// use. -func NewResourceInstance() *ResourceInstance { - return &ResourceInstance{ - Deposed: map[DeposedKey]*ResourceInstanceObjectSrc{}, - } -} - -// HasCurrent returns true if this resource instance has a "current"-generation -// object. Most instances do, but this can briefly be false during a -// create-before-destroy replace operation when the current has been deposed -// but its replacement has not yet been created. -func (i *ResourceInstance) HasCurrent() bool { - return i != nil && i.Current != nil -} - -// HasDeposed returns true if this resource instance has a deposed object -// with the given key. -func (i *ResourceInstance) HasDeposed(key DeposedKey) bool { - return i != nil && i.Deposed[key] != nil -} - -// HasAnyDeposed returns true if this resource instance has one or more -// deposed objects. -func (i *ResourceInstance) HasAnyDeposed() bool { - return i != nil && len(i.Deposed) > 0 -} - -// HasObjects returns true if this resource has any objects at all, whether -// current or deposed. -func (i *ResourceInstance) HasObjects() bool { - return i.Current != nil || len(i.Deposed) != 0 -} - -// deposeCurrentObject is part of the real implementation of -// SyncState.DeposeResourceInstanceObject. The exported method uses a lock -// to ensure that we can safely allocate an unused deposed key without -// collision. -func (i *ResourceInstance) deposeCurrentObject(forceKey DeposedKey) DeposedKey { - if !i.HasCurrent() { - return NotDeposed - } - - key := forceKey - if key == NotDeposed { - key = i.findUnusedDeposedKey() - } else { - if _, exists := i.Deposed[key]; exists { - panic(fmt.Sprintf("forced key %s is already in use", forceKey)) - } - } - i.Deposed[key] = i.Current - i.Current = nil - return key -} - -// GetGeneration retrieves the object of the given generation from the -// ResourceInstance, or returns nil if there is no such object. -// -// If the given generation is nil or invalid, this method will panic. -func (i *ResourceInstance) GetGeneration(gen Generation) *ResourceInstanceObjectSrc { - if gen == CurrentGen { - return i.Current - } - if dk, ok := gen.(DeposedKey); ok { - return i.Deposed[dk] - } - if gen == nil { - panic(fmt.Sprintf("get with nil Generation")) - } - // Should never fall out here, since the above covers all possible - // Generation values. - panic(fmt.Sprintf("get invalid Generation %#v", gen)) -} - -// FindUnusedDeposedKey generates a unique DeposedKey that is guaranteed not to -// already be in use for this instance at the time of the call. -// -// Note that the validity of this result may change if new deposed keys are -// allocated before it is used. To avoid this risk, instead use the -// DeposeResourceInstanceObject method on the SyncState wrapper type, which -// allocates a key and uses it atomically. -func (i *ResourceInstance) FindUnusedDeposedKey() DeposedKey { - return i.findUnusedDeposedKey() -} - -// findUnusedDeposedKey generates a unique DeposedKey that is guaranteed not to -// already be in use for this instance. -func (i *ResourceInstance) findUnusedDeposedKey() DeposedKey { - for { - key := NewDeposedKey() - if _, exists := i.Deposed[key]; !exists { - return key - } - // Spin until we find a unique one. This shouldn't take long, because - // we have a 32-bit keyspace and there's rarely more than one deposed - // instance. - } -} - -// EachMode specifies the multi-instance mode for a resource. -type EachMode rune - -const ( - NoEach EachMode = 0 - EachList EachMode = 'L' - EachMap EachMode = 'M' -) - -//go:generate stringer -type EachMode - -func eachModeForInstanceKey(key addrs.InstanceKey) EachMode { - switch key.(type) { - case addrs.IntKey: - return EachList - case addrs.StringKey: - return EachMap - default: - if key == addrs.NoKey { - return NoEach - } - panic(fmt.Sprintf("don't know an each mode for instance key %#v", key)) - } -} - -// DeposedKey is a 8-character hex string used to uniquely identify deposed -// instance objects in the state. -type DeposedKey string - -// NotDeposed is a special invalid value of DeposedKey that is used to represent -// the absense of a deposed key. It must not be used as an actual deposed key. -const NotDeposed = DeposedKey("") - -var deposedKeyRand = rand.New(rand.NewSource(time.Now().UnixNano())) - -// NewDeposedKey generates a pseudo-random deposed key. Because of the short -// length of these keys, uniqueness is not a natural consequence and so the -// caller should test to see if the generated key is already in use and generate -// another if so, until a unique key is found. -func NewDeposedKey() DeposedKey { - v := deposedKeyRand.Uint32() - return DeposedKey(fmt.Sprintf("%08x", v)) -} - -func (k DeposedKey) String() string { - return string(k) -} - -func (k DeposedKey) GoString() string { - ks := string(k) - switch { - case ks == "": - return "states.NotDeposed" - default: - return fmt.Sprintf("states.DeposedKey(%s)", ks) - } -} - -// Generation is a helper method to convert a DeposedKey into a Generation. -// If the reciever is anything other than NotDeposed then the result is -// just the same value as a Generation. If the receiver is NotDeposed then -// the result is CurrentGen. -func (k DeposedKey) Generation() Generation { - if k == NotDeposed { - return CurrentGen - } - return k -} - -// generation is an implementation of Generation. -func (k DeposedKey) generation() {} diff --git a/vendor/github.com/hashicorp/terraform/states/state.go b/vendor/github.com/hashicorp/terraform/states/state.go deleted file mode 100644 index 1f842359..00000000 --- a/vendor/github.com/hashicorp/terraform/states/state.go +++ /dev/null @@ -1,229 +0,0 @@ -package states - -import ( - "sort" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" -) - -// State is the top-level type of a Terraform state. -// -// A state should be mutated only via its accessor methods, to ensure that -// invariants are preserved. -// -// Access to State and the nested values within it is not concurrency-safe, -// so when accessing a State object concurrently it is the caller's -// responsibility to ensure that only one write is in progress at a time -// and that reads only occur when no write is in progress. The most common -// way to acheive this is to wrap the State in a SyncState and use the -// higher-level atomic operations supported by that type. -type State struct { - // Modules contains the state for each module. The keys in this map are - // an implementation detail and must not be used by outside callers. - Modules map[string]*Module -} - -// NewState constructs a minimal empty state, containing an empty root module. -func NewState() *State { - modules := map[string]*Module{} - modules[addrs.RootModuleInstance.String()] = NewModule(addrs.RootModuleInstance) - return &State{ - Modules: modules, - } -} - -// BuildState is a helper -- primarily intended for tests -- to build a state -// using imperative code against the StateSync type while still acting as -// an expression of type *State to assign into a containing struct. -func BuildState(cb func(*SyncState)) *State { - s := NewState() - cb(s.SyncWrapper()) - return s -} - -// Empty returns true if there are no resources or populated output values -// in the receiver. In other words, if this state could be safely replaced -// with the return value of NewState and be functionally equivalent. -func (s *State) Empty() bool { - if s == nil { - return true - } - for _, ms := range s.Modules { - if len(ms.Resources) != 0 { - return false - } - if len(ms.OutputValues) != 0 { - return false - } - } - return true -} - -// Module returns the state for the module with the given address, or nil if -// the requested module is not tracked in the state. -func (s *State) Module(addr addrs.ModuleInstance) *Module { - if s == nil { - panic("State.Module on nil *State") - } - return s.Modules[addr.String()] -} - -// RemoveModule removes the module with the given address from the state, -// unless it is the root module. The root module cannot be deleted, and so -// this method will panic if that is attempted. -// -// Removing a module implicitly discards all of the resources, outputs and -// local values within it, and so this should usually be done only for empty -// modules. For callers accessing the state through a SyncState wrapper, modules -// are automatically pruned if they are empty after one of their contained -// elements is removed. -func (s *State) RemoveModule(addr addrs.ModuleInstance) { - if addr.IsRoot() { - panic("attempted to remove root module") - } - - delete(s.Modules, addr.String()) -} - -// RootModule is a convenient alias for Module(addrs.RootModuleInstance). -func (s *State) RootModule() *Module { - if s == nil { - panic("RootModule called on nil State") - } - return s.Modules[addrs.RootModuleInstance.String()] -} - -// EnsureModule returns the state for the module with the given address, -// creating and adding a new one if necessary. -// -// Since this might modify the state to add a new instance, it is considered -// to be a write operation. -func (s *State) EnsureModule(addr addrs.ModuleInstance) *Module { - ms := s.Module(addr) - if ms == nil { - ms = NewModule(addr) - s.Modules[addr.String()] = ms - } - return ms -} - -// HasResources returns true if there is at least one resource (of any mode) -// present in the receiving state. -func (s *State) HasResources() bool { - if s == nil { - return false - } - for _, ms := range s.Modules { - if len(ms.Resources) > 0 { - return true - } - } - return false -} - -// Resource returns the state for the resource with the given address, or nil -// if no such resource is tracked in the state. -func (s *State) Resource(addr addrs.AbsResource) *Resource { - ms := s.Module(addr.Module) - if ms == nil { - return nil - } - return ms.Resource(addr.Resource) -} - -// ResourceInstance returns the state for the resource instance with the given -// address, or nil if no such resource is tracked in the state. -func (s *State) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstance { - if s == nil { - panic("State.ResourceInstance on nil *State") - } - ms := s.Module(addr.Module) - if ms == nil { - return nil - } - return ms.ResourceInstance(addr.Resource) -} - -// OutputValue returns the state for the output value with the given address, -// or nil if no such output value is tracked in the state. -func (s *State) OutputValue(addr addrs.AbsOutputValue) *OutputValue { - ms := s.Module(addr.Module) - if ms == nil { - return nil - } - return ms.OutputValues[addr.OutputValue.Name] -} - -// LocalValue returns the value of the named local value with the given address, -// or cty.NilVal if no such value is tracked in the state. -func (s *State) LocalValue(addr addrs.AbsLocalValue) cty.Value { - ms := s.Module(addr.Module) - if ms == nil { - return cty.NilVal - } - return ms.LocalValues[addr.LocalValue.Name] -} - -// ProviderAddrs returns a list of all of the provider configuration addresses -// referenced throughout the receiving state. -// -// The result is de-duplicated so that each distinct address appears only once. -func (s *State) ProviderAddrs() []addrs.AbsProviderConfig { - if s == nil { - return nil - } - - m := map[string]addrs.AbsProviderConfig{} - for _, ms := range s.Modules { - for _, rc := range ms.Resources { - m[rc.ProviderConfig.String()] = rc.ProviderConfig - } - } - if len(m) == 0 { - return nil - } - - // This is mainly just so we'll get stable results for testing purposes. - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - - ret := make([]addrs.AbsProviderConfig, len(keys)) - for i, key := range keys { - ret[i] = m[key] - } - - return ret -} - -// PruneResourceHusks is a specialized method that will remove any Resource -// objects that do not contain any instances, even if they have an EachMode. -// -// This should generally be used only after a "terraform destroy" operation, -// to finalize the cleanup of the state. It is not correct to use this after -// other operations because if a resource has "count = 0" or "for_each" over -// an empty collection then we want to retain it in the state so that references -// to it, particularly in "strange" contexts like "terraform console", can be -// properly resolved. -// -// This method MUST NOT be called concurrently with other readers and writers -// of the receiving state. -func (s *State) PruneResourceHusks() { - for _, m := range s.Modules { - m.PruneResourceHusks() - if len(m.Resources) == 0 && !m.Addr.IsRoot() { - s.RemoveModule(m.Addr) - } - } -} - -// SyncWrapper returns a SyncState object wrapping the receiver. -func (s *State) SyncWrapper() *SyncState { - return &SyncState{ - state: s, - } -} diff --git a/vendor/github.com/hashicorp/terraform/states/state_deepcopy.go b/vendor/github.com/hashicorp/terraform/states/state_deepcopy.go deleted file mode 100644 index ea717d00..00000000 --- a/vendor/github.com/hashicorp/terraform/states/state_deepcopy.go +++ /dev/null @@ -1,218 +0,0 @@ -package states - -import ( - "github.com/hashicorp/terraform/addrs" - "github.com/zclconf/go-cty/cty" -) - -// Taking deep copies of states is an important operation because state is -// otherwise a mutable data structure that is challenging to share across -// many separate callers. It is important that the DeepCopy implementations -// in this file comprehensively copy all parts of the state data structure -// that could be mutated via pointers. - -// DeepCopy returns a new state that contains equivalent data to the reciever -// but shares no backing memory in common. -// -// As with all methods on State, this method is not safe to use concurrently -// with writing to any portion of the recieving data structure. It is the -// caller's responsibility to ensure mutual exclusion for the duration of the -// operation, but may then freely modify the receiver and the returned copy -// independently once this method returns. -func (s *State) DeepCopy() *State { - if s == nil { - return nil - } - - modules := make(map[string]*Module, len(s.Modules)) - for k, m := range s.Modules { - modules[k] = m.DeepCopy() - } - return &State{ - Modules: modules, - } -} - -// DeepCopy returns a new module state that contains equivalent data to the -// receiver but shares no backing memory in common. -// -// As with all methods on Module, this method is not safe to use concurrently -// with writing to any portion of the recieving data structure. It is the -// caller's responsibility to ensure mutual exclusion for the duration of the -// operation, but may then freely modify the receiver and the returned copy -// independently once this method returns. -func (ms *Module) DeepCopy() *Module { - if ms == nil { - return nil - } - - resources := make(map[string]*Resource, len(ms.Resources)) - for k, r := range ms.Resources { - resources[k] = r.DeepCopy() - } - outputValues := make(map[string]*OutputValue, len(ms.OutputValues)) - for k, v := range ms.OutputValues { - outputValues[k] = v.DeepCopy() - } - localValues := make(map[string]cty.Value, len(ms.LocalValues)) - for k, v := range ms.LocalValues { - // cty.Value is immutable, so we don't need to copy these. - localValues[k] = v - } - - return &Module{ - Addr: ms.Addr, // technically mutable, but immutable by convention - Resources: resources, - OutputValues: outputValues, - LocalValues: localValues, - } -} - -// DeepCopy returns a new resource state that contains equivalent data to the -// receiver but shares no backing memory in common. -// -// As with all methods on Resource, this method is not safe to use concurrently -// with writing to any portion of the recieving data structure. It is the -// caller's responsibility to ensure mutual exclusion for the duration of the -// operation, but may then freely modify the receiver and the returned copy -// independently once this method returns. -func (rs *Resource) DeepCopy() *Resource { - if rs == nil { - return nil - } - - instances := make(map[addrs.InstanceKey]*ResourceInstance, len(rs.Instances)) - for k, i := range rs.Instances { - instances[k] = i.DeepCopy() - } - - return &Resource{ - Addr: rs.Addr, - EachMode: rs.EachMode, - Instances: instances, - ProviderConfig: rs.ProviderConfig, // technically mutable, but immutable by convention - } -} - -// DeepCopy returns a new resource instance state that contains equivalent data -// to the receiver but shares no backing memory in common. -// -// As with all methods on ResourceInstance, this method is not safe to use -// concurrently with writing to any portion of the recieving data structure. It -// is the caller's responsibility to ensure mutual exclusion for the duration -// of the operation, but may then freely modify the receiver and the returned -// copy independently once this method returns. -func (is *ResourceInstance) DeepCopy() *ResourceInstance { - if is == nil { - return nil - } - - deposed := make(map[DeposedKey]*ResourceInstanceObjectSrc, len(is.Deposed)) - for k, obj := range is.Deposed { - deposed[k] = obj.DeepCopy() - } - - return &ResourceInstance{ - Current: is.Current.DeepCopy(), - Deposed: deposed, - } -} - -// DeepCopy returns a new resource instance object that contains equivalent data -// to the receiver but shares no backing memory in common. -// -// As with all methods on ResourceInstanceObjectSrc, this method is not safe to -// use concurrently with writing to any portion of the recieving data structure. -// It is the caller's responsibility to ensure mutual exclusion for the duration -// of the operation, but may then freely modify the receiver and the returned -// copy independently once this method returns. -func (obj *ResourceInstanceObjectSrc) DeepCopy() *ResourceInstanceObjectSrc { - if obj == nil { - return nil - } - - var attrsFlat map[string]string - if obj.AttrsFlat != nil { - attrsFlat = make(map[string]string, len(obj.AttrsFlat)) - for k, v := range obj.AttrsFlat { - attrsFlat[k] = v - } - } - - var attrsJSON []byte - if obj.AttrsJSON != nil { - attrsJSON = make([]byte, len(obj.AttrsJSON)) - copy(attrsJSON, obj.AttrsJSON) - } - - var private []byte - if obj.Private != nil { - private := make([]byte, len(obj.Private)) - copy(private, obj.Private) - } - - // Some addrs.Referencable implementations are technically mutable, but - // we treat them as immutable by convention and so we don't deep-copy here. - dependencies := make([]addrs.Referenceable, len(obj.Dependencies)) - copy(dependencies, obj.Dependencies) - - return &ResourceInstanceObjectSrc{ - Status: obj.Status, - SchemaVersion: obj.SchemaVersion, - Private: private, - AttrsFlat: attrsFlat, - AttrsJSON: attrsJSON, - Dependencies: dependencies, - } -} - -// DeepCopy returns a new resource instance object that contains equivalent data -// to the receiver but shares no backing memory in common. -// -// As with all methods on ResourceInstanceObject, this method is not safe to use -// concurrently with writing to any portion of the recieving data structure. It -// is the caller's responsibility to ensure mutual exclusion for the duration -// of the operation, but may then freely modify the receiver and the returned -// copy independently once this method returns. -func (obj *ResourceInstanceObject) DeepCopy() *ResourceInstanceObject { - if obj == nil { - return nil - } - - var private []byte - if obj.Private != nil { - private := make([]byte, len(obj.Private)) - copy(private, obj.Private) - } - - // Some addrs.Referencable implementations are technically mutable, but - // we treat them as immutable by convention and so we don't deep-copy here. - dependencies := make([]addrs.Referenceable, len(obj.Dependencies)) - copy(dependencies, obj.Dependencies) - - return &ResourceInstanceObject{ - Value: obj.Value, - Status: obj.Status, - Private: private, - Dependencies: dependencies, - } -} - -// DeepCopy returns a new output value state that contains equivalent data -// to the receiver but shares no backing memory in common. -// -// As with all methods on OutputValue, this method is not safe to use -// concurrently with writing to any portion of the recieving data structure. It -// is the caller's responsibility to ensure mutual exclusion for the duration -// of the operation, but may then freely modify the receiver and the returned -// copy independently once this method returns. -func (os *OutputValue) DeepCopy() *OutputValue { - if os == nil { - return nil - } - - return &OutputValue{ - Value: os.Value, - Sensitive: os.Sensitive, - } -} diff --git a/vendor/github.com/hashicorp/terraform/states/state_equal.go b/vendor/github.com/hashicorp/terraform/states/state_equal.go deleted file mode 100644 index ea20967e..00000000 --- a/vendor/github.com/hashicorp/terraform/states/state_equal.go +++ /dev/null @@ -1,18 +0,0 @@ -package states - -import ( - "reflect" -) - -// Equal returns true if the receiver is functionally equivalent to other, -// including any ephemeral portions of the state that would not be included -// if the state were saved to files. -// -// To test only the persistent portions of two states for equality, instead -// use statefile.StatesMarshalEqual. -func (s *State) Equal(other *State) bool { - // For the moment this is sufficient, but we may need to do something - // more elaborate in future if we have any portions of state that require - // more sophisticated comparisons. - return reflect.DeepEqual(s, other) -} diff --git a/vendor/github.com/hashicorp/terraform/states/state_filter.go b/vendor/github.com/hashicorp/terraform/states/state_filter.go deleted file mode 100644 index de5595cf..00000000 --- a/vendor/github.com/hashicorp/terraform/states/state_filter.go +++ /dev/null @@ -1,180 +0,0 @@ -package states - -import ( - "fmt" - "sort" - - "github.com/hashicorp/terraform/addrs" -) - -// Filter is responsible for filtering and searching a state. -// -// This is a separate struct from State rather than a method on State -// because Filter might create sidecar data structures to optimize -// filtering on the state. -// -// If you change the State, the filter created is invalid and either -// Reset should be called or a new one should be allocated. Filter -// will not watch State for changes and do this for you. If you filter after -// changing the State without calling Reset, the behavior is not defined. -type Filter struct { - State *State -} - -// Filter takes the addresses specified by fs and finds all the matches. -// The values of fs are resource addressing syntax that can be parsed by -// ParseResourceAddress. -func (f *Filter) Filter(fs ...string) ([]*FilterResult, error) { - // Parse all the addresses - as := make([]addrs.Targetable, len(fs)) - for i, v := range fs { - if addr, diags := addrs.ParseModuleInstanceStr(v); !diags.HasErrors() { - as[i] = addr - continue - } - if addr, diags := addrs.ParseAbsResourceStr(v); !diags.HasErrors() { - as[i] = addr - continue - } - if addr, diags := addrs.ParseAbsResourceInstanceStr(v); !diags.HasErrors() { - as[i] = addr - continue - } - return nil, fmt.Errorf("Error parsing address: %s", v) - } - - // If we weren't given any filters, then we list all - if len(fs) == 0 { - as = append(as, addrs.Targetable(nil)) - } - - // Filter each of the address. We keep track of this in a map to - // strip duplicates. - resultSet := make(map[string]*FilterResult) - for _, addr := range as { - for _, v := range f.filterSingle(addr) { - resultSet[v.String()] = v - } - } - - // Make the result list - results := make([]*FilterResult, 0, len(resultSet)) - for _, v := range resultSet { - results = append(results, v) - } - - // Sort the results - sort.Slice(results, func(i, j int) bool { - a, b := results[i], results[j] - - // If the addresses are different it is just lexographic sorting - if a.Address.String() != b.Address.String() { - return a.Address.String() < b.Address.String() - } - - // Addresses are the same, which means it matters on the type - return a.SortedType() < b.SortedType() - }) - - return results, nil -} - -func (f *Filter) filterSingle(addr addrs.Targetable) []*FilterResult { - // The slice to keep track of results - var results []*FilterResult - - // Check if we received a module instance address that - // should be used as module filter, and if not set the - // filter to the root module instance. - filter, ok := addr.(addrs.ModuleInstance) - if !ok { - filter = addrs.RootModuleInstance - } - - // Go through modules first. - modules := make([]*Module, 0, len(f.State.Modules)) - for _, m := range f.State.Modules { - if filter.IsRoot() || filter.Equal(m.Addr) || filter.IsAncestor(m.Addr) { - modules = append(modules, m) - - // Only add the module to the results if we searched - // for a non-root module and found a (partial) match. - if (addr == nil && !m.Addr.IsRoot()) || - (!filter.IsRoot() && (filter.Equal(m.Addr) || filter.IsAncestor(m.Addr))) { - results = append(results, &FilterResult{ - Address: m.Addr, - Value: m, - }) - } - } - } - - // With the modules set, go through all the resources within - // the modules to find relevant resources. - for _, m := range modules { - for _, rs := range m.Resources { - if f.relevant(addr, rs.Addr.Absolute(m.Addr), addrs.NoKey) { - results = append(results, &FilterResult{ - Address: rs.Addr.Absolute(m.Addr), - Value: rs, - }) - } - - for key, is := range rs.Instances { - if f.relevant(addr, rs.Addr.Absolute(m.Addr), key) { - results = append(results, &FilterResult{ - Address: rs.Addr.Absolute(m.Addr).Instance(key), - Value: is, - }) - } - } - } - } - - return results -} - -func (f *Filter) relevant(filter addrs.Targetable, rs addrs.AbsResource, key addrs.InstanceKey) bool { - switch filter := filter.(type) { - case addrs.AbsResource: - if filter.Module != nil { - return filter.Equal(rs) - } - return filter.Resource.Equal(rs.Resource) - case addrs.AbsResourceInstance: - if filter.Module != nil { - return filter.Equal(rs.Instance(key)) - } - return filter.Resource.Equal(rs.Resource.Instance(key)) - default: - return true - } -} - -// FilterResult is a single result from a filter operation. Filter can -// match multiple things within a state (curently modules and resources). -type FilterResult struct { - // Address is the address that can be used to reference this exact result. - Address addrs.Targetable - - // Value is the actual value. This must be type switched on. It can be - // any either a `Module` or `ResourceInstance`. - Value interface{} -} - -func (r *FilterResult) String() string { - return fmt.Sprintf("%T: %s", r.Value, r.Address) -} - -func (r *FilterResult) SortedType() int { - switch r.Value.(type) { - case *Module: - return 0 - case *Resource: - return 1 - case *ResourceInstance: - return 2 - default: - return 50 - } -} diff --git a/vendor/github.com/hashicorp/terraform/states/state_string.go b/vendor/github.com/hashicorp/terraform/states/state_string.go deleted file mode 100644 index bca4581c..00000000 --- a/vendor/github.com/hashicorp/terraform/states/state_string.go +++ /dev/null @@ -1,279 +0,0 @@ -package states - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "sort" - "strings" - - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/config/hcl2shim" -) - -// String returns a rather-odd string representation of the entire state. -// -// This is intended to match the behavior of the older terraform.State.String -// method that is used in lots of existing tests. It should not be used in -// new tests: instead, use "cmp" to directly compare the state data structures -// and print out a diff if they do not match. -// -// This method should never be used in non-test code, whether directly by call -// or indirectly via a %s or %q verb in package fmt. -func (s *State) String() string { - if s == nil { - return "" - } - - // sort the modules by name for consistent output - modules := make([]string, 0, len(s.Modules)) - for m := range s.Modules { - modules = append(modules, m) - } - sort.Strings(modules) - - var buf bytes.Buffer - for _, name := range modules { - m := s.Modules[name] - mStr := m.testString() - - // If we're the root module, we just write the output directly. - if m.Addr.IsRoot() { - buf.WriteString(mStr + "\n") - continue - } - - // We need to build out a string that resembles the not-quite-standard - // format that terraform.State.String used to use, where there's a - // "module." prefix but then just a chain of all of the module names - // without any further "module." portions. - buf.WriteString("module") - for _, step := range m.Addr { - buf.WriteByte('.') - buf.WriteString(step.Name) - if step.InstanceKey != addrs.NoKey { - buf.WriteByte('[') - buf.WriteString(step.InstanceKey.String()) - buf.WriteByte(']') - } - } - buf.WriteString(":\n") - - s := bufio.NewScanner(strings.NewReader(mStr)) - for s.Scan() { - text := s.Text() - if text != "" { - text = " " + text - } - - buf.WriteString(fmt.Sprintf("%s\n", text)) - } - } - - return strings.TrimSpace(buf.String()) -} - -// testString is used to produce part of the output of State.String. It should -// never be used directly. -func (m *Module) testString() string { - var buf bytes.Buffer - - if len(m.Resources) == 0 { - buf.WriteString("") - } - - // We use AbsResourceInstance here, even though everything belongs to - // the same module, just because we have a sorting behavior defined - // for those but not for just ResourceInstance. - addrsOrder := make([]addrs.AbsResourceInstance, 0, len(m.Resources)) - for _, rs := range m.Resources { - for ik := range rs.Instances { - addrsOrder = append(addrsOrder, rs.Addr.Instance(ik).Absolute(addrs.RootModuleInstance)) - } - } - - sort.Slice(addrsOrder, func(i, j int) bool { - return addrsOrder[i].Less(addrsOrder[j]) - }) - - for _, fakeAbsAddr := range addrsOrder { - addr := fakeAbsAddr.Resource - rs := m.Resource(addr.ContainingResource()) - is := m.ResourceInstance(addr) - - // Here we need to fake up a legacy-style address as the old state - // types would've used, since that's what our tests against those - // old types expect. The significant difference is that instancekey - // is dot-separated rather than using index brackets. - k := addr.ContainingResource().String() - if addr.Key != addrs.NoKey { - switch tk := addr.Key.(type) { - case addrs.IntKey: - k = fmt.Sprintf("%s.%d", k, tk) - default: - // No other key types existed for the legacy types, so we - // can do whatever we want here. We'll just use our standard - // syntax for these. - k = k + tk.String() - } - } - - id := LegacyInstanceObjectID(is.Current) - - taintStr := "" - if is.Current != nil && is.Current.Status == ObjectTainted { - taintStr = " (tainted)" - } - - deposedStr := "" - if len(is.Deposed) > 0 { - deposedStr = fmt.Sprintf(" (%d deposed)", len(is.Deposed)) - } - - buf.WriteString(fmt.Sprintf("%s:%s%s\n", k, taintStr, deposedStr)) - buf.WriteString(fmt.Sprintf(" ID = %s\n", id)) - buf.WriteString(fmt.Sprintf(" provider = %s\n", rs.ProviderConfig.String())) - - // Attributes were a flatmap before, but are not anymore. To preserve - // our old output as closely as possible we need to do a conversion - // to flatmap. Normally we'd want to do this with schema for - // accuracy, but for our purposes here it only needs to be approximate. - // This should produce an identical result for most cases, though - // in particular will differ in a few cases: - // - The keys used for elements in a set will be different - // - Values for attributes of type cty.DynamicPseudoType will be - // misinterpreted (but these weren't possible in old world anyway) - var attributes map[string]string - if obj := is.Current; obj != nil { - switch { - case obj.AttrsFlat != nil: - // Easy (but increasingly unlikely) case: the state hasn't - // actually been upgraded to the new form yet. - attributes = obj.AttrsFlat - case obj.AttrsJSON != nil: - ty, err := ctyjson.ImpliedType(obj.AttrsJSON) - if err == nil { - val, err := ctyjson.Unmarshal(obj.AttrsJSON, ty) - if err == nil { - attributes = hcl2shim.FlatmapValueFromHCL2(val) - } - } - } - } - attrKeys := make([]string, 0, len(attributes)) - for ak, val := range attributes { - if ak == "id" { - continue - } - - // don't show empty containers in the output - if val == "0" && (strings.HasSuffix(ak, ".#") || strings.HasSuffix(ak, ".%")) { - continue - } - - attrKeys = append(attrKeys, ak) - } - - sort.Strings(attrKeys) - - for _, ak := range attrKeys { - av := attributes[ak] - buf.WriteString(fmt.Sprintf(" %s = %s\n", ak, av)) - } - - // CAUTION: Since deposed keys are now random strings instead of - // incrementing integers, this result will not be deterministic - // if there is more than one deposed object. - i := 1 - for _, t := range is.Deposed { - id := LegacyInstanceObjectID(t) - taintStr := "" - if t.Status == ObjectTainted { - taintStr = " (tainted)" - } - buf.WriteString(fmt.Sprintf(" Deposed ID %d = %s%s\n", i, id, taintStr)) - i++ - } - - if obj := is.Current; obj != nil && len(obj.Dependencies) > 0 { - buf.WriteString(fmt.Sprintf("\n Dependencies:\n")) - for _, dep := range obj.Dependencies { - buf.WriteString(fmt.Sprintf(" %s\n", dep.String())) - } - } - } - - if len(m.OutputValues) > 0 { - buf.WriteString("\nOutputs:\n\n") - - ks := make([]string, 0, len(m.OutputValues)) - for k := range m.OutputValues { - ks = append(ks, k) - } - sort.Strings(ks) - - for _, k := range ks { - v := m.OutputValues[k] - lv := hcl2shim.ConfigValueFromHCL2(v.Value) - switch vTyped := lv.(type) { - case string: - buf.WriteString(fmt.Sprintf("%s = %s\n", k, vTyped)) - case []interface{}: - buf.WriteString(fmt.Sprintf("%s = %s\n", k, vTyped)) - case map[string]interface{}: - var mapKeys []string - for key := range vTyped { - mapKeys = append(mapKeys, key) - } - sort.Strings(mapKeys) - - var mapBuf bytes.Buffer - mapBuf.WriteString("{") - for _, key := range mapKeys { - mapBuf.WriteString(fmt.Sprintf("%s:%s ", key, vTyped[key])) - } - mapBuf.WriteString("}") - - buf.WriteString(fmt.Sprintf("%s = %s\n", k, mapBuf.String())) - default: - buf.WriteString(fmt.Sprintf("%s = %#v\n", k, lv)) - } - } - } - - return buf.String() -} - -// LegacyInstanceObjectID is a helper for extracting an object id value from -// an instance object in a way that approximates how we used to do this -// for the old state types. ID is no longer first-class, so this is preserved -// only for compatibility with old tests that include the id as part of their -// expected value. -func LegacyInstanceObjectID(obj *ResourceInstanceObjectSrc) string { - if obj == nil { - return "" - } - - if obj.AttrsJSON != nil { - type WithID struct { - ID string `json:"id"` - } - var withID WithID - err := json.Unmarshal(obj.AttrsJSON, &withID) - if err == nil { - return withID.ID - } - } else if obj.AttrsFlat != nil { - if flatID, exists := obj.AttrsFlat["id"]; exists { - return flatID - } - } - - // For resource types created after we removed id as special there may - // not actually be one at all. This is okay because older tests won't - // encounter this, and new tests shouldn't be using ids. - return "" -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/diagnostics.go b/vendor/github.com/hashicorp/terraform/states/statefile/diagnostics.go deleted file mode 100644 index a6d88ecd..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/diagnostics.go +++ /dev/null @@ -1,62 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - - "github.com/hashicorp/terraform/tfdiags" -) - -const invalidFormat = "Invalid state file format" - -// jsonUnmarshalDiags is a helper that translates errors returned from -// json.Unmarshal into hopefully-more-helpful diagnostics messages. -func jsonUnmarshalDiags(err error) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - if err == nil { - return diags - } - - switch tErr := err.(type) { - case *json.SyntaxError: - // We've usually already successfully parsed a source file as JSON at - // least once before we'd use jsonUnmarshalDiags with it (to sniff - // the version number) so this particular error should not appear much - // in practice. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - invalidFormat, - fmt.Sprintf("The state file could not be parsed as JSON: syntax error at byte offset %d.", tErr.Offset), - )) - case *json.UnmarshalTypeError: - // This is likely to be the most common area, describing a - // non-conformance between the file and the expected file format - // at a semantic level. - if tErr.Field != "" { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - invalidFormat, - fmt.Sprintf("The state file field %q has invalid value %s", tErr.Field, tErr.Value), - )) - break - } else { - // Without a field name, we can't really say anything helpful. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - invalidFormat, - "The state file does not conform to the expected JSON data structure.", - )) - } - default: - // Fallback for all other types of errors. This can happen only for - // custom UnmarshalJSON implementations, so should be encountered - // only rarely. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - invalidFormat, - fmt.Sprintf("The state file does not conform to the expected JSON data structure: %s.", err.Error()), - )) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/doc.go b/vendor/github.com/hashicorp/terraform/states/statefile/doc.go deleted file mode 100644 index 625d0cf4..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package statefile deals with the file format used to serialize states for -// persistent storage and then deserialize them into memory again later. -package statefile diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/file.go b/vendor/github.com/hashicorp/terraform/states/statefile/file.go deleted file mode 100644 index 6e202401..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/file.go +++ /dev/null @@ -1,62 +0,0 @@ -package statefile - -import ( - version "github.com/hashicorp/go-version" - - "github.com/hashicorp/terraform/states" - tfversion "github.com/hashicorp/terraform/version" -) - -// File is the in-memory representation of a state file. It includes the state -// itself along with various metadata used to track changing state files for -// the same configuration over time. -type File struct { - // TerraformVersion is the version of Terraform that wrote this state file. - TerraformVersion *version.Version - - // Serial is incremented on any operation that modifies - // the State file. It is used to detect potentially conflicting - // updates. - Serial uint64 - - // Lineage is set when a new, blank state file is created and then - // never updated. This allows us to determine whether the serials - // of two states can be meaningfully compared. - // Apart from the guarantee that collisions between two lineages - // are very unlikely, this value is opaque and external callers - // should only compare lineage strings byte-for-byte for equality. - Lineage string - - // State is the actual state represented by this file. - State *states.State -} - -func New(state *states.State, lineage string, serial uint64) *File { - // To make life easier on callers, we'll accept a nil state here and just - // allocate an empty one, which is required for this file to be successfully - // written out. - if state == nil { - state = states.NewState() - } - - return &File{ - TerraformVersion: tfversion.SemVer, - State: state, - Lineage: lineage, - Serial: serial, - } -} - -// DeepCopy is a convenience method to create a new File object whose state -// is a deep copy of the receiver's, as implemented by states.State.DeepCopy. -func (f *File) DeepCopy() *File { - if f == nil { - return nil - } - return &File{ - TerraformVersion: f.TerraformVersion, - Serial: f.Serial, - Lineage: f.Lineage, - State: f.State.DeepCopy(), - } -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/marshal_equal.go b/vendor/github.com/hashicorp/terraform/states/statefile/marshal_equal.go deleted file mode 100644 index 4948b39b..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/marshal_equal.go +++ /dev/null @@ -1,40 +0,0 @@ -package statefile - -import ( - "bytes" - - "github.com/hashicorp/terraform/states" -) - -// StatesMarshalEqual returns true if and only if the two given states have -// an identical (byte-for-byte) statefile representation. -// -// This function compares only the portions of the state that are persisted -// in state files, so for example it will not return false if the only -// differences between the two states are local values or descendent module -// outputs. -func StatesMarshalEqual(a, b *states.State) bool { - var aBuf bytes.Buffer - var bBuf bytes.Buffer - - // nil states are not valid states, and so they can never martial equal. - if a == nil || b == nil { - return false - } - - // We write here some temporary files that have no header information - // populated, thus ensuring that we're only comparing the state itself - // and not any metadata. - err := Write(&File{State: a}, &aBuf) - if err != nil { - // Should never happen, because we're writing to an in-memory buffer - panic(err) - } - err = Write(&File{State: b}, &bBuf) - if err != nil { - // Should never happen, because we're writing to an in-memory buffer - panic(err) - } - - return bytes.Equal(aBuf.Bytes(), bBuf.Bytes()) -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/read.go b/vendor/github.com/hashicorp/terraform/states/statefile/read.go deleted file mode 100644 index d691c029..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/read.go +++ /dev/null @@ -1,209 +0,0 @@ -package statefile - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - - version "github.com/hashicorp/go-version" - - "github.com/hashicorp/terraform/tfdiags" - tfversion "github.com/hashicorp/terraform/version" -) - -// ErrNoState is returned by ReadState when the state file is empty. -var ErrNoState = errors.New("no state") - -// Read reads a state from the given reader. -// -// Legacy state format versions 1 through 3 are supported, but the result will -// contain object attributes in the deprecated "flatmap" format and so must -// be upgraded by the caller before use. -// -// If the state file is empty, the special error value ErrNoState is returned. -// Otherwise, the returned error might be a wrapper around tfdiags.Diagnostics -// potentially describing multiple errors. -func Read(r io.Reader) (*File, error) { - // Some callers provide us a "typed nil" *os.File here, which would - // cause us to panic below if we tried to use it. - if f, ok := r.(*os.File); ok && f == nil { - return nil, ErrNoState - } - - var diags tfdiags.Diagnostics - - // We actually just buffer the whole thing in memory, because states are - // generally not huge and we need to do be able to sniff for a version - // number before full parsing. - src, err := ioutil.ReadAll(r) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to read state file", - fmt.Sprintf("The state file could not be read: %s", err), - )) - return nil, diags.Err() - } - - if len(src) == 0 { - return nil, ErrNoState - } - - state, diags := readState(src) - if diags.HasErrors() { - return nil, diags.Err() - } - - if state == nil { - // Should never happen - panic("readState returned nil state with no errors") - } - - if state.TerraformVersion != nil && state.TerraformVersion.GreaterThan(tfversion.SemVer) { - return state, fmt.Errorf( - "state snapshot was created by Terraform v%s, which is newer than current v%s; upgrade to Terraform v%s or greater to work with this state", - state.TerraformVersion, - tfversion.SemVer, - state.TerraformVersion, - ) - } - - return state, diags.Err() -} - -func readState(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - if looksLikeVersion0(src) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - "The state is stored in a legacy binary format that is not supported since Terraform v0.7. To continue, first upgrade the state using Terraform 0.6.16 or earlier.", - )) - return nil, diags - } - - version, versionDiags := sniffJSONStateVersion(src) - diags = diags.Append(versionDiags) - if versionDiags.HasErrors() { - return nil, diags - } - - switch version { - case 0: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - "The state file uses JSON syntax but has a version number of zero. There was never a JSON-based state format zero, so this state file is invalid and cannot be processed.", - )) - return nil, diags - case 1: - return readStateV1(src) - case 2: - return readStateV2(src) - case 3: - return readStateV3(src) - case 4: - return readStateV4(src) - default: - thisVersion := tfversion.SemVer.String() - creatingVersion := sniffJSONStateTerraformVersion(src) - switch { - case creatingVersion != "": - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - fmt.Sprintf("The state file uses format version %d, which is not supported by Terraform %s. This state file was created by Terraform %s.", version, thisVersion, creatingVersion), - )) - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - fmt.Sprintf("The state file uses format version %d, which is not supported by Terraform %s. This state file may have been created by a newer version of Terraform.", version, thisVersion), - )) - } - return nil, diags - } -} - -func sniffJSONStateVersion(src []byte) (uint64, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - type VersionSniff struct { - Version *uint64 `json:"version"` - } - var sniff VersionSniff - err := json.Unmarshal(src, &sniff) - if err != nil { - switch tErr := err.(type) { - case *json.SyntaxError: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - fmt.Sprintf("The state file could not be parsed as JSON: syntax error at byte offset %d.", tErr.Offset), - )) - case *json.UnmarshalTypeError: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - fmt.Sprintf("The version in the state file is %s. A positive whole number is required.", tErr.Value), - )) - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - "The state file could not be parsed as JSON.", - )) - } - } - - if sniff.Version == nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - "The state file does not have a \"version\" attribute, which is required to identify the format version.", - )) - return 0, diags - } - - return *sniff.Version, diags -} - -// sniffJSONStateTerraformVersion attempts to sniff the Terraform version -// specification from the given state file source code. The result is either -// a version string or an empty string if no version number could be extracted. -// -// This is a best-effort function intended to produce nicer error messages. It -// should not be used for any real processing. -func sniffJSONStateTerraformVersion(src []byte) string { - type VersionSniff struct { - Version string `json:"terraform_version"` - } - var sniff VersionSniff - - err := json.Unmarshal(src, &sniff) - if err != nil { - return "" - } - - // Attempt to parse the string as a version so we won't report garbage - // as a version number. - _, err = version.NewVersion(sniff.Version) - if err != nil { - return "" - } - - return sniff.Version -} - -// unsupportedFormat is a diagnostic summary message for when the state file -// seems to not be a state file at all, or is not a supported version. -// -// Use invalidFormat instead for the subtly-different case of "this looks like -// it's intended to be a state file but it's not structured correctly". -const unsupportedFormat = "Unsupported state file format" - -const upgradeFailed = "State format upgrade failed" diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/version0.go b/vendor/github.com/hashicorp/terraform/states/statefile/version0.go deleted file mode 100644 index 9b533317..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/version0.go +++ /dev/null @@ -1,23 +0,0 @@ -package statefile - -// looksLikeVersion0 sniffs for the signature indicating a version 0 state -// file. -// -// Version 0 was the number retroactively assigned to Terraform's initial -// (unversioned) binary state file format, which was later superseded by the -// version 1 format in JSON. -// -// Version 0 is no longer supported, so this is used only to detect it and -// return a nice error to the user. -func looksLikeVersion0(src []byte) bool { - // Version 0 files begin with the magic prefix "tfstate". - const magic = "tfstate" - if len(src) < len(magic) { - // Not even long enough to have the magic prefix - return false - } - if string(src[0:len(magic)]) == magic { - return true - } - return false -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/version1.go b/vendor/github.com/hashicorp/terraform/states/statefile/version1.go deleted file mode 100644 index 80d711bc..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/version1.go +++ /dev/null @@ -1,174 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - - "github.com/hashicorp/terraform/tfdiags" -) - -func readStateV1(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV1 := &stateV1{} - err := json.Unmarshal(src, sV1) - if err != nil { - diags = diags.Append(jsonUnmarshalDiags(err)) - return nil, diags - } - - file, prepDiags := prepareStateV1(sV1) - diags = diags.Append(prepDiags) - return file, diags -} - -func prepareStateV1(sV1 *stateV1) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV2, err := upgradeStateV1ToV2(sV1) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - upgradeFailed, - fmt.Sprintf("Error upgrading state file format from version 1 to version 2: %s.", err), - )) - return nil, diags - } - - file, prepDiags := prepareStateV2(sV2) - diags = diags.Append(prepDiags) - return file, diags -} - -// stateV1 is a representation of the legacy JSON state format version 1. -// -// It is only used to read version 1 JSON files prior to upgrading them to -// the current format. -type stateV1 struct { - // Version is the protocol version. "1" for a StateV1. - Version int `json:"version"` - - // Serial is incremented on any operation that modifies - // the State file. It is used to detect potentially conflicting - // updates. - Serial int64 `json:"serial"` - - // Remote is used to track the metadata required to - // pull and push state files from a remote storage endpoint. - Remote *remoteStateV1 `json:"remote,omitempty"` - - // Modules contains all the modules in a breadth-first order - Modules []*moduleStateV1 `json:"modules"` -} - -type remoteStateV1 struct { - // Type controls the client we use for the remote state - Type string `json:"type"` - - // Config is used to store arbitrary configuration that - // is type specific - Config map[string]string `json:"config"` -} - -type moduleStateV1 struct { - // Path is the import path from the root module. Modules imports are - // always disjoint, so the path represents amodule tree - Path []string `json:"path"` - - // Outputs declared by the module and maintained for each module - // even though only the root module technically needs to be kept. - // This allows operators to inspect values at the boundaries. - Outputs map[string]string `json:"outputs"` - - // Resources is a mapping of the logically named resource to - // the state of the resource. Each resource may actually have - // N instances underneath, although a user only needs to think - // about the 1:1 case. - Resources map[string]*resourceStateV1 `json:"resources"` - - // Dependencies are a list of things that this module relies on - // existing to remain intact. For example: an module may depend - // on a VPC ID given by an aws_vpc resource. - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a module that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on,omitempty"` -} - -type resourceStateV1 struct { - // This is filled in and managed by Terraform, and is the resource - // type itself such as "mycloud_instance". If a resource provider sets - // this value, it won't be persisted. - Type string `json:"type"` - - // Dependencies are a list of things that this resource relies on - // existing to remain intact. For example: an AWS instance might - // depend on a subnet (which itself might depend on a VPC, and so - // on). - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a resource that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on,omitempty"` - - // Primary is the current active instance for this resource. - // It can be replaced but only after a successful creation. - // This is the instances on which providers will act. - Primary *instanceStateV1 `json:"primary"` - - // Tainted is used to track any underlying instances that - // have been created but are in a bad or unknown state and - // need to be cleaned up subsequently. In the - // standard case, there is only at most a single instance. - // However, in pathological cases, it is possible for the number - // of instances to accumulate. - Tainted []*instanceStateV1 `json:"tainted,omitempty"` - - // Deposed is used in the mechanics of CreateBeforeDestroy: the existing - // Primary is Deposed to get it out of the way for the replacement Primary to - // be created by Apply. If the replacement Primary creates successfully, the - // Deposed instance is cleaned up. If there were problems creating the - // replacement, the instance remains in the Deposed list so it can be - // destroyed in a future run. Functionally, Deposed instances are very - // similar to Tainted instances in that Terraform is only tracking them in - // order to remember to destroy them. - Deposed []*instanceStateV1 `json:"deposed,omitempty"` - - // Provider is used when a resource is connected to a provider with an alias. - // If this string is empty, the resource is connected to the default provider, - // e.g. "aws_instance" goes with the "aws" provider. - // If the resource block contained a "provider" key, that value will be set here. - Provider string `json:"provider,omitempty"` -} - -type instanceStateV1 struct { - // A unique ID for this resource. This is opaque to Terraform - // and is only meant as a lookup mechanism for the providers. - ID string `json:"id"` - - // Attributes are basic information about the resource. Any keys here - // are accessible in variable format within Terraform configurations: - // ${resourcetype.name.attribute}. - Attributes map[string]string `json:"attributes,omitempty"` - - // Meta is a simple K/V map that is persisted to the State but otherwise - // ignored by Terraform core. It's meant to be used for accounting by - // external client code. - Meta map[string]string `json:"meta,omitempty"` -} - -type ephemeralStateV1 struct { - // ConnInfo is used for the providers to export information which is - // used to connect to the resource for provisioning. For example, - // this could contain SSH or WinRM credentials. - ConnInfo map[string]string `json:"-"` -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/version1_upgrade.go b/vendor/github.com/hashicorp/terraform/states/statefile/version1_upgrade.go deleted file mode 100644 index 0b417e1c..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/version1_upgrade.go +++ /dev/null @@ -1,172 +0,0 @@ -package statefile - -import ( - "fmt" - "log" - - "github.com/mitchellh/copystructure" -) - -// upgradeStateV1ToV2 is used to upgrade a V1 state representation -// into a V2 state representation -func upgradeStateV1ToV2(old *stateV1) (*stateV2, error) { - log.Printf("[TRACE] statefile.Read: upgrading format from v1 to v2") - if old == nil { - return nil, nil - } - - remote, err := old.Remote.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading State V1: %v", err) - } - - modules := make([]*moduleStateV2, len(old.Modules)) - for i, module := range old.Modules { - upgraded, err := module.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading State V1: %v", err) - } - modules[i] = upgraded - } - if len(modules) == 0 { - modules = nil - } - - newState := &stateV2{ - Version: 2, - Serial: old.Serial, - Remote: remote, - Modules: modules, - } - - return newState, nil -} - -func (old *remoteStateV1) upgradeToV2() (*remoteStateV2, error) { - if old == nil { - return nil, nil - } - - config, err := copystructure.Copy(old.Config) - if err != nil { - return nil, fmt.Errorf("Error upgrading RemoteState V1: %v", err) - } - - return &remoteStateV2{ - Type: old.Type, - Config: config.(map[string]string), - }, nil -} - -func (old *moduleStateV1) upgradeToV2() (*moduleStateV2, error) { - if old == nil { - return nil, nil - } - - pathRaw, err := copystructure.Copy(old.Path) - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - path, ok := pathRaw.([]string) - if !ok { - return nil, fmt.Errorf("Error upgrading ModuleState V1: path is not a list of strings") - } - if len(path) == 0 { - // We found some V1 states with a nil path. Assume root. - path = []string{"root"} - } - - // Outputs needs upgrading to use the new structure - outputs := make(map[string]*outputStateV2) - for key, output := range old.Outputs { - outputs[key] = &outputStateV2{ - Type: "string", - Value: output, - Sensitive: false, - } - } - - resources := make(map[string]*resourceStateV2) - for key, oldResource := range old.Resources { - upgraded, err := oldResource.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - resources[key] = upgraded - } - - dependencies, err := copystructure.Copy(old.Dependencies) - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - - return &moduleStateV2{ - Path: path, - Outputs: outputs, - Resources: resources, - Dependencies: dependencies.([]string), - }, nil -} - -func (old *resourceStateV1) upgradeToV2() (*resourceStateV2, error) { - if old == nil { - return nil, nil - } - - dependencies, err := copystructure.Copy(old.Dependencies) - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - - primary, err := old.Primary.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - - deposed := make([]*instanceStateV2, len(old.Deposed)) - for i, v := range old.Deposed { - upgraded, err := v.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - deposed[i] = upgraded - } - if len(deposed) == 0 { - deposed = nil - } - - return &resourceStateV2{ - Type: old.Type, - Dependencies: dependencies.([]string), - Primary: primary, - Deposed: deposed, - Provider: old.Provider, - }, nil -} - -func (old *instanceStateV1) upgradeToV2() (*instanceStateV2, error) { - if old == nil { - return nil, nil - } - - attributes, err := copystructure.Copy(old.Attributes) - if err != nil { - return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) - } - - meta, err := copystructure.Copy(old.Meta) - if err != nil { - return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) - } - - newMeta := make(map[string]interface{}) - for k, v := range meta.(map[string]string) { - newMeta[k] = v - } - - return &instanceStateV2{ - ID: old.ID, - Attributes: attributes.(map[string]string), - Meta: newMeta, - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/version2.go b/vendor/github.com/hashicorp/terraform/states/statefile/version2.go deleted file mode 100644 index 6fe2ab8e..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/version2.go +++ /dev/null @@ -1,209 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - "sync" - - "github.com/hashicorp/terraform/tfdiags" -) - -func readStateV2(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV2 := &stateV2{} - err := json.Unmarshal(src, sV2) - if err != nil { - diags = diags.Append(jsonUnmarshalDiags(err)) - return nil, diags - } - - file, prepDiags := prepareStateV2(sV2) - diags = diags.Append(prepDiags) - return file, diags -} - -func prepareStateV2(sV2 *stateV2) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV3, err := upgradeStateV2ToV3(sV2) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - upgradeFailed, - fmt.Sprintf("Error upgrading state file format from version 2 to version 3: %s.", err), - )) - return nil, diags - } - - file, prepDiags := prepareStateV3(sV3) - diags = diags.Append(prepDiags) - return file, diags -} - -// stateV2 is a representation of the legacy JSON state format version 2. -// -// It is only used to read version 2 JSON files prior to upgrading them to -// the current format. -type stateV2 struct { - // Version is the state file protocol version. - Version int `json:"version"` - - // TFVersion is the version of Terraform that wrote this state. - TFVersion string `json:"terraform_version,omitempty"` - - // Serial is incremented on any operation that modifies - // the State file. It is used to detect potentially conflicting - // updates. - Serial int64 `json:"serial"` - - // Lineage is set when a new, blank state is created and then - // never updated. This allows us to determine whether the serials - // of two states can be meaningfully compared. - // Apart from the guarantee that collisions between two lineages - // are very unlikely, this value is opaque and external callers - // should only compare lineage strings byte-for-byte for equality. - Lineage string `json:"lineage"` - - // Remote is used to track the metadata required to - // pull and push state files from a remote storage endpoint. - Remote *remoteStateV2 `json:"remote,omitempty"` - - // Backend tracks the configuration for the backend in use with - // this state. This is used to track any changes in the backend - // configuration. - Backend *backendStateV2 `json:"backend,omitempty"` - - // Modules contains all the modules in a breadth-first order - Modules []*moduleStateV2 `json:"modules"` -} - -type remoteStateV2 struct { - // Type controls the client we use for the remote state - Type string `json:"type"` - - // Config is used to store arbitrary configuration that - // is type specific - Config map[string]string `json:"config"` -} - -type outputStateV2 struct { - // Sensitive describes whether the output is considered sensitive, - // which may lead to masking the value on screen in some cases. - Sensitive bool `json:"sensitive"` - // Type describes the structure of Value. Valid values are "string", - // "map" and "list" - Type string `json:"type"` - // Value contains the value of the output, in the structure described - // by the Type field. - Value interface{} `json:"value"` - - mu sync.Mutex -} - -type moduleStateV2 struct { - // Path is the import path from the root module. Modules imports are - // always disjoint, so the path represents amodule tree - Path []string `json:"path"` - - // Locals are kept only transiently in-memory, because we can always - // re-compute them. - Locals map[string]interface{} `json:"-"` - - // Outputs declared by the module and maintained for each module - // even though only the root module technically needs to be kept. - // This allows operators to inspect values at the boundaries. - Outputs map[string]*outputStateV2 `json:"outputs"` - - // Resources is a mapping of the logically named resource to - // the state of the resource. Each resource may actually have - // N instances underneath, although a user only needs to think - // about the 1:1 case. - Resources map[string]*resourceStateV2 `json:"resources"` - - // Dependencies are a list of things that this module relies on - // existing to remain intact. For example: an module may depend - // on a VPC ID given by an aws_vpc resource. - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a module that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on"` -} - -type resourceStateV2 struct { - // This is filled in and managed by Terraform, and is the resource - // type itself such as "mycloud_instance". If a resource provider sets - // this value, it won't be persisted. - Type string `json:"type"` - - // Dependencies are a list of things that this resource relies on - // existing to remain intact. For example: an AWS instance might - // depend on a subnet (which itself might depend on a VPC, and so - // on). - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a resource that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on"` - - // Primary is the current active instance for this resource. - // It can be replaced but only after a successful creation. - // This is the instances on which providers will act. - Primary *instanceStateV2 `json:"primary"` - - // Deposed is used in the mechanics of CreateBeforeDestroy: the existing - // Primary is Deposed to get it out of the way for the replacement Primary to - // be created by Apply. If the replacement Primary creates successfully, the - // Deposed instance is cleaned up. - // - // If there were problems creating the replacement Primary, the Deposed - // instance and the (now tainted) replacement Primary will be swapped so the - // tainted replacement will be cleaned up instead. - // - // An instance will remain in the Deposed list until it is successfully - // destroyed and purged. - Deposed []*instanceStateV2 `json:"deposed"` - - // Provider is used when a resource is connected to a provider with an alias. - // If this string is empty, the resource is connected to the default provider, - // e.g. "aws_instance" goes with the "aws" provider. - // If the resource block contained a "provider" key, that value will be set here. - Provider string `json:"provider"` - - mu sync.Mutex -} - -type instanceStateV2 struct { - // A unique ID for this resource. This is opaque to Terraform - // and is only meant as a lookup mechanism for the providers. - ID string `json:"id"` - - // Attributes are basic information about the resource. Any keys here - // are accessible in variable format within Terraform configurations: - // ${resourcetype.name.attribute}. - Attributes map[string]string `json:"attributes"` - - // Meta is a simple K/V map that is persisted to the State but otherwise - // ignored by Terraform core. It's meant to be used for accounting by - // external client code. The value here must only contain Go primitives - // and collections. - Meta map[string]interface{} `json:"meta"` - - // Tainted is used to mark a resource for recreation. - Tainted bool `json:"tainted"` -} - -type backendStateV2 struct { - Type string `json:"type"` // Backend type - ConfigRaw json.RawMessage `json:"config"` // Backend raw config - Hash int `json:"hash"` // Hash of portion of configuration from config files -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/version2_upgrade.go b/vendor/github.com/hashicorp/terraform/states/statefile/version2_upgrade.go deleted file mode 100644 index 2d03c07c..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/version2_upgrade.go +++ /dev/null @@ -1,145 +0,0 @@ -package statefile - -import ( - "fmt" - "log" - "regexp" - "sort" - "strconv" - "strings" - - "github.com/mitchellh/copystructure" -) - -func upgradeStateV2ToV3(old *stateV2) (*stateV3, error) { - if old == nil { - return (*stateV3)(nil), nil - } - - var new *stateV3 - { - copy, err := copystructure.Config{Lock: true}.Copy(old) - if err != nil { - panic(err) - } - newWrongType := copy.(*stateV2) - newRightType := (stateV3)(*newWrongType) - new = &newRightType - } - - // Set the new version number - new.Version = 3 - - // Change the counts for things which look like maps to use the % - // syntax. Remove counts for empty collections - they will be added - // back in later. - for _, module := range new.Modules { - for _, resource := range module.Resources { - // Upgrade Primary - if resource.Primary != nil { - upgradeAttributesV2ToV3(resource.Primary) - } - - // Upgrade Deposed - for _, deposed := range resource.Deposed { - upgradeAttributesV2ToV3(deposed) - } - } - } - - return new, nil -} - -func upgradeAttributesV2ToV3(instanceState *instanceStateV2) error { - collectionKeyRegexp := regexp.MustCompile(`^(.*\.)#$`) - collectionSubkeyRegexp := regexp.MustCompile(`^([^\.]+)\..*`) - - // Identify the key prefix of anything which is a collection - var collectionKeyPrefixes []string - for key := range instanceState.Attributes { - if submatches := collectionKeyRegexp.FindAllStringSubmatch(key, -1); len(submatches) > 0 { - collectionKeyPrefixes = append(collectionKeyPrefixes, submatches[0][1]) - } - } - sort.Strings(collectionKeyPrefixes) - - log.Printf("[STATE UPGRADE] Detected the following collections in state: %v", collectionKeyPrefixes) - - // This could be rolled into fewer loops, but it is somewhat clearer this way, and will not - // run very often. - for _, prefix := range collectionKeyPrefixes { - // First get the actual keys that belong to this prefix - var potentialKeysMatching []string - for key := range instanceState.Attributes { - if strings.HasPrefix(key, prefix) { - potentialKeysMatching = append(potentialKeysMatching, strings.TrimPrefix(key, prefix)) - } - } - sort.Strings(potentialKeysMatching) - - var actualKeysMatching []string - for _, key := range potentialKeysMatching { - if submatches := collectionSubkeyRegexp.FindAllStringSubmatch(key, -1); len(submatches) > 0 { - actualKeysMatching = append(actualKeysMatching, submatches[0][1]) - } else { - if key != "#" { - actualKeysMatching = append(actualKeysMatching, key) - } - } - } - actualKeysMatching = uniqueSortedStrings(actualKeysMatching) - - // Now inspect the keys in order to determine whether this is most likely to be - // a map, list or set. There is room for error here, so we log in each case. If - // there is no method of telling, we remove the key from the InstanceState in - // order that it will be recreated. Again, this could be rolled into fewer loops - // but we prefer clarity. - - oldCountKey := fmt.Sprintf("%s#", prefix) - - // First, detect "obvious" maps - which have non-numeric keys (mostly). - hasNonNumericKeys := false - for _, key := range actualKeysMatching { - if _, err := strconv.Atoi(key); err != nil { - hasNonNumericKeys = true - } - } - if hasNonNumericKeys { - newCountKey := fmt.Sprintf("%s%%", prefix) - - instanceState.Attributes[newCountKey] = instanceState.Attributes[oldCountKey] - delete(instanceState.Attributes, oldCountKey) - log.Printf("[STATE UPGRADE] Detected %s as a map. Replaced count = %s", - strings.TrimSuffix(prefix, "."), instanceState.Attributes[newCountKey]) - } - - // Now detect empty collections and remove them from state. - if len(actualKeysMatching) == 0 { - delete(instanceState.Attributes, oldCountKey) - log.Printf("[STATE UPGRADE] Detected %s as an empty collection. Removed from state.", - strings.TrimSuffix(prefix, ".")) - } - } - - return nil -} - -// uniqueSortedStrings removes duplicates from a slice of strings and returns -// a sorted slice of the unique strings. -func uniqueSortedStrings(input []string) []string { - uniquemap := make(map[string]struct{}) - for _, str := range input { - uniquemap[str] = struct{}{} - } - - output := make([]string, len(uniquemap)) - - i := 0 - for key := range uniquemap { - output[i] = key - i = i + 1 - } - - sort.Strings(output) - return output -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/version3.go b/vendor/github.com/hashicorp/terraform/states/statefile/version3.go deleted file mode 100644 index ab6414b0..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/version3.go +++ /dev/null @@ -1,50 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - - "github.com/hashicorp/terraform/tfdiags" -) - -func readStateV3(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV3 := &stateV3{} - err := json.Unmarshal(src, sV3) - if err != nil { - diags = diags.Append(jsonUnmarshalDiags(err)) - return nil, diags - } - - file, prepDiags := prepareStateV3(sV3) - diags = diags.Append(prepDiags) - return file, diags -} - -func prepareStateV3(sV3 *stateV3) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV4, err := upgradeStateV3ToV4(sV3) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - upgradeFailed, - fmt.Sprintf("Error upgrading state file format from version 3 to version 4: %s.", err), - )) - return nil, diags - } - - file, prepDiags := prepareStateV4(sV4) - diags = diags.Append(prepDiags) - return file, diags -} - -// stateV2 is a representation of the legacy JSON state format version 3. -// -// It is only used to read version 3 JSON files prior to upgrading them to -// the current format. -// -// The differences between version 2 and version 3 are only in the data and -// not in the structure, so stateV3 actually shares the same structs as -// stateV2. Type stateV3 represents that the data within is formatted as -// expected by the V3 format, rather than the V2 format. -type stateV3 stateV2 diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/version3_upgrade.go b/vendor/github.com/hashicorp/terraform/states/statefile/version3_upgrade.go deleted file mode 100644 index 7ec1c946..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/version3_upgrade.go +++ /dev/null @@ -1,415 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" - - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" -) - -func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) { - - if old.Serial < 0 { - // The new format is using uint64 here, which should be fine for any - // real state (we only used positive integers in practice) but we'll - // catch this explicitly here to avoid weird behavior if a state file - // has been tampered with in some way. - return nil, fmt.Errorf("state has serial less than zero, which is invalid") - } - - new := &stateV4{ - TerraformVersion: old.TFVersion, - Serial: uint64(old.Serial), - Lineage: old.Lineage, - RootOutputs: map[string]outputStateV4{}, - Resources: []resourceStateV4{}, - } - - if new.TerraformVersion == "" { - // Older formats considered this to be optional, but now it's required - // and so we'll stub it out with something that's definitely older - // than the version that really created this state. - new.TerraformVersion = "0.0.0" - } - - for _, msOld := range old.Modules { - if len(msOld.Path) < 1 || msOld.Path[0] != "root" { - return nil, fmt.Errorf("state contains invalid module path %#v", msOld.Path) - } - - // Convert legacy-style module address into our newer address type. - // Since these old formats are only generated by versions of Terraform - // that don't support count and for_each on modules, we can just assume - // all of the modules are unkeyed. - moduleAddr := make(addrs.ModuleInstance, len(msOld.Path)-1) - for i, name := range msOld.Path[1:] { - moduleAddr[i] = addrs.ModuleInstanceStep{ - Name: name, - InstanceKey: addrs.NoKey, - } - } - - // In a v3 state file, a "resource state" is actually an instance - // state, so we need to fill in a missing level of heirarchy here - // by lazily creating resource states as we encounter them. - // We'll track them in here, keyed on the string representation of - // the resource address. - resourceStates := map[string]*resourceStateV4{} - - for legacyAddr, rsOld := range msOld.Resources { - instAddr, err := parseLegacyResourceAddress(legacyAddr) - if err != nil { - return nil, err - } - - resAddr := instAddr.Resource - rs, exists := resourceStates[resAddr.String()] - if !exists { - var modeStr string - switch resAddr.Mode { - case addrs.ManagedResourceMode: - modeStr = "managed" - case addrs.DataResourceMode: - modeStr = "data" - default: - return nil, fmt.Errorf("state contains resource %s with an unsupported resource mode", resAddr) - } - - // In state versions prior to 4 we allowed each instance of a - // resource to have its own provider configuration address, - // which makes no real sense in practice because providers - // are associated with resources in the configuration. We - // elevate that to the resource level during this upgrade, - // implicitly taking the provider address of the first instance - // we encounter for each resource. While this is lossy in - // theory, in practice there is no reason for these values to - // differ between instances. - var providerAddr addrs.AbsProviderConfig - oldProviderAddr := rsOld.Provider - if strings.Contains(oldProviderAddr, "provider.") { - // Smells like a new-style provider address, but we'll test it. - var diags tfdiags.Diagnostics - providerAddr, diags = addrs.ParseAbsProviderConfigStr(oldProviderAddr) - if diags.HasErrors() { - return nil, diags.Err() - } - } else { - // Smells like an old-style module-local provider address, - // which we'll need to migrate. We'll assume it's referring - // to the same module the resource is in, which might be - // incorrect but it'll get fixed up next time any updates - // are made to an instance. - if oldProviderAddr != "" { - localAddr, diags := addrs.ParseProviderConfigCompactStr(oldProviderAddr) - if diags.HasErrors() { - return nil, diags.Err() - } - providerAddr = localAddr.Absolute(moduleAddr) - } else { - providerAddr = resAddr.DefaultProviderConfig().Absolute(moduleAddr) - } - } - - rs = &resourceStateV4{ - Module: moduleAddr.String(), - Mode: modeStr, - Type: resAddr.Type, - Name: resAddr.Name, - Instances: []instanceObjectStateV4{}, - ProviderConfig: providerAddr.String(), - } - resourceStates[resAddr.String()] = rs - } - - // Now we'll deal with the instance itself, which may either be - // the first instance in a resource we just created or an additional - // instance for a resource added on a prior loop. - instKey := instAddr.Key - if isOld := rsOld.Primary; isOld != nil { - isNew, err := upgradeInstanceObjectV3ToV4(rsOld, isOld, instKey, states.NotDeposed) - if err != nil { - return nil, fmt.Errorf("failed to migrate primary generation of %s: %s", instAddr, err) - } - rs.Instances = append(rs.Instances, *isNew) - } - for i, isOld := range rsOld.Deposed { - // When we migrate old instances we'll use sequential deposed - // keys just so that the upgrade result is deterministic. New - // deposed keys allocated moving forward will be pseudorandomly - // selected, but we check for collisions and so these - // non-random ones won't hurt. - deposedKey := states.DeposedKey(fmt.Sprintf("%08x", i+1)) - isNew, err := upgradeInstanceObjectV3ToV4(rsOld, isOld, instKey, deposedKey) - if err != nil { - return nil, fmt.Errorf("failed to migrate deposed generation index %d of %s: %s", i, instAddr, err) - } - rs.Instances = append(rs.Instances, *isNew) - } - - if instKey != addrs.NoKey && rs.EachMode == "" { - rs.EachMode = "list" - } - } - - for _, rs := range resourceStates { - new.Resources = append(new.Resources, *rs) - } - - if len(msOld.Path) == 1 && msOld.Path[0] == "root" { - // We'll migrate the outputs for this module too, then. - for name, oldOS := range msOld.Outputs { - newOS := outputStateV4{ - Sensitive: oldOS.Sensitive, - } - - valRaw := oldOS.Value - valSrc, err := json.Marshal(valRaw) - if err != nil { - // Should never happen, because this value came from JSON - // in the first place and so we're just round-tripping here. - return nil, fmt.Errorf("failed to serialize output %q value as JSON: %s", name, err) - } - - // The "type" field in state V2 wasn't really that useful - // since it was only able to capture string vs. list vs. map. - // For this reason, during upgrade we'll just discard it - // altogether and use cty's idea of the implied type of - // turning our old value into JSON. - ty, err := ctyjson.ImpliedType(valSrc) - if err != nil { - // REALLY should never happen, because we literally just - // encoded this as JSON above! - return nil, fmt.Errorf("failed to parse output %q value from JSON: %s", name, err) - } - - // ImpliedType tends to produce structural types, but since older - // version of Terraform didn't support those a collection type - // is probably what was intended, so we'll see if we can - // interpret our value as one. - ty = simplifyImpliedValueType(ty) - - tySrc, err := ctyjson.MarshalType(ty) - if err != nil { - return nil, fmt.Errorf("failed to serialize output %q type as JSON: %s", name, err) - } - - newOS.ValueRaw = json.RawMessage(valSrc) - newOS.ValueTypeRaw = json.RawMessage(tySrc) - - new.RootOutputs[name] = newOS - } - } - } - - new.normalize() - - return new, nil -} - -func upgradeInstanceObjectV3ToV4(rsOld *resourceStateV2, isOld *instanceStateV2, instKey addrs.InstanceKey, deposedKey states.DeposedKey) (*instanceObjectStateV4, error) { - - // Schema versions were, in prior formats, a private concern of the provider - // SDK, and not a first-class concept in the state format. Here we're - // sniffing for the pre-0.12 SDK's way of representing schema versions - // and promoting it to our first-class field if we find it. We'll ignore - // it if it doesn't look like what the SDK would've written. If this - // sniffing fails then we'll assume schema version 0. - var schemaVersion uint64 - migratedSchemaVersion := false - if raw, exists := isOld.Meta["schema_version"]; exists { - switch tv := raw.(type) { - case string: - v, err := strconv.ParseUint(tv, 10, 64) - if err == nil { - schemaVersion = v - migratedSchemaVersion = true - } - case int: - schemaVersion = uint64(tv) - migratedSchemaVersion = true - case float64: - schemaVersion = uint64(tv) - migratedSchemaVersion = true - } - } - - private := map[string]interface{}{} - for k, v := range isOld.Meta { - if k == "schema_version" && migratedSchemaVersion { - // We're gonna promote this into our first-class schema version field - continue - } - private[k] = v - } - var privateJSON []byte - if len(private) != 0 { - var err error - privateJSON, err = json.Marshal(private) - if err != nil { - // This shouldn't happen, because the Meta values all came from JSON - // originally anyway. - return nil, fmt.Errorf("cannot serialize private instance object data: %s", err) - } - } - - var status string - if isOld.Tainted { - status = "tainted" - } - - var instKeyRaw interface{} - switch tk := instKey.(type) { - case addrs.IntKey: - instKeyRaw = int(tk) - case addrs.StringKey: - instKeyRaw = string(tk) - default: - if instKeyRaw != nil { - return nil, fmt.Errorf("insupported instance key: %#v", instKey) - } - } - - var attributes map[string]string - if isOld.Attributes != nil { - attributes = make(map[string]string, len(isOld.Attributes)) - for k, v := range isOld.Attributes { - attributes[k] = v - } - } - if isOld.ID != "" { - // As a special case, if we don't already have an "id" attribute and - // yet there's a non-empty first-class ID on the old object then we'll - // create a synthetic id attribute to avoid losing that first-class id. - // In practice this generally arises only in tests where state literals - // are hand-written in a non-standard way; real code prior to 0.12 - // would always force the first-class ID to be copied into the - // id attribute before storing. - if attributes == nil { - attributes = make(map[string]string, len(isOld.Attributes)) - } - if idVal := attributes["id"]; idVal == "" { - attributes["id"] = isOld.ID - } - } - - dependencies := make([]string, len(rsOld.Dependencies)) - for i, v := range rsOld.Dependencies { - dependencies[i] = strings.TrimSuffix(v, ".*") - } - - return &instanceObjectStateV4{ - IndexKey: instKeyRaw, - Status: status, - Deposed: string(deposedKey), - AttributesFlat: attributes, - Dependencies: dependencies, - SchemaVersion: schemaVersion, - PrivateRaw: privateJSON, - }, nil -} - -// parseLegacyResourceAddress parses the different identifier format used -// state formats before version 4, like "instance.name.0". -func parseLegacyResourceAddress(s string) (addrs.ResourceInstance, error) { - var ret addrs.ResourceInstance - - // Split based on ".". Every resource address should have at least two - // elements (type and name). - parts := strings.Split(s, ".") - if len(parts) < 2 || len(parts) > 4 { - return ret, fmt.Errorf("invalid internal resource address format: %s", s) - } - - // Data resource if we have at least 3 parts and the first one is data - ret.Resource.Mode = addrs.ManagedResourceMode - if len(parts) > 2 && parts[0] == "data" { - ret.Resource.Mode = addrs.DataResourceMode - parts = parts[1:] - } - - // If we're not a data resource and we have more than 3, then it is an error - if len(parts) > 3 && ret.Resource.Mode != addrs.DataResourceMode { - return ret, fmt.Errorf("invalid internal resource address format: %s", s) - } - - // Build the parts of the resource address that are guaranteed to exist - ret.Resource.Type = parts[0] - ret.Resource.Name = parts[1] - ret.Key = addrs.NoKey - - // If we have more parts, then we have an index. Parse that. - if len(parts) > 2 { - idx, err := strconv.ParseInt(parts[2], 0, 0) - if err != nil { - return ret, fmt.Errorf("error parsing resource address %q: %s", s, err) - } - - ret.Key = addrs.IntKey(idx) - } - - return ret, nil -} - -// simplifyImpliedValueType attempts to heuristically simplify a value type -// derived from a legacy stored output value into something simpler that -// is closer to what would've fitted into the pre-v0.12 value type system. -func simplifyImpliedValueType(ty cty.Type) cty.Type { - switch { - case ty.IsTupleType(): - // If all of the element types are the same then we'll make this - // a list instead. This is very likely to be true, since prior versions - // of Terraform did not officially support mixed-type collections. - - if ty.Equals(cty.EmptyTuple) { - // Don't know what the element type would be, then. - return ty - } - - etys := ty.TupleElementTypes() - ety := etys[0] - for _, other := range etys[1:] { - if !other.Equals(ety) { - // inconsistent types - return ty - } - } - ety = simplifyImpliedValueType(ety) - return cty.List(ety) - - case ty.IsObjectType(): - // If all of the attribute types are the same then we'll make this - // a map instead. This is very likely to be true, since prior versions - // of Terraform did not officially support mixed-type collections. - - if ty.Equals(cty.EmptyObject) { - // Don't know what the element type would be, then. - return ty - } - - atys := ty.AttributeTypes() - var ety cty.Type - for _, other := range atys { - if ety == cty.NilType { - ety = other - continue - } - if !other.Equals(ety) { - // inconsistent types - return ty - } - } - ety = simplifyImpliedValueType(ety) - return cty.Map(ety) - - default: - // No other normalizations are possible - return ty - } -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/version4.go b/vendor/github.com/hashicorp/terraform/states/statefile/version4.go deleted file mode 100644 index ee8b6523..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/version4.go +++ /dev/null @@ -1,604 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - "io" - "sort" - - version "github.com/hashicorp/go-version" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" -) - -func readStateV4(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV4 := &stateV4{} - err := json.Unmarshal(src, sV4) - if err != nil { - diags = diags.Append(jsonUnmarshalDiags(err)) - return nil, diags - } - - file, prepDiags := prepareStateV4(sV4) - diags = diags.Append(prepDiags) - return file, diags -} - -func prepareStateV4(sV4 *stateV4) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - var tfVersion *version.Version - if sV4.TerraformVersion != "" { - var err error - tfVersion, err = version.NewVersion(sV4.TerraformVersion) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid Terraform version string", - fmt.Sprintf("State file claims to have been written by Terraform version %q, which is not a valid version string.", sV4.TerraformVersion), - )) - } - } - - file := &File{ - TerraformVersion: tfVersion, - Serial: sV4.Serial, - Lineage: sV4.Lineage, - } - - state := states.NewState() - - for _, rsV4 := range sV4.Resources { - rAddr := addrs.Resource{ - Type: rsV4.Type, - Name: rsV4.Name, - } - switch rsV4.Mode { - case "managed": - rAddr.Mode = addrs.ManagedResourceMode - case "data": - rAddr.Mode = addrs.DataResourceMode - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource mode in state", - fmt.Sprintf("State contains a resource with mode %q (%q %q) which is not supported.", rsV4.Mode, rAddr.Type, rAddr.Name), - )) - continue - } - - moduleAddr := addrs.RootModuleInstance - if rsV4.Module != "" { - var addrDiags tfdiags.Diagnostics - moduleAddr, addrDiags = addrs.ParseModuleInstanceStr(rsV4.Module) - diags = diags.Append(addrDiags) - if addrDiags.HasErrors() { - continue - } - } - - providerAddr, addrDiags := addrs.ParseAbsProviderConfigStr(rsV4.ProviderConfig) - diags.Append(addrDiags) - if addrDiags.HasErrors() { - continue - } - - var eachMode states.EachMode - switch rsV4.EachMode { - case "": - eachMode = states.NoEach - case "list": - eachMode = states.EachList - case "map": - eachMode = states.EachMap - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource metadata in state", - fmt.Sprintf("Resource %s has invalid \"each\" value %q in state.", rAddr.Absolute(moduleAddr), eachMode), - )) - continue - } - - ms := state.EnsureModule(moduleAddr) - - // Ensure the resource container object is present in the state. - ms.SetResourceMeta(rAddr, eachMode, providerAddr) - - for _, isV4 := range rsV4.Instances { - keyRaw := isV4.IndexKey - var key addrs.InstanceKey - switch tk := keyRaw.(type) { - case int: - key = addrs.IntKey(tk) - case float64: - // Since JSON only has one number type, reading from encoding/json - // gives us a float64 here even if the number is whole. - // float64 has a smaller integer range than int, but in practice - // we rarely have more than a few tens of instances and so - // it's unlikely that we'll exhaust the 52 bits in a float64. - key = addrs.IntKey(int(tk)) - case string: - key = addrs.StringKey(tk) - default: - if keyRaw != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource instance metadata in state", - fmt.Sprintf("Resource %s has an instance with the invalid instance key %#v.", rAddr.Absolute(moduleAddr), keyRaw), - )) - continue - } - key = addrs.NoKey - } - - instAddr := rAddr.Instance(key) - - obj := &states.ResourceInstanceObjectSrc{ - SchemaVersion: isV4.SchemaVersion, - } - - { - // Instance attributes - switch { - case isV4.AttributesRaw != nil: - obj.AttrsJSON = isV4.AttributesRaw - case isV4.AttributesFlat != nil: - obj.AttrsFlat = isV4.AttributesFlat - default: - // This is odd, but we'll accept it and just treat the - // object has being empty. In practice this should arise - // only from the contrived sort of state objects we tend - // to hand-write inline in tests. - obj.AttrsJSON = []byte{'{', '}'} - } - } - - { - // Status - raw := isV4.Status - switch raw { - case "": - obj.Status = states.ObjectReady - case "tainted": - obj.Status = states.ObjectTainted - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource instance metadata in state", - fmt.Sprintf("Instance %s has invalid status %q.", instAddr.Absolute(moduleAddr), raw), - )) - continue - } - } - - if raw := isV4.PrivateRaw; len(raw) > 0 { - obj.Private = raw - } - - { - depsRaw := isV4.Dependencies - deps := make([]addrs.Referenceable, 0, len(depsRaw)) - for _, depRaw := range depsRaw { - ref, refDiags := addrs.ParseRefStr(depRaw) - diags = diags.Append(refDiags) - if refDiags.HasErrors() { - continue - } - if len(ref.Remaining) != 0 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource instance metadata in state", - fmt.Sprintf("Instance %s declares dependency on %q, which is not a reference to a dependable object.", instAddr.Absolute(moduleAddr), depRaw), - )) - } - if ref.Subject == nil { - // Should never happen - panic(fmt.Sprintf("parsing dependency %q for instance %s returned a nil address", depRaw, instAddr.Absolute(moduleAddr))) - } - deps = append(deps, ref.Subject) - } - obj.Dependencies = deps - } - - switch { - case isV4.Deposed != "": - dk := states.DeposedKey(isV4.Deposed) - if len(dk) != 8 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource instance metadata in state", - fmt.Sprintf("Instance %s has an object with deposed key %q, which is not correctly formatted.", instAddr.Absolute(moduleAddr), isV4.Deposed), - )) - continue - } - is := ms.ResourceInstance(instAddr) - if is.HasDeposed(dk) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Duplicate resource instance in state", - fmt.Sprintf("Instance %s deposed object %q appears multiple times in the state file.", instAddr.Absolute(moduleAddr), dk), - )) - continue - } - - ms.SetResourceInstanceDeposed(instAddr, dk, obj, providerAddr) - default: - is := ms.ResourceInstance(instAddr) - if is.HasCurrent() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Duplicate resource instance in state", - fmt.Sprintf("Instance %s appears multiple times in the state file.", instAddr.Absolute(moduleAddr)), - )) - continue - } - - ms.SetResourceInstanceCurrent(instAddr, obj, providerAddr) - } - } - - // We repeat this after creating the instances because - // SetResourceInstanceCurrent automatically resets this metadata based - // on the incoming objects. That behavior is useful when we're making - // piecemeal updates to the state during an apply, but when we're - // reading the state file we want to reflect its contents exactly. - ms.SetResourceMeta(rAddr, eachMode, providerAddr) - } - - // The root module is special in that we persist its attributes and thus - // need to reload them now. (For descendent modules we just re-calculate - // them based on the latest configuration on each run.) - { - rootModule := state.RootModule() - for name, fos := range sV4.RootOutputs { - os := &states.OutputValue{} - os.Sensitive = fos.Sensitive - - ty, err := ctyjson.UnmarshalType([]byte(fos.ValueTypeRaw)) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid output value type in state", - fmt.Sprintf("The state file has an invalid type specification for output %q: %s.", name, err), - )) - continue - } - - val, err := ctyjson.Unmarshal([]byte(fos.ValueRaw), ty) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid output value saved in state", - fmt.Sprintf("The state file has an invalid value for output %q: %s.", name, err), - )) - continue - } - - os.Value = val - rootModule.OutputValues[name] = os - } - } - - file.State = state - return file, diags -} - -func writeStateV4(file *File, w io.Writer) tfdiags.Diagnostics { - // Here we'll convert back from the "File" representation to our - // stateV4 struct representation and write that. - // - // While we support legacy state formats for reading, we only support the - // latest for writing and so if a V5 is added in future then this function - // should be deleted and replaced with a writeStateV5, even though the - // read/prepare V4 functions above would stick around. - - var diags tfdiags.Diagnostics - if file == nil || file.State == nil { - panic("attempt to write nil state to file") - } - - var terraformVersion string - if file.TerraformVersion != nil { - terraformVersion = file.TerraformVersion.String() - } - - sV4 := &stateV4{ - TerraformVersion: terraformVersion, - Serial: file.Serial, - Lineage: file.Lineage, - RootOutputs: map[string]outputStateV4{}, - Resources: []resourceStateV4{}, - } - - for name, os := range file.State.RootModule().OutputValues { - src, err := ctyjson.Marshal(os.Value, os.Value.Type()) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize output value in state", - fmt.Sprintf("An error occured while serializing output value %q: %s.", name, err), - )) - continue - } - - typeSrc, err := ctyjson.MarshalType(os.Value.Type()) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize output value in state", - fmt.Sprintf("An error occured while serializing the type of output value %q: %s.", name, err), - )) - continue - } - - sV4.RootOutputs[name] = outputStateV4{ - Sensitive: os.Sensitive, - ValueRaw: json.RawMessage(src), - ValueTypeRaw: json.RawMessage(typeSrc), - } - } - - for _, ms := range file.State.Modules { - moduleAddr := ms.Addr - for _, rs := range ms.Resources { - resourceAddr := rs.Addr - - var mode string - switch resourceAddr.Mode { - case addrs.ManagedResourceMode: - mode = "managed" - case addrs.DataResourceMode: - mode = "data" - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize resource in state", - fmt.Sprintf("Resource %s has mode %s, which cannot be serialized in state", resourceAddr.Absolute(moduleAddr), resourceAddr.Mode), - )) - continue - } - - var eachMode string - switch rs.EachMode { - case states.NoEach: - eachMode = "" - case states.EachList: - eachMode = "list" - case states.EachMap: - eachMode = "map" - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize resource in state", - fmt.Sprintf("Resource %s has \"each\" mode %s, which cannot be serialized in state", resourceAddr.Absolute(moduleAddr), rs.EachMode), - )) - continue - } - - sV4.Resources = append(sV4.Resources, resourceStateV4{ - Module: moduleAddr.String(), - Mode: mode, - Type: resourceAddr.Type, - Name: resourceAddr.Name, - EachMode: eachMode, - ProviderConfig: rs.ProviderConfig.String(), - Instances: []instanceObjectStateV4{}, - }) - rsV4 := &(sV4.Resources[len(sV4.Resources)-1]) - - for key, is := range rs.Instances { - if is.HasCurrent() { - var objDiags tfdiags.Diagnostics - rsV4.Instances, objDiags = appendInstanceObjectStateV4( - rs, is, key, is.Current, states.NotDeposed, - rsV4.Instances, - ) - diags = diags.Append(objDiags) - } - for dk, obj := range is.Deposed { - var objDiags tfdiags.Diagnostics - rsV4.Instances, objDiags = appendInstanceObjectStateV4( - rs, is, key, obj, dk, - rsV4.Instances, - ) - diags = diags.Append(objDiags) - } - } - } - } - - sV4.normalize() - - src, err := json.MarshalIndent(sV4, "", " ") - if err != nil { - // Shouldn't happen if we do our conversion to *stateV4 correctly above. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize state", - fmt.Sprintf("An error occured while serializing the state to save it. This is a bug in Terraform and should be reported: %s.", err), - )) - return diags - } - src = append(src, '\n') - - _, err = w.Write(src) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to write state", - fmt.Sprintf("An error occured while writing the serialized state: %s.", err), - )) - return diags - } - - return diags -} - -func appendInstanceObjectStateV4(rs *states.Resource, is *states.ResourceInstance, key addrs.InstanceKey, obj *states.ResourceInstanceObjectSrc, deposed states.DeposedKey, isV4s []instanceObjectStateV4) ([]instanceObjectStateV4, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - var status string - switch obj.Status { - case states.ObjectReady: - status = "" - case states.ObjectTainted: - status = "tainted" - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize resource instance in state", - fmt.Sprintf("Instance %s has status %s, which cannot be saved in state.", rs.Addr.Instance(key), obj.Status), - )) - } - - var privateRaw []byte - if len(obj.Private) > 0 { - privateRaw = obj.Private - } - - deps := make([]string, len(obj.Dependencies)) - for i, depAddr := range obj.Dependencies { - deps[i] = depAddr.String() - } - - var rawKey interface{} - switch tk := key.(type) { - case addrs.IntKey: - rawKey = int(tk) - case addrs.StringKey: - rawKey = string(tk) - default: - if key != addrs.NoKey { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize resource instance in state", - fmt.Sprintf("Instance %s has an unsupported instance key: %#v.", rs.Addr.Instance(key), key), - )) - } - } - - return append(isV4s, instanceObjectStateV4{ - IndexKey: rawKey, - Deposed: string(deposed), - Status: status, - SchemaVersion: obj.SchemaVersion, - AttributesFlat: obj.AttrsFlat, - AttributesRaw: obj.AttrsJSON, - PrivateRaw: privateRaw, - Dependencies: deps, - }), diags -} - -type stateV4 struct { - Version stateVersionV4 `json:"version"` - TerraformVersion string `json:"terraform_version"` - Serial uint64 `json:"serial"` - Lineage string `json:"lineage"` - RootOutputs map[string]outputStateV4 `json:"outputs"` - Resources []resourceStateV4 `json:"resources"` -} - -// normalize makes some in-place changes to normalize the way items are -// stored to ensure that two functionally-equivalent states will be stored -// identically. -func (s *stateV4) normalize() { - sort.Stable(sortResourcesV4(s.Resources)) - for _, rs := range s.Resources { - sort.Stable(sortInstancesV4(rs.Instances)) - } -} - -type outputStateV4 struct { - ValueRaw json.RawMessage `json:"value"` - ValueTypeRaw json.RawMessage `json:"type"` - Sensitive bool `json:"sensitive,omitempty"` -} - -type resourceStateV4 struct { - Module string `json:"module,omitempty"` - Mode string `json:"mode"` - Type string `json:"type"` - Name string `json:"name"` - EachMode string `json:"each,omitempty"` - ProviderConfig string `json:"provider"` - Instances []instanceObjectStateV4 `json:"instances"` -} - -type instanceObjectStateV4 struct { - IndexKey interface{} `json:"index_key,omitempty"` - Status string `json:"status,omitempty"` - Deposed string `json:"deposed,omitempty"` - - SchemaVersion uint64 `json:"schema_version"` - AttributesRaw json.RawMessage `json:"attributes,omitempty"` - AttributesFlat map[string]string `json:"attributes_flat,omitempty"` - - PrivateRaw []byte `json:"private,omitempty"` - - Dependencies []string `json:"depends_on,omitempty"` -} - -// stateVersionV4 is a weird special type we use to produce our hard-coded -// "version": 4 in the JSON serialization. -type stateVersionV4 struct{} - -func (sv stateVersionV4) MarshalJSON() ([]byte, error) { - return []byte{'4'}, nil -} - -func (sv stateVersionV4) UnmarshalJSON([]byte) error { - // Nothing to do: we already know we're version 4 - return nil -} - -type sortResourcesV4 []resourceStateV4 - -func (sr sortResourcesV4) Len() int { return len(sr) } -func (sr sortResourcesV4) Swap(i, j int) { sr[i], sr[j] = sr[j], sr[i] } -func (sr sortResourcesV4) Less(i, j int) bool { - switch { - case sr[i].Mode != sr[j].Mode: - return sr[i].Mode < sr[j].Mode - case sr[i].Type != sr[j].Type: - return sr[i].Type < sr[j].Type - case sr[i].Name != sr[j].Name: - return sr[i].Name < sr[j].Name - default: - return false - } -} - -type sortInstancesV4 []instanceObjectStateV4 - -func (si sortInstancesV4) Len() int { return len(si) } -func (si sortInstancesV4) Swap(i, j int) { si[i], si[j] = si[j], si[i] } -func (si sortInstancesV4) Less(i, j int) bool { - ki := si[i].IndexKey - kj := si[j].IndexKey - if ki != kj { - if (ki == nil) != (kj == nil) { - return ki == nil - } - if kii, isInt := ki.(int); isInt { - if kji, isInt := kj.(int); isInt { - return kii < kji - } - return true - } - if kis, isStr := ki.(string); isStr { - if kjs, isStr := kj.(string); isStr { - return kis < kjs - } - return true - } - } - if si[i].Deposed != si[j].Deposed { - return si[i].Deposed < si[j].Deposed - } - return false -} diff --git a/vendor/github.com/hashicorp/terraform/states/statefile/write.go b/vendor/github.com/hashicorp/terraform/states/statefile/write.go deleted file mode 100644 index cff3742d..00000000 --- a/vendor/github.com/hashicorp/terraform/states/statefile/write.go +++ /dev/null @@ -1,12 +0,0 @@ -package statefile - -import ( - "io" -) - -// Write writes the given state to the given writer in the current state -// serialization format. -func Write(s *File, w io.Writer) error { - diags := writeStateV4(s, w) - return diags.Err() -} diff --git a/vendor/github.com/hashicorp/terraform/states/sync.go b/vendor/github.com/hashicorp/terraform/states/sync.go deleted file mode 100644 index a3774467..00000000 --- a/vendor/github.com/hashicorp/terraform/states/sync.go +++ /dev/null @@ -1,537 +0,0 @@ -package states - -import ( - "log" - "sync" - - "github.com/hashicorp/terraform/addrs" - "github.com/zclconf/go-cty/cty" -) - -// SyncState is a wrapper around State that provides concurrency-safe access to -// various common operations that occur during a Terraform graph walk, or other -// similar concurrent contexts. -// -// When a SyncState wrapper is in use, no concurrent direct access to the -// underlying objects is permitted unless the caller first acquires an explicit -// lock, using the Lock and Unlock methods. Most callers should _not_ -// explicitly lock, and should instead use the other methods of this type that -// handle locking automatically. -// -// Since SyncState is able to safely consolidate multiple updates into a single -// atomic operation, many of its methods are at a higher level than those -// of the underlying types, and operate on the state as a whole rather than -// on individual sub-structures of the state. -// -// SyncState can only protect against races within its own methods. It cannot -// provide any guarantees about the order in which concurrent operations will -// be processed, so callers may still need to employ higher-level techniques -// for ensuring correct operation sequencing, such as building and walking -// a dependency graph. -type SyncState struct { - state *State - lock sync.RWMutex -} - -// Module returns a snapshot of the state of the module instance with the given -// address, or nil if no such module is tracked. -// -// The return value is a pointer to a copy of the module state, which the -// caller may then freely access and mutate. However, since the module state -// tends to be a large data structure with many child objects, where possible -// callers should prefer to use a more granular accessor to access a child -// module directly, and thus reduce the amount of copying required. -func (s *SyncState) Module(addr addrs.ModuleInstance) *Module { - s.lock.RLock() - ret := s.state.Module(addr).DeepCopy() - s.lock.RUnlock() - return ret -} - -// RemoveModule removes the entire state for the given module, taking with -// it any resources associated with the module. This should generally be -// called only for modules whose resources have all been destroyed, but -// that is not enforced by this method. -func (s *SyncState) RemoveModule(addr addrs.ModuleInstance) { - s.lock.Lock() - defer s.lock.Unlock() - - s.state.RemoveModule(addr) -} - -// OutputValue returns a snapshot of the state of the output value with the -// given address, or nil if no such output value is tracked. -// -// The return value is a pointer to a copy of the output value state, which the -// caller may then freely access and mutate. -func (s *SyncState) OutputValue(addr addrs.AbsOutputValue) *OutputValue { - s.lock.RLock() - ret := s.state.OutputValue(addr).DeepCopy() - s.lock.RUnlock() - return ret -} - -// SetOutputValue writes a given output value into the state, overwriting -// any existing value of the same name. -// -// If the module containing the output is not yet tracked in state then it -// be added as a side-effect. -func (s *SyncState) SetOutputValue(addr addrs.AbsOutputValue, value cty.Value, sensitive bool) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetOutputValue(addr.OutputValue.Name, value, sensitive) -} - -// RemoveOutputValue removes the stored value for the output value with the -// given address. -// -// If this results in its containing module being empty, the module will be -// pruned from the state as a side-effect. -func (s *SyncState) RemoveOutputValue(addr addrs.AbsOutputValue) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return - } - ms.RemoveOutputValue(addr.OutputValue.Name) - s.maybePruneModule(addr.Module) -} - -// LocalValue returns the current value associated with the given local value -// address. -func (s *SyncState) LocalValue(addr addrs.AbsLocalValue) cty.Value { - s.lock.RLock() - // cty.Value is immutable, so we don't need any extra copying here. - ret := s.state.LocalValue(addr) - s.lock.RUnlock() - return ret -} - -// SetLocalValue writes a given output value into the state, overwriting -// any existing value of the same name. -// -// If the module containing the local value is not yet tracked in state then it -// will be added as a side-effect. -func (s *SyncState) SetLocalValue(addr addrs.AbsLocalValue, value cty.Value) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetLocalValue(addr.LocalValue.Name, value) -} - -// RemoveLocalValue removes the stored value for the local value with the -// given address. -// -// If this results in its containing module being empty, the module will be -// pruned from the state as a side-effect. -func (s *SyncState) RemoveLocalValue(addr addrs.AbsLocalValue) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return - } - ms.RemoveLocalValue(addr.LocalValue.Name) - s.maybePruneModule(addr.Module) -} - -// Resource returns a snapshot of the state of the resource with the given -// address, or nil if no such resource is tracked. -// -// The return value is a pointer to a copy of the resource state, which the -// caller may then freely access and mutate. -func (s *SyncState) Resource(addr addrs.AbsResource) *Resource { - s.lock.RLock() - ret := s.state.Resource(addr).DeepCopy() - s.lock.RUnlock() - return ret -} - -// ResourceInstance returns a snapshot of the state the resource instance with -// the given address, or nil if no such instance is tracked. -// -// The return value is a pointer to a copy of the instance state, which the -// caller may then freely access and mutate. -func (s *SyncState) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstance { - s.lock.RLock() - ret := s.state.ResourceInstance(addr).DeepCopy() - s.lock.RUnlock() - return ret -} - -// ResourceInstanceObject returns a snapshot of the current instance object -// of the given generation belonging to the instance with the given address, -// or nil if no such object is tracked.. -// -// The return value is a pointer to a copy of the object, which the caller may -// then freely access and mutate. -func (s *SyncState) ResourceInstanceObject(addr addrs.AbsResourceInstance, gen Generation) *ResourceInstanceObjectSrc { - s.lock.RLock() - defer s.lock.RUnlock() - - inst := s.state.ResourceInstance(addr) - if inst == nil { - return nil - } - return inst.GetGeneration(gen).DeepCopy() -} - -// SetResourceMeta updates the resource-level metadata for the resource at -// the given address, creating the containing module state and resource state -// as a side-effect if not already present. -func (s *SyncState) SetResourceMeta(addr addrs.AbsResource, eachMode EachMode, provider addrs.AbsProviderConfig) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetResourceMeta(addr.Resource, eachMode, provider) -} - -// RemoveResource removes the entire state for the given resource, taking with -// it any instances associated with the resource. This should generally be -// called only for resource objects whose instances have all been destroyed, -// but that is not enforced by this method. (Use RemoveResourceIfEmpty instead -// to safely check first.) -func (s *SyncState) RemoveResource(addr addrs.AbsResource) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.RemoveResource(addr.Resource) - s.maybePruneModule(addr.Module) -} - -// RemoveResourceIfEmpty is similar to RemoveResource but first checks to -// make sure there are no instances or objects left in the resource. -// -// Returns true if the resource was removed, or false if remaining child -// objects prevented its removal. Returns true also if the resource was -// already absent, and thus no action needed to be taken. -func (s *SyncState) RemoveResourceIfEmpty(addr addrs.AbsResource) bool { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return true // nothing to do - } - rs := ms.Resource(addr.Resource) - if rs == nil { - return true // nothing to do - } - if len(rs.Instances) != 0 { - // We don't check here for the possibility of instances that exist - // but don't have any objects because it's the responsibility of the - // instance-mutation methods to prune those away automatically. - return false - } - ms.RemoveResource(addr.Resource) - s.maybePruneModule(addr.Module) - return true -} - -// MaybeFixUpResourceInstanceAddressForCount deals with the situation where a -// resource has changed from having "count" set to not set, or vice-versa, and -// so we need to rename the zeroth instance key to no key at all, or vice-versa. -// -// Set countEnabled to true if the resource has count set in its new -// configuration, or false if it does not. -// -// The state is modified in-place if necessary, moving a resource instance -// between the two addresses. The return value is true if a change was made, -// and false otherwise. -func (s *SyncState) MaybeFixUpResourceInstanceAddressForCount(addr addrs.AbsResource, countEnabled bool) bool { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return false - } - - relAddr := addr.Resource - rs := ms.Resource(relAddr) - if rs == nil { - return false - } - huntKey := addrs.NoKey - replaceKey := addrs.InstanceKey(addrs.IntKey(0)) - if !countEnabled { - huntKey, replaceKey = replaceKey, huntKey - } - - is, exists := rs.Instances[huntKey] - if !exists { - return false - } - - if _, exists := rs.Instances[replaceKey]; exists { - // If the replacement key also exists then we'll do nothing and keep both. - return false - } - - // If we get here then we need to "rename" from hunt to replace - rs.Instances[replaceKey] = is - delete(rs.Instances, huntKey) - return true -} - -// SetResourceInstanceCurrent saves the given instance object as the current -// generation of the resource instance with the given address, simulataneously -// updating the recorded provider configuration address, dependencies, and -// resource EachMode. -// -// Any existing current instance object for the given resource is overwritten. -// Set obj to nil to remove the primary generation object altogether. If there -// are no deposed objects then the instance as a whole will be removed, which -// may in turn also remove the containing module if it becomes empty. -// -// The caller must ensure that the given ResourceInstanceObject is not -// concurrently mutated during this call, but may be freely used again once -// this function returns. -// -// The provider address and "each mode" are resource-wide settings and so they -// are updated for all other instances of the same resource as a side-effect of -// this call. -// -// If the containing module for this resource or the resource itself are not -// already tracked in state then they will be added as a side-effect. -func (s *SyncState) SetResourceInstanceCurrent(addr addrs.AbsResourceInstance, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetResourceInstanceCurrent(addr.Resource, obj.DeepCopy(), provider) - s.maybePruneModule(addr.Module) -} - -// SetResourceInstanceDeposed saves the given instance object as a deposed -// generation of the resource instance with the given address and deposed key. -// -// Call this method only for pre-existing deposed objects that already have -// a known DeposedKey. For example, this method is useful if reloading objects -// that were persisted to a state file. To mark the current object as deposed, -// use DeposeResourceInstanceObject instead. -// -// The caller must ensure that the given ResourceInstanceObject is not -// concurrently mutated during this call, but may be freely used again once -// this function returns. -// -// The resource that contains the given instance must already exist in the -// state, or this method will panic. Use Resource to check first if its -// presence is not already guaranteed. -// -// Any existing current instance object for the given resource and deposed key -// is overwritten. Set obj to nil to remove the deposed object altogether. If -// the instance is left with no objects after this operation then it will -// be removed from its containing resource altogether. -// -// If the containing module for this resource or the resource itself are not -// already tracked in state then they will be added as a side-effect. -func (s *SyncState) SetResourceInstanceDeposed(addr addrs.AbsResourceInstance, key DeposedKey, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetResourceInstanceDeposed(addr.Resource, key, obj.DeepCopy(), provider) - s.maybePruneModule(addr.Module) -} - -// DeposeResourceInstanceObject moves the current instance object for the -// given resource instance address into the deposed set, leaving the instance -// without a current object. -// -// The return value is the newly-allocated deposed key, or NotDeposed if the -// given instance is already lacking a current object. -// -// If the containing module for this resource or the resource itself are not -// already tracked in state then there cannot be a current object for the -// given instance, and so NotDeposed will be returned without modifying the -// state at all. -func (s *SyncState) DeposeResourceInstanceObject(addr addrs.AbsResourceInstance) DeposedKey { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return NotDeposed - } - - return ms.deposeResourceInstanceObject(addr.Resource, NotDeposed) -} - -// DeposeResourceInstanceObjectForceKey is like DeposeResourceInstanceObject -// but uses a pre-allocated key. It's the caller's responsibility to ensure -// that there aren't any races to use a particular key; this method will panic -// if the given key is already in use. -func (s *SyncState) DeposeResourceInstanceObjectForceKey(addr addrs.AbsResourceInstance, forcedKey DeposedKey) { - s.lock.Lock() - defer s.lock.Unlock() - - if forcedKey == NotDeposed { - // Usage error: should use DeposeResourceInstanceObject in this case - panic("DeposeResourceInstanceObjectForceKey called without forced key") - } - - ms := s.state.Module(addr.Module) - if ms == nil { - return // Nothing to do, since there can't be any current object either. - } - - ms.deposeResourceInstanceObject(addr.Resource, forcedKey) -} - -// ForgetResourceInstanceAll removes the record of all objects associated with -// the specified resource instance, if present. If not present, this is a no-op. -func (s *SyncState) ForgetResourceInstanceAll(addr addrs.AbsResourceInstance) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return - } - ms.ForgetResourceInstanceAll(addr.Resource) - s.maybePruneModule(addr.Module) -} - -// ForgetResourceInstanceDeposed removes the record of the deposed object with -// the given address and key, if present. If not present, this is a no-op. -func (s *SyncState) ForgetResourceInstanceDeposed(addr addrs.AbsResourceInstance, key DeposedKey) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return - } - ms.ForgetResourceInstanceDeposed(addr.Resource, key) - s.maybePruneModule(addr.Module) -} - -// MaybeRestoreResourceInstanceDeposed will restore the deposed object with the -// given key on the specified resource as the current object for that instance -// if and only if that would not cause us to forget an existing current -// object for that instance. -// -// Returns true if the object was restored to current, or false if no change -// was made at all. -func (s *SyncState) MaybeRestoreResourceInstanceDeposed(addr addrs.AbsResourceInstance, key DeposedKey) bool { - s.lock.Lock() - defer s.lock.Unlock() - - if key == NotDeposed { - panic("MaybeRestoreResourceInstanceDeposed called without DeposedKey") - } - - ms := s.state.Module(addr.Module) - if ms == nil { - // Nothing to do, since the specified deposed object cannot exist. - return false - } - - return ms.maybeRestoreResourceInstanceDeposed(addr.Resource, key) -} - -// RemovePlannedResourceInstanceObjects removes from the state any resource -// instance objects that have the status ObjectPlanned, indiciating that they -// are just transient placeholders created during planning. -// -// Note that this does not restore any "ready" or "tainted" object that might -// have been present before the planned object was written. The only real use -// for this method is in preparing the state created during a refresh walk, -// where we run the planning step for certain instances just to create enough -// information to allow correct expression evaluation within provider and -// data resource blocks. Discarding planned instances in that case is okay -// because the refresh phase only creates planned objects to stand in for -// objects that don't exist yet, and thus the planned object must have been -// absent before by definition. -func (s *SyncState) RemovePlannedResourceInstanceObjects() { - // TODO: Merge together the refresh and plan phases into a single walk, - // so we can remove the need to create this "partial plan" during refresh - // that we then need to clean up before proceeding. - - s.lock.Lock() - defer s.lock.Unlock() - - for _, ms := range s.state.Modules { - moduleAddr := ms.Addr - - for _, rs := range ms.Resources { - resAddr := rs.Addr - - for ik, is := range rs.Instances { - instAddr := resAddr.Instance(ik) - - if is.Current != nil && is.Current.Status == ObjectPlanned { - // Setting the current instance to nil removes it from the - // state altogether if there are not also deposed instances. - ms.SetResourceInstanceCurrent(instAddr, nil, rs.ProviderConfig) - } - - for dk, obj := range is.Deposed { - // Deposed objects should never be "planned", but we'll - // do this anyway for the sake of completeness. - if obj.Status == ObjectPlanned { - ms.ForgetResourceInstanceDeposed(instAddr, dk) - } - } - } - } - - // We may have deleted some objects, which means that we may have - // left a module empty, and so we must prune to preserve the invariant - // that only the root module is allowed to be empty. - s.maybePruneModule(moduleAddr) - } -} - -// Lock acquires an explicit lock on the state, allowing direct read and write -// access to the returned state object. The caller must call Unlock once -// access is no longer needed, and then immediately discard the state pointer -// pointer. -// -// Most callers should not use this. Instead, use the concurrency-safe -// accessors and mutators provided directly on SyncState. -func (s *SyncState) Lock() *State { - s.lock.Lock() - return s.state -} - -// Unlock releases a lock previously acquired by Lock, at which point the -// caller must cease all use of the state pointer that was returned. -// -// Do not call this method except to end an explicit lock acquired by -// Lock. If a caller calls Unlock without first holding the lock, behavior -// is undefined. -func (s *SyncState) Unlock() { - s.lock.Unlock() -} - -// maybePruneModule will remove a module from the state altogether if it is -// empty, unless it's the root module which must always be present. -// -// This helper method is not concurrency-safe on its own, so must only be -// called while the caller is already holding the lock for writing. -func (s *SyncState) maybePruneModule(addr addrs.ModuleInstance) { - if addr.IsRoot() { - // We never prune the root. - return - } - - ms := s.state.Module(addr) - if ms == nil { - return - } - - if ms.empty() { - log.Printf("[TRACE] states.SyncState: pruning %s because it is empty", addr) - s.state.RemoveModule(addr) - } -} diff --git a/vendor/github.com/hashicorp/terraform/svchost/disco/disco.go b/vendor/github.com/hashicorp/terraform/svchost/disco/disco.go index 1963cbd1..7fc49da9 100644 --- a/vendor/github.com/hashicorp/terraform/svchost/disco/disco.go +++ b/vendor/github.com/hashicorp/terraform/svchost/disco/disco.go @@ -8,7 +8,6 @@ package disco import ( "encoding/json" "errors" - "fmt" "io" "io/ioutil" "log" @@ -18,36 +17,28 @@ import ( "time" cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/terraform/httpclient" "github.com/hashicorp/terraform/svchost" "github.com/hashicorp/terraform/svchost/auth" ) const ( - // Fixed path to the discovery manifest. - discoPath = "/.well-known/terraform.json" - - // Arbitrary-but-small number to prevent runaway redirect loops. - maxRedirects = 3 - - // Arbitrary-but-small time limit to prevent UI "hangs" during discovery. - discoTimeout = 11 * time.Second - - // 1MB - to prevent abusive services from using loads of our memory. - maxDiscoDocBytes = 1 * 1024 * 1024 + discoPath = "/.well-known/terraform.json" + maxRedirects = 3 // arbitrary-but-small number to prevent runaway redirect loops + discoTimeout = 11 * time.Second // arbitrary-but-small time limit to prevent UI "hangs" during discovery + maxDiscoDocBytes = 1 * 1024 * 1024 // 1MB - to prevent abusive services from using loads of our memory ) -// httpTransport is overridden during tests, to skip TLS verification. -var httpTransport = cleanhttp.DefaultPooledTransport() +var httpTransport = cleanhttp.DefaultPooledTransport() // overridden during tests, to skip TLS verification // Disco is the main type in this package, which allows discovery on given // hostnames and caches the results by hostname to avoid repeated requests // for the same information. type Disco struct { - hostCache map[svchost.Hostname]*Host + hostCache map[svchost.Hostname]Host credsSrc auth.CredentialsSource // Transport is a custom http.RoundTripper to use. + // A package default is used if this is nil. Transport http.RoundTripper } @@ -59,11 +50,7 @@ func New() *Disco { // NewWithCredentialsSource returns a new discovery object initialized with // the given credentials source. func NewWithCredentialsSource(credsSrc auth.CredentialsSource) *Disco { - return &Disco{ - hostCache: make(map[svchost.Hostname]*Host), - credsSrc: credsSrc, - Transport: httpTransport, - } + return &Disco{credsSrc: credsSrc} } // SetCredentialsSource provides a credentials source that will be used to @@ -77,11 +64,11 @@ func (d *Disco) SetCredentialsSource(src auth.CredentialsSource) { // CredentialsForHost returns a non-nil HostCredentials if the embedded source has // credentials available for the host, and a nil HostCredentials if it does not. -func (d *Disco) CredentialsForHost(hostname svchost.Hostname) (auth.HostCredentials, error) { +func (d *Disco) CredentialsForHost(host svchost.Hostname) (auth.HostCredentials, error) { if d.credsSrc == nil { return nil, nil } - return d.credsSrc.ForHost(hostname) + return d.credsSrc.ForHost(host) } // ForceHostServices provides a pre-defined set of services for a given @@ -94,20 +81,20 @@ func (d *Disco) CredentialsForHost(hostname svchost.Hostname) (auth.HostCredenti // discovery, yielding the same results as if the given map were published // at the host's default discovery URL, though using absolute URLs is strongly // recommended to make the configured behavior more explicit. -func (d *Disco) ForceHostServices(hostname svchost.Hostname, services map[string]interface{}) { +func (d *Disco) ForceHostServices(host svchost.Hostname, services map[string]interface{}) { + if d.hostCache == nil { + d.hostCache = map[svchost.Hostname]Host{} + } if services == nil { services = map[string]interface{}{} } - - d.hostCache[hostname] = &Host{ + d.hostCache[host] = Host{ discoURL: &url.URL{ Scheme: "https", - Host: string(hostname), + Host: string(host), Path: discoPath, }, - hostname: hostname.ForDisplay(), - services: services, - transport: d.Transport, + services: services, } } @@ -117,143 +104,138 @@ func (d *Disco) ForceHostServices(hostname svchost.Hostname, services map[string // // If a given hostname supports no Terraform services at all, a non-nil but // empty Host object is returned. When giving feedback to the end user about -// such situations, we say "host does not provide a service", -// regardless of whether that is due to that service specifically being absent -// or due to the host not providing Terraform services at all, since we don't -// wish to expose the detail of whole-host discovery to an end-user. -func (d *Disco) Discover(hostname svchost.Hostname) (*Host, error) { - if host, cached := d.hostCache[hostname]; cached { - return host, nil +// such situations, we say e.g. "the host doesn't provide a module +// registry", regardless of whether that is due to that service specifically +// being absent or due to the host not providing Terraform services at all, +// since we don't wish to expose the detail of whole-host discovery to an +// end-user. +func (d *Disco) Discover(host svchost.Hostname) Host { + if d.hostCache == nil { + d.hostCache = map[svchost.Hostname]Host{} + } + if cache, cached := d.hostCache[host]; cached { + return cache } - host, err := d.discover(hostname) - if err != nil { - return nil, err - } - d.hostCache[hostname] = host - - return host, nil + ret := d.discover(host) + d.hostCache[host] = ret + return ret } // DiscoverServiceURL is a convenience wrapper for discovery on a given // hostname and then looking up a particular service in the result. -func (d *Disco) DiscoverServiceURL(hostname svchost.Hostname, serviceID string) (*url.URL, error) { - host, err := d.Discover(hostname) - if err != nil { - return nil, err - } - return host.ServiceURL(serviceID) +func (d *Disco) DiscoverServiceURL(host svchost.Hostname, serviceID string) *url.URL { + return d.Discover(host).ServiceURL(serviceID) } // discover implements the actual discovery process, with its result cached // by the public-facing Discover method. -func (d *Disco) discover(hostname svchost.Hostname) (*Host, error) { +func (d *Disco) discover(host svchost.Hostname) Host { discoURL := &url.URL{ Scheme: "https", - Host: hostname.String(), + Host: host.String(), Path: discoPath, } + t := d.Transport + if t == nil { + t = httpTransport + } + client := &http.Client{ - Transport: d.Transport, + Transport: t, Timeout: discoTimeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { log.Printf("[DEBUG] Service discovery redirected to %s", req.URL) if len(via) > maxRedirects { - return errors.New("too many redirects") // this error will never actually be seen + return errors.New("too many redirects") // (this error message will never actually be seen) } return nil }, } req := &http.Request{ - Header: make(http.Header), Method: "GET", URL: discoURL, } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", httpclient.UserAgentString()) - creds, err := d.CredentialsForHost(hostname) - if err != nil { - log.Printf("[WARN] Failed to get credentials for %s: %s (ignoring)", hostname, err) - } - if creds != nil { - // Update the request to include credentials. - creds.PrepareRequest(req) + if creds, err := d.CredentialsForHost(host); err != nil { + log.Printf("[WARN] Failed to get credentials for %s: %s (ignoring)", host, err) + } else if creds != nil { + creds.PrepareRequest(req) // alters req to include credentials } - log.Printf("[DEBUG] Service discovery for %s at %s", hostname, discoURL) + log.Printf("[DEBUG] Service discovery for %s at %s", host, discoURL) + + ret := Host{ + discoURL: discoURL, + } resp, err := client.Do(req) if err != nil { - return nil, fmt.Errorf("Failed to request discovery document: %v", err) + log.Printf("[WARN] Failed to request discovery document: %s", err) + return ret // empty } defer resp.Body.Close() - host := &Host{ - // Use the discovery URL from resp.Request in - // case the client followed any redirects. - discoURL: resp.Request.URL, - hostname: hostname.ForDisplay(), - transport: d.Transport, - } - - // Return the host without any services. - if resp.StatusCode == 404 { - return host, nil - } - if resp.StatusCode != 200 { - return nil, fmt.Errorf("Failed to request discovery document: %s", resp.Status) + log.Printf("[WARN] Failed to request discovery document: %s", resp.Status) + return ret // empty } + // If the client followed any redirects, we will have a new URL to use + // as our base for relative resolution. + ret.discoURL = resp.Request.URL + contentType := resp.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { - return nil, fmt.Errorf("Discovery URL has a malformed Content-Type %q", contentType) + log.Printf("[WARN] Discovery URL has malformed Content-Type %q", contentType) + return ret // empty } if mediaType != "application/json" { - return nil, fmt.Errorf("Discovery URL returned an unsupported Content-Type %q", mediaType) + log.Printf("[DEBUG] Discovery URL returned Content-Type %q, rather than application/json", mediaType) + return ret // empty } - // This doesn't catch chunked encoding, because ContentLength is -1 in that case. + // (this doesn't catch chunked encoding, because ContentLength is -1 in that case...) if resp.ContentLength > maxDiscoDocBytes { // Size limit here is not a contractual requirement and so we may // adjust it over time if we find a different limit is warranted. - return nil, fmt.Errorf( - "Discovery doc response is too large (got %d bytes; limit %d)", - resp.ContentLength, maxDiscoDocBytes, - ) + log.Printf("[WARN] Discovery doc response is too large (got %d bytes; limit %d)", resp.ContentLength, maxDiscoDocBytes) + return ret // empty } - // If the response is using chunked encoding then we can't predict its - // size, but we'll at least prevent reading the entire thing into memory. + // If the response is using chunked encoding then we can't predict + // its size, but we'll at least prevent reading the entire thing into + // memory. lr := io.LimitReader(resp.Body, maxDiscoDocBytes) servicesBytes, err := ioutil.ReadAll(lr) if err != nil { - return nil, fmt.Errorf("Error reading discovery document body: %v", err) + log.Printf("[WARN] Error reading discovery document body: %s", err) + return ret // empty } var services map[string]interface{} err = json.Unmarshal(servicesBytes, &services) if err != nil { - return nil, fmt.Errorf("Failed to decode discovery document as a JSON object: %v", err) + log.Printf("[WARN] Failed to decode discovery document as a JSON object: %s", err) + return ret // empty } - host.services = services - return host, nil + ret.services = services + return ret } // Forget invalidates any cached record of the given hostname. If the host // has no cache entry then this is a no-op. -func (d *Disco) Forget(hostname svchost.Hostname) { - delete(d.hostCache, hostname) +func (d *Disco) Forget(host svchost.Hostname) { + delete(d.hostCache, host) } // ForgetAll is like Forget, but for all of the hostnames that have cache entries. func (d *Disco) ForgetAll() { - d.hostCache = make(map[svchost.Hostname]*Host) + d.hostCache = nil } diff --git a/vendor/github.com/hashicorp/terraform/svchost/disco/host.go b/vendor/github.com/hashicorp/terraform/svchost/disco/host.go index ab9514c4..faf58220 100644 --- a/vendor/github.com/hashicorp/terraform/svchost/disco/host.go +++ b/vendor/github.com/hashicorp/terraform/svchost/disco/host.go @@ -1,264 +1,51 @@ package disco import ( - "encoding/json" - "fmt" - "log" - "net/http" "net/url" - "os" - "strconv" - "strings" - "time" - - "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform/httpclient" ) -const versionServiceID = "versions.v1" - -// Host represents a service discovered host. type Host struct { - discoURL *url.URL - hostname string - services map[string]interface{} - transport http.RoundTripper -} - -// Constraints represents the version constraints of a service. -type Constraints struct { - Service string `json:"service"` - Product string `json:"product"` - Minimum string `json:"minimum"` - Maximum string `json:"maximum"` - Excluding []string `json:"excluding"` -} - -// ErrServiceNotProvided is returned when the service is not provided. -type ErrServiceNotProvided struct { - hostname string - service string -} - -// Error returns a customized error message. -func (e *ErrServiceNotProvided) Error() string { - if e.hostname == "" { - return fmt.Sprintf("host does not provide a %s service", e.service) - } - return fmt.Sprintf("host %s does not provide a %s service", e.hostname, e.service) -} - -// ErrVersionNotSupported is returned when the version is not supported. -type ErrVersionNotSupported struct { - hostname string - service string - version string -} - -// Error returns a customized error message. -func (e *ErrVersionNotSupported) Error() string { - if e.hostname == "" { - return fmt.Sprintf("host does not support %s version %s", e.service, e.version) - } - return fmt.Sprintf("host %s does not support %s version %s", e.hostname, e.service, e.version) -} - -// ErrNoVersionConstraints is returned when checkpoint was disabled -// or the endpoint to query for version constraints was unavailable. -type ErrNoVersionConstraints struct { - disabled bool -} - -// Error returns a customized error message. -func (e *ErrNoVersionConstraints) Error() string { - if e.disabled { - return "checkpoint disabled" - } - return "unable to contact versions service" + discoURL *url.URL + services map[string]interface{} } // ServiceURL returns the URL associated with the given service identifier, // which should be of the form "servicename.vN". // -// A non-nil result is always an absolute URL with a scheme of either HTTPS -// or HTTP. -func (h *Host) ServiceURL(id string) (*url.URL, error) { - svc, ver, err := parseServiceID(id) - if err != nil { - return nil, err - } - - // No services supported for an empty Host. - if h == nil || h.services == nil { - return nil, &ErrServiceNotProvided{service: svc} +// A non-nil result is always an absolute URL with a scheme of either https +// or http. +// +// If the requested service is not supported by the host, this method returns +// a nil URL. +// +// If the discovery document entry for the given service is invalid (not a URL), +// it is treated as absent, also returning a nil URL. +func (h Host) ServiceURL(id string) *url.URL { + if h.services == nil { + return nil // no services supported for an empty Host } urlStr, ok := h.services[id].(string) if !ok { - // See if we have a matching service as that would indicate - // the service is supported, but not the requested version. - for serviceID := range h.services { - if strings.HasPrefix(serviceID, svc+".") { - return nil, &ErrVersionNotSupported{ - hostname: h.hostname, - service: svc, - version: ver.Original(), - } - } - } - - // No discovered services match the requested service. - return nil, &ErrServiceNotProvided{hostname: h.hostname, service: svc} + return nil } - u, err := url.Parse(urlStr) + ret, err := url.Parse(urlStr) if err != nil { - return nil, fmt.Errorf("Failed to parse service URL: %v", err) + return nil } - - // Make relative URLs absolute using our discovery URL. - if !u.IsAbs() { - u = h.discoURL.ResolveReference(u) + if !ret.IsAbs() { + ret = h.discoURL.ResolveReference(ret) // make absolute using our discovery doc URL } - - if u.Scheme != "https" && u.Scheme != "http" { - return nil, fmt.Errorf("Service URL is using an unsupported scheme: %s", u.Scheme) + if ret.Scheme != "https" && ret.Scheme != "http" { + return nil } - if u.User != nil { - return nil, fmt.Errorf("Embedded username/password information is not permitted") + if ret.User != nil { + // embedded username/password information is not permitted; credentials + // are handled out of band. + return nil } + ret.Fragment = "" // fragment part is irrelevant, since we're not a browser - // Fragment part is irrelevant, since we're not a browser. - u.Fragment = "" - - return h.discoURL.ResolveReference(u), nil -} - -// VersionConstraints returns the contraints for a given service identifier -// (which should be of the form "servicename.vN") and product. -// -// When an exact (service and version) match is found, the constraints for -// that service are returned. -// -// When the requested version is not provided but the service is, we will -// search for all alternative versions. If mutliple alternative versions -// are found, the contrains of the latest available version are returned. -// -// When a service is not provided at all an error will be returned instead. -// -// When checkpoint is disabled or when a 404 is returned after making the -// HTTP call, an ErrNoVersionConstraints error will be returned. -func (h *Host) VersionConstraints(id, product string) (*Constraints, error) { - svc, _, err := parseServiceID(id) - if err != nil { - return nil, err - } - - // Return early if checkpoint is disabled. - if disabled := os.Getenv("CHECKPOINT_DISABLE"); disabled != "" { - return nil, &ErrNoVersionConstraints{disabled: true} - } - - // No services supported for an empty Host. - if h == nil || h.services == nil { - return nil, &ErrServiceNotProvided{service: svc} - } - - // Try to get the service URL for the version service and - // return early if the service isn't provided by the host. - u, err := h.ServiceURL(versionServiceID) - if err != nil { - return nil, err - } - - // Check if we have an exact (service and version) match. - if _, ok := h.services[id].(string); !ok { - // If we don't have an exact match, we search for all matching - // services and then use the service ID of the latest version. - var services []string - for serviceID := range h.services { - if strings.HasPrefix(serviceID, svc+".") { - services = append(services, serviceID) - } - } - - if len(services) == 0 { - // No discovered services match the requested service. - return nil, &ErrServiceNotProvided{hostname: h.hostname, service: svc} - } - - // Set id to the latest service ID we found. - var latest *version.Version - for _, serviceID := range services { - if _, ver, err := parseServiceID(serviceID); err == nil { - if latest == nil || latest.LessThan(ver) { - id = serviceID - latest = ver - } - } - } - } - - // Set a default timeout of 1 sec for the versions request (in milliseconds) - timeout := 1000 - if v, err := strconv.Atoi(os.Getenv("CHECKPOINT_TIMEOUT")); err == nil { - timeout = v - } - - client := &http.Client{ - Transport: h.transport, - Timeout: time.Duration(timeout) * time.Millisecond, - } - - // Prepare the service URL by setting the service and product. - v := u.Query() - v.Set("product", product) - u.Path += id - u.RawQuery = v.Encode() - - // Create a new request. - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - return nil, fmt.Errorf("Failed to create version constraints request: %v", err) - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", httpclient.UserAgentString()) - - log.Printf("[DEBUG] Retrieve version constraints for service %s and product %s", id, product) - - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("Failed to request version constraints: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode == 404 { - return nil, &ErrNoVersionConstraints{disabled: false} - } - - if resp.StatusCode != 200 { - return nil, fmt.Errorf("Failed to request version constraints: %s", resp.Status) - } - - // Parse the constraints from the response body. - result := &Constraints{} - if err := json.NewDecoder(resp.Body).Decode(result); err != nil { - return nil, fmt.Errorf("Error parsing version constraints: %v", err) - } - - return result, nil -} - -func parseServiceID(id string) (string, *version.Version, error) { - parts := strings.SplitN(id, ".", 2) - if len(parts) != 2 { - return "", nil, fmt.Errorf("Invalid service ID format (i.e. service.vN): %s", id) - } - - version, err := version.NewVersion(parts[1]) - if err != nil { - return "", nil, fmt.Errorf("Invalid service version: %v", err) - } - - return parts[0], version, nil + return h.discoURL.ResolveReference(ret) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/context.go b/vendor/github.com/hashicorp/terraform/terraform/context.go index afdba99c..f133cc20 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/context.go +++ b/vendor/github.com/hashicorp/terraform/terraform/context.go @@ -1,26 +1,20 @@ package terraform import ( - "bytes" "context" "fmt" "log" + "sort" "strings" "sync" - "github.com/hashicorp/hcl" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/lang" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/states/statefile" "github.com/hashicorp/terraform/tfdiags" + + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/hcl" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" + "github.com/hashicorp/terraform/version" ) // InputMode defines what sort of input will be asked for when Input @@ -57,18 +51,19 @@ var ( // ContextOpts are the user-configurable options to create a context with // NewContext. type ContextOpts struct { - Config *configs.Config - Changes *plans.Changes - State *states.State - Targets []addrs.Targetable - Variables InputValues - Meta *ContextMeta - Destroy bool - - Hooks []Hook - Parallelism int - ProviderResolver providers.Resolver - Provisioners map[string]ProvisionerFactory + Meta *ContextMeta + Destroy bool + Diff *Diff + Hooks []Hook + Module *module.Tree + Parallelism int + State *State + StateFutureAllowed bool + ProviderResolver ResourceProviderResolver + Provisioners map[string]ResourceProvisionerFactory + Shadow bool + Targets []string + Variables map[string]interface{} // If non-nil, will apply as additional constraints on the provider // plugins that will be requested from the provider resolver. @@ -88,25 +83,32 @@ type ContextMeta struct { // Context represents all the context that Terraform needs in order to // perform operations on infrastructure. This structure is built using -// NewContext. +// NewContext. See the documentation for that. +// +// Extra functions on Context can be found in context_*.go files. type Context struct { - config *configs.Config - changes *plans.Changes - state *states.State - targets []addrs.Targetable - variables InputValues - meta *ContextMeta - destroy bool + // Maintainer note: Anytime this struct is changed, please verify + // that newShadowContext still does the right thing. Tests should + // fail regardless but putting this note here as well. - hooks []Hook components contextComponentFactory - schemas *Schemas + destroy bool + diff *Diff + diffLock sync.RWMutex + hooks []Hook + meta *ContextMeta + module *module.Tree sh *stopHook + shadow bool + state *State + stateLock sync.RWMutex + targets []string uiInput UIInput + variables map[string]interface{} l sync.Mutex // Lock acquired during any task parallelSem Semaphore - providerInputConfig map[string]map[string]cty.Value + providerInputConfig map[string]map[string]interface{} providerSHA256s map[string][]byte runLock sync.Mutex runCond *sync.Cond @@ -115,23 +117,17 @@ type Context struct { shadowErr error } -// (additional methods on Context can be found in context_*.go files.) - // NewContext creates a new Context structure. // -// Once a Context is created, the caller must not access or mutate any of -// the objects referenced (directly or indirectly) by the ContextOpts fields. -// -// If the returned diagnostics contains errors then the resulting context is -// invalid and must not be used. -func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { - log.Printf("[TRACE] terraform.NewContext: starting") - diags := CheckCoreVersionRequirements(opts.Config) - // If version constraints are not met then we'll bail early since otherwise - // we're likely to just see a bunch of other errors related to - // incompatibilities, which could be overwhelming for the user. - if diags.HasErrors() { - return nil, diags +// Once a Context is creator, the pointer values within ContextOpts +// should not be mutated in any way, since the pointers are copied, not +// the values themselves. +func NewContext(opts *ContextOpts) (*Context, error) { + // Validate the version requirement if it is given + if opts.Module != nil { + if err := CheckRequiredVersion(opts.Module); err != nil { + return nil, err + } } // Copy all the hooks and add our stop hook. We don't append directly @@ -143,9 +139,21 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { state := opts.State if state == nil { - state = states.NewState() + state = new(State) + state.init() } + // If our state is from the future, then error. Callers can avoid + // this error by explicitly setting `StateFutureAllowed`. + if err := CheckStateVersion(state); err != nil && !opts.StateFutureAllowed { + return nil, err + } + + // Explicitly reset our state version to our current version so that + // any operations we do will write out that our latest version + // has run. + state.TFVersion = version.Version + // Determine parallelism, default to 10. We do this both to limit // CPU pressure but also to have an extra guard against rate throttling // from providers. @@ -160,84 +168,60 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { // 2 - Take values specified in -var flags, overriding values // set by environment variables if necessary. This includes // values taken from -var-file in addition. - var variables InputValues - if opts.Config != nil { - // Default variables from the configuration seed our map. - variables = DefaultVariableValues(opts.Config.Module.Variables) + variables := make(map[string]interface{}) + if opts.Module != nil { + var err error + variables, err = Variables(opts.Module, opts.Variables) + if err != nil { + return nil, err + } } - // Variables provided by the caller (from CLI, environment, etc) can - // override the defaults. - variables = variables.Override(opts.Variables) // Bind available provider plugins to the constraints in config - var providerFactories map[string]providers.Factory + var providers map[string]ResourceProviderFactory if opts.ProviderResolver != nil { - deps := ConfigTreeDependencies(opts.Config, state) + var err error + deps := ModuleTreeDependencies(opts.Module, state) reqd := deps.AllPluginRequirements() if opts.ProviderSHA256s != nil && !opts.SkipProviderVerify { reqd.LockExecutables(opts.ProviderSHA256s) } - log.Printf("[TRACE] terraform.NewContext: resolving provider version selections") - - var providerDiags tfdiags.Diagnostics - providerFactories, providerDiags = resourceProviderFactories(opts.ProviderResolver, reqd) - diags = diags.Append(providerDiags) - - if diags.HasErrors() { - return nil, diags + providers, err = resourceProviderFactories(opts.ProviderResolver, reqd) + if err != nil { + return nil, err } } else { - providerFactories = make(map[string]providers.Factory) + providers = make(map[string]ResourceProviderFactory) } - components := &basicComponentFactory{ - providers: providerFactories, - provisioners: opts.Provisioners, + diff := opts.Diff + if diff == nil { + diff = &Diff{} } - log.Printf("[TRACE] terraform.NewContext: loading provider schemas") - schemas, err := LoadSchemas(opts.Config, opts.State, components) - if err != nil { - diags = diags.Append(err) - return nil, diags - } - - changes := opts.Changes - if changes == nil { - changes = plans.NewChanges() - } - - config := opts.Config - if config == nil { - config = configs.NewEmptyConfig() - } - - log.Printf("[TRACE] terraform.NewContext: complete") - return &Context{ - components: components, - schemas: schemas, - destroy: opts.Destroy, - changes: changes, - hooks: hooks, - meta: opts.Meta, - config: config, - state: state, - targets: opts.Targets, - uiInput: opts.UIInput, - variables: variables, + components: &basicComponentFactory{ + providers: providers, + provisioners: opts.Provisioners, + }, + destroy: opts.Destroy, + diff: diff, + hooks: hooks, + meta: opts.Meta, + module: opts.Module, + shadow: opts.Shadow, + state: state, + targets: opts.Targets, + uiInput: opts.UIInput, + variables: variables, parallelSem: NewSemaphore(par), - providerInputConfig: make(map[string]map[string]cty.Value), + providerInputConfig: make(map[string]map[string]interface{}), providerSHA256s: opts.ProviderSHA256s, sh: sh, }, nil } -func (c *Context) Schemas() *Schemas { - return c.schemas -} - type ContextGraphOpts struct { // If true, validates the graph structure (checks for cycles). Validate bool @@ -249,7 +233,7 @@ type ContextGraphOpts struct { // Graph returns the graph used for the given operation type. // // The most extensive or complex graph type is GraphTypePlan. -func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, tfdiags.Diagnostics) { +func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, error) { if opts == nil { opts = &ContextGraphOpts{Validate: true} } @@ -258,71 +242,65 @@ func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, tfdiags. switch typ { case GraphTypeApply: return (&ApplyGraphBuilder{ - Config: c.config, - Changes: c.changes, - State: c.state, - Components: c.components, - Schemas: c.schemas, - Targets: c.targets, - Destroy: c.destroy, - Validate: opts.Validate, - }).Build(addrs.RootModuleInstance) + Module: c.module, + Diff: c.diff, + State: c.state, + Providers: c.components.ResourceProviders(), + Provisioners: c.components.ResourceProvisioners(), + Targets: c.targets, + Destroy: c.destroy, + Validate: opts.Validate, + }).Build(RootModulePath) + case GraphTypeInput: + // The input graph is just a slightly modified plan graph + fallthrough case GraphTypeValidate: // The validate graph is just a slightly modified plan graph fallthrough case GraphTypePlan: // Create the plan graph builder p := &PlanGraphBuilder{ - Config: c.config, - State: c.state, - Components: c.components, - Schemas: c.schemas, - Targets: c.targets, - Validate: opts.Validate, + Module: c.module, + State: c.state, + Providers: c.components.ResourceProviders(), + Targets: c.targets, + Validate: opts.Validate, } // Some special cases for other graph types shared with plan currently var b GraphBuilder = p switch typ { + case GraphTypeInput: + b = InputGraphBuilder(p) case GraphTypeValidate: + // We need to set the provisioners so those can be validated + p.Provisioners = c.components.ResourceProvisioners() + b = ValidateGraphBuilder(p) } - return b.Build(addrs.RootModuleInstance) + return b.Build(RootModulePath) case GraphTypePlanDestroy: return (&DestroyPlanGraphBuilder{ - Config: c.config, - State: c.state, - Components: c.components, - Schemas: c.schemas, - Targets: c.targets, - Validate: opts.Validate, - }).Build(addrs.RootModuleInstance) + Module: c.module, + State: c.state, + Targets: c.targets, + Validate: opts.Validate, + }).Build(RootModulePath) case GraphTypeRefresh: return (&RefreshGraphBuilder{ - Config: c.config, - State: c.state, - Components: c.components, - Schemas: c.schemas, - Targets: c.targets, - Validate: opts.Validate, - }).Build(addrs.RootModuleInstance) - - case GraphTypeEval: - return (&EvalGraphBuilder{ - Config: c.config, - State: c.state, - Components: c.components, - Schemas: c.schemas, - }).Build(addrs.RootModuleInstance) - - default: - // Should never happen, because the above is exhaustive for all graph types. - panic(fmt.Errorf("unsupported graph type %s", typ)) + Module: c.module, + State: c.state, + Providers: c.components.ResourceProviders(), + Targets: c.targets, + Validate: opts.Validate, + }).Build(RootModulePath) } + + return nil, fmt.Errorf("unknown graph type: %s", typ) } // ShadowError returns any errors caught during a shadow operation. @@ -355,72 +333,141 @@ func (c *Context) ShadowError() error { // State returns a copy of the current state associated with this context. // // This cannot safely be called in parallel with any other Context function. -func (c *Context) State() *states.State { +func (c *Context) State() *State { return c.state.DeepCopy() } -// Eval produces a scope in which expressions can be evaluated for -// the given module path. -// -// This method must first evaluate any ephemeral values (input variables, local -// values, and output values) in the configuration. These ephemeral values are -// not included in the persisted state, so they must be re-computed using other -// values in the state before they can be properly evaluated. The updated -// values are retained in the main state associated with the receiving context. -// -// This function takes no action against remote APIs but it does need access -// to all provider and provisioner instances in order to obtain their schemas -// for type checking. -// -// The result is an evaluation scope that can be used to resolve references -// against the root module. If the returned diagnostics contains errors then -// the returned scope may be nil. If it is not nil then it may still be used -// to attempt expression evaluation or other analysis, but some expressions -// may not behave as expected. -func (c *Context) Eval(path addrs.ModuleInstance) (*lang.Scope, tfdiags.Diagnostics) { - // This is intended for external callers such as the "terraform console" - // command. Internally, we create an evaluator in c.walk before walking - // the graph, and create scopes in ContextGraphWalker. - - var diags tfdiags.Diagnostics - defer c.acquireRun("eval")() - - // Start with a copy of state so that we don't affect any instances - // that other methods may have already returned. - c.state = c.state.DeepCopy() - var walker *ContextGraphWalker - - graph, graphDiags := c.Graph(GraphTypeEval, nil) - diags = diags.Append(graphDiags) - if !diags.HasErrors() { - var walkDiags tfdiags.Diagnostics - walker, walkDiags = c.walk(graph, walkEval) - diags = diags.Append(walker.NonFatalDiagnostics) - diags = diags.Append(walkDiags) +// Interpolater returns an Interpolater built on a copy of the state +// that can be used to test interpolation values. +func (c *Context) Interpolater() *Interpolater { + var varLock sync.Mutex + var stateLock sync.RWMutex + return &Interpolater{ + Operation: walkApply, + Meta: c.meta, + Module: c.module, + State: c.state.DeepCopy(), + StateLock: &stateLock, + VariableValues: c.variables, + VariableValuesLock: &varLock, } - - if walker == nil { - // If we skipped walking the graph (due to errors) then we'll just - // use a placeholder graph walker here, which'll refer to the - // unmodified state. - walker = c.graphWalker(walkEval) - } - - // This is a bit weird since we don't normally evaluate outside of - // the context of a walk, but we'll "re-enter" our desired path here - // just to get hold of an EvalContext for it. GraphContextBuiltin - // caches its contexts, so we should get hold of the context that was - // previously used for evaluation here, unless we skipped walking. - evalCtx := walker.EnterPath(path) - return evalCtx.EvaluationScope(nil, EvalDataForNoInstanceKey), diags } -// Interpolater is no longer used. Use Evaluator instead. -// -// The interpolator returned from this function will return an error on any use. -func (c *Context) Interpolater() *Interpolater { - // FIXME: Remove this once all callers are updated to no longer use it. - return &Interpolater{} +// Input asks for input to fill variables and provider configurations. +// This modifies the configuration in-place, so asking for Input twice +// may result in different UI output showing different current values. +func (c *Context) Input(mode InputMode) error { + defer c.acquireRun("input")() + + if mode&InputModeVar != 0 { + // Walk the variables first for the root module. We walk them in + // alphabetical order for UX reasons. + rootConf := c.module.Config() + names := make([]string, len(rootConf.Variables)) + m := make(map[string]*config.Variable) + for i, v := range rootConf.Variables { + names[i] = v.Name + m[v.Name] = v + } + sort.Strings(names) + for _, n := range names { + // If we only care about unset variables, then if the variable + // is set, continue on. + if mode&InputModeVarUnset != 0 { + if _, ok := c.variables[n]; ok { + continue + } + } + + var valueType config.VariableType + + v := m[n] + switch valueType = v.Type(); valueType { + case config.VariableTypeUnknown: + continue + case config.VariableTypeMap: + // OK + case config.VariableTypeList: + // OK + case config.VariableTypeString: + // OK + default: + panic(fmt.Sprintf("Unknown variable type: %#v", v.Type())) + } + + // If the variable is not already set, and the variable defines a + // default, use that for the value. + if _, ok := c.variables[n]; !ok { + if v.Default != nil { + c.variables[n] = v.Default.(string) + continue + } + } + + // this should only happen during tests + if c.uiInput == nil { + log.Println("[WARN] Content.uiInput is nil") + continue + } + + // Ask the user for a value for this variable + var value string + retry := 0 + for { + var err error + value, err = c.uiInput.Input(&InputOpts{ + Id: fmt.Sprintf("var.%s", n), + Query: fmt.Sprintf("var.%s", n), + Description: v.Description, + }) + if err != nil { + return fmt.Errorf( + "Error asking for %s: %s", n, err) + } + + if value == "" && v.Required() { + // Redo if it is required, but abort if we keep getting + // blank entries + if retry > 2 { + return fmt.Errorf("missing required value for %q", n) + } + retry++ + continue + } + + break + } + + // no value provided, so don't set the variable at all + if value == "" { + continue + } + + decoded, err := parseVariableAsHCL(n, value, valueType) + if err != nil { + return err + } + + if decoded != nil { + c.variables[n] = decoded + } + } + } + + if mode&InputModeProvider != 0 { + // Build the graph + graph, err := c.Graph(GraphTypeInput, nil) + if err != nil { + return err + } + + // Do the walk + if _, err := c.walk(graph, walkInput); err != nil { + return err + } + } + + return nil } // Apply applies the changes represented by this context and returns @@ -437,16 +484,23 @@ func (c *Context) Interpolater() *Interpolater { // State() method. Currently the helper/resource testing framework relies // on the absence of a returned state to determine if Destroy can be // called, so that will need to be refactored before this can be changed. -func (c *Context) Apply() (*states.State, tfdiags.Diagnostics) { +func (c *Context) Apply() (*State, error) { defer c.acquireRun("apply")() + // Check there are no empty target parameter values + for _, target := range c.targets { + if target == "" { + return nil, fmt.Errorf("Target parameter must not have empty value") + } + } + // Copy our own state c.state = c.state.DeepCopy() // Build the graph. - graph, diags := c.Graph(GraphTypeApply, nil) - if diags.HasErrors() { - return nil, diags + graph, err := c.Graph(GraphTypeApply, nil) + if err != nil { + return nil, err } // Determine the operation @@ -456,30 +510,15 @@ func (c *Context) Apply() (*states.State, tfdiags.Diagnostics) { } // Walk the graph - walker, walkDiags := c.walk(graph, operation) - diags = diags.Append(walker.NonFatalDiagnostics) - diags = diags.Append(walkDiags) - - if c.destroy && !diags.HasErrors() { - // If we know we were trying to destroy objects anyway, and we - // completed without any errors, then we'll also prune out any - // leftover empty resource husks (left after all of the instances - // of a resource with "count" or "for_each" are destroyed) to - // help ensure we end up with an _actually_ empty state, assuming - // we weren't destroying with -target here. - // - // (This doesn't actually take into account -target, but that should - // be okay because it doesn't throw away anything we can't recompute - // on a subsequent "terraform plan" run, if the resources are still - // present in the configuration. However, this _will_ cause "count = 0" - // resources to read as unknown during the next refresh walk, which - // may cause some additional churn if used in a data resource or - // provider block, until we remove refreshing as a separate walk and - // just do it as part of the plan walk.) - c.state.PruneResourceHusks() + walker, err := c.walk(graph, operation) + if len(walker.ValidationErrors) > 0 { + err = multierror.Append(err, walker.ValidationErrors...) } - return c.state, diags + // Clean out any unused things + c.state.prune() + + return c.state, err } // Plan generates an execution plan for the given context. @@ -489,45 +528,38 @@ func (c *Context) Apply() (*states.State, tfdiags.Diagnostics) { // // Plan also updates the diff of this context to be the diff generated // by the plan, so Apply can be called after. -func (c *Context) Plan() (*plans.Plan, tfdiags.Diagnostics) { +func (c *Context) Plan() (*Plan, error) { defer c.acquireRun("plan")() - c.changes = plans.NewChanges() - var diags tfdiags.Diagnostics - - varVals := make(map[string]plans.DynamicValue, len(c.variables)) - for k, iv := range c.variables { - // We use cty.DynamicPseudoType here so that we'll save both the - // value _and_ its dynamic type in the plan, so we can recover - // exactly the same value later. - dv, err := plans.NewDynamicValue(iv.Value, cty.DynamicPseudoType) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to prepare variable value for plan", - fmt.Sprintf("The value for variable %q could not be serialized to store in the plan: %s.", k, err), - )) - continue + // Check there are no empty target parameter values + for _, target := range c.targets { + if target == "" { + return nil, fmt.Errorf("Target parameter must not have empty value") } - varVals[k] = dv } - p := &plans.Plan{ - VariableValues: varVals, - TargetAddrs: c.targets, - ProviderSHA256s: c.providerSHA256s, + p := &Plan{ + Module: c.module, + Vars: c.variables, + State: c.state, + Targets: c.targets, + + TerraformVersion: version.String(), + ProviderSHA256s: c.providerSHA256s, } var operation walkOperation if c.destroy { operation = walkPlanDestroy + p.Destroy = true } else { // Set our state to be something temporary. We do this so that // the plan can update a fake state so that variables work, then // we replace it back with our old state. old := c.state if old == nil { - c.state = states.NewState() + c.state = &State{} + c.state.init() } else { c.state = old.DeepCopy() } @@ -538,27 +570,57 @@ func (c *Context) Plan() (*plans.Plan, tfdiags.Diagnostics) { operation = walkPlan } + // Setup our diff + c.diffLock.Lock() + c.diff = new(Diff) + c.diff.init() + c.diffLock.Unlock() + // Build the graph. graphType := GraphTypePlan if c.destroy { graphType = GraphTypePlanDestroy } - graph, graphDiags := c.Graph(graphType, nil) - diags = diags.Append(graphDiags) - if graphDiags.HasErrors() { - return nil, diags + graph, err := c.Graph(graphType, nil) + if err != nil { + return nil, err } // Do the walk - walker, walkDiags := c.walk(graph, operation) - diags = diags.Append(walker.NonFatalDiagnostics) - diags = diags.Append(walkDiags) - if walkDiags.HasErrors() { - return nil, diags + walker, err := c.walk(graph, operation) + if err != nil { + return nil, err } - p.Changes = c.changes + p.Diff = c.diff - return p, diags + // If this is true, it means we're running unit tests. In this case, + // we perform a deep copy just to ensure that all context tests also + // test that a diff is copy-able. This will panic if it fails. This + // is enabled during unit tests. + // + // This should never be true during production usage, but even if it is, + // it can't do any real harm. + if contextTestDeepCopyOnPlan { + p.Diff.DeepCopy() + } + + /* + // We don't do the reverification during the new destroy plan because + // it will use a different apply process. + if X_legacyGraph { + // Now that we have a diff, we can build the exact graph that Apply will use + // and catch any possible cycles during the Plan phase. + if _, err := c.Graph(GraphTypeLegacy, nil); err != nil { + return nil, err + } + } + */ + + var errs error + if len(walker.ValidationErrors) > 0 { + errs = multierror.Append(errs, walker.ValidationErrors...) + } + return p, errs } // Refresh goes through all the resources in the state and refreshes them @@ -567,46 +629,27 @@ func (c *Context) Plan() (*plans.Plan, tfdiags.Diagnostics) { // // Even in the case an error is returned, the state may be returned and // will potentially be partially updated. -func (c *Context) Refresh() (*states.State, tfdiags.Diagnostics) { +func (c *Context) Refresh() (*State, error) { defer c.acquireRun("refresh")() // Copy our own state c.state = c.state.DeepCopy() - // Refresh builds a partial changeset as part of its work because it must - // create placeholder stubs for any resource instances that'll be created - // in subsequent plan so that provider configurations and data resources - // can interpolate from them. This plan is always thrown away after - // the operation completes, restoring any existing changeset. - oldChanges := c.changes - defer func() { c.changes = oldChanges }() - c.changes = plans.NewChanges() - // Build the graph. - graph, diags := c.Graph(GraphTypeRefresh, nil) - if diags.HasErrors() { - return nil, diags + graph, err := c.Graph(GraphTypeRefresh, nil) + if err != nil { + return nil, err } // Do the walk - _, walkDiags := c.walk(graph, walkRefresh) - diags = diags.Append(walkDiags) - if walkDiags.HasErrors() { - return nil, diags + if _, err := c.walk(graph, walkRefresh); err != nil { + return nil, err } - // During our walk we will have created planned object placeholders in - // state for resource instances that are in configuration but not yet - // created. These were created only to allow expression evaluation to - // work properly in provider and data blocks during the walk and must - // now be discarded, since a subsequent plan walk is responsible for - // creating these "for real". - // TODO: Consolidate refresh and plan into a single walk, so that the - // refresh walk doesn't need to emulate various aspects of the plan - // walk in order to properly evaluate provider and data blocks. - c.state.SyncWrapper().RemovePlannedResourceInstanceObjects() + // Clean out any unused things + c.state.prune() - return c.state, diags + return c.state, nil } // Stop stops the running task. @@ -632,33 +675,32 @@ func (c *Context) Stop() { // Grab the condition var before we exit if cond := c.runCond; cond != nil { - log.Printf("[INFO] terraform: waiting for graceful stop to complete") cond.Wait() } log.Printf("[WARN] terraform: stop complete") } -// Validate performs semantic validation of the configuration, and returning -// any warnings or errors. -// -// Syntax and structural checks are performed by the configuration loader, -// and so are not repeated here. +// Validate validates the configuration and returns any warnings or errors. func (c *Context) Validate() tfdiags.Diagnostics { defer c.acquireRun("validate")() var diags tfdiags.Diagnostics - // Validate input variables. We do this only for the values supplied - // by the root module, since child module calls are validated when we - // visit their graph nodes. - if c.config != nil { - varDiags := checkInputVariables(c.config.Module.Variables, c.variables) - diags = diags.Append(varDiags) + // Validate the configuration itself + diags = diags.Append(c.module.Validate()) + + // This only needs to be done for the root module, since inter-module + // variables are validated in the module tree. + if config := c.module.Config(); config != nil { + // Validate the user variables + for _, err := range smcUserVariables(config, c.variables) { + diags = diags.Append(err) + } } - // If we have errors at this point then we probably won't be able to - // construct a graph without producing redundant errors, so we'll halt early. + // If we have errors at this point, the graphing has no chance, + // so just bail early. if diags.HasErrors() { return diags } @@ -667,41 +709,48 @@ func (c *Context) Validate() tfdiags.Diagnostics { // We also validate the graph generated here, but this graph doesn't // necessarily match the graph that Plan will generate, so we'll validate the // graph again later after Planning. - graph, graphDiags := c.Graph(GraphTypeValidate, nil) - diags = diags.Append(graphDiags) - if graphDiags.HasErrors() { + graph, err := c.Graph(GraphTypeValidate, nil) + if err != nil { + diags = diags.Append(err) return diags } // Walk - walker, walkDiags := c.walk(graph, walkValidate) - diags = diags.Append(walker.NonFatalDiagnostics) - diags = diags.Append(walkDiags) - if walkDiags.HasErrors() { - return diags + walker, err := c.walk(graph, walkValidate) + if err != nil { + diags = diags.Append(err) + } + + sort.Strings(walker.ValidationWarnings) + sort.Slice(walker.ValidationErrors, func(i, j int) bool { + return walker.ValidationErrors[i].Error() < walker.ValidationErrors[j].Error() + }) + + for _, warn := range walker.ValidationWarnings { + diags = diags.Append(tfdiags.SimpleWarning(warn)) + } + for _, err := range walker.ValidationErrors { + diags = diags.Append(err) } return diags } -// Config returns the configuration tree associated with this context. -func (c *Context) Config() *configs.Config { - return c.config +// Module returns the module tree associated with this context. +func (c *Context) Module() *module.Tree { + return c.module } // Variables will return the mapping of variables that were defined // for this Context. If Input was called, this mapping may be different // than what was given. -func (c *Context) Variables() InputValues { +func (c *Context) Variables() map[string]interface{} { return c.variables } // SetVariable sets a variable after a context has already been built. -func (c *Context) SetVariable(k string, v cty.Value) { - c.variables[k] = &InputValue{ - Value: v, - SourceType: ValueFromCaller, - } +func (c *Context) SetVariable(k string, v interface{}) { + c.variables[k] = v } func (c *Context) acquireRun(phase string) func() { @@ -718,6 +767,9 @@ func (c *Context) acquireRun(phase string) func() { // Build our lock c.runCond = sync.NewCond(&c.l) + // Setup debugging + dbug.SetPhase(phase) + // Create a new run context c.runContext, c.runContextCancel = context.WithCancel(context.Background()) @@ -735,6 +787,11 @@ func (c *Context) releaseRun() { c.l.Lock() defer c.l.Unlock() + // setting the phase to "INVALID" lets us easily detect if we have + // operations happening outside of a run, or we missed setting the proper + // phase + dbug.SetPhase("INVALID") + // End our run. We check if runContext is non-nil because it can be // set to nil if it was cancelled via Stop() if c.runContextCancel != nil { @@ -750,33 +807,30 @@ func (c *Context) releaseRun() { c.runContext = nil } -func (c *Context) walk(graph *Graph, operation walkOperation) (*ContextGraphWalker, tfdiags.Diagnostics) { +func (c *Context) walk(graph *Graph, operation walkOperation) (*ContextGraphWalker, error) { + // Keep track of the "real" context which is the context that does + // the real work: talking to real providers, modifying real state, etc. + realCtx := c + log.Printf("[DEBUG] Starting graph walk: %s", operation.String()) - walker := c.graphWalker(operation) + walker := &ContextGraphWalker{ + Context: realCtx, + Operation: operation, + StopContext: c.runContext, + } // Watch for a stop so we can call the provider Stop() API. watchStop, watchWait := c.watchStop(walker) // Walk the real graph, this will block until it completes - diags := graph.Walk(walker) + realErr := graph.Walk(walker) // Close the channel so the watcher stops, and wait for it to return. close(watchStop) <-watchWait - return walker, diags -} - -func (c *Context) graphWalker(operation walkOperation) *ContextGraphWalker { - return &ContextGraphWalker{ - Context: c, - State: c.state.SyncWrapper(), - Changes: c.changes.SyncWrapper(), - Operation: operation, - StopContext: c.runContext, - RootVariableValues: c.variables, - } + return walker, realErr } // watchStop immediately returns a `stop` and a `wait` chan after dispatching @@ -809,13 +863,12 @@ func (c *Context) watchStop(walker *ContextGraphWalker) (chan struct{}, <-chan s } // If we're here, we're stopped, trigger the call. - log.Printf("[TRACE] Context: requesting providers and provisioners to gracefully stop") { // Copy the providers so that a misbehaved blocking Stop doesn't // completely hang Terraform. walker.providerLock.Lock() - ps := make([]providers.Interface, 0, len(walker.providerCache)) + ps := make([]ResourceProvider, 0, len(walker.providerCache)) for _, p := range walker.providerCache { ps = append(ps, p) } @@ -832,7 +885,7 @@ func (c *Context) watchStop(walker *ContextGraphWalker) (chan struct{}, <-chan s { // Call stop on all the provisioners walker.provisionerLock.Lock() - ps := make([]provisioners.Interface, 0, len(walker.provisionerCache)) + ps := make([]ResourceProvisioner, 0, len(walker.provisionerCache)) for _, p := range walker.provisionerCache { ps = append(ps, p) } @@ -902,37 +955,3 @@ func parseVariableAsHCL(name string, input string, targetType config.VariableTyp panic(fmt.Errorf("unknown type %s", targetType.Printable())) } } - -// ShimLegacyState is a helper that takes the legacy state type and -// converts it to the new state type. -// -// This is implemented as a state file upgrade, so it will not preserve -// parts of the state structure that are not included in a serialized state, -// such as the resolved results of any local values, outputs in non-root -// modules, etc. -func ShimLegacyState(legacy *State) (*states.State, error) { - if legacy == nil { - return nil, nil - } - var buf bytes.Buffer - err := WriteState(legacy, &buf) - if err != nil { - return nil, err - } - f, err := statefile.Read(&buf) - if err != nil { - return nil, err - } - return f.State, err -} - -// MustShimLegacyState is a wrapper around ShimLegacyState that panics if -// the conversion does not succeed. This is primarily intended for tests where -// the given legacy state is an object constructed within the test. -func MustShimLegacyState(legacy *State) *states.State { - ret, err := ShimLegacyState(legacy) - if err != nil { - panic(err) - } - return ret -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/context_components.go b/vendor/github.com/hashicorp/terraform/terraform/context_components.go index 26ec9959..6f507445 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/context_components.go +++ b/vendor/github.com/hashicorp/terraform/terraform/context_components.go @@ -2,9 +2,6 @@ package terraform import ( "fmt" - - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" ) // contextComponentFactory is the interface that Context uses @@ -15,25 +12,25 @@ type contextComponentFactory interface { // ResourceProvider creates a new ResourceProvider with the given // type. The "uid" is a unique identifier for this provider being // initialized that can be used for internal tracking. - ResourceProvider(typ, uid string) (providers.Interface, error) + ResourceProvider(typ, uid string) (ResourceProvider, error) ResourceProviders() []string // ResourceProvisioner creates a new ResourceProvisioner with the // given type. The "uid" is a unique identifier for this provisioner // being initialized that can be used for internal tracking. - ResourceProvisioner(typ, uid string) (provisioners.Interface, error) + ResourceProvisioner(typ, uid string) (ResourceProvisioner, error) ResourceProvisioners() []string } // basicComponentFactory just calls a factory from a map directly. type basicComponentFactory struct { - providers map[string]providers.Factory - provisioners map[string]ProvisionerFactory + providers map[string]ResourceProviderFactory + provisioners map[string]ResourceProvisionerFactory } func (c *basicComponentFactory) ResourceProviders() []string { result := make([]string, len(c.providers)) - for k := range c.providers { + for k, _ := range c.providers { result = append(result, k) } @@ -42,14 +39,14 @@ func (c *basicComponentFactory) ResourceProviders() []string { func (c *basicComponentFactory) ResourceProvisioners() []string { result := make([]string, len(c.provisioners)) - for k := range c.provisioners { + for k, _ := range c.provisioners { result = append(result, k) } return result } -func (c *basicComponentFactory) ResourceProvider(typ, uid string) (providers.Interface, error) { +func (c *basicComponentFactory) ResourceProvider(typ, uid string) (ResourceProvider, error) { f, ok := c.providers[typ] if !ok { return nil, fmt.Errorf("unknown provider %q", typ) @@ -58,7 +55,7 @@ func (c *basicComponentFactory) ResourceProvider(typ, uid string) (providers.Int return f() } -func (c *basicComponentFactory) ResourceProvisioner(typ, uid string) (provisioners.Interface, error) { +func (c *basicComponentFactory) ResourceProvisioner(typ, uid string) (ResourceProvisioner, error) { f, ok := c.provisioners[typ] if !ok { return nil, fmt.Errorf("unknown provisioner %q", typ) diff --git a/vendor/github.com/hashicorp/terraform/terraform/context_graph_type.go b/vendor/github.com/hashicorp/terraform/terraform/context_graph_type.go index 0a424a01..084f0105 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/context_graph_type.go +++ b/vendor/github.com/hashicorp/terraform/terraform/context_graph_type.go @@ -14,8 +14,8 @@ const ( GraphTypePlan GraphTypePlanDestroy GraphTypeApply + GraphTypeInput GraphTypeValidate - GraphTypeEval // only visits in-memory elements such as variables, locals, and outputs. ) // GraphTypeMap is a mapping of human-readable string to GraphType. This @@ -23,10 +23,10 @@ const ( // graph types. var GraphTypeMap = map[string]GraphType{ "apply": GraphTypeApply, + "input": GraphTypeInput, "plan": GraphTypePlan, "plan-destroy": GraphTypePlanDestroy, "refresh": GraphTypeRefresh, "legacy": GraphTypeLegacy, "validate": GraphTypeValidate, - "eval": GraphTypeEval, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/context_import.go b/vendor/github.com/hashicorp/terraform/terraform/context_import.go index 313e9094..e9401431 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/context_import.go +++ b/vendor/github.com/hashicorp/terraform/terraform/context_import.go @@ -1,10 +1,7 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config/module" ) // ImportOpts are used as the configuration for Import. @@ -12,23 +9,23 @@ type ImportOpts struct { // Targets are the targets to import Targets []*ImportTarget - // Config is optional, and specifies a config tree that will be loaded - // into the graph and evaluated. This is the source for provider - // configurations. - Config *configs.Config + // Module is optional, and specifies a config module that is loaded + // into the graph and evaluated. The use case for this is to provide + // provider configuration. + Module *module.Tree } // ImportTarget is a single resource to import. type ImportTarget struct { - // Addr is the address for the resource instance that the new object should - // be imported into. - Addr addrs.AbsResourceInstance + // Addr is the full resource address of the resource to import. + // Example: "module.foo.aws_instance.bar" + Addr string // ID is the ID of the resource to import. This is resource-specific. ID string - // ProviderAddr is the address of the provider that should handle the import. - ProviderAddr addrs.AbsProviderConfig + // Provider string + Provider string } // Import takes already-created external resources and brings them @@ -41,9 +38,7 @@ type ImportTarget struct { // Further, this operation also gracefully handles partial state. If during // an import there is a failure, all previously imported resources remain // imported. -func (c *Context) Import(opts *ImportOpts) (*states.State, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - +func (c *Context) Import(opts *ImportOpts) (*State, error) { // Hold a lock since we can modify our own state here defer c.acquireRun("import")() @@ -52,32 +47,31 @@ func (c *Context) Import(opts *ImportOpts) (*states.State, tfdiags.Diagnostics) // If no module is given, default to the module configured with // the Context. - config := opts.Config - if config == nil { - config = c.config + module := opts.Module + if module == nil { + module = c.module } // Initialize our graph builder builder := &ImportGraphBuilder{ ImportTargets: opts.Targets, - Config: config, - Components: c.components, - Schemas: c.schemas, + Module: module, + Providers: c.components.ResourceProviders(), } // Build the graph! - graph, graphDiags := builder.Build(addrs.RootModuleInstance) - diags = diags.Append(graphDiags) - if graphDiags.HasErrors() { - return c.state, diags + graph, err := builder.Build(RootModulePath) + if err != nil { + return c.state, err } // Walk it - _, walkDiags := c.walk(graph, walkImport) - diags = diags.Append(walkDiags) - if walkDiags.HasErrors() { - return c.state, diags + if _, err := c.walk(graph, walkImport); err != nil { + return c.state, err } - return c.state, diags + // Clean the state + c.state.prune() + + return c.state, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/context_input.go b/vendor/github.com/hashicorp/terraform/terraform/context_input.go deleted file mode 100644 index 7c5b7ecb..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/context_input.go +++ /dev/null @@ -1,248 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - "sort" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcldec" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/tfdiags" -) - -// Input asks for input to fill variables and provider configurations. -// This modifies the configuration in-place, so asking for Input twice -// may result in different UI output showing different current values. -func (c *Context) Input(mode InputMode) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - defer c.acquireRun("input")() - - if c.uiInput == nil { - log.Printf("[TRACE] Context.Input: uiInput is nil, so skipping") - return diags - } - - if mode&InputModeVar != 0 { - log.Printf("[TRACE] Context.Input: Prompting for variables") - - // Walk the variables first for the root module. We walk them in - // alphabetical order for UX reasons. - configs := c.config.Module.Variables - names := make([]string, 0, len(configs)) - for name := range configs { - names = append(names, name) - } - sort.Strings(names) - Variables: - for _, n := range names { - v := configs[n] - - // If we only care about unset variables, then we should set any - // variable that is already set. - if mode&InputModeVarUnset != 0 { - if _, isSet := c.variables[n]; isSet { - continue - } - } - - // this should only happen during tests - if c.uiInput == nil { - log.Println("[WARN] Context.uiInput is nil during input walk") - continue - } - - // Ask the user for a value for this variable - var rawValue string - retry := 0 - for { - var err error - rawValue, err = c.uiInput.Input(&InputOpts{ - Id: fmt.Sprintf("var.%s", n), - Query: fmt.Sprintf("var.%s", n), - Description: v.Description, - }) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to request interactive input", - fmt.Sprintf("Terraform attempted to request a value for var.%s interactively, but encountered an error: %s.", n, err), - )) - return diags - } - - if rawValue == "" && v.Default == cty.NilVal { - // Redo if it is required, but abort if we keep getting - // blank entries - if retry > 2 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Required variable not assigned", - fmt.Sprintf("The variable %q is required, so Terraform cannot proceed without a defined value for it.", n), - )) - continue Variables - } - retry++ - continue - } - - break - } - - val, valDiags := v.ParsingMode.Parse(n, rawValue) - diags = diags.Append(valDiags) - if diags.HasErrors() { - continue - } - - c.variables[n] = &InputValue{ - Value: val, - SourceType: ValueFromInput, - } - } - } - - if mode&InputModeProvider != 0 { - log.Printf("[TRACE] Context.Input: Prompting for provider arguments") - - // We prompt for input only for provider configurations defined in - // the root module. At the time of writing that is an arbitrary - // restriction, but we have future plans to support "count" and - // "for_each" on modules that will then prevent us from supporting - // input for child module configurations anyway (since we'd need to - // dynamic-expand first), and provider configurations in child modules - // are not recommended since v0.11 anyway, so this restriction allows - // us to keep this relatively simple without significant hardship. - - pcs := make(map[string]*configs.Provider) - pas := make(map[string]addrs.ProviderConfig) - for _, pc := range c.config.Module.ProviderConfigs { - addr := pc.Addr() - pcs[addr.String()] = pc - pas[addr.String()] = addr - log.Printf("[TRACE] Context.Input: Provider %s declared at %s", addr, pc.DeclRange) - } - // We also need to detect _implied_ provider configs from resources. - // These won't have *configs.Provider objects, but they will still - // exist in the map and we'll just treat them as empty below. - for _, rc := range c.config.Module.ManagedResources { - pa := rc.ProviderConfigAddr() - if pa.Alias != "" { - continue // alias configurations cannot be implied - } - if _, exists := pcs[pa.String()]; !exists { - pcs[pa.String()] = nil - pas[pa.String()] = pa - log.Printf("[TRACE] Context.Input: Provider %s implied by resource block at %s", pa, rc.DeclRange) - } - } - for _, rc := range c.config.Module.DataResources { - pa := rc.ProviderConfigAddr() - if pa.Alias != "" { - continue // alias configurations cannot be implied - } - if _, exists := pcs[pa.String()]; !exists { - pcs[pa.String()] = nil - pas[pa.String()] = pa - log.Printf("[TRACE] Context.Input: Provider %s implied by data block at %s", pa, rc.DeclRange) - } - } - - for pk, pa := range pas { - pc := pcs[pk] // will be nil if this is an implied config - - // Wrap the input into a namespace - input := &PrefixUIInput{ - IdPrefix: pk, - QueryPrefix: pk + ".", - UIInput: c.uiInput, - } - - schema := c.schemas.ProviderConfig(pa.Type) - if schema == nil { - // Could either be an incorrect config or just an incomplete - // mock in tests. We'll let a later pass decide, and just - // ignore this for the purposes of gathering input. - log.Printf("[TRACE] Context.Input: No schema available for provider type %q", pa.Type) - continue - } - - // For our purposes here we just want to detect if attrbutes are - // set in config at all, so rather than doing a full decode - // (which would require us to prepare an evalcontext, etc) we'll - // use the low-level HCL API to process only the top-level - // structure. - var attrExprs hcl.Attributes // nil if there is no config - if pc != nil && pc.Config != nil { - lowLevelSchema := schemaForInputSniffing(hcldec.ImpliedSchema(schema.DecoderSpec())) - content, _, diags := pc.Config.PartialContent(lowLevelSchema) - if diags.HasErrors() { - log.Printf("[TRACE] Context.Input: %s has decode error, so ignoring: %s", pa, diags.Error()) - continue - } - attrExprs = content.Attributes - } - - keys := make([]string, 0, len(schema.Attributes)) - for key := range schema.Attributes { - keys = append(keys, key) - } - sort.Strings(keys) - - vals := map[string]cty.Value{} - for _, key := range keys { - attrS := schema.Attributes[key] - if attrS.Optional { - continue - } - if attrExprs != nil { - if _, exists := attrExprs[key]; exists { - continue - } - } - if !attrS.Type.Equals(cty.String) { - continue - } - - log.Printf("[TRACE] Context.Input: Prompting for %s argument %s", pa, key) - rawVal, err := input.Input(&InputOpts{ - Id: key, - Query: key, - Description: attrS.Description, - }) - if err != nil { - log.Printf("[TRACE] Context.Input: Failed to prompt for %s argument %s: %s", pa, key, err) - continue - } - - vals[key] = cty.StringVal(rawVal) - } - - c.providerInputConfig[pk] = vals - log.Printf("[TRACE] Context.Input: Input for %s: %#v", pk, vals) - } - } - - return diags -} - -// schemaForInputSniffing returns a transformed version of a given schema -// that marks all attributes as optional, which the Context.Input method can -// use to detect whether a required argument is set without missing arguments -// themselves generating errors. -func schemaForInputSniffing(schema *hcl.BodySchema) *hcl.BodySchema { - ret := &hcl.BodySchema{ - Attributes: make([]hcl.AttributeSchema, len(schema.Attributes)), - Blocks: schema.Blocks, - } - - for i, attrS := range schema.Attributes { - ret.Attributes[i] = attrS - ret.Attributes[i].Required = false - } - - return ret -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/debug.go b/vendor/github.com/hashicorp/terraform/terraform/debug.go new file mode 100644 index 00000000..265339f6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/debug.go @@ -0,0 +1,523 @@ +package terraform + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "sync" + "time" +) + +// DebugInfo is the global handler for writing the debug archive. All methods +// are safe to call concurrently. Setting DebugInfo to nil will disable writing +// the debug archive. All methods are safe to call on the nil value. +var dbug *debugInfo + +// SetDebugInfo initializes the debug handler with a backing file in the +// provided directory. This must be called before any other terraform package +// operations or not at all. Once his is called, CloseDebugInfo should be +// called before program exit. +func SetDebugInfo(path string) error { + if os.Getenv("TF_DEBUG") == "" { + return nil + } + + di, err := newDebugInfoFile(path) + if err != nil { + return err + } + + dbug = di + return nil +} + +// CloseDebugInfo is the exported interface to Close the debug info handler. +// The debug handler needs to be closed before program exit, so we export this +// function to be deferred in the appropriate entrypoint for our executable. +func CloseDebugInfo() error { + return dbug.Close() +} + +// newDebugInfoFile initializes the global debug handler with a backing file in +// the provided directory. +func newDebugInfoFile(dir string) (*debugInfo, error) { + err := os.MkdirAll(dir, 0755) + if err != nil { + return nil, err + } + + // FIXME: not guaranteed unique, but good enough for now + name := fmt.Sprintf("debug-%s", time.Now().Format("2006-01-02-15-04-05.999999999")) + archivePath := filepath.Join(dir, name+".tar.gz") + + f, err := os.OpenFile(archivePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666) + if err != nil { + return nil, err + } + return newDebugInfo(name, f) +} + +// newDebugInfo initializes the global debug handler. +func newDebugInfo(name string, w io.Writer) (*debugInfo, error) { + gz := gzip.NewWriter(w) + + d := &debugInfo{ + name: name, + w: w, + gz: gz, + tar: tar.NewWriter(gz), + } + + // create the subdirs we need + topHdr := &tar.Header{ + Name: name, + Typeflag: tar.TypeDir, + Mode: 0755, + } + graphsHdr := &tar.Header{ + Name: name + "/graphs", + Typeflag: tar.TypeDir, + Mode: 0755, + } + err := d.tar.WriteHeader(topHdr) + // if the first errors, the second will too + err = d.tar.WriteHeader(graphsHdr) + if err != nil { + return nil, err + } + + return d, nil +} + +// debugInfo provides various methods for writing debug information to a +// central archive. The debugInfo struct should be initialized once before any +// output is written, and Close should be called before program exit. All +// exported methods on debugInfo will be safe for concurrent use. The exported +// methods are also all safe to call on a nil pointer, so that there is no need +// for conditional blocks before writing debug information. +// +// Each write operation done by the debugInfo will flush the gzip.Writer and +// tar.Writer, and call Sync() or Flush() on the output writer as needed. This +// ensures that as much data as possible is written to storage in the event of +// a crash. The append format of the tar file, and the stream format of the +// gzip writer allow easy recovery f the data in the event that the debugInfo +// is not closed before program exit. +type debugInfo struct { + sync.Mutex + + // archive root directory name + name string + + // current operation phase + phase string + + // step is monotonic counter for for recording the order of operations + step int + + // flag to protect Close() + closed bool + + // the debug log output is in a tar.gz format, written to the io.Writer w + w io.Writer + gz *gzip.Writer + tar *tar.Writer +} + +// Set the name of the current operational phase in the debug handler. Each file +// in the archive will contain the name of the phase in which it was created, +// i.e. "input", "apply", "plan", "refresh", "validate" +func (d *debugInfo) SetPhase(phase string) { + if d == nil { + return + } + d.Lock() + defer d.Unlock() + + d.phase = phase +} + +// Close the debugInfo, finalizing the data in storage. This closes the +// tar.Writer, the gzip.Wrtier, and if the output writer is an io.Closer, it is +// also closed. +func (d *debugInfo) Close() error { + if d == nil { + return nil + } + + d.Lock() + defer d.Unlock() + + if d.closed { + return nil + } + d.closed = true + + d.tar.Close() + d.gz.Close() + + if c, ok := d.w.(io.Closer); ok { + return c.Close() + } + return nil +} + +// debug buffer is an io.WriteCloser that will write itself to the debug +// archive when closed. +type debugBuffer struct { + debugInfo *debugInfo + name string + buf bytes.Buffer +} + +func (b *debugBuffer) Write(d []byte) (int, error) { + return b.buf.Write(d) +} + +func (b *debugBuffer) Close() error { + return b.debugInfo.WriteFile(b.name, b.buf.Bytes()) +} + +// ioutils only has a noop ReadCloser +type nopWriteCloser struct{} + +func (nopWriteCloser) Write([]byte) (int, error) { return 0, nil } +func (nopWriteCloser) Close() error { return nil } + +// NewFileWriter returns an io.WriteClose that will be buffered and written to +// the debug archive when closed. +func (d *debugInfo) NewFileWriter(name string) io.WriteCloser { + if d == nil { + return nopWriteCloser{} + } + + return &debugBuffer{ + debugInfo: d, + name: name, + } +} + +type syncer interface { + Sync() error +} + +type flusher interface { + Flush() error +} + +// Flush the tar.Writer and the gzip.Writer. Flush() or Sync() will be called +// on the output writer if they are available. +func (d *debugInfo) flush() { + d.tar.Flush() + d.gz.Flush() + + if f, ok := d.w.(flusher); ok { + f.Flush() + } + + if s, ok := d.w.(syncer); ok { + s.Sync() + } +} + +// WriteFile writes data as a single file to the debug arhive. +func (d *debugInfo) WriteFile(name string, data []byte) error { + if d == nil { + return nil + } + + d.Lock() + defer d.Unlock() + return d.writeFile(name, data) +} + +func (d *debugInfo) writeFile(name string, data []byte) error { + defer d.flush() + path := fmt.Sprintf("%s/%d-%s-%s", d.name, d.step, d.phase, name) + d.step++ + + hdr := &tar.Header{ + Name: path, + Mode: 0644, + Size: int64(len(data)), + } + err := d.tar.WriteHeader(hdr) + if err != nil { + return err + } + + _, err = d.tar.Write(data) + return err +} + +// DebugHook implements all methods of the terraform.Hook interface, and writes +// the arguments to a file in the archive. When a suitable format for the +// argument isn't available, the argument is encoded using json.Marshal. If the +// debug handler is nil, all DebugHook methods are noop, so no time is spent in +// marshaling the data structures. +type DebugHook struct{} + +func (*DebugHook) PreApply(ii *InstanceInfo, is *InstanceState, id *InstanceDiff) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + + if ii != nil { + buf.WriteString(ii.HumanId() + "\n") + } + + if is != nil { + buf.WriteString(is.String() + "\n") + } + + idCopy, err := id.Copy() + if err != nil { + return HookActionContinue, err + } + js, err := json.MarshalIndent(idCopy, "", " ") + if err != nil { + return HookActionContinue, err + } + buf.Write(js) + + dbug.WriteFile("hook-PreApply", buf.Bytes()) + + return HookActionContinue, nil +} + +func (*DebugHook) PostApply(ii *InstanceInfo, is *InstanceState, err error) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + + if ii != nil { + buf.WriteString(ii.HumanId() + "\n") + } + + if is != nil { + buf.WriteString(is.String() + "\n") + } + + if err != nil { + buf.WriteString(err.Error()) + } + + dbug.WriteFile("hook-PostApply", buf.Bytes()) + + return HookActionContinue, nil +} + +func (*DebugHook) PreDiff(ii *InstanceInfo, is *InstanceState) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId() + "\n") + } + + if is != nil { + buf.WriteString(is.String()) + buf.WriteString("\n") + } + dbug.WriteFile("hook-PreDiff", buf.Bytes()) + + return HookActionContinue, nil +} + +func (*DebugHook) PostDiff(ii *InstanceInfo, id *InstanceDiff) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId() + "\n") + } + + idCopy, err := id.Copy() + if err != nil { + return HookActionContinue, err + } + js, err := json.MarshalIndent(idCopy, "", " ") + if err != nil { + return HookActionContinue, err + } + buf.Write(js) + + dbug.WriteFile("hook-PostDiff", buf.Bytes()) + + return HookActionContinue, nil +} + +func (*DebugHook) PreProvisionResource(ii *InstanceInfo, is *InstanceState) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId() + "\n") + } + + if is != nil { + buf.WriteString(is.String()) + buf.WriteString("\n") + } + dbug.WriteFile("hook-PreProvisionResource", buf.Bytes()) + + return HookActionContinue, nil +} + +func (*DebugHook) PostProvisionResource(ii *InstanceInfo, is *InstanceState) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId()) + buf.WriteString("\n") + } + + if is != nil { + buf.WriteString(is.String()) + buf.WriteString("\n") + } + dbug.WriteFile("hook-PostProvisionResource", buf.Bytes()) + return HookActionContinue, nil +} + +func (*DebugHook) PreProvision(ii *InstanceInfo, s string) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId()) + buf.WriteString("\n") + } + buf.WriteString(s + "\n") + + dbug.WriteFile("hook-PreProvision", buf.Bytes()) + return HookActionContinue, nil +} + +func (*DebugHook) PostProvision(ii *InstanceInfo, s string, err error) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId() + "\n") + } + buf.WriteString(s + "\n") + + dbug.WriteFile("hook-PostProvision", buf.Bytes()) + return HookActionContinue, nil +} + +func (*DebugHook) ProvisionOutput(ii *InstanceInfo, s1 string, s2 string) { + if dbug == nil { + return + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId()) + buf.WriteString("\n") + } + buf.WriteString(s1 + "\n") + buf.WriteString(s2 + "\n") + + dbug.WriteFile("hook-ProvisionOutput", buf.Bytes()) +} + +func (*DebugHook) PreRefresh(ii *InstanceInfo, is *InstanceState) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId() + "\n") + } + + if is != nil { + buf.WriteString(is.String()) + buf.WriteString("\n") + } + dbug.WriteFile("hook-PreRefresh", buf.Bytes()) + return HookActionContinue, nil +} + +func (*DebugHook) PostRefresh(ii *InstanceInfo, is *InstanceState) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId()) + buf.WriteString("\n") + } + + if is != nil { + buf.WriteString(is.String()) + buf.WriteString("\n") + } + dbug.WriteFile("hook-PostRefresh", buf.Bytes()) + return HookActionContinue, nil +} + +func (*DebugHook) PreImportState(ii *InstanceInfo, s string) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + if ii != nil { + buf.WriteString(ii.HumanId()) + buf.WriteString("\n") + } + buf.WriteString(s + "\n") + + dbug.WriteFile("hook-PreImportState", buf.Bytes()) + return HookActionContinue, nil +} + +func (*DebugHook) PostImportState(ii *InstanceInfo, iss []*InstanceState) (HookAction, error) { + if dbug == nil { + return HookActionContinue, nil + } + + var buf bytes.Buffer + + if ii != nil { + buf.WriteString(ii.HumanId() + "\n") + } + + for _, is := range iss { + if is != nil { + buf.WriteString(is.String() + "\n") + } + } + dbug.WriteFile("hook-PostImportState", buf.Bytes()) + return HookActionContinue, nil +} + +// skip logging this for now, since it could be huge +func (*DebugHook) PostStateUpdate(*State) (HookAction, error) { + return HookActionContinue, nil +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/diff.go b/vendor/github.com/hashicorp/terraform/terraform/diff.go index 3f26117a..d6dc5506 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/diff.go +++ b/vendor/github.com/hashicorp/terraform/terraform/diff.go @@ -4,20 +4,12 @@ import ( "bufio" "bytes" "fmt" - "log" "reflect" "regexp" "sort" - "strconv" "strings" "sync" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/hcl2shim" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/zclconf/go-cty/cty" - "github.com/mitchellh/copystructure" ) @@ -77,24 +69,8 @@ func (d *Diff) Prune() { // // This should be the preferred method to add module diffs since it // allows us to optimize lookups later as well as control sorting. -func (d *Diff) AddModule(path addrs.ModuleInstance) *ModuleDiff { - // Lower the new-style address into a legacy-style address. - // This requires that none of the steps have instance keys, which is - // true for all addresses at the time of implementing this because - // "count" and "for_each" are not yet implemented for modules. - legacyPath := make([]string, len(path)) - for i, step := range path { - if step.InstanceKey != addrs.NoKey { - // FIXME: Once the rest of Terraform is ready to use count and - // for_each, remove all of this and just write the addrs.ModuleInstance - // value itself into the ModuleState. - panic("diff cannot represent modules with count or for_each keys") - } - - legacyPath[i] = step.Name - } - - m := &ModuleDiff{Path: legacyPath} +func (d *Diff) AddModule(path []string) *ModuleDiff { + m := &ModuleDiff{Path: path} m.init() d.Modules = append(d.Modules, m) return m @@ -103,7 +79,7 @@ func (d *Diff) AddModule(path addrs.ModuleInstance) *ModuleDiff { // ModuleByPath is used to lookup the module diff for the given path. // This should be the preferred lookup mechanism as it allows for future // lookup optimizations. -func (d *Diff) ModuleByPath(path addrs.ModuleInstance) *ModuleDiff { +func (d *Diff) ModuleByPath(path []string) *ModuleDiff { if d == nil { return nil } @@ -111,8 +87,7 @@ func (d *Diff) ModuleByPath(path addrs.ModuleInstance) *ModuleDiff { if mod.Path == nil { panic("missing module path") } - modPath := normalizeModulePath(mod.Path) - if modPath.String() == path.String() { + if reflect.DeepEqual(mod.Path, path) { return mod } } @@ -121,7 +96,7 @@ func (d *Diff) ModuleByPath(path addrs.ModuleInstance) *ModuleDiff { // RootModule returns the ModuleState for the root module func (d *Diff) RootModule() *ModuleDiff { - root := d.ModuleByPath(addrs.RootModuleInstance) + root := d.ModuleByPath(rootModulePath) if root == nil { panic("missing root module") } @@ -191,8 +166,7 @@ func (d *Diff) String() string { keys := make([]string, 0, len(d.Modules)) lookup := make(map[string]*ModuleDiff) for _, m := range d.Modules { - addr := normalizeModulePath(m.Path) - key := addr.String() + key := fmt.Sprintf("module.%s", strings.Join(m.Path[1:], ".")) keys = append(keys, key) lookup[key] = m } @@ -410,495 +384,6 @@ type InstanceDiff struct { func (d *InstanceDiff) Lock() { d.mu.Lock() } func (d *InstanceDiff) Unlock() { d.mu.Unlock() } -// ApplyToValue merges the receiver into the given base value, returning a -// new value that incorporates the planned changes. The given value must -// conform to the given schema, or this method will panic. -// -// This method is intended for shimming old subsystems that still use this -// legacy diff type to work with the new-style types. -func (d *InstanceDiff) ApplyToValue(base cty.Value, schema *configschema.Block) (cty.Value, error) { - // Create an InstanceState attributes from our existing state. - // We can use this to more easily apply the diff changes. - attrs := hcl2shim.FlatmapValueFromHCL2(base) - applied, err := d.Apply(attrs, schema) - if err != nil { - return base, err - } - - val, err := hcl2shim.HCL2ValueFromFlatmap(applied, schema.ImpliedType()) - if err != nil { - return base, err - } - - return schema.CoerceValue(val) -} - -// Apply applies the diff to the provided flatmapped attributes, -// returning the new instance attributes. -// -// This method is intended for shimming old subsystems that still use this -// legacy diff type to work with the new-style types. -func (d *InstanceDiff) Apply(attrs map[string]string, schema *configschema.Block) (map[string]string, error) { - // We always build a new value here, even if the given diff is "empty", - // because we might be planning to create a new instance that happens - // to have no attributes set, and so we want to produce an empty object - // rather than just echoing back the null old value. - if attrs == nil { - attrs = map[string]string{} - } - - // Rather applying the diff to mutate the attrs, we'll copy new values into - // here to avoid the possibility of leaving stale values. - result := map[string]string{} - - if d.Destroy || d.DestroyDeposed || d.DestroyTainted { - return result, nil - } - - return d.applyBlockDiff(nil, attrs, schema) -} - -func (d *InstanceDiff) applyBlockDiff(path []string, attrs map[string]string, schema *configschema.Block) (map[string]string, error) { - result := map[string]string{} - - name := "" - if len(path) > 0 { - name = path[len(path)-1] - } - - // localPrefix is used to build the local result map - localPrefix := "" - if name != "" { - localPrefix = name + "." - } - - // iterate over the schema rather than the attributes, so we can handle - // different block types separately from plain attributes - for n, attrSchema := range schema.Attributes { - var err error - newAttrs, err := d.applyAttrDiff(append(path, n), attrs, attrSchema) - - if err != nil { - return result, err - } - - for k, v := range newAttrs { - result[localPrefix+k] = v - } - } - - blockPrefix := strings.Join(path, ".") - if blockPrefix != "" { - blockPrefix += "." - } - for n, block := range schema.BlockTypes { - // we need to find the set of all keys that traverse this block - candidateKeys := map[string]bool{} - blockKey := blockPrefix + n + "." - localBlockPrefix := localPrefix + n + "." - - // we can only trust the diff for sets, since the path changes, so don't - // count existing values as candidate keys. If it turns out we're - // keeping the attributes, we will catch it down below with "keepBlock" - // after we check the set count. - if block.Nesting != configschema.NestingSet { - for k := range attrs { - if strings.HasPrefix(k, blockKey) { - nextDot := strings.Index(k[len(blockKey):], ".") - if nextDot < 0 { - continue - } - nextDot += len(blockKey) - candidateKeys[k[len(blockKey):nextDot]] = true - } - } - } - - for k, diff := range d.Attributes { - if strings.HasPrefix(k, blockKey) { - nextDot := strings.Index(k[len(blockKey):], ".") - if nextDot < 0 { - continue - } - - if diff.NewRemoved { - continue - } - - nextDot += len(blockKey) - candidateKeys[k[len(blockKey):nextDot]] = true - } - } - - // check each set candidate to see if it was removed. - // we need to do this, because when entire sets are removed, they may - // have the wrong key, and ony show diffs going to "" - if block.Nesting == configschema.NestingSet { - for k := range candidateKeys { - indexPrefix := strings.Join(append(path, n, k), ".") + "." - keep := false - // now check each set element to see if it's a new diff, or one - // that we're dropping. Since we're only applying the "New" - // portion of the set, we can ignore diffs that only contain "Old" - for attr, diff := range d.Attributes { - if !strings.HasPrefix(attr, indexPrefix) { - continue - } - - // check for empty "count" keys - if (strings.HasSuffix(attr, ".#") || strings.HasSuffix(attr, ".%")) && diff.New == "0" { - continue - } - - // removed items don't count either - if diff.NewRemoved { - continue - } - - // this must be a diff to keep - keep = true - break - } - if !keep { - delete(candidateKeys, k) - } - } - } - - for k := range candidateKeys { - newAttrs, err := d.applyBlockDiff(append(path, n, k), attrs, &block.Block) - if err != nil { - return result, err - } - - for attr, v := range newAttrs { - result[localBlockPrefix+attr] = v - } - } - - keepBlock := true - // check this block's count diff directly first, since we may not - // have candidates because it was removed and only set to "0" - if diff, ok := d.Attributes[blockKey+"#"]; ok { - if diff.New == "0" || diff.NewRemoved { - keepBlock = false - } - } - - // if there was no diff at all, then we need to keep the block attributes - if len(candidateKeys) == 0 && keepBlock { - for k, v := range attrs { - if strings.HasPrefix(k, blockKey) { - // we need the key relative to this block, so remove the - // entire prefix, then re-insert the block name. - localKey := localBlockPrefix + k[len(blockKey):] - result[localKey] = v - } - } - } - - if countDiff, ok := d.Attributes[strings.Join(append(path, n, "#"), ".")]; ok { - if countDiff.NewComputed { - result[localBlockPrefix+"#"] = hcl2shim.UnknownVariableValue - } else { - result[localBlockPrefix+"#"] = countDiff.New - - // While sets are complete, list are not, and we may not have all the - // information to track removals. If the list was truncated, we need to - // remove the extra items from the result. - if block.Nesting == configschema.NestingList && - countDiff.New != "" && countDiff.New != hcl2shim.UnknownVariableValue { - length, _ := strconv.Atoi(countDiff.New) - for k := range result { - if !strings.HasPrefix(k, localBlockPrefix) { - continue - } - - index := k[len(localBlockPrefix):] - nextDot := strings.Index(index, ".") - if nextDot < 1 { - continue - } - index = index[:nextDot] - i, err := strconv.Atoi(index) - if err != nil { - // this shouldn't happen since we added these - // ourself, but make note of it just in case. - log.Printf("[ERROR] bad list index in %q: %s", k, err) - continue - } - if i >= length { - delete(result, k) - } - } - } - } - } else { - result[localBlockPrefix+"#"] = countFlatmapContainerValues(localBlockPrefix+"#", result) - } - } - - return result, nil -} - -func (d *InstanceDiff) applyAttrDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { - ty := attrSchema.Type - switch { - case ty.IsListType(), ty.IsTupleType(), ty.IsMapType(), ty.IsSetType(): - return d.applyCollectionDiff(path, attrs, attrSchema) - default: - return d.applySingleAttrDiff(path, attrs, attrSchema) - } -} - -func (d *InstanceDiff) applySingleAttrDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { - currentKey := strings.Join(path, ".") - - attr := path[len(path)-1] - - result := map[string]string{} - diff := d.Attributes[currentKey] - old, exists := attrs[currentKey] - - if diff != nil && diff.NewComputed { - result[attr] = config.UnknownVariableValue - return result, nil - } - - // "id" must exist and not be an empty string, or it must be unknown. - // This only applied to top-level "id" fields. - if attr == "id" && len(path) == 1 { - if old == "" { - result[attr] = config.UnknownVariableValue - } else { - result[attr] = old - } - return result, nil - } - - // attribute diffs are sometimes missed, so assume no diff means keep the - // old value - if diff == nil { - if exists { - result[attr] = old - } else { - // We need required values, so set those with an empty value. It - // must be set in the config, since if it were missing it would have - // failed validation. - if attrSchema.Required { - // we only set a missing string here, since bool or number types - // would have distinct zero value which shouldn't have been - // lost. - if attrSchema.Type == cty.String { - result[attr] = "" - } - } - } - return result, nil - } - - if diff.Old == diff.New && diff.New == "" { - // this can only be a valid empty string - if attrSchema.Type == cty.String { - result[attr] = "" - } - return result, nil - } - - // check for missmatched diff values - if exists && - old != diff.Old && - old != config.UnknownVariableValue && - diff.Old != config.UnknownVariableValue { - return result, fmt.Errorf("diff apply conflict for %s: diff expects %q, but prior value has %q", attr, diff.Old, old) - } - - if attrSchema.Computed && diff.NewComputed { - result[attr] = config.UnknownVariableValue - return result, nil - } - - if diff.NewRemoved { - // don't set anything in the new value - return result, nil - } - - result[attr] = diff.New - - return result, nil -} - -func (d *InstanceDiff) applyCollectionDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { - result := map[string]string{} - - prefix := "" - if len(path) > 1 { - prefix = strings.Join(path[:len(path)-1], ".") + "." - } - - name := "" - if len(path) > 0 { - name = path[len(path)-1] - } - - currentKey := prefix + name - - // check the index first for special handling - for k, diff := range d.Attributes { - // check the index value, which can be set, and 0 - if k == currentKey+".#" || k == currentKey+".%" || k == currentKey { - if diff.NewRemoved { - return result, nil - } - - if diff.NewComputed { - result[k[len(prefix):]] = config.UnknownVariableValue - return result, nil - } - - // do what the diff tells us to here, so that it's consistent with applies - if diff.New == "0" { - result[k[len(prefix):]] = "0" - return result, nil - } - } - } - - // collect all the keys from the diff and the old state - noDiff := true - keys := map[string]bool{} - for k := range d.Attributes { - if !strings.HasPrefix(k, currentKey+".") { - continue - } - noDiff = false - keys[k] = true - } - - noAttrs := true - for k := range attrs { - if !strings.HasPrefix(k, currentKey+".") { - continue - } - noAttrs = false - keys[k] = true - } - - // If there's no diff and no attrs, then there's no value at all. - // This prevents an unexpected zero-count attribute in the attributes. - if noDiff && noAttrs { - return result, nil - } - - idx := "#" - if attrSchema.Type.IsMapType() { - idx = "%" - } - - for k := range keys { - // generate an schema placeholder for the values - elSchema := &configschema.Attribute{ - Type: attrSchema.Type.ElementType(), - } - - res, err := d.applySingleAttrDiff(append(path, k[len(currentKey)+1:]), attrs, elSchema) - if err != nil { - return result, err - } - - for k, v := range res { - result[name+"."+k] = v - } - } - - // Just like in nested list blocks, for simple lists we may need to fill in - // missing empty strings. - countKey := name + "." + idx - count := result[countKey] - length, _ := strconv.Atoi(count) - - if count != "" && count != hcl2shim.UnknownVariableValue && - attrSchema.Type.Equals(cty.List(cty.String)) { - // insert empty strings into missing indexes - for i := 0; i < length; i++ { - key := fmt.Sprintf("%s.%d", name, i) - if _, ok := result[key]; !ok { - result[key] = "" - } - } - } - - // now check for truncation in any type of list - if attrSchema.Type.IsListType() { - for key := range result { - if key == countKey { - continue - } - - if len(key) <= len(name)+1 { - // not sure what this is, but don't panic - continue - } - - index := key[len(name)+1:] - - // It is possible to have nested sets or maps, so look for another dot - dot := strings.Index(index, ".") - if dot > 0 { - index = index[:dot] - } - - // This shouldn't have any more dots, since the element type is only string. - num, err := strconv.Atoi(index) - if err != nil { - log.Printf("[ERROR] bad list index in %q: %s", currentKey, err) - continue - } - - if num >= length { - delete(result, key) - } - } - } - - // Fill in the count value if it was missing for some reason: - if result[countKey] == "" { - result[countKey] = countFlatmapContainerValues(countKey, result) - } - - return result, nil -} - -// countFlatmapContainerValues returns the number of values in the flatmapped container -// (set, map, list) indexed by key. The key argument is expected to include the -// trailing ".#", or ".%". -func countFlatmapContainerValues(key string, attrs map[string]string) string { - if len(key) < 3 || !(strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { - panic(fmt.Sprintf("invalid index value %q", key)) - } - - prefix := key[:len(key)-1] - items := map[string]int{} - - for k := range attrs { - if k == key { - continue - } - if !strings.HasPrefix(k, prefix) { - continue - } - - suffix := k[len(prefix):] - dot := strings.Index(suffix, ".") - if dot > 0 { - suffix = suffix[:dot] - } - - items[suffix]++ - } - return strconv.Itoa(len(items)) -} - // ResourceAttrDiff is the diff of a single attribute of a resource. type ResourceAttrDiff struct { Old string // Old Value diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval.go b/vendor/github.com/hashicorp/terraform/terraform/eval.go index 48ed3533..10d9c228 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval.go @@ -2,8 +2,7 @@ package terraform import ( "log" - - "github.com/hashicorp/terraform/tfdiags" + "strings" ) // EvalNode is the interface that must be implemented by graph nodes to @@ -47,21 +46,15 @@ func Eval(n EvalNode, ctx EvalContext) (interface{}, error) { func EvalRaw(n EvalNode, ctx EvalContext) (interface{}, error) { path := "unknown" if ctx != nil { - path = ctx.Path().String() - } - if path == "" { - path = "" + path = strings.Join(ctx.Path(), ".") } log.Printf("[TRACE] %s: eval: %T", path, n) output, err := n.Eval(ctx) if err != nil { - switch err.(type) { - case EvalEarlyExitError: - log.Printf("[TRACE] %s: eval: %T, early exit err: %s", path, n, err) - case tfdiags.NonFatalError: - log.Printf("[WARN] %s: eval: %T, non-fatal err: %s", path, n, err) - default: + if _, ok := err.(EvalEarlyExitError); ok { + log.Printf("[TRACE] %s: eval: %T, err: %s", path, n, err) + } else { log.Printf("[ERROR] %s: eval: %T, err: %s", path, n, err) } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_apply.go b/vendor/github.com/hashicorp/terraform/terraform/eval_apply.go index 1da62d30..b9b48064 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_apply.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_apply.go @@ -3,315 +3,119 @@ package terraform import ( "fmt" "log" - "strings" + "strconv" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/plans/objchange" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config" ) // EvalApply is an EvalNode implementation that writes the diff to // the full diff. type EvalApply struct { - Addr addrs.ResourceInstance - Config *configs.Resource - Dependencies []addrs.Referenceable - State **states.ResourceInstanceObject - Change **plans.ResourceInstanceChange - ProviderAddr addrs.AbsProviderConfig - Provider *providers.Interface - ProviderSchema **ProviderSchema - Output **states.ResourceInstanceObject - CreateNew *bool - Error *error + Info *InstanceInfo + State **InstanceState + Diff **InstanceDiff + Provider *ResourceProvider + Output **InstanceState + CreateNew *bool + Error *error } // TODO: test func (n *EvalApply) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - - change := *n.Change + diff := *n.Diff provider := *n.Provider state := *n.State - absAddr := n.Addr.Absolute(ctx.Path()) + // If we have no diff, we have nothing to do! + if diff.Empty() { + log.Printf( + "[DEBUG] apply: %s: diff is empty, doing nothing.", n.Info.Id) + return nil, nil + } + + // Remove any output values from the diff + for k, ad := range diff.CopyAttributes() { + if ad.Type == DiffAttrOutput { + diff.DelAttribute(k) + } + } + + // If the state is nil, make it non-nil if state == nil { - state = &states.ResourceInstanceObject{} - } - - schema, _ := (*n.ProviderSchema).SchemaForResourceType(n.Addr.Resource.Mode, n.Addr.Resource.Type) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) + state = new(InstanceState) } + state.init() + // Flag if we're creating a new instance if n.CreateNew != nil { - *n.CreateNew = (change.Action == plans.Create || change.Action.IsReplace()) + *n.CreateNew = state.ID == "" && !diff.GetDestroy() || diff.RequiresNew() } - configVal := cty.NullVal(cty.DynamicPseudoType) - if n.Config != nil { - var configDiags tfdiags.Diagnostics - keyData := EvalDataForInstanceKey(n.Addr.Key) - configVal, _, configDiags = ctx.EvaluateBlock(n.Config.Config, schema, nil, keyData) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } + // With the completed diff, apply! + log.Printf("[DEBUG] apply: %s: executing Apply", n.Info.Id) + state, err := provider.Apply(n.Info, state, diff) + if state == nil { + state = new(InstanceState) + } + state.init() + + // Force the "id" attribute to be our ID + if state.ID != "" { + state.Attributes["id"] = state.ID } - log.Printf("[DEBUG] %s: applying the planned %s change", n.Addr.Absolute(ctx.Path()), change.Action) - resp := provider.ApplyResourceChange(providers.ApplyResourceChangeRequest{ - TypeName: n.Addr.Resource.Type, - PriorState: change.Before, - Config: configVal, - PlannedState: change.After, - PlannedPrivate: change.Private, - }) - applyDiags := resp.Diagnostics - if n.Config != nil { - applyDiags = applyDiags.InConfigBody(n.Config.Config) - } - diags = diags.Append(applyDiags) - - // Even if there are errors in the returned diagnostics, the provider may - // have returned a _partial_ state for an object that already exists but - // failed to fully configure, and so the remaining code must always run - // to completion but must be defensive against the new value being - // incomplete. - newVal := resp.NewState - - if newVal == cty.NilVal { - // Providers are supposed to return a partial new value even when errors - // occur, but sometimes they don't and so in that case we'll patch that up - // by just using the prior state, so we'll at least keep track of the - // object for the user to retry. - newVal = change.Before - - // As a special case, we'll set the new value to null if it looks like - // we were trying to execute a delete, because the provider in this case - // probably left the newVal unset intending it to be interpreted as "null". - if change.After.IsNull() { - newVal = cty.NullVal(schema.ImpliedType()) - } - - // Ideally we'd produce an error or warning here if newVal is nil and - // there are no errors in diags, because that indicates a buggy - // provider not properly reporting its result, but unfortunately many - // of our historical test mocks behave in this way and so producing - // a diagnostic here fails hundreds of tests. Instead, we must just - // silently retain the old value for now. Returning a nil value with - // no errors is still always considered a bug in the provider though, - // and should be fixed for any "real" providers that do it. - } - - var conformDiags tfdiags.Diagnostics - for _, err := range newVal.Type().TestConformance(schema.ImpliedType()) { - conformDiags = conformDiags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q produced an invalid value after apply for %s. The result cannot not be saved in the Terraform state.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - diags = diags.Append(conformDiags) - if conformDiags.HasErrors() { - // Bail early in this particular case, because an object that doesn't - // conform to the schema can't be saved in the state anyway -- the - // serializer will reject it. - return nil, diags.Err() - } - - // After this point we have a type-conforming result object and so we - // must always run to completion to ensure it can be saved. If n.Error - // is set then we must not return a non-nil error, in order to allow - // evaluation to continue to a later point where our state object will - // be saved. - - // By this point there must not be any unknown values remaining in our - // object, because we've applied the change and we can't save unknowns - // in our persistent state. If any are present then we will indicate an - // error (which is always a bug in the provider) but we will also replace - // them with nulls so that we can successfully save the portions of the - // returned value that are known. - if !newVal.IsWhollyKnown() { - // To generate better error messages, we'll go for a walk through the - // value and make a separate diagnostic for each unknown value we - // find. - cty.Walk(newVal, func(path cty.Path, val cty.Value) (bool, error) { - if !val.IsKnown() { - pathStr := tfdiags.FormatCtyPath(path) - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider returned invalid result object after apply", - fmt.Sprintf( - "After the apply operation, the provider still indicated an unknown value for %s%s. All values must be known after apply, so this is always a bug in the provider and should be reported in the provider's own repository. Terraform will still save the other known object values in the state.", - n.Addr.Absolute(ctx.Path()), pathStr, - ), - )) - } - return true, nil - }) - - // NOTE: This operation can potentially be lossy if there are multiple - // elements in a set that differ only by unknown values: after - // replacing with null these will be merged together into a single set - // element. Since we can only get here in the presence of a provider - // bug, we accept this because storing a result here is always a - // best-effort sort of thing. - newVal = cty.UnknownAsNull(newVal) - } - - if change.Action != plans.Delete && !diags.HasErrors() { - // Only values that were marked as unknown in the planned value are allowed - // to change during the apply operation. (We do this after the unknown-ness - // check above so that we also catch anything that became unknown after - // being known during plan.) - // - // If we are returning other errors anyway then we'll give this - // a pass since the other errors are usually the explanation for - // this one and so it's more helpful to let the user focus on the - // root cause rather than distract with this extra problem. - if errs := objchange.AssertObjectCompatible(schema, change.After, newVal); len(errs) > 0 { - if resp.LegacyTypeSystem { - // The shimming of the old type system in the legacy SDK is not precise - // enough to pass this consistency check, so we'll give it a pass here, - // but we will generate a warning about it so that we are more likely - // to notice in the logs if an inconsistency beyond the type system - // leads to a downstream provider failure. - var buf strings.Builder - fmt.Fprintf(&buf, "[WARN] Provider %q produced an unexpected new value for %s, but we are tolerating it because it is using the legacy plugin SDK.\n The following problems may be the cause of any confusing errors from downstream operations:", n.ProviderAddr.ProviderConfig.Type, absAddr) - for _, err := range errs { - fmt.Fprintf(&buf, "\n - %s", tfdiags.FormatError(err)) - } - log.Print(buf.String()) - - // The sort of inconsistency we won't catch here is if a known value - // in the plan is changed during apply. That can cause downstream - // problems because a dependent resource would make its own plan based - // on the planned value, and thus get a different result during the - // apply phase. This will usually lead to a "Provider produced invalid plan" - // error that incorrectly blames the downstream resource for the change. - } else { - for _, err := range errs { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced inconsistent result after apply", - fmt.Sprintf( - "When applying changes to %s, provider %q produced an unexpected new value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - absAddr, n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatError(err), - ), - )) - } - } - } - } - - // If a provider returns a null or non-null object at the wrong time then - // we still want to save that but it often causes some confusing behaviors - // where it seems like Terraform is failing to take any action at all, - // so we'll generate some errors to draw attention to it. - if !diags.HasErrors() { - if change.Action == plans.Delete && !newVal.IsNull() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider returned invalid result object after apply", - fmt.Sprintf( - "After applying a %s plan, the provider returned a non-null object for %s. Destroying should always produce a null value, so this is always a bug in the provider and should be reported in the provider's own repository. Terraform will still save this errant object in the state for debugging and recovery.", - change.Action, n.Addr.Absolute(ctx.Path()), - ), - )) - } - if change.Action != plans.Delete && newVal.IsNull() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider returned invalid result object after apply", - fmt.Sprintf( - "After applying a %s plan, the provider returned a null object for %s. Only destroying should always produce a null value, so this is always a bug in the provider and should be reported in the provider's own repository.", - change.Action, n.Addr.Absolute(ctx.Path()), - ), - )) - } - } - - // Sometimes providers return a null value when an operation fails for some - // reason, but for any action other than delete we'd rather keep the prior - // state so that the error can be corrected on a subsequent run. We must - // only do this for null new value though, or else we may discard partial - // updates the provider was able to complete. - if change.Action != plans.Delete && diags.HasErrors() && newVal.IsNull() { - // Otherwise, we'll continue but using the prior state as the new value, - // making this effectively a no-op. If the item really _has_ been - // deleted then our next refresh will detect that and fix it up. - // If change.Action is Create then change.Before will also be null, - // which is fine. - newVal = change.Before - } - - var newState *states.ResourceInstanceObject - if !newVal.IsNull() { // null value indicates that the object is deleted, so we won't set a new state in that case - newState = &states.ResourceInstanceObject{ - Status: states.ObjectReady, - Value: newVal, - Private: resp.Private, - Dependencies: n.Dependencies, // Should be populated by the caller from the StateDependencies method on the resource instance node + // If the value is the unknown variable value, then it is an error. + // In this case we record the error and remove it from the state + for ak, av := range state.Attributes { + if av == config.UnknownVariableValue { + err = multierror.Append(err, fmt.Errorf( + "Attribute with unknown value: %s", ak)) + delete(state.Attributes, ak) } } // Write the final state if n.Output != nil { - *n.Output = newState + *n.Output = state } - if diags.HasErrors() { - // If the caller provided an error pointer then they are expected to - // handle the error some other way and we treat our own result as - // success. + // If there are no errors, then we append it to our output error + // if we have one, otherwise we just output it. + if err != nil { if n.Error != nil { - err := diags.Err() - *n.Error = err - log.Printf("[DEBUG] %s: apply errored, but we're indicating that via the Error pointer rather than returning it: %s", n.Addr.Absolute(ctx.Path()), err) - return nil, nil + helpfulErr := fmt.Errorf("%s: %s", n.Info.Id, err.Error()) + *n.Error = multierror.Append(*n.Error, helpfulErr) + } else { + return nil, err } } - return nil, diags.ErrWithWarnings() + return nil, nil } // EvalApplyPre is an EvalNode implementation that does the pre-Apply work type EvalApplyPre struct { - Addr addrs.ResourceInstance - Gen states.Generation - State **states.ResourceInstanceObject - Change **plans.ResourceInstanceChange + Info *InstanceInfo + State **InstanceState + Diff **InstanceDiff } // TODO: test func (n *EvalApplyPre) Eval(ctx EvalContext) (interface{}, error) { - change := *n.Change - absAddr := n.Addr.Absolute(ctx.Path()) + state := *n.State + diff := *n.Diff - if change == nil { - panic(fmt.Sprintf("EvalApplyPre for %s called with nil Change", absAddr)) + // If the state is nil, make it non-nil + if state == nil { + state = new(InstanceState) } + state.init() - if resourceHasUserVisibleApply(n.Addr) { - priorState := change.Before - plannedNewState := change.After - + if resourceHasUserVisibleApply(n.Info) { + // Call post-apply hook err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreApply(absAddr, n.Gen, change.Action, priorState, plannedNewState) + return h.PreApply(n.Info, state, diff) }) if err != nil { return nil, err @@ -323,9 +127,8 @@ func (n *EvalApplyPre) Eval(ctx EvalContext) (interface{}, error) { // EvalApplyPost is an EvalNode implementation that does the post-Apply work type EvalApplyPost struct { - Addr addrs.ResourceInstance - Gen states.Generation - State **states.ResourceInstanceObject + Info *InstanceInfo + State **InstanceState Error *error } @@ -333,93 +136,33 @@ type EvalApplyPost struct { func (n *EvalApplyPost) Eval(ctx EvalContext) (interface{}, error) { state := *n.State - if resourceHasUserVisibleApply(n.Addr) { - absAddr := n.Addr.Absolute(ctx.Path()) - var newState cty.Value - if state != nil { - newState = state.Value - } else { - newState = cty.NullVal(cty.DynamicPseudoType) - } - var err error - if n.Error != nil { - err = *n.Error - } - - hookErr := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostApply(absAddr, n.Gen, newState, err) + if resourceHasUserVisibleApply(n.Info) { + // Call post-apply hook + err := ctx.Hook(func(h Hook) (HookAction, error) { + return h.PostApply(n.Info, state, *n.Error) }) - if hookErr != nil { - return nil, hookErr + if err != nil { + return nil, err } } return nil, *n.Error } -// EvalMaybeTainted is an EvalNode that takes the planned change, new value, -// and possible error from an apply operation and produces a new instance -// object marked as tainted if it appears that a create operation has failed. -// -// This EvalNode never returns an error, to ensure that a subsequent EvalNode -// can still record the possibly-tainted object in the state. -type EvalMaybeTainted struct { - Addr addrs.ResourceInstance - Gen states.Generation - Change **plans.ResourceInstanceChange - State **states.ResourceInstanceObject - Error *error - - // If StateOutput is not nil, its referent will be assigned either the same - // pointer as State or a new object with its status set as Tainted, - // depending on whether an error is given and if this was a create action. - StateOutput **states.ResourceInstanceObject -} - -// TODO: test -func (n *EvalMaybeTainted) Eval(ctx EvalContext) (interface{}, error) { - state := *n.State - change := *n.Change - err := *n.Error - - if state != nil && state.Status == states.ObjectTainted { - log.Printf("[TRACE] EvalMaybeTainted: %s was already tainted, so nothing to do", n.Addr.Absolute(ctx.Path())) - return nil, nil - } - - if n.StateOutput != nil { - if err != nil && change.Action == plans.Create { - // If there are errors during a _create_ then the object is - // in an undefined state, and so we'll mark it as tainted so - // we can try again on the next run. - // - // We don't do this for other change actions because errors - // during updates will often not change the remote object at all. - // If there _were_ changes prior to the error, it's the provider's - // responsibility to record the effect of those changes in the - // object value it returned. - log.Printf("[TRACE] EvalMaybeTainted: %s encountered an error during creation, so it is now marked as tainted", n.Addr.Absolute(ctx.Path())) - *n.StateOutput = state.AsTainted() - } else { - *n.StateOutput = state - } - } - - return nil, nil -} - // resourceHasUserVisibleApply returns true if the given resource is one where // apply actions should be exposed to the user. // // Certain resources do apply actions only as an implementation detail, so // these should not be advertised to code outside of this package. -func resourceHasUserVisibleApply(addr addrs.ResourceInstance) bool { +func resourceHasUserVisibleApply(info *InstanceInfo) bool { + addr := info.ResourceAddress() + // Only managed resources have user-visible apply actions. // In particular, this excludes data resources since we "apply" these // only as an implementation detail of removing them from state when // they are destroyed. (When reading, they don't get here at all because // we present them as "Refresh" actions.) - return addr.ContainingResource().Mode == addrs.ManagedResourceMode + return addr.Mode == config.ManagedResourceMode } // EvalApplyProvisioners is an EvalNode implementation that executes @@ -428,33 +171,23 @@ func resourceHasUserVisibleApply(addr addrs.ResourceInstance) bool { // TODO(mitchellh): This should probably be split up into a more fine-grained // ApplyProvisioner (single) that is looped over. type EvalApplyProvisioners struct { - Addr addrs.ResourceInstance - State **states.ResourceInstanceObject - ResourceConfig *configs.Resource + Info *InstanceInfo + State **InstanceState + Resource *config.Resource + InterpResource *Resource CreateNew *bool Error *error // When is the type of provisioner to run at this point - When configs.ProvisionerWhen + When config.ProvisionerWhen } // TODO: test func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) state := *n.State - if state == nil { - log.Printf("[TRACE] EvalApplyProvisioners: %s has no state, so skipping provisioners", n.Addr) - return nil, nil - } - if n.When == configs.ProvisionerWhenCreate && n.CreateNew != nil && !*n.CreateNew { + + if n.CreateNew != nil && !*n.CreateNew { // If we're not creating a new resource, then don't run provisioners - log.Printf("[TRACE] EvalApplyProvisioners: %s is not freshly-created, so no provisioning is required", n.Addr) - return nil, nil - } - if state.Status == states.ObjectTainted { - // No point in provisioning an object that is already tainted, since - // it's going to get recreated on the next apply anyway. - log.Printf("[TRACE] EvalApplyProvisioners: %s is tainted, so skipping provisioning", n.Addr) return nil, nil } @@ -464,7 +197,14 @@ func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { return nil, nil } + // taint tells us whether to enable tainting. + taint := n.When == config.ProvisionerWhenCreate + if n.Error != nil && *n.Error != nil { + if taint { + state.Tainted = true + } + // We're already tainted, so just return out return nil, nil } @@ -472,7 +212,7 @@ func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { { // Call pre hook err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreProvisionInstance(absAddr, state.Value) + return h.PreProvisionResource(n.Info, state) }) if err != nil { return nil, err @@ -483,19 +223,18 @@ func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { // if we have one, otherwise we just output it. err := n.apply(ctx, provs) if err != nil { - *n.Error = multierror.Append(*n.Error, err) - if n.Error == nil { - return nil, err - } else { - log.Printf("[TRACE] EvalApplyProvisioners: %s provisioning failed, but we will continue anyway at the caller's request", absAddr) - return nil, nil + if taint { + state.Tainted = true } + + *n.Error = multierror.Append(*n.Error, err) + return nil, err } { // Call post hook err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostProvisionInstance(absAddr, state.Value) + return h.PostProvisionResource(n.Info, state) }) if err != nil { return nil, err @@ -507,18 +246,18 @@ func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { // filterProvisioners filters the provisioners on the resource to only // the provisioners specified by the "when" option. -func (n *EvalApplyProvisioners) filterProvisioners() []*configs.Provisioner { +func (n *EvalApplyProvisioners) filterProvisioners() []*config.Provisioner { // Fast path the zero case - if n.ResourceConfig == nil || n.ResourceConfig.Managed == nil { + if n.Resource == nil { return nil } - if len(n.ResourceConfig.Managed.Provisioners) == 0 { + if len(n.Resource.Provisioners) == 0 { return nil } - result := make([]*configs.Provisioner, 0, len(n.ResourceConfig.Managed.Provisioners)) - for _, p := range n.ResourceConfig.Managed.Provisioners { + result := make([]*config.Provisioner, 0, len(n.Resource.Provisioners)) + for _, p := range n.Resource.Provisioners { if p.When == n.When { result = append(result, p) } @@ -527,71 +266,64 @@ func (n *EvalApplyProvisioners) filterProvisioners() []*configs.Provisioner { return result } -func (n *EvalApplyProvisioners) apply(ctx EvalContext, provs []*configs.Provisioner) error { - var diags tfdiags.Diagnostics - instanceAddr := n.Addr - absAddr := instanceAddr.Absolute(ctx.Path()) +func (n *EvalApplyProvisioners) apply(ctx EvalContext, provs []*config.Provisioner) error { + state := *n.State - // If there's a connection block defined directly inside the resource block - // then it'll serve as a base connection configuration for all of the - // provisioners. - var baseConn hcl.Body - if n.ResourceConfig.Managed != nil && n.ResourceConfig.Managed.Connection != nil { - baseConn = n.ResourceConfig.Managed.Connection.Config - } + // Store the original connection info, restore later + origConnInfo := state.Ephemeral.ConnInfo + defer func() { + state.Ephemeral.ConnInfo = origConnInfo + }() for _, prov := range provs { - log.Printf("[TRACE] EvalApplyProvisioners: provisioning %s with %q", absAddr, prov.Type) - // Get the provisioner provisioner := ctx.Provisioner(prov.Type) - schema := ctx.ProvisionerSchema(prov.Type) - keyData := EvalDataForInstanceKey(instanceAddr.Key) - - // Evaluate the main provisioner configuration. - config, _, configDiags := ctx.EvaluateBlock(prov.Config, schema, instanceAddr, keyData) - diags = diags.Append(configDiags) - - // If the provisioner block contains a connection block of its own then - // it can override the base connection configuration, if any. - var localConn hcl.Body - if prov.Connection != nil { - localConn = prov.Connection.Config + // Interpolate the provisioner config + provConfig, err := ctx.Interpolate(prov.RawConfig.Copy(), n.InterpResource) + if err != nil { + return err } - var connBody hcl.Body - switch { - case baseConn != nil && localConn != nil: - // Our standard merging logic applies here, similar to what we do - // with _override.tf configuration files: arguments from the - // base connection block will be masked by any arguments of the - // same name in the local connection block. - connBody = configs.MergeBodies(baseConn, localConn) - case baseConn != nil: - connBody = baseConn - case localConn != nil: - connBody = localConn + // Interpolate the conn info, since it may contain variables + connInfo, err := ctx.Interpolate(prov.ConnInfo.Copy(), n.InterpResource) + if err != nil { + return err } - // start with an empty connInfo - connInfo := cty.NullVal(connectionBlockSupersetSchema.ImpliedType()) - - if connBody != nil { - var connInfoDiags tfdiags.Diagnostics - connInfo, _, connInfoDiags = ctx.EvaluateBlock(connBody, connectionBlockSupersetSchema, instanceAddr, keyData) - diags = diags.Append(connInfoDiags) - if diags.HasErrors() { - // "on failure continue" setting only applies to failures of the - // provisioner itself, not to invalid configuration. - return diags.Err() + // Merge the connection information + overlay := make(map[string]string) + if origConnInfo != nil { + for k, v := range origConnInfo { + overlay[k] = v } } + for k, v := range connInfo.Config { + switch vt := v.(type) { + case string: + overlay[k] = vt + case int64: + overlay[k] = strconv.FormatInt(vt, 10) + case int32: + overlay[k] = strconv.FormatInt(int64(vt), 10) + case int: + overlay[k] = strconv.FormatInt(int64(vt), 10) + case float32: + overlay[k] = strconv.FormatFloat(float64(vt), 'f', 3, 32) + case float64: + overlay[k] = strconv.FormatFloat(vt, 'f', 3, 64) + case bool: + overlay[k] = strconv.FormatBool(vt) + default: + overlay[k] = fmt.Sprintf("%v", vt) + } + } + state.Ephemeral.ConnInfo = overlay { // Call pre hook err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreProvisionInstanceStep(absAddr, prov.Type) + return h.PreProvision(n.Info, prov.Type) }) if err != nil { return err @@ -601,37 +333,31 @@ func (n *EvalApplyProvisioners) apply(ctx EvalContext, provs []*configs.Provisio // The output function outputFn := func(msg string) { ctx.Hook(func(h Hook) (HookAction, error) { - h.ProvisionOutput(absAddr, prov.Type, msg) + h.ProvisionOutput(n.Info, prov.Type, msg) return HookActionContinue, nil }) } + // Invoke the Provisioner output := CallbackUIOutput{OutputFn: outputFn} - resp := provisioner.ProvisionResource(provisioners.ProvisionResourceRequest{ - Config: config, - Connection: connInfo, - UIOutput: &output, - }) - applyDiags := resp.Diagnostics.InConfigBody(prov.Config) + applyErr := provisioner.Apply(&output, state, provConfig) // Call post hook hookErr := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostProvisionInstanceStep(absAddr, prov.Type, applyDiags.Err()) + return h.PostProvision(n.Info, prov.Type, applyErr) }) - switch prov.OnFailure { - case configs.ProvisionerOnFailureContinue: - if applyDiags.HasErrors() { - log.Printf("[WARN] Errors while provisioning %s with %q, but continuing as requested in configuration", n.Addr, prov.Type) - } else { - // Maybe there are warnings that we still want to see - diags = diags.Append(applyDiags) - } - default: - diags = diags.Append(applyDiags) - if applyDiags.HasErrors() { - log.Printf("[WARN] Errors while provisioning %s with %q, so aborting", n.Addr, prov.Type) - return diags.Err() + // Handle the error before we deal with the hook + if applyErr != nil { + // Determine failure behavior + switch prov.OnFailure { + case config.ProvisionerOnFailureContinue: + log.Printf( + "[INFO] apply: %s [%s]: error during provision, continue requested", + n.Info.Id, prov.Type) + + case config.ProvisionerOnFailureFail: + return applyErr } } @@ -641,5 +367,6 @@ func (n *EvalApplyProvisioners) apply(ctx EvalContext, provs []*configs.Provisio } } - return diags.ErrWithWarnings() + return nil + } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_check_prevent_destroy.go b/vendor/github.com/hashicorp/terraform/terraform/eval_check_prevent_destroy.go index 4dff0c84..715e79e1 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_check_prevent_destroy.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_check_prevent_destroy.go @@ -3,44 +3,33 @@ package terraform import ( "fmt" - "github.com/hashicorp/terraform/plans" - - "github.com/hashicorp/hcl2/hcl" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config" ) // EvalPreventDestroy is an EvalNode implementation that returns an // error if a resource has PreventDestroy configured and the diff // would destroy the resource. type EvalCheckPreventDestroy struct { - Addr addrs.ResourceInstance - Config *configs.Resource - Change **plans.ResourceInstanceChange + Resource *config.Resource + ResourceId string + Diff **InstanceDiff } func (n *EvalCheckPreventDestroy) Eval(ctx EvalContext) (interface{}, error) { - if n.Change == nil || *n.Change == nil || n.Config == nil || n.Config.Managed == nil { + if n.Diff == nil || *n.Diff == nil || n.Resource == nil { return nil, nil } - change := *n.Change - preventDestroy := n.Config.Managed.PreventDestroy + diff := *n.Diff + preventDestroy := n.Resource.Lifecycle.PreventDestroy - if (change.Action == plans.Delete || change.Action.IsReplace()) && preventDestroy { - var diags tfdiags.Diagnostics - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Instance cannot be destroyed", - Detail: fmt.Sprintf( - "Resource %s has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed. To avoid this error and continue with the plan, either disable lifecycle.prevent_destroy or reduce the scope of the plan using the -target flag.", - n.Addr.Absolute(ctx.Path()).String(), - ), - Subject: &n.Config.DeclRange, - }) - return nil, diags.Err() + if diff.GetDestroy() && preventDestroy { + resourceId := n.ResourceId + if resourceId == "" { + resourceId = n.Resource.Id() + } + + return nil, fmt.Errorf(preventDestroyErrStr, resourceId) } return nil, nil diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_context.go b/vendor/github.com/hashicorp/terraform/terraform/eval_context.go index 08f3059e..86481ded 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_context.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_context.go @@ -1,16 +1,9 @@ package terraform import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/lang" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" + "sync" + + "github.com/hashicorp/terraform/config" ) // EvalContext is the interface that is given to eval nodes to execute. @@ -20,7 +13,7 @@ type EvalContext interface { Stopped() <-chan struct{} // Path is the current module path. - Path() addrs.ModuleInstance + Path() []string // Hook is used to call hook methods. The callback is called for each // hook and should return the hook action to take and the error. @@ -29,105 +22,68 @@ type EvalContext interface { // Input is the UIInput object for interacting with the UI. Input() UIInput - // InitProvider initializes the provider with the given type and address, and + // InitProvider initializes the provider with the given type and name, and // returns the implementation of the resource provider or an error. // // It is an error to initialize the same provider more than once. - InitProvider(typ string, addr addrs.ProviderConfig) (providers.Interface, error) + InitProvider(typ string, name string) (ResourceProvider, error) - // Provider gets the provider instance with the given address (already + // Provider gets the provider instance with the given name (already // initialized) or returns nil if the provider isn't initialized. - // - // This method expects an _absolute_ provider configuration address, since - // resources in one module are able to use providers from other modules. - // InitProvider must've been called on the EvalContext of the module - // that owns the given provider before calling this method. - Provider(addrs.AbsProviderConfig) providers.Interface - - // ProviderSchema retrieves the schema for a particular provider, which - // must have already been initialized with InitProvider. - // - // This method expects an _absolute_ provider configuration address, since - // resources in one module are able to use providers from other modules. - ProviderSchema(addrs.AbsProviderConfig) *ProviderSchema + Provider(string) ResourceProvider // CloseProvider closes provider connections that aren't needed anymore. - CloseProvider(addrs.ProviderConfig) error + CloseProvider(string) error // ConfigureProvider configures the provider with the given // configuration. This is a separate context call because this call // is used to store the provider configuration for inheritance lookups // with ParentProviderConfig(). - ConfigureProvider(addrs.ProviderConfig, cty.Value) tfdiags.Diagnostics + ConfigureProvider(string, *ResourceConfig) error // ProviderInput and SetProviderInput are used to configure providers // from user input. - ProviderInput(addrs.ProviderConfig) map[string]cty.Value - SetProviderInput(addrs.ProviderConfig, map[string]cty.Value) + ProviderInput(string) map[string]interface{} + SetProviderInput(string, map[string]interface{}) // InitProvisioner initializes the provisioner with the given name and // returns the implementation of the resource provisioner or an error. // // It is an error to initialize the same provisioner more than once. - InitProvisioner(string) (provisioners.Interface, error) + InitProvisioner(string) (ResourceProvisioner, error) // Provisioner gets the provisioner instance with the given name (already // initialized) or returns nil if the provisioner isn't initialized. - Provisioner(string) provisioners.Interface - - // ProvisionerSchema retrieves the main configuration schema for a - // particular provisioner, which must have already been initialized with - // InitProvisioner. - ProvisionerSchema(string) *configschema.Block + Provisioner(string) ResourceProvisioner // CloseProvisioner closes provisioner connections that aren't needed // anymore. CloseProvisioner(string) error - // EvaluateBlock takes the given raw configuration block and associated - // schema and evaluates it to produce a value of an object type that - // conforms to the implied type of the schema. + // Interpolate takes the given raw configuration and completes + // the interpolations, returning the processed ResourceConfig. // - // The "self" argument is optional. If given, it is the referenceable - // address that the name "self" should behave as an alias for when - // evaluating. Set this to nil if the "self" object should not be available. - // - // The "key" argument is also optional. If given, it is the instance key - // of the current object within the multi-instance container it belongs - // to. For example, on a resource block with "count" set this should be - // set to a different addrs.IntKey for each instance created from that - // block. Set this to addrs.NoKey if not appropriate. - // - // The returned body is an expanded version of the given body, with any - // "dynamic" blocks replaced with zero or more static blocks. This can be - // used to extract correct source location information about attributes of - // the returned object value. - EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) + // The resource argument is optional. If given, it is the resource + // that is currently being acted upon. + Interpolate(*config.RawConfig, *Resource) (*ResourceConfig, error) - // EvaluateExpr takes the given HCL expression and evaluates it to produce - // a value. - // - // The "self" argument is optional. If given, it is the referenceable - // address that the name "self" should behave as an alias for when - // evaluating. Set this to nil if the "self" object should not be available. - EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) + // InterpolateProvider takes a ProviderConfig and interpolates it with the + // stored interpolation scope. Since provider configurations can be + // inherited, the interpolation scope may be different from the current + // context path. Interplation is otherwise executed the same as in the + // Interpolation method. + InterpolateProvider(*config.ProviderConfig, *Resource) (*ResourceConfig, error) - // EvaluationScope returns a scope that can be used to evaluate reference - // addresses in this context. - EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope + // SetVariables sets the variables for the module within + // this context with the name n. This function call is additive: + // the second parameter is merged with any previous call. + SetVariables(string, map[string]interface{}) - // SetModuleCallArguments defines values for the variables of a particular - // child module call. - // - // Calling this function multiple times has merging behavior, keeping any - // previously-set keys that are not present in the new map. - SetModuleCallArguments(addrs.ModuleCallInstance, map[string]cty.Value) + // Diff returns the global diff as well as the lock that should + // be used to modify that diff. + Diff() (*Diff, *sync.RWMutex) - // Changes returns the writer object that can be used to write new proposed - // changes into the global changes set. - Changes() *plans.ChangesSync - - // State returns a wrapper object that provides safe concurrent access to - // the global state. - State() *states.SyncState + // State returns the global state as well as the lock that should + // be used to modify that state. + State() (*State, *sync.RWMutex) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_context_builtin.go b/vendor/github.com/hashicorp/terraform/terraform/eval_context_builtin.go index 20b37933..1b6ee5a6 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_context_builtin.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_context_builtin.go @@ -6,20 +6,7 @@ import ( "log" "sync" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" - "github.com/hashicorp/terraform/version" - - "github.com/hashicorp/terraform/states" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/lang" - "github.com/hashicorp/terraform/tfdiags" - - "github.com/hashicorp/terraform/addrs" - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/terraform/config" ) // BuiltinEvalContext is an EvalContext implementation that is used by @@ -29,47 +16,35 @@ type BuiltinEvalContext struct { StopContext context.Context // PathValue is the Path that this context is operating within. - PathValue addrs.ModuleInstance + PathValue []string - // Evaluator is used for evaluating expressions within the scope of this - // eval context. - Evaluator *Evaluator - - // Schemas is a repository of all of the schemas we should need to - // decode configuration blocks and expressions. This must be constructed by - // the caller to include schemas for all of the providers, resource types, - // data sources and provisioners used by the given configuration and - // state. + // Interpolater setting below affect the interpolation of variables. // - // This must not be mutated during evaluation. - Schemas *Schemas - - // VariableValues contains the variable values across all modules. This - // structure is shared across the entire containing context, and so it - // may be accessed only when holding VariableValuesLock. - // The keys of the first level of VariableValues are the string - // representations of addrs.ModuleInstance values. The second-level keys - // are variable names within each module instance. - VariableValues map[string]map[string]cty.Value - VariableValuesLock *sync.Mutex + // The InterpolaterVars are the exact value for ${var.foo} values. + // The map is shared between all contexts and is a mapping of + // PATH to KEY to VALUE. Because it is shared by all contexts as well + // as the Interpolater itself, it is protected by InterpolaterVarLock + // which must be locked during any access to the map. + Interpolater *Interpolater + InterpolaterVars map[string]map[string]interface{} + InterpolaterVarLock *sync.Mutex Components contextComponentFactory Hooks []Hook InputValue UIInput - ProviderCache map[string]providers.Interface - ProviderInputConfig map[string]map[string]cty.Value + ProviderCache map[string]ResourceProvider + ProviderInputConfig map[string]map[string]interface{} ProviderLock *sync.Mutex - ProvisionerCache map[string]provisioners.Interface + ProvisionerCache map[string]ResourceProvisioner ProvisionerLock *sync.Mutex - ChangesValue *plans.ChangesSync - StateValue *states.SyncState + DiffValue *Diff + DiffLock *sync.RWMutex + StateValue *State + StateLock *sync.RWMutex once sync.Once } -// BuiltinEvalContext implements EvalContext -var _ EvalContext = (*BuiltinEvalContext)(nil) - func (ctx *BuiltinEvalContext) Stopped() <-chan struct{} { // This can happen during tests. During tests, we just block forever. if ctx.StopContext == nil { @@ -103,13 +78,12 @@ func (ctx *BuiltinEvalContext) Input() UIInput { return ctx.InputValue } -func (ctx *BuiltinEvalContext) InitProvider(typeName string, addr addrs.ProviderConfig) (providers.Interface, error) { +func (ctx *BuiltinEvalContext) InitProvider(typeName, name string) (ResourceProvider, error) { ctx.once.Do(ctx.init) - absAddr := addr.Absolute(ctx.Path()) // If we already initialized, it is an error - if p := ctx.Provider(absAddr); p != nil { - return nil, fmt.Errorf("%s is already initialized", addr) + if p := ctx.Provider(name); p != nil { + return nil, fmt.Errorf("Provider '%s' already initialized", name) } // Warning: make sure to acquire these locks AFTER the call to Provider @@ -117,102 +91,85 @@ func (ctx *BuiltinEvalContext) InitProvider(typeName string, addr addrs.Provider ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() - key := absAddr.String() - - p, err := ctx.Components.ResourceProvider(typeName, key) + p, err := ctx.Components.ResourceProvider(typeName, name) if err != nil { return nil, err } - log.Printf("[TRACE] BuiltinEvalContext: Initialized %q provider for %s", typeName, absAddr) - ctx.ProviderCache[key] = p - + ctx.ProviderCache[name] = p return p, nil } -func (ctx *BuiltinEvalContext) Provider(addr addrs.AbsProviderConfig) providers.Interface { +func (ctx *BuiltinEvalContext) Provider(n string) ResourceProvider { ctx.once.Do(ctx.init) ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() - return ctx.ProviderCache[addr.String()] + return ctx.ProviderCache[n] } -func (ctx *BuiltinEvalContext) ProviderSchema(addr addrs.AbsProviderConfig) *ProviderSchema { - ctx.once.Do(ctx.init) - - return ctx.Schemas.ProviderSchema(addr.ProviderConfig.Type) -} - -func (ctx *BuiltinEvalContext) CloseProvider(addr addrs.ProviderConfig) error { +func (ctx *BuiltinEvalContext) CloseProvider(n string) error { ctx.once.Do(ctx.init) ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() - key := addr.Absolute(ctx.Path()).String() - provider := ctx.ProviderCache[key] + var provider interface{} + provider = ctx.ProviderCache[n] if provider != nil { - delete(ctx.ProviderCache, key) - return provider.Close() + if p, ok := provider.(ResourceProviderCloser); ok { + delete(ctx.ProviderCache, n) + return p.Close() + } } return nil } -func (ctx *BuiltinEvalContext) ConfigureProvider(addr addrs.ProviderConfig, cfg cty.Value) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - absAddr := addr.Absolute(ctx.Path()) - p := ctx.Provider(absAddr) +func (ctx *BuiltinEvalContext) ConfigureProvider( + n string, cfg *ResourceConfig) error { + p := ctx.Provider(n) if p == nil { - diags = diags.Append(fmt.Errorf("%s not initialized", addr)) - return diags + return fmt.Errorf("Provider '%s' not initialized", n) } - - providerSchema := ctx.ProviderSchema(absAddr) - if providerSchema == nil { - diags = diags.Append(fmt.Errorf("schema for %s is not available", absAddr)) - return diags - } - - req := providers.ConfigureRequest{ - TerraformVersion: version.String(), - Config: cfg, - } - - resp := p.Configure(req) - return resp.Diagnostics + return p.Configure(cfg) } -func (ctx *BuiltinEvalContext) ProviderInput(pc addrs.ProviderConfig) map[string]cty.Value { +func (ctx *BuiltinEvalContext) ProviderInput(n string) map[string]interface{} { ctx.ProviderLock.Lock() defer ctx.ProviderLock.Unlock() - if !ctx.Path().IsRoot() { - // Only root module provider configurations can have input. - return nil + // Make a copy of the path so we can safely edit it + path := ctx.Path() + pathCopy := make([]string, len(path)+1) + copy(pathCopy, path) + + // Go up the tree. + for i := len(path) - 1; i >= 0; i-- { + pathCopy[i+1] = n + k := PathCacheKey(pathCopy[:i+2]) + if v, ok := ctx.ProviderInputConfig[k]; ok { + return v + } } - return ctx.ProviderInputConfig[pc.String()] + return nil } -func (ctx *BuiltinEvalContext) SetProviderInput(pc addrs.ProviderConfig, c map[string]cty.Value) { - absProvider := pc.Absolute(ctx.Path()) - - if !ctx.Path().IsRoot() { - // Only root module provider configurations can have input. - log.Printf("[WARN] BuiltinEvalContext: attempt to SetProviderInput for non-root module") - return - } +func (ctx *BuiltinEvalContext) SetProviderInput(n string, c map[string]interface{}) { + providerPath := make([]string, len(ctx.Path())+1) + copy(providerPath, ctx.Path()) + providerPath[len(providerPath)-1] = n // Save the configuration ctx.ProviderLock.Lock() - ctx.ProviderInputConfig[absProvider.String()] = c + ctx.ProviderInputConfig[PathCacheKey(providerPath)] = c ctx.ProviderLock.Unlock() } -func (ctx *BuiltinEvalContext) InitProvisioner(n string) (provisioners.Interface, error) { +func (ctx *BuiltinEvalContext) InitProvisioner( + n string) (ResourceProvisioner, error) { ctx.once.Do(ctx.init) // If we already initialized, it is an error @@ -225,7 +182,10 @@ func (ctx *BuiltinEvalContext) InitProvisioner(n string) (provisioners.Interface ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() - key := PathObjectCacheKey(ctx.Path(), n) + provPath := make([]string, len(ctx.Path())+1) + copy(provPath, ctx.Path()) + provPath[len(provPath)-1] = n + key := PathCacheKey(provPath) p, err := ctx.Components.ResourceProvisioner(n, key) if err != nil { @@ -233,24 +193,20 @@ func (ctx *BuiltinEvalContext) InitProvisioner(n string) (provisioners.Interface } ctx.ProvisionerCache[key] = p - return p, nil } -func (ctx *BuiltinEvalContext) Provisioner(n string) provisioners.Interface { +func (ctx *BuiltinEvalContext) Provisioner(n string) ResourceProvisioner { ctx.once.Do(ctx.init) ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() - key := PathObjectCacheKey(ctx.Path(), n) - return ctx.ProvisionerCache[key] -} + provPath := make([]string, len(ctx.Path())+1) + copy(provPath, ctx.Path()) + provPath[len(provPath)-1] = n -func (ctx *BuiltinEvalContext) ProvisionerSchema(n string) *configschema.Block { - ctx.once.Do(ctx.init) - - return ctx.Schemas.ProvisionerConfig(n) + return ctx.ProvisionerCache[PathCacheKey(provPath)] } func (ctx *BuiltinEvalContext) CloseProvisioner(n string) error { @@ -259,70 +215,106 @@ func (ctx *BuiltinEvalContext) CloseProvisioner(n string) error { ctx.ProvisionerLock.Lock() defer ctx.ProvisionerLock.Unlock() - key := PathObjectCacheKey(ctx.Path(), n) + provPath := make([]string, len(ctx.Path())+1) + copy(provPath, ctx.Path()) + provPath[len(provPath)-1] = n - prov := ctx.ProvisionerCache[key] + var prov interface{} + prov = ctx.ProvisionerCache[PathCacheKey(provPath)] if prov != nil { - return prov.Close() + if p, ok := prov.(ResourceProvisionerCloser); ok { + delete(ctx.ProvisionerCache, PathCacheKey(provPath)) + return p.Close() + } } return nil } -func (ctx *BuiltinEvalContext) EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - scope := ctx.EvaluationScope(self, keyData) - body, evalDiags := scope.ExpandBlock(body, schema) - diags = diags.Append(evalDiags) - val, evalDiags := scope.EvalBlock(body, schema) - diags = diags.Append(evalDiags) - return val, body, diags -} +func (ctx *BuiltinEvalContext) Interpolate( + cfg *config.RawConfig, r *Resource) (*ResourceConfig, error) { -func (ctx *BuiltinEvalContext) EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { - scope := ctx.EvaluationScope(self, EvalDataForNoInstanceKey) - return scope.EvalExpr(expr, wantType) -} + if cfg != nil { + scope := &InterpolationScope{ + Path: ctx.Path(), + Resource: r, + } -func (ctx *BuiltinEvalContext) EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope { - data := &evaluationStateData{ - Evaluator: ctx.Evaluator, - ModulePath: ctx.PathValue, - InstanceKeyData: keyData, - Operation: ctx.Evaluator.Operation, + vs, err := ctx.Interpolater.Values(scope, cfg.Variables) + if err != nil { + return nil, err + } + + // Do the interpolation + if err := cfg.Interpolate(vs); err != nil { + return nil, err + } } - return ctx.Evaluator.Scope(data, self) + + result := NewResourceConfig(cfg) + result.interpolateForce() + return result, nil } -func (ctx *BuiltinEvalContext) Path() addrs.ModuleInstance { +func (ctx *BuiltinEvalContext) InterpolateProvider( + pc *config.ProviderConfig, r *Resource) (*ResourceConfig, error) { + + var cfg *config.RawConfig + + if pc != nil && pc.RawConfig != nil { + scope := &InterpolationScope{ + Path: ctx.Path(), + Resource: r, + } + + cfg = pc.RawConfig + + vs, err := ctx.Interpolater.Values(scope, cfg.Variables) + if err != nil { + return nil, err + } + + // Do the interpolation + if err := cfg.Interpolate(vs); err != nil { + return nil, err + } + } + + result := NewResourceConfig(cfg) + result.interpolateForce() + return result, nil +} + +func (ctx *BuiltinEvalContext) Path() []string { return ctx.PathValue } -func (ctx *BuiltinEvalContext) SetModuleCallArguments(n addrs.ModuleCallInstance, vals map[string]cty.Value) { - ctx.VariableValuesLock.Lock() - defer ctx.VariableValuesLock.Unlock() +func (ctx *BuiltinEvalContext) SetVariables(n string, vs map[string]interface{}) { + ctx.InterpolaterVarLock.Lock() + defer ctx.InterpolaterVarLock.Unlock() - childPath := n.ModuleInstance(ctx.PathValue) - key := childPath.String() + path := make([]string, len(ctx.Path())+1) + copy(path, ctx.Path()) + path[len(path)-1] = n + key := PathCacheKey(path) - args := ctx.VariableValues[key] - if args == nil { - args = make(map[string]cty.Value) - ctx.VariableValues[key] = vals - return + vars := ctx.InterpolaterVars[key] + if vars == nil { + vars = make(map[string]interface{}) + ctx.InterpolaterVars[key] = vars } - for k, v := range vals { - args[k] = v + for k, v := range vs { + vars[k] = v } } -func (ctx *BuiltinEvalContext) Changes() *plans.ChangesSync { - return ctx.ChangesValue +func (ctx *BuiltinEvalContext) Diff() (*Diff, *sync.RWMutex) { + return ctx.DiffValue, ctx.DiffLock } -func (ctx *BuiltinEvalContext) State() *states.SyncState { - return ctx.StateValue +func (ctx *BuiltinEvalContext) State() (*State, *sync.RWMutex) { + return ctx.StateValue, ctx.StateLock } func (ctx *BuiltinEvalContext) init() { diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_context_mock.go b/vendor/github.com/hashicorp/terraform/terraform/eval_context_mock.go index 195ecc5c..64645179 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_context_mock.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_context_mock.go @@ -1,20 +1,9 @@ package terraform import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcldec" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" + "sync" - "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/lang" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // MockEvalContext is a mock version of EvalContext that can be used @@ -31,84 +20,43 @@ type MockEvalContext struct { InputInput UIInput InitProviderCalled bool - InitProviderType string - InitProviderAddr addrs.ProviderConfig - InitProviderProvider providers.Interface + InitProviderName string + InitProviderProvider ResourceProvider InitProviderError error ProviderCalled bool - ProviderAddr addrs.AbsProviderConfig - ProviderProvider providers.Interface - - ProviderSchemaCalled bool - ProviderSchemaAddr addrs.AbsProviderConfig - ProviderSchemaSchema *ProviderSchema + ProviderName string + ProviderProvider ResourceProvider CloseProviderCalled bool - CloseProviderAddr addrs.ProviderConfig - CloseProviderProvider providers.Interface + CloseProviderName string + CloseProviderProvider ResourceProvider ProviderInputCalled bool - ProviderInputAddr addrs.ProviderConfig - ProviderInputValues map[string]cty.Value + ProviderInputName string + ProviderInputConfig map[string]interface{} SetProviderInputCalled bool - SetProviderInputAddr addrs.ProviderConfig - SetProviderInputValues map[string]cty.Value + SetProviderInputName string + SetProviderInputConfig map[string]interface{} ConfigureProviderCalled bool - ConfigureProviderAddr addrs.ProviderConfig - ConfigureProviderConfig cty.Value - ConfigureProviderDiags tfdiags.Diagnostics + ConfigureProviderName string + ConfigureProviderConfig *ResourceConfig + ConfigureProviderError error InitProvisionerCalled bool InitProvisionerName string - InitProvisionerProvisioner provisioners.Interface + InitProvisionerProvisioner ResourceProvisioner InitProvisionerError error ProvisionerCalled bool ProvisionerName string - ProvisionerProvisioner provisioners.Interface - - ProvisionerSchemaCalled bool - ProvisionerSchemaName string - ProvisionerSchemaSchema *configschema.Block + ProvisionerProvisioner ResourceProvisioner CloseProvisionerCalled bool CloseProvisionerName string - CloseProvisionerProvisioner provisioners.Interface - - EvaluateBlockCalled bool - EvaluateBlockBody hcl.Body - EvaluateBlockSchema *configschema.Block - EvaluateBlockSelf addrs.Referenceable - EvaluateBlockKeyData InstanceKeyEvalData - EvaluateBlockResultFunc func( - body hcl.Body, - schema *configschema.Block, - self addrs.Referenceable, - keyData InstanceKeyEvalData, - ) (cty.Value, hcl.Body, tfdiags.Diagnostics) // overrides the other values below, if set - EvaluateBlockResult cty.Value - EvaluateBlockExpandedBody hcl.Body - EvaluateBlockDiags tfdiags.Diagnostics - - EvaluateExprCalled bool - EvaluateExprExpr hcl.Expression - EvaluateExprWantType cty.Type - EvaluateExprSelf addrs.Referenceable - EvaluateExprResultFunc func( - expr hcl.Expression, - wantType cty.Type, - self addrs.Referenceable, - ) (cty.Value, tfdiags.Diagnostics) // overrides the other values below, if set - EvaluateExprResult cty.Value - EvaluateExprDiags tfdiags.Diagnostics - - EvaluationScopeCalled bool - EvaluationScopeSelf addrs.Referenceable - EvaluationScopeKeyData InstanceKeyEvalData - EvaluationScopeScope *lang.Scope + CloseProvisionerProvisioner ResourceProvisioner InterpolateCalled bool InterpolateConfig *config.RawConfig @@ -123,22 +71,21 @@ type MockEvalContext struct { InterpolateProviderError error PathCalled bool - PathPath addrs.ModuleInstance + PathPath []string - SetModuleCallArgumentsCalled bool - SetModuleCallArgumentsModule addrs.ModuleCallInstance - SetModuleCallArgumentsValues map[string]cty.Value + SetVariablesCalled bool + SetVariablesModule string + SetVariablesVariables map[string]interface{} - ChangesCalled bool - ChangesChanges *plans.ChangesSync + DiffCalled bool + DiffDiff *Diff + DiffLock *sync.RWMutex StateCalled bool - StateState *states.SyncState + StateState *State + StateLock *sync.RWMutex } -// MockEvalContext implements EvalContext -var _ EvalContext = (*MockEvalContext)(nil) - func (c *MockEvalContext) Stopped() <-chan struct{} { c.StoppedCalled = true return c.StoppedValue @@ -160,157 +107,61 @@ func (c *MockEvalContext) Input() UIInput { return c.InputInput } -func (c *MockEvalContext) InitProvider(t string, addr addrs.ProviderConfig) (providers.Interface, error) { +func (c *MockEvalContext) InitProvider(t, n string) (ResourceProvider, error) { c.InitProviderCalled = true - c.InitProviderType = t - c.InitProviderAddr = addr + c.InitProviderName = n return c.InitProviderProvider, c.InitProviderError } -func (c *MockEvalContext) Provider(addr addrs.AbsProviderConfig) providers.Interface { +func (c *MockEvalContext) Provider(n string) ResourceProvider { c.ProviderCalled = true - c.ProviderAddr = addr + c.ProviderName = n return c.ProviderProvider } -func (c *MockEvalContext) ProviderSchema(addr addrs.AbsProviderConfig) *ProviderSchema { - c.ProviderSchemaCalled = true - c.ProviderSchemaAddr = addr - return c.ProviderSchemaSchema -} - -func (c *MockEvalContext) CloseProvider(addr addrs.ProviderConfig) error { +func (c *MockEvalContext) CloseProvider(n string) error { c.CloseProviderCalled = true - c.CloseProviderAddr = addr + c.CloseProviderName = n return nil } -func (c *MockEvalContext) ConfigureProvider(addr addrs.ProviderConfig, cfg cty.Value) tfdiags.Diagnostics { +func (c *MockEvalContext) ConfigureProvider(n string, cfg *ResourceConfig) error { c.ConfigureProviderCalled = true - c.ConfigureProviderAddr = addr + c.ConfigureProviderName = n c.ConfigureProviderConfig = cfg - return c.ConfigureProviderDiags + return c.ConfigureProviderError } -func (c *MockEvalContext) ProviderInput(addr addrs.ProviderConfig) map[string]cty.Value { +func (c *MockEvalContext) ProviderInput(n string) map[string]interface{} { c.ProviderInputCalled = true - c.ProviderInputAddr = addr - return c.ProviderInputValues + c.ProviderInputName = n + return c.ProviderInputConfig } -func (c *MockEvalContext) SetProviderInput(addr addrs.ProviderConfig, vals map[string]cty.Value) { +func (c *MockEvalContext) SetProviderInput(n string, cfg map[string]interface{}) { c.SetProviderInputCalled = true - c.SetProviderInputAddr = addr - c.SetProviderInputValues = vals + c.SetProviderInputName = n + c.SetProviderInputConfig = cfg } -func (c *MockEvalContext) InitProvisioner(n string) (provisioners.Interface, error) { +func (c *MockEvalContext) InitProvisioner(n string) (ResourceProvisioner, error) { c.InitProvisionerCalled = true c.InitProvisionerName = n return c.InitProvisionerProvisioner, c.InitProvisionerError } -func (c *MockEvalContext) Provisioner(n string) provisioners.Interface { +func (c *MockEvalContext) Provisioner(n string) ResourceProvisioner { c.ProvisionerCalled = true c.ProvisionerName = n return c.ProvisionerProvisioner } -func (c *MockEvalContext) ProvisionerSchema(n string) *configschema.Block { - c.ProvisionerSchemaCalled = true - c.ProvisionerSchemaName = n - return c.ProvisionerSchemaSchema -} - func (c *MockEvalContext) CloseProvisioner(n string) error { c.CloseProvisionerCalled = true c.CloseProvisionerName = n return nil } -func (c *MockEvalContext) EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { - c.EvaluateBlockCalled = true - c.EvaluateBlockBody = body - c.EvaluateBlockSchema = schema - c.EvaluateBlockSelf = self - c.EvaluateBlockKeyData = keyData - if c.EvaluateBlockResultFunc != nil { - return c.EvaluateBlockResultFunc(body, schema, self, keyData) - } - return c.EvaluateBlockResult, c.EvaluateBlockExpandedBody, c.EvaluateBlockDiags -} - -func (c *MockEvalContext) EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { - c.EvaluateExprCalled = true - c.EvaluateExprExpr = expr - c.EvaluateExprWantType = wantType - c.EvaluateExprSelf = self - if c.EvaluateExprResultFunc != nil { - return c.EvaluateExprResultFunc(expr, wantType, self) - } - return c.EvaluateExprResult, c.EvaluateExprDiags -} - -// installSimpleEval is a helper to install a simple mock implementation of -// both EvaluateBlock and EvaluateExpr into the receiver. -// -// These default implementations will either evaluate the given input against -// the scope in field EvaluationScopeScope or, if it is nil, with no eval -// context at all so that only constant values may be used. -// -// This function overwrites any existing functions installed in fields -// EvaluateBlockResultFunc and EvaluateExprResultFunc. -func (c *MockEvalContext) installSimpleEval() { - c.EvaluateBlockResultFunc = func(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { - if scope := c.EvaluationScopeScope; scope != nil { - // Fully-functional codepath. - var diags tfdiags.Diagnostics - body, diags = scope.ExpandBlock(body, schema) - if diags.HasErrors() { - return cty.DynamicVal, body, diags - } - val, evalDiags := c.EvaluationScopeScope.EvalBlock(body, schema) - diags = diags.Append(evalDiags) - if evalDiags.HasErrors() { - return cty.DynamicVal, body, diags - } - return val, body, diags - } - - // Fallback codepath supporting constant values only. - val, hclDiags := hcldec.Decode(body, schema.DecoderSpec(), nil) - return val, body, tfdiags.Diagnostics(nil).Append(hclDiags) - } - c.EvaluateExprResultFunc = func(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { - if scope := c.EvaluationScopeScope; scope != nil { - // Fully-functional codepath. - return scope.EvalExpr(expr, wantType) - } - - // Fallback codepath supporting constant values only. - var diags tfdiags.Diagnostics - val, hclDiags := expr.Value(nil) - diags = diags.Append(hclDiags) - if hclDiags.HasErrors() { - return cty.DynamicVal, diags - } - var err error - val, err = convert.Convert(val, wantType) - if err != nil { - diags = diags.Append(err) - return cty.DynamicVal, diags - } - return val, diags - } -} - -func (c *MockEvalContext) EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope { - c.EvaluationScopeCalled = true - c.EvaluationScopeSelf = self - c.EvaluationScopeKeyData = keyData - return c.EvaluationScopeScope -} - func (c *MockEvalContext) Interpolate( config *config.RawConfig, resource *Resource) (*ResourceConfig, error) { c.InterpolateCalled = true @@ -327,23 +178,23 @@ func (c *MockEvalContext) InterpolateProvider( return c.InterpolateProviderConfigResult, c.InterpolateError } -func (c *MockEvalContext) Path() addrs.ModuleInstance { +func (c *MockEvalContext) Path() []string { c.PathCalled = true return c.PathPath } -func (c *MockEvalContext) SetModuleCallArguments(n addrs.ModuleCallInstance, values map[string]cty.Value) { - c.SetModuleCallArgumentsCalled = true - c.SetModuleCallArgumentsModule = n - c.SetModuleCallArgumentsValues = values +func (c *MockEvalContext) SetVariables(n string, vs map[string]interface{}) { + c.SetVariablesCalled = true + c.SetVariablesModule = n + c.SetVariablesVariables = vs } -func (c *MockEvalContext) Changes() *plans.ChangesSync { - c.ChangesCalled = true - return c.ChangesChanges +func (c *MockEvalContext) Diff() (*Diff, *sync.RWMutex) { + c.DiffCalled = true + return c.DiffDiff, c.DiffLock } -func (c *MockEvalContext) State() *states.SyncState { +func (c *MockEvalContext) State() (*State, *sync.RWMutex) { c.StateCalled = true - return c.StateState + return c.StateState, c.StateLock } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_count.go b/vendor/github.com/hashicorp/terraform/terraform/eval_count.go index 9c15d7de..2ae56a75 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_count.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_count.go @@ -1,121 +1,58 @@ package terraform import ( - "fmt" - "log" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" + "github.com/hashicorp/terraform/config" ) -// evaluateResourceCountExpression is our standard mechanism for interpreting an -// expression given for a "count" argument on a resource. This should be called -// from the DynamicExpand of a node representing a resource in order to -// determine the final count value. -// -// If the result is zero or positive and no error diagnostics are returned, then -// the result is the literal count value to use. -// -// If the result is -1, this indicates that the given expression is nil and so -// the "count" behavior should not be enabled for this resource at all. -// -// If error diagnostics are returned then the result is always the meaningless -// placeholder value -1, except in one case: if the count expression evaluates -// to an unknown number value then the result is zero, allowing this situation -// to be treated by the caller as special if needed. For example, an early -// graph walk may wish to just silently skip resources with unknown counts -// to allow them to be dealt with in a later graph walk where more information -// is available. -func evaluateResourceCountExpression(expr hcl.Expression, ctx EvalContext) (int, tfdiags.Diagnostics) { - if expr == nil { - return -1, nil - } +// EvalCountFixZeroOneBoundary is an EvalNode that fixes up the state +// when there is a resource count with zero/one boundary, i.e. fixing +// a resource named "aws_instance.foo" to "aws_instance.foo.0" and vice-versa. +type EvalCountFixZeroOneBoundary struct { + Resource *config.Resource +} - var diags tfdiags.Diagnostics - var count int - - countVal, countDiags := ctx.EvaluateExpr(expr, cty.Number, nil) - diags = diags.Append(countDiags) - if diags.HasErrors() { - return -1, diags - } - - switch { - case countVal.IsNull(): - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is null. An integer is required.`, - Subject: expr.Range().Ptr(), - }) - return -1, diags - case !countVal.IsKnown(): - // Currently this is a rather bad outcome from a UX standpoint, since we have - // no real mechanism to deal with this situation and all we can do is produce - // an error message. - // FIXME: In future, implement a built-in mechanism for deferring changes that - // can't yet be predicted, and use it to guide the user through several - // plan/apply steps until the desired configuration is eventually reached. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The "count" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work around this, use the -target argument to first apply only the resources that the count depends on.`, - Subject: expr.Range().Ptr(), - }) - // We return zero+errors in this one case to allow callers to handle - // an unknown count as special. This is rarely necessary, but is used - // by the validate walk in particular so that it can just skip - // validation in this case, assuming a later walk will take care of it. - return 0, diags - } - - err := gocty.FromCtyValue(countVal, &count) +// TODO: test +func (n *EvalCountFixZeroOneBoundary) Eval(ctx EvalContext) (interface{}, error) { + // Get the count, important for knowing whether we're supposed to + // be adding the zero, or trimming it. + count, err := n.Resource.Count() if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err), - Subject: expr.Range().Ptr(), - }) - return -1, diags - } - if count < 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is unsuitable: negative numbers are not supported.`, - Subject: expr.Range().Ptr(), - }) - return -1, diags + return nil, err } - return count, diags -} - -// fixResourceCountSetTransition is a helper function to fix up the state when a -// resource transitions its "count" from being set to unset or vice-versa, -// treating a 0-key and a no-key instance as aliases for one another across -// the transition. -// -// The correct time to call this function is in the DynamicExpand method for -// a node representing a resource, just after evaluating the count with -// evaluateResourceCountExpression, and before any other analysis of the -// state such as orphan detection. -// -// This function calls methods on the given EvalContext to update the current -// state in-place, if necessary. It is a no-op if there is no count transition -// taking place. -// -// Since the state is modified in-place, this function must take a writer lock -// on the state. The caller must therefore not also be holding a state lock, -// or this function will block forever awaiting the lock. -func fixResourceCountSetTransition(ctx EvalContext, addr addrs.AbsResource, countEnabled bool) { - state := ctx.State() - changed := state.MaybeFixUpResourceInstanceAddressForCount(addr, countEnabled) - if changed { - log.Printf("[TRACE] renamed first %s instance in transient state due to count argument change", addr) + // Figure what to look for and what to replace it with + hunt := n.Resource.Id() + replace := hunt + ".0" + if count < 2 { + hunt, replace = replace, hunt } + + state, lock := ctx.State() + + // Get a lock so we can access this instance and potentially make + // changes to it. + lock.Lock() + defer lock.Unlock() + + // Look for the module state. If we don't have one, then it doesn't matter. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { + return nil, nil + } + + // Look for the resource state. If we don't have one, then it is okay. + rs, ok := mod.Resources[hunt] + if !ok { + return nil, nil + } + + // If the replacement key exists, we just keep both + if _, ok := mod.Resources[replace]; ok { + return nil, nil + } + + mod.Resources[replace] = rs + delete(mod.Resources, hunt) + + return nil, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_count_boundary.go b/vendor/github.com/hashicorp/terraform/terraform/eval_count_boundary.go index 647c58d1..91e2b904 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_count_boundary.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_count_boundary.go @@ -1,11 +1,7 @@ package terraform import ( - "fmt" "log" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" ) // EvalCountFixZeroOneBoundaryGlobal is an EvalNode that fixes up the state @@ -13,34 +9,22 @@ import ( // a resource named "aws_instance.foo" to "aws_instance.foo.0" and vice-versa. // // This works on the global state. -type EvalCountFixZeroOneBoundaryGlobal struct { - Config *configs.Config -} +type EvalCountFixZeroOneBoundaryGlobal struct{} // TODO: test func (n *EvalCountFixZeroOneBoundaryGlobal) Eval(ctx EvalContext) (interface{}, error) { - // We'll temporarily lock the state to grab the modules, then work on each - // one separately while taking a lock again for each separate resource. - // This means that if another caller concurrently adds a module here while - // we're working then we won't update it, but that's no worse than the - // concurrent writer blocking for our entire fixup process and _then_ - // adding a new module, and in practice the graph node associated with - // this eval depends on everything else in the graph anyway, so there - // should not be concurrent writers. - state := ctx.State().Lock() - moduleAddrs := make([]addrs.ModuleInstance, 0, len(state.Modules)) - for _, m := range state.Modules { - moduleAddrs = append(moduleAddrs, m.Addr) - } - ctx.State().Unlock() + // Get the state and lock it since we'll potentially modify it + state, lock := ctx.State() + lock.Lock() + defer lock.Unlock() - for _, addr := range moduleAddrs { - cfg := n.Config.DescendentForInstance(addr) - if cfg == nil { - log.Printf("[WARN] Not fixing up EachModes for %s because it has no config", addr) - continue - } - if err := n.fixModule(ctx, addr); err != nil { + // Prune the state since we require a clean state to work + state.prune() + + // Go through each modules since the boundaries are restricted to a + // module scope. + for _, m := range state.Modules { + if err := n.fixModule(m); err != nil { return nil, err } } @@ -48,29 +32,46 @@ func (n *EvalCountFixZeroOneBoundaryGlobal) Eval(ctx EvalContext) (interface{}, return nil, nil } -func (n *EvalCountFixZeroOneBoundaryGlobal) fixModule(ctx EvalContext, moduleAddr addrs.ModuleInstance) error { - ms := ctx.State().Module(moduleAddr) - cfg := n.Config.DescendentForInstance(moduleAddr) - if ms == nil { - // Theoretically possible for a concurrent writer to delete a module - // while we're running, but in practice the graph node that called us - // depends on everything else in the graph and so there can never - // be a concurrent writer. - return fmt.Errorf("[WARN] no state found for %s while trying to fix up EachModes", moduleAddr) - } - if cfg == nil { - return fmt.Errorf("[WARN] no config found for %s while trying to fix up EachModes", moduleAddr) +func (n *EvalCountFixZeroOneBoundaryGlobal) fixModule(m *ModuleState) error { + // Counts keeps track of keys and their counts + counts := make(map[string]int) + for k, _ := range m.Resources { + // Parse the key + key, err := ParseResourceStateKey(k) + if err != nil { + return err + } + + // Set the index to -1 so that we can keep count + key.Index = -1 + + // Increment + counts[key.String()]++ } - for _, r := range ms.Resources { - addr := r.Addr.Absolute(moduleAddr) - rCfg := cfg.Module.ResourceByAddr(r.Addr) - if rCfg == nil { - log.Printf("[WARN] Not fixing up EachModes for %s because it has no config", addr) + // Go through the counts and do the fixup for each resource + for raw, count := range counts { + // Search and replace this resource + search := raw + replace := raw + ".0" + if count < 2 { + search, replace = replace, search + } + log.Printf("[TRACE] EvalCountFixZeroOneBoundaryGlobal: count %d, search %q, replace %q", count, search, replace) + + // Look for the resource state. If we don't have one, then it is okay. + rs, ok := m.Resources[search] + if !ok { continue } - hasCount := rCfg.Count != nil - fixResourceCountSetTransition(ctx, addr, hasCount) + + // If the replacement key exists, we just keep both + if _, ok := m.Resources[replace]; ok { + continue + } + + m.Resources[replace] = rs + delete(m.Resources, search) } return nil diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_diff.go b/vendor/github.com/hashicorp/terraform/terraform/eval_diff.go index 461a0b50..26205ce5 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_diff.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_diff.go @@ -1,114 +1,92 @@ package terraform import ( - "bytes" "fmt" "log" - "reflect" "strings" - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/plans/objchange" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/version" ) -// EvalCheckPlannedChange is an EvalNode implementation that produces errors -// if the _actual_ expected value is not compatible with what was recorded -// in the plan. -// -// Errors here are most often indicative of a bug in the provider, so our -// error messages will report with that in mind. It's also possible that -// there's a bug in Terraform's Core's own "proposed new value" code in -// EvalDiff. -type EvalCheckPlannedChange struct { - Addr addrs.ResourceInstance - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - - // We take ResourceInstanceChange objects here just because that's what's - // convenient to pass in from the evaltree implementation, but we really - // only look at the "After" value of each change. - Planned, Actual **plans.ResourceInstanceChange +// EvalCompareDiff is an EvalNode implementation that compares two diffs +// and errors if the diffs are not equal. +type EvalCompareDiff struct { + Info *InstanceInfo + One, Two **InstanceDiff } -func (n *EvalCheckPlannedChange) Eval(ctx EvalContext) (interface{}, error) { - providerSchema := *n.ProviderSchema - plannedChange := *n.Planned - actualChange := *n.Actual +// TODO: test +func (n *EvalCompareDiff) Eval(ctx EvalContext) (interface{}, error) { + one, two := *n.One, *n.Two - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support %q", n.Addr.Resource.Type) + // If either are nil, let them be empty + if one == nil { + one = new(InstanceDiff) + one.init() } - - var diags tfdiags.Diagnostics - absAddr := n.Addr.Absolute(ctx.Path()) - - log.Printf("[TRACE] EvalCheckPlannedChange: Verifying that actual change (action %s) matches planned change (action %s)", actualChange.Action, plannedChange.Action) - - if plannedChange.Action != actualChange.Action { - switch { - case plannedChange.Action == plans.Update && actualChange.Action == plans.NoOp: - // It's okay for an update to become a NoOp once we've filled in - // all of the unknown values, since the final values might actually - // match what was there before after all. - log.Printf("[DEBUG] After incorporating new values learned so far during apply, %s change has become NoOp", absAddr) - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced inconsistent final plan", - fmt.Sprintf( - "When expanding the plan for %s to include new values learned so far during apply, provider %q changed the planned action from %s to %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - absAddr, n.ProviderAddr.ProviderConfig.Type, - plannedChange.Action, actualChange.Action, - ), - )) + if two == nil { + two = new(InstanceDiff) + two.init() + } + oneId, _ := one.GetAttribute("id") + twoId, _ := two.GetAttribute("id") + one.DelAttribute("id") + two.DelAttribute("id") + defer func() { + if oneId != nil { + one.SetAttribute("id", oneId) } + if twoId != nil { + two.SetAttribute("id", twoId) + } + }() + + if same, reason := one.Same(two); !same { + log.Printf("[ERROR] %s: diffs didn't match", n.Info.Id) + log.Printf("[ERROR] %s: reason: %s", n.Info.Id, reason) + log.Printf("[ERROR] %s: diff one: %#v", n.Info.Id, one) + log.Printf("[ERROR] %s: diff two: %#v", n.Info.Id, two) + return nil, fmt.Errorf( + "%s: diffs didn't match during apply. This is a bug with "+ + "Terraform and should be reported as a GitHub Issue.\n"+ + "\n"+ + "Please include the following information in your report:\n"+ + "\n"+ + " Terraform Version: %s\n"+ + " Resource ID: %s\n"+ + " Mismatch reason: %s\n"+ + " Diff One (usually from plan): %#v\n"+ + " Diff Two (usually from apply): %#v\n"+ + "\n"+ + "Also include as much context as you can about your config, state, "+ + "and the steps you performed to trigger this error.\n", + n.Info.Id, version.Version, n.Info.Id, reason, one, two) } - errs := objchange.AssertObjectCompatible(schema, plannedChange.After, actualChange.After) - for _, err := range errs { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced inconsistent final plan", - fmt.Sprintf( - "When expanding the plan for %s to include new values learned so far during apply, provider %q produced an invalid new value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - absAddr, n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatError(err), - ), - )) - } - return nil, diags.Err() + return nil, nil } -// EvalDiff is an EvalNode implementation that detects changes for a given -// resource instance. +// EvalDiff is an EvalNode implementation that does a refresh for +// a resource. type EvalDiff struct { - Addr addrs.ResourceInstance - Config *configs.Resource - Provider *providers.Interface - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - State **states.ResourceInstanceObject - PreviousDiff **plans.ResourceInstanceChange + Name string + Info *InstanceInfo + Config **ResourceConfig + Provider *ResourceProvider + Diff **InstanceDiff + State **InstanceState + OutputDiff **InstanceDiff + OutputState **InstanceState - // CreateBeforeDestroy is set if either the resource's own config sets - // create_before_destroy explicitly or if dependencies have forced the - // resource to be handled as create_before_destroy in order to avoid - // a dependency cycle. - CreateBeforeDestroy bool - - OutputChange **plans.ResourceInstanceChange - OutputValue *cty.Value - OutputState **states.ResourceInstanceObject + // Resource is needed to fetch the ignore_changes list so we can + // filter user-requested ignored attributes from the diff. + Resource *config.Resource + // Stub is used to flag the generated InstanceDiff as a stub. This is used to + // ensure that the node exists to perform interpolations and generate + // computed paths off of, but not as an actual diff where resouces should be + // counted, and not as a diff that should be acted on. Stub bool } @@ -117,303 +95,81 @@ func (n *EvalDiff) Eval(ctx EvalContext) (interface{}, error) { state := *n.State config := *n.Config provider := *n.Provider - providerSchema := *n.ProviderSchema - - if providerSchema == nil { - return nil, fmt.Errorf("provider schema is unavailable for %s", n.Addr) - } - if n.ProviderAddr.ProviderConfig.Type == "" { - panic(fmt.Sprintf("EvalDiff for %s does not have ProviderAddr set", n.Addr.Absolute(ctx.Path()))) - } - - var diags tfdiags.Diagnostics - - // Evaluate the configuration - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) - } - keyData := EvalDataForInstanceKey(n.Addr.Key) - configVal, _, configDiags := ctx.EvaluateBlock(config.Config, schema, nil, keyData) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } - - absAddr := n.Addr.Absolute(ctx.Path()) - var priorVal cty.Value - var priorValTainted cty.Value - var priorPrivate []byte - if state != nil { - if state.Status != states.ObjectTainted { - priorVal = state.Value - priorPrivate = state.Private - } else { - // If the prior state is tainted then we'll proceed below like - // we're creating an entirely new object, but then turn it into - // a synthetic "Replace" change at the end, creating the same - // result as if the provider had marked at least one argument - // change as "requires replacement". - priorValTainted = state.Value - priorVal = cty.NullVal(schema.ImpliedType()) - } - } else { - priorVal = cty.NullVal(schema.ImpliedType()) - } - - proposedNewVal := objchange.ProposedNewObject(schema, priorVal, configVal) // Call pre-diff hook if !n.Stub { err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreDiff(absAddr, states.CurrentGen, priorVal, proposedNewVal) + return h.PreDiff(n.Info, state) }) if err != nil { return nil, err } } - // The provider gets an opportunity to customize the proposed new value, - // which in turn produces the _planned_ new value. - resp := provider.PlanResourceChange(providers.PlanResourceChangeRequest{ - TypeName: n.Addr.Resource.Type, - Config: configVal, - PriorState: priorVal, - ProposedNewState: proposedNewVal, - PriorPrivate: priorPrivate, + // The state for the diff must never be nil + diffState := state + if diffState == nil { + diffState = new(InstanceState) + } + diffState.init() + + // Diff! + diff, err := provider.Diff(n.Info, diffState, config) + if err != nil { + return nil, err + } + if diff == nil { + diff = new(InstanceDiff) + } + + // Set DestroyDeposed if we have deposed instances + _, err = readInstanceFromState(ctx, n.Name, nil, func(rs *ResourceState) (*InstanceState, error) { + if len(rs.Deposed) > 0 { + diff.DestroyDeposed = true + } + + return nil, nil }) - diags = diags.Append(resp.Diagnostics.InConfigBody(config.Config)) - if diags.HasErrors() { - return nil, diags.Err() + if err != nil { + return nil, err } - plannedNewVal := resp.PlannedState - plannedPrivate := resp.PlannedPrivate - - if plannedNewVal == cty.NilVal { - // Should never happen. Since real-world providers return via RPC a nil - // is always a bug in the client-side stub. This is more likely caused - // by an incompletely-configured mock provider in tests, though. - panic(fmt.Sprintf("PlanResourceChange of %s produced nil value", absAddr.String())) + // Preserve the DestroyTainted flag + if n.Diff != nil { + diff.SetTainted((*n.Diff).GetDestroyTainted()) } - // We allow the planned new value to disagree with configuration _values_ - // here, since that allows the provider to do special logic like a - // DiffSuppressFunc, but we still require that the provider produces - // a value whose type conforms to the schema. - for _, err := range plannedNewVal.Type().TestConformance(schema.ImpliedType()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid plan", - fmt.Sprintf( - "Provider %q planned an invalid value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() + // Require a destroy if there is an ID and it requires new. + if diff.RequiresNew() && state != nil && state.ID != "" { + diff.SetDestroy(true) } - if errs := objchange.AssertPlanValid(schema, priorVal, configVal, plannedNewVal); len(errs) > 0 { - if resp.LegacyTypeSystem { - // The shimming of the old type system in the legacy SDK is not precise - // enough to pass this consistency check, so we'll give it a pass here, - // but we will generate a warning about it so that we are more likely - // to notice in the logs if an inconsistency beyond the type system - // leads to a downstream provider failure. - var buf strings.Builder - fmt.Fprintf(&buf, "[WARN] Provider %q produced an invalid plan for %s, but we are tolerating it because it is using the legacy plugin SDK.\n The following problems may be the cause of any confusing errors from downstream operations:", n.ProviderAddr.ProviderConfig.Type, absAddr) - for _, err := range errs { - fmt.Fprintf(&buf, "\n - %s", tfdiags.FormatError(err)) - } - log.Print(buf.String()) - } else { - for _, err := range errs { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid plan", - fmt.Sprintf( - "Provider %q planned an invalid value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - return nil, diags.Err() + // If we're creating a new resource, compute its ID + if diff.RequiresNew() || state == nil || state.ID == "" { + var oldID string + if state != nil { + oldID = state.Attributes["id"] } - } - { - var moreDiags tfdiags.Diagnostics - plannedNewVal, moreDiags = n.processIgnoreChanges(priorVal, plannedNewVal) - diags = diags.Append(moreDiags) - if moreDiags.HasErrors() { - return nil, diags.Err() - } - } - - // The provider produces a list of paths to attributes whose changes mean - // that we must replace rather than update an existing remote object. - // However, we only need to do that if the identified attributes _have_ - // actually changed -- particularly after we may have undone some of the - // changes in processIgnoreChanges -- so now we'll filter that list to - // include only where changes are detected. - reqRep := cty.NewPathSet() - if len(resp.RequiresReplace) > 0 { - for _, path := range resp.RequiresReplace { - if priorVal.IsNull() { - // If prior is null then we don't expect any RequiresReplace at all, - // because this is a Create action. - continue - } - - priorChangedVal, priorPathDiags := hcl.ApplyPath(priorVal, path, nil) - plannedChangedVal, plannedPathDiags := hcl.ApplyPath(plannedNewVal, path, nil) - if plannedPathDiags.HasErrors() && priorPathDiags.HasErrors() { - // This means the path was invalid in both the prior and new - // values, which is an error with the provider itself. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid plan", - fmt.Sprintf( - "Provider %q has indicated \"requires replacement\" on %s for a non-existent attribute path %#v.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, path, - ), - )) - continue - } - - // Make sure we have valid Values for both values. - // Note: if the opposing value was of the type - // cty.DynamicPseudoType, the type assigned here may not exactly - // match the schema. This is fine here, since we're only going to - // check for equality, but if the NullVal is to be used, we need to - // check the schema for th true type. - switch { - case priorChangedVal == cty.NilVal && plannedChangedVal == cty.NilVal: - // this should never happen without ApplyPath errors above - panic("requires replace path returned 2 nil values") - case priorChangedVal == cty.NilVal: - priorChangedVal = cty.NullVal(plannedChangedVal.Type()) - case plannedChangedVal == cty.NilVal: - plannedChangedVal = cty.NullVal(priorChangedVal.Type()) - } - - eqV := plannedChangedVal.Equals(priorChangedVal) - if !eqV.IsKnown() || eqV.False() { - reqRep.Add(path) - } - } - if diags.HasErrors() { - return nil, diags.Err() - } - } - - eqV := plannedNewVal.Equals(priorVal) - eq := eqV.IsKnown() && eqV.True() - - var action plans.Action - switch { - case priorVal.IsNull(): - action = plans.Create - case eq: - action = plans.NoOp - case !reqRep.Empty(): - // If there are any "requires replace" paths left _after our filtering - // above_ then this is a replace action. - if n.CreateBeforeDestroy { - action = plans.CreateThenDelete - } else { - action = plans.DeleteThenCreate - } - default: - action = plans.Update - // "Delete" is never chosen here, because deletion plans are always - // created more directly elsewhere, such as in "orphan" handling. - } - - if action.IsReplace() { - // In this strange situation we want to produce a change object that - // shows our real prior object but has a _new_ object that is built - // from a null prior object, since we're going to delete the one - // that has all the computed values on it. - // - // Therefore we'll ask the provider to plan again here, giving it - // a null object for the prior, and then we'll meld that with the - // _actual_ prior state to produce a correctly-shaped replace change. - // The resulting change should show any computed attributes changing - // from known prior values to unknown values, unless the provider is - // able to predict new values for any of these computed attributes. - nullPriorVal := cty.NullVal(schema.ImpliedType()) - - // create a new proposed value from the null state and the config - proposedNewVal = objchange.ProposedNewObject(schema, nullPriorVal, configVal) - - resp = provider.PlanResourceChange(providers.PlanResourceChangeRequest{ - TypeName: n.Addr.Resource.Type, - Config: configVal, - PriorState: nullPriorVal, - ProposedNewState: proposedNewVal, - PriorPrivate: plannedPrivate, + // Add diff to compute new ID + diff.init() + diff.SetAttribute("id", &ResourceAttrDiff{ + Old: oldID, + NewComputed: true, + RequiresNew: true, + Type: DiffAttrOutput, }) - // We need to tread carefully here, since if there are any warnings - // in here they probably also came out of our previous call to - // PlanResourceChange above, and so we don't want to repeat them. - // Consequently, we break from the usual pattern here and only - // append these new diagnostics if there's at least one error inside. - if resp.Diagnostics.HasErrors() { - diags = diags.Append(resp.Diagnostics.InConfigBody(config.Config)) - return nil, diags.Err() - } - plannedNewVal = resp.PlannedState - plannedPrivate = resp.PlannedPrivate - for _, err := range schema.ImpliedType().TestConformance(plannedNewVal.Type()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid plan", - fmt.Sprintf( - "Provider %q planned an invalid value for %s%s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, tfdiags.FormatError(err), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() - } } - // If our prior value was tainted then we actually want this to appear - // as a replace change, even though so far we've been treating it as a - // create. - if action == plans.Create && priorValTainted != cty.NilVal { - if n.CreateBeforeDestroy { - action = plans.CreateThenDelete - } else { - action = plans.DeleteThenCreate - } - priorVal = priorValTainted - } - - // As a special case, if we have a previous diff (presumably from the plan - // phases, whereas we're now in the apply phase) and it was for a replace, - // we've already deleted the original object from state by the time we - // get here and so we would've ended up with a _create_ action this time, - // which we now need to paper over to get a result consistent with what - // we originally intended. - if n.PreviousDiff != nil { - prevChange := *n.PreviousDiff - if prevChange.Action.IsReplace() && action == plans.Create { - log.Printf("[TRACE] EvalDiff: %s treating Create change as %s change to match with earlier plan", absAddr, prevChange.Action) - action = prevChange.Action - priorVal = prevChange.Before - } + // filter out ignored resources + if err := n.processIgnoreChanges(diff); err != nil { + return nil, err } // Call post-refresh hook if !n.Stub { - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostDiff(absAddr, states.CurrentGen, action, priorVal, plannedNewVal) + err = ctx.Hook(func(h Hook) (HookAction, error) { + return h.PostDiff(n.Info, diff) }) if err != nil { return nil, err @@ -421,135 +177,30 @@ func (n *EvalDiff) Eval(ctx EvalContext) (interface{}, error) { } // Update our output if we care - if n.OutputChange != nil { - *n.OutputChange = &plans.ResourceInstanceChange{ - Addr: absAddr, - Private: plannedPrivate, - ProviderAddr: n.ProviderAddr, - Change: plans.Change{ - Action: action, - Before: priorVal, - After: plannedNewVal, - }, - RequiredReplace: reqRep, - } - } - - if n.OutputValue != nil { - *n.OutputValue = configVal + if n.OutputDiff != nil { + *n.OutputDiff = diff } // Update the state if we care if n.OutputState != nil { - *n.OutputState = &states.ResourceInstanceObject{ - // We use the special "planned" status here to note that this - // object's value is not yet complete. Objects with this status - // cannot be used during expression evaluation, so the caller - // must _also_ record the returned change in the active plan, - // which the expression evaluator will use in preference to this - // incomplete value recorded in the state. - Status: states.ObjectPlanned, - Value: plannedNewVal, + *n.OutputState = state + + // Merge our state so that the state is updated with our plan + if !diff.Empty() && n.OutputState != nil { + *n.OutputState = state.MergeDiff(diff) } } return nil, nil } -func (n *EvalDiff) processIgnoreChanges(prior, proposed cty.Value) (cty.Value, tfdiags.Diagnostics) { - // ignore_changes only applies when an object already exists, since we - // can't ignore changes to a thing we've not created yet. - if prior.IsNull() { - return proposed, nil - } - - ignoreChanges := n.Config.Managed.IgnoreChanges - ignoreAll := n.Config.Managed.IgnoreAllChanges - - if len(ignoreChanges) == 0 && !ignoreAll { - return proposed, nil - } - if ignoreAll { - return prior, nil - } - if prior.IsNull() || proposed.IsNull() { - // Ignore changes doesn't apply when we're creating for the first time. - // Proposed should never be null here, but if it is then we'll just let it be. - return proposed, nil - } - - return processIgnoreChangesIndividual(prior, proposed, ignoreChanges) -} - -func processIgnoreChangesIndividual(prior, proposed cty.Value, ignoreChanges []hcl.Traversal) (cty.Value, tfdiags.Diagnostics) { - // When we walk below we will be using cty.Path values for comparison, so - // we'll convert our traversals here so we can compare more easily. - ignoreChangesPath := make([]cty.Path, len(ignoreChanges)) - for i, traversal := range ignoreChanges { - path := make(cty.Path, len(traversal)) - for si, step := range traversal { - switch ts := step.(type) { - case hcl.TraverseRoot: - path[si] = cty.GetAttrStep{ - Name: ts.Name, - } - case hcl.TraverseAttr: - path[si] = cty.GetAttrStep{ - Name: ts.Name, - } - case hcl.TraverseIndex: - path[si] = cty.IndexStep{ - Key: ts.Key, - } - default: - panic(fmt.Sprintf("unsupported traversal step %#v", step)) - } - } - ignoreChangesPath[i] = path - } - - var diags tfdiags.Diagnostics - ret, _ := cty.Transform(proposed, func(path cty.Path, v cty.Value) (cty.Value, error) { - // First we must see if this is a path that's being ignored at all. - // We're looking for an exact match here because this walk will visit - // leaf values first and then their containers, and we want to do - // the "ignore" transform once we reach the point indicated, throwing - // away any deeper values we already produced at that point. - var ignoreTraversal hcl.Traversal - for i, candidate := range ignoreChangesPath { - if reflect.DeepEqual(path, candidate) { - ignoreTraversal = ignoreChanges[i] - } - } - if ignoreTraversal == nil { - return v, nil - } - - // If we're able to follow the same path through the prior value, - // we'll take the value there instead, effectively undoing the - // change that was planned. - priorV, diags := hcl.ApplyPath(prior, path, nil) - if diags.HasErrors() { - // We just ignore the errors and move on here, since we assume it's - // just because the prior value was a slightly-different shape. - // It could potentially also be that the traversal doesn't match - // the schema, but we should've caught that during the validate - // walk if so. - return v, nil - } - return priorV, nil - }) - return ret, diags -} - -func (n *EvalDiff) processIgnoreChangesOld(diff *InstanceDiff) error { - if diff == nil || n.Config == nil || n.Config.Managed == nil { +func (n *EvalDiff) processIgnoreChanges(diff *InstanceDiff) error { + if diff == nil || n.Resource == nil || n.Resource.Id() == "" { return nil } - ignoreChanges := n.Config.Managed.IgnoreChanges - ignoreAll := n.Config.Managed.IgnoreAllChanges + ignoreChanges := n.Resource.Lifecycle.IgnoreChanges - if len(ignoreChanges) == 0 && !ignoreAll { + if len(ignoreChanges) == 0 { return nil } @@ -569,14 +220,9 @@ func (n *EvalDiff) processIgnoreChangesOld(diff *InstanceDiff) error { // get the complete set of keys we want to ignore ignorableAttrKeys := make(map[string]bool) - for k := range attrs { - if ignoreAll { - ignorableAttrKeys[k] = true - continue - } - for _, ignoredTraversal := range ignoreChanges { - ignoredKey := legacyFlatmapKeyForTraversal(ignoredTraversal) - if k == ignoredKey || strings.HasPrefix(k, ignoredKey+".") { + for _, ignoredKey := range ignoreChanges { + for k := range attrs { + if ignoredKey == "*" || strings.HasPrefix(k, ignoredKey) { ignorableAttrKeys[k] = true } } @@ -639,56 +285,14 @@ func (n *EvalDiff) processIgnoreChangesOld(diff *InstanceDiff) error { // If we didn't hit any of our early exit conditions, we can filter the diff. for k := range ignorableAttrKeys { - log.Printf("[DEBUG] [EvalIgnoreChanges] %s: Ignoring diff attribute: %s", n.Addr.String(), k) + log.Printf("[DEBUG] [EvalIgnoreChanges] %s - Ignoring diff attribute: %s", + n.Resource.Id(), k) diff.DelAttribute(k) } return nil } -// legacyFlagmapKeyForTraversal constructs a key string compatible with what -// the flatmap package would generate for an attribute addressable by the given -// traversal. -// -// This is used only to shim references to attributes within the diff and -// state structures, which have not (at the time of writing) yet been updated -// to use the newer HCL-based representations. -func legacyFlatmapKeyForTraversal(traversal hcl.Traversal) string { - var buf bytes.Buffer - first := true - for _, step := range traversal { - if !first { - buf.WriteByte('.') - } - switch ts := step.(type) { - case hcl.TraverseRoot: - buf.WriteString(ts.Name) - case hcl.TraverseAttr: - buf.WriteString(ts.Name) - case hcl.TraverseIndex: - val := ts.Key - switch val.Type() { - case cty.Number: - bf := val.AsBigFloat() - buf.WriteString(bf.String()) - case cty.String: - s := val.AsString() - buf.WriteString(s) - default: - // should never happen, since no other types appear in - // traversals in practice. - buf.WriteByte('?') - } - default: - // should never happen, since we've covered all of the types - // that show up in parsed traversals in practice. - buf.WriteByte('?') - } - first = false - } - return buf.String() -} - // a group of key-*ResourceAttrDiff pairs from the same flatmapped container type flatAttrDiff map[string]*ResourceAttrDiff @@ -739,213 +343,159 @@ func groupContainers(d *InstanceDiff) map[string]flatAttrDiff { // EvalDiffDestroy is an EvalNode implementation that returns a plain // destroy diff. type EvalDiffDestroy struct { - Addr addrs.ResourceInstance - DeposedKey states.DeposedKey - State **states.ResourceInstanceObject - ProviderAddr addrs.AbsProviderConfig - - Output **plans.ResourceInstanceChange - OutputState **states.ResourceInstanceObject + Info *InstanceInfo + State **InstanceState + Output **InstanceDiff } // TODO: test func (n *EvalDiffDestroy) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) state := *n.State - if n.ProviderAddr.ProviderConfig.Type == "" { - if n.DeposedKey == "" { - panic(fmt.Sprintf("EvalDiffDestroy for %s does not have ProviderAddr set", absAddr)) - } else { - panic(fmt.Sprintf("EvalDiffDestroy for %s (deposed %s) does not have ProviderAddr set", absAddr, n.DeposedKey)) - } - } - - // If there is no state or our attributes object is null then we're already - // destroyed. - if state == nil || state.Value.IsNull() { + // If there is no state or we don't have an ID, we're already destroyed + if state == nil || state.ID == "" { return nil, nil } // Call pre-diff hook err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreDiff( - absAddr, n.DeposedKey.Generation(), - state.Value, - cty.NullVal(cty.DynamicPseudoType), - ) + return h.PreDiff(n.Info, state) }) if err != nil { return nil, err } - // Change is always the same for a destroy. We don't need the provider's - // help for this one. - // TODO: Should we give the provider an opportunity to veto this? - change := &plans.ResourceInstanceChange{ - Addr: absAddr, - DeposedKey: n.DeposedKey, - Change: plans.Change{ - Action: plans.Delete, - Before: state.Value, - After: cty.NullVal(cty.DynamicPseudoType), - }, - ProviderAddr: n.ProviderAddr, - } + // The diff + diff := &InstanceDiff{Destroy: true} // Call post-diff hook err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostDiff( - absAddr, - n.DeposedKey.Generation(), - change.Action, - change.Before, - change.After, - ) + return h.PostDiff(n.Info, diff) }) if err != nil { return nil, err } // Update our output - *n.Output = change - - if n.OutputState != nil { - // Record our proposed new state, which is nil because we're destroying. - *n.OutputState = nil - } + *n.Output = diff return nil, nil } -// EvalReduceDiff is an EvalNode implementation that takes a planned resource -// instance change as might be produced by EvalDiff or EvalDiffDestroy and -// "simplifies" it to a single atomic action to be performed by a specific -// graph node. -// -// Callers must specify whether they are a destroy node or a regular apply -// node. If the result is NoOp then the given change requires no action for -// the specific graph node calling this and so evaluation of the that graph -// node should exit early and take no action. -// -// The object written to OutChange may either be identical to InChange or -// a new change object derived from InChange. Because of the former case, the -// caller must not mutate the object returned in OutChange. -type EvalReduceDiff struct { - Addr addrs.ResourceInstance - InChange **plans.ResourceInstanceChange - Destroy bool - OutChange **plans.ResourceInstanceChange +// EvalDiffDestroyModule is an EvalNode implementation that writes the diff to +// the full diff. +type EvalDiffDestroyModule struct { + Path []string } // TODO: test -func (n *EvalReduceDiff) Eval(ctx EvalContext) (interface{}, error) { - in := *n.InChange - out := in.Simplify(n.Destroy) - if n.OutChange != nil { - *n.OutChange = out - } - if out.Action != in.Action { - if n.Destroy { - log.Printf("[TRACE] EvalReduceDiff: %s change simplified from %s to %s for destroy node", n.Addr, in.Action, out.Action) - } else { - log.Printf("[TRACE] EvalReduceDiff: %s change simplified from %s to %s for apply node", n.Addr, in.Action, out.Action) - } +func (n *EvalDiffDestroyModule) Eval(ctx EvalContext) (interface{}, error) { + diff, lock := ctx.Diff() + + // Acquire the lock so that we can do this safely concurrently + lock.Lock() + defer lock.Unlock() + + // Write the diff + modDiff := diff.ModuleByPath(n.Path) + if modDiff == nil { + modDiff = diff.AddModule(n.Path) } + modDiff.Destroy = true + return nil, nil } -// EvalReadDiff is an EvalNode implementation that retrieves the planned -// change for a particular resource instance object. -type EvalReadDiff struct { - Addr addrs.ResourceInstance - DeposedKey states.DeposedKey - ProviderSchema **ProviderSchema - Change **plans.ResourceInstanceChange +// EvalFilterDiff is an EvalNode implementation that filters the diff +// according to some filter. +type EvalFilterDiff struct { + // Input and output + Diff **InstanceDiff + Output **InstanceDiff + + // Destroy, if true, will only include a destroy diff if it is set. + Destroy bool } -func (n *EvalReadDiff) Eval(ctx EvalContext) (interface{}, error) { - providerSchema := *n.ProviderSchema - changes := ctx.Changes() - addr := n.Addr.Absolute(ctx.Path()) - - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) - } - - gen := states.CurrentGen - if n.DeposedKey != states.NotDeposed { - gen = n.DeposedKey - } - csrc := changes.GetResourceInstanceChange(addr, gen) - if csrc == nil { - log.Printf("[TRACE] EvalReadDiff: No planned change recorded for %s", addr) +func (n *EvalFilterDiff) Eval(ctx EvalContext) (interface{}, error) { + if *n.Diff == nil { return nil, nil } - change, err := csrc.Decode(schema.ImpliedType()) - if err != nil { - return nil, fmt.Errorf("failed to decode planned changes for %s: %s", addr, err) - } - if n.Change != nil { - *n.Change = change + input := *n.Diff + result := new(InstanceDiff) + + if n.Destroy { + if input.GetDestroy() || input.RequiresNew() { + result.SetDestroy(true) + } } - log.Printf("[TRACE] EvalReadDiff: Read %s change from plan for %s", change.Action, addr) + if n.Output != nil { + *n.Output = result + } return nil, nil } -// EvalWriteDiff is an EvalNode implementation that saves a planned change -// for an instance object into the set of global planned changes. +// EvalReadDiff is an EvalNode implementation that writes the diff to +// the full diff. +type EvalReadDiff struct { + Name string + Diff **InstanceDiff +} + +func (n *EvalReadDiff) Eval(ctx EvalContext) (interface{}, error) { + diff, lock := ctx.Diff() + + // Acquire the lock so that we can do this safely concurrently + lock.Lock() + defer lock.Unlock() + + // Write the diff + modDiff := diff.ModuleByPath(ctx.Path()) + if modDiff == nil { + return nil, nil + } + + *n.Diff = modDiff.Resources[n.Name] + + return nil, nil +} + +// EvalWriteDiff is an EvalNode implementation that writes the diff to +// the full diff. type EvalWriteDiff struct { - Addr addrs.ResourceInstance - DeposedKey states.DeposedKey - ProviderSchema **ProviderSchema - Change **plans.ResourceInstanceChange + Name string + Diff **InstanceDiff } // TODO: test func (n *EvalWriteDiff) Eval(ctx EvalContext) (interface{}, error) { - changes := ctx.Changes() - addr := n.Addr.Absolute(ctx.Path()) - if n.Change == nil || *n.Change == nil { - // Caller sets nil to indicate that we need to remove a change from - // the set of changes. - gen := states.CurrentGen - if n.DeposedKey != states.NotDeposed { - gen = n.DeposedKey - } - changes.RemoveResourceInstanceChange(addr, gen) - return nil, nil + diff, lock := ctx.Diff() + + // The diff to write, if its empty it should write nil + var diffVal *InstanceDiff + if n.Diff != nil { + diffVal = *n.Diff + } + if diffVal.Empty() { + diffVal = nil } - providerSchema := *n.ProviderSchema - change := *n.Change + // Acquire the lock so that we can do this safely concurrently + lock.Lock() + defer lock.Unlock() - if change.Addr.String() != addr.String() || change.DeposedKey != n.DeposedKey { - // Should never happen, and indicates a bug in the caller. - panic("inconsistent address and/or deposed key in EvalWriteDiff") + // Write the diff + modDiff := diff.ModuleByPath(ctx.Path()) + if modDiff == nil { + modDiff = diff.AddModule(ctx.Path()) } - - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) - } - - csrc, err := change.Encode(schema.ImpliedType()) - if err != nil { - return nil, fmt.Errorf("failed to encode planned changes for %s: %s", addr, err) - } - - changes.AppendResourceInstanceChange(csrc) - if n.DeposedKey == states.NotDeposed { - log.Printf("[TRACE] EvalWriteDiff: recorded %s change for %s", change.Action, addr) + if diffVal != nil { + modDiff.Resources[n.Name] = diffVal } else { - log.Printf("[TRACE] EvalWriteDiff: recorded %s change for %s deposed object %s", change.Action, addr, n.DeposedKey) + delete(modDiff.Resources, n.Name) } return nil, nil diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_import_state.go b/vendor/github.com/hashicorp/terraform/terraform/eval_import_state.go index a60f4a0a..62cc581f 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_import_state.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_import_state.go @@ -2,63 +2,47 @@ package terraform import ( "fmt" - "log" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // EvalImportState is an EvalNode implementation that performs an // ImportState operation on a provider. This will return the imported // states but won't modify any actual state. type EvalImportState struct { - Addr addrs.ResourceInstance - Provider *providers.Interface - ID string - Output *[]providers.ImportedResource + Provider *ResourceProvider + Info *InstanceInfo + Id string + Output *[]*InstanceState } // TODO: test func (n *EvalImportState) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) provider := *n.Provider - var diags tfdiags.Diagnostics { // Call pre-import hook err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreImportState(absAddr, n.ID) + return h.PreImportState(n.Info, n.Id) }) if err != nil { return nil, err } } - resp := provider.ImportResourceState(providers.ImportResourceStateRequest{ - TypeName: n.Addr.Resource.Type, - ID: n.ID, - }) - diags = diags.Append(resp.Diagnostics) - if diags.HasErrors() { - return nil, diags.Err() - } - - imported := resp.ImportedResources - - for _, obj := range imported { - log.Printf("[TRACE] EvalImportState: import %s %q produced instance object of type %s", absAddr.String(), n.ID, obj.TypeName) + // Import! + state, err := provider.ImportState(n.Info, n.Id) + if err != nil { + return nil, fmt.Errorf( + "import %s (id: %s): %s", n.Info.HumanId(), n.Id, err) } if n.Output != nil { - *n.Output = imported + *n.Output = state } { // Call post-import hook err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostImportState(absAddr, imported) + return h.PostImportState(n.Info, state) }) if err != nil { return nil, err @@ -71,25 +55,22 @@ func (n *EvalImportState) Eval(ctx EvalContext) (interface{}, error) { // EvalImportStateVerify verifies the state after ImportState and // after the refresh to make sure it is non-nil and valid. type EvalImportStateVerify struct { - Addr addrs.ResourceInstance - State **states.ResourceInstanceObject + Info *InstanceInfo + Id string + State **InstanceState } // TODO: test func (n *EvalImportStateVerify) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - state := *n.State - if state.Value.IsNull() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Cannot import non-existent remote object", - fmt.Sprintf( - "While attempting to import an existing object to %s, the provider detected that no object exists with the given id. Only pre-existing objects can be imported; check that the id is correct and that it is associated with the provider's configured region or endpoint, or use \"terraform apply\" to create a new remote object for this resource.", - n.Addr.String(), - ), - )) + if state.Empty() { + return nil, fmt.Errorf( + "import %s (id: %s): Terraform detected a resource with this ID doesn't\n"+ + "exist. Please verify the ID is correct. You cannot import non-existent\n"+ + "resources using Terraform import.", + n.Info.HumanId(), + n.Id) } - return nil, diags.ErrWithWarnings() + return nil, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_interpolate.go b/vendor/github.com/hashicorp/terraform/terraform/eval_interpolate.go new file mode 100644 index 00000000..6a78a6bb --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_interpolate.go @@ -0,0 +1,56 @@ +package terraform + +import ( + "log" + + "github.com/hashicorp/terraform/config" +) + +// EvalInterpolate is an EvalNode implementation that takes a raw +// configuration and interpolates it. +type EvalInterpolate struct { + Config *config.RawConfig + Resource *Resource + Output **ResourceConfig + ContinueOnErr bool +} + +func (n *EvalInterpolate) Eval(ctx EvalContext) (interface{}, error) { + rc, err := ctx.Interpolate(n.Config, n.Resource) + if err != nil { + if n.ContinueOnErr { + log.Printf("[WARN] Interpolation %q failed: %s", n.Config.Key, err) + return nil, EvalEarlyExitError{} + } + return nil, err + } + + if n.Output != nil { + *n.Output = rc + } + + return nil, nil +} + +// EvalInterpolateProvider is an EvalNode implementation that takes a +// ProviderConfig and interpolates it. Provider configurations are the only +// "inherited" type of configuration we have, and the original raw config may +// have a different interpolation scope. +type EvalInterpolateProvider struct { + Config *config.ProviderConfig + Resource *Resource + Output **ResourceConfig +} + +func (n *EvalInterpolateProvider) Eval(ctx EvalContext) (interface{}, error) { + rc, err := ctx.InterpolateProvider(n.Config, n.Resource) + if err != nil { + return nil, err + } + + if n.Output != nil { + *n.Output = rc + } + + return nil, nil +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_lang.go b/vendor/github.com/hashicorp/terraform/terraform/eval_lang.go deleted file mode 100644 index 0c051f76..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_lang.go +++ /dev/null @@ -1,61 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform/addrs" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// EvalConfigBlock is an EvalNode implementation that takes a raw -// configuration block and evaluates any expressions within it. -// -// ExpandedConfig is populated with the result of expanding any "dynamic" -// blocks in the given body, which can be useful for extracting correct source -// location information for specific attributes in the result. -type EvalConfigBlock struct { - Config *hcl.Body - Schema *configschema.Block - SelfAddr addrs.Referenceable - Output *cty.Value - ExpandedConfig *hcl.Body - ContinueOnErr bool -} - -func (n *EvalConfigBlock) Eval(ctx EvalContext) (interface{}, error) { - val, body, diags := ctx.EvaluateBlock(*n.Config, n.Schema, n.SelfAddr, EvalDataForNoInstanceKey) - if diags.HasErrors() && n.ContinueOnErr { - log.Printf("[WARN] Block evaluation failed: %s", diags.Err()) - return nil, EvalEarlyExitError{} - } - - if n.Output != nil { - *n.Output = val - } - if n.ExpandedConfig != nil { - *n.ExpandedConfig = body - } - - return nil, diags.ErrWithWarnings() -} - -// EvalConfigExpr is an EvalNode implementation that takes a raw configuration -// expression and evaluates it. -type EvalConfigExpr struct { - Expr hcl.Expression - SelfAddr addrs.Referenceable - Output *cty.Value -} - -func (n *EvalConfigExpr) Eval(ctx EvalContext) (interface{}, error) { - val, diags := ctx.EvaluateExpr(n.Expr, cty.DynamicPseudoType, n.SelfAddr) - - if n.Output != nil { - *n.Output = val - } - - return nil, diags.ErrWithWarnings() -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_local.go b/vendor/github.com/hashicorp/terraform/terraform/eval_local.go index bad9ac5b..a4b2a505 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_local.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_local.go @@ -3,55 +3,56 @@ package terraform import ( "fmt" - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/lang" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config" ) // EvalLocal is an EvalNode implementation that evaluates the // expression for a local value and writes it into a transient part of // the state. type EvalLocal struct { - Addr addrs.LocalValue - Expr hcl.Expression + Name string + Value *config.RawConfig } func (n *EvalLocal) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - - // We ignore diags here because any problems we might find will be found - // again in EvaluateExpr below. - refs, _ := lang.ReferencesInExpr(n.Expr) - for _, ref := range refs { - if ref.Subject == n.Addr { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Self-referencing local value", - Detail: fmt.Sprintf("Local value %s cannot use its own result as part of its expression.", n.Addr), - Subject: ref.SourceRange.ToHCL().Ptr(), - Context: n.Expr.Range().Ptr(), - }) - } - } - if diags.HasErrors() { - return nil, diags.Err() + cfg, err := ctx.Interpolate(n.Value, nil) + if err != nil { + return nil, fmt.Errorf("local.%s: %s", n.Name, err) } - val, moreDiags := ctx.EvaluateExpr(n.Expr, cty.DynamicPseudoType, nil) - diags = diags.Append(moreDiags) - if moreDiags.HasErrors() { - return nil, diags.Err() - } - - state := ctx.State() + state, lock := ctx.State() if state == nil { return nil, fmt.Errorf("cannot write local value to nil state") } - state.SetLocalValue(n.Addr.Absolute(ctx.Path()), val) + // Get a write lock so we can access the state + lock.Lock() + defer lock.Unlock() + + // Look for the module state. If we don't have one, create it. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { + mod = state.AddModule(ctx.Path()) + } + + // Get the value from the config + var valueRaw interface{} = config.UnknownVariableValue + if cfg != nil { + var ok bool + valueRaw, ok = cfg.Get("value") + if !ok { + valueRaw = "" + } + if cfg.IsComputed("value") { + valueRaw = config.UnknownVariableValue + } + } + + if mod.Locals == nil { + // initialize + mod.Locals = map[string]interface{}{} + } + mod.Locals[n.Name] = valueRaw return nil, nil } @@ -60,15 +61,26 @@ func (n *EvalLocal) Eval(ctx EvalContext) (interface{}, error) { // from the state. Locals aren't persisted, but we don't need to evaluate them // during destroy. type EvalDeleteLocal struct { - Addr addrs.LocalValue + Name string } func (n *EvalDeleteLocal) Eval(ctx EvalContext) (interface{}, error) { - state := ctx.State() + state, lock := ctx.State() if state == nil { return nil, nil } - state.RemoveLocalValue(n.Addr.Absolute(ctx.Path())) + // Get a write lock so we can access this instance + lock.Lock() + defer lock.Unlock() + + // Look for the module state. If we don't have one, create it. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { + return nil, nil + } + + delete(mod.Locals, n.Name) + return nil, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_output.go b/vendor/github.com/hashicorp/terraform/terraform/eval_output.go index 10573971..a8346276 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_output.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_output.go @@ -4,132 +4,131 @@ import ( "fmt" "log" - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/states" + "github.com/hashicorp/terraform/config" ) // EvalDeleteOutput is an EvalNode implementation that deletes an output // from the state. type EvalDeleteOutput struct { - Addr addrs.OutputValue + Name string } // TODO: test func (n *EvalDeleteOutput) Eval(ctx EvalContext) (interface{}, error) { - state := ctx.State() + state, lock := ctx.State() if state == nil { return nil, nil } - state.RemoveOutputValue(n.Addr.Absolute(ctx.Path())) + // Get a write lock so we can access this instance + lock.Lock() + defer lock.Unlock() + + // Look for the module state. If we don't have one, create it. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { + return nil, nil + } + + delete(mod.Outputs, n.Name) + return nil, nil } // EvalWriteOutput is an EvalNode implementation that writes the output // for the given name to the current state. type EvalWriteOutput struct { - Addr addrs.OutputValue + Name string Sensitive bool - Expr hcl.Expression + Value *config.RawConfig // ContinueOnErr allows interpolation to fail during Input ContinueOnErr bool } // TODO: test func (n *EvalWriteOutput) Eval(ctx EvalContext) (interface{}, error) { - addr := n.Addr.Absolute(ctx.Path()) - - // This has to run before we have a state lock, since evaluation also + // This has to run before we have a state lock, since interpolation also // reads the state - val, diags := ctx.EvaluateExpr(n.Expr, cty.DynamicPseudoType, nil) - // We'll handle errors below, after we have loaded the module. + cfg, err := ctx.Interpolate(n.Value, nil) + // handle the error after we have the module from the state - state := ctx.State() + state, lock := ctx.State() if state == nil { - return nil, nil + return nil, fmt.Errorf("cannot write state to nil state") } - changes := ctx.Changes() // may be nil, if we're not working on a changeset + // Get a write lock so we can access this instance + lock.Lock() + defer lock.Unlock() + // Look for the module state. If we don't have one, create it. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { + mod = state.AddModule(ctx.Path()) + } // handling the interpolation error - if diags.HasErrors() { + if err != nil { if n.ContinueOnErr || flagWarnOutputErrors { - log.Printf("[ERROR] Output interpolation %q failed: %s", n.Addr.Name, diags.Err()) + log.Printf("[ERROR] Output interpolation %q failed: %s", n.Name, err) // if we're continuing, make sure the output is included, and - // marked as unknown. If the evaluator was able to find a type - // for the value in spite of the error then we'll use it. - n.setValue(addr, state, changes, cty.UnknownVal(val.Type())) + // marked as unknown + mod.Outputs[n.Name] = &OutputState{ + Type: "string", + Value: config.UnknownVariableValue, + } return nil, EvalEarlyExitError{} } - return nil, diags.Err() + return nil, err } - n.setValue(addr, state, changes, val) + // Get the value from the config + var valueRaw interface{} = config.UnknownVariableValue + if cfg != nil { + var ok bool + valueRaw, ok = cfg.Get("value") + if !ok { + valueRaw = "" + } + if cfg.IsComputed("value") { + valueRaw = config.UnknownVariableValue + } + } + + switch valueTyped := valueRaw.(type) { + case string: + mod.Outputs[n.Name] = &OutputState{ + Type: "string", + Sensitive: n.Sensitive, + Value: valueTyped, + } + case []interface{}: + mod.Outputs[n.Name] = &OutputState{ + Type: "list", + Sensitive: n.Sensitive, + Value: valueTyped, + } + case map[string]interface{}: + mod.Outputs[n.Name] = &OutputState{ + Type: "map", + Sensitive: n.Sensitive, + Value: valueTyped, + } + case []map[string]interface{}: + // an HCL map is multi-valued, so if this was read out of a config the + // map may still be in a slice. + if len(valueTyped) == 1 { + mod.Outputs[n.Name] = &OutputState{ + Type: "map", + Sensitive: n.Sensitive, + Value: valueTyped[0], + } + break + } + return nil, fmt.Errorf("output %s type (%T) with %d values not valid for type map", + n.Name, valueTyped, len(valueTyped)) + default: + return nil, fmt.Errorf("output %s is not a valid type (%T)\n", n.Name, valueTyped) + } return nil, nil } - -func (n *EvalWriteOutput) setValue(addr addrs.AbsOutputValue, state *states.SyncState, changes *plans.ChangesSync, val cty.Value) { - if val.IsKnown() && !val.IsNull() { - // The state itself doesn't represent unknown values, so we null them - // out here and then we'll save the real unknown value in the planned - // changeset below, if we have one on this graph walk. - log.Printf("[TRACE] EvalWriteOutput: Saving value for %s in state", addr) - stateVal := cty.UnknownAsNull(val) - state.SetOutputValue(addr, stateVal, n.Sensitive) - } else { - log.Printf("[TRACE] EvalWriteOutput: Removing %s from state (it is now null)", addr) - state.RemoveOutputValue(addr) - } - - // If we also have an active changeset then we'll replicate the value in - // there. This is used in preference to the state where present, since it - // *is* able to represent unknowns, while the state cannot. - if changes != nil { - // For the moment we are not properly tracking changes to output - // values, and just marking them always as "Create" or "Destroy" - // actions. A future release will rework the output lifecycle so we - // can track their changes properly, in a similar way to how we work - // with resource instances. - - var change *plans.OutputChange - if !val.IsNull() { - change = &plans.OutputChange{ - Addr: addr, - Sensitive: n.Sensitive, - Change: plans.Change{ - Action: plans.Create, - Before: cty.NullVal(cty.DynamicPseudoType), - After: val, - }, - } - } else { - change = &plans.OutputChange{ - Addr: addr, - Sensitive: n.Sensitive, - Change: plans.Change{ - // This is just a weird placeholder delete action since - // we don't have an actual prior value to indicate. - // FIXME: Generate real planned changes for output values - // that include the old values. - Action: plans.Delete, - Before: cty.NullVal(cty.DynamicPseudoType), - After: cty.NullVal(cty.DynamicPseudoType), - }, - } - } - - cs, err := change.Encode() - if err != nil { - // Should never happen, since we just constructed this right above - panic(fmt.Sprintf("planned change for %s could not be encoded: %s", addr, err)) - } - log.Printf("[TRACE] EvalWriteOutput: Saving %s change for %s in changeset", change.Action, addr) - changes.RemoveOutputChange(addr) // remove any existing planned change, if present - changes.AppendOutputChange(cs) // add the new planned change - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_provider.go b/vendor/github.com/hashicorp/terraform/terraform/eval_provider.go index 7df6584a..61f6ff94 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_provider.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_provider.go @@ -2,86 +2,50 @@ package terraform import ( "fmt" - "log" - "github.com/hashicorp/hcl2/hcl" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config" ) -func buildProviderConfig(ctx EvalContext, addr addrs.ProviderConfig, config *configs.Provider) hcl.Body { - var configBody hcl.Body - if config != nil { - configBody = config.Config +// EvalBuildProviderConfig outputs a *ResourceConfig that is properly +// merged with parents and inputs on top of what is configured in the file. +type EvalBuildProviderConfig struct { + Provider string + Config **ResourceConfig + Output **ResourceConfig +} + +func (n *EvalBuildProviderConfig) Eval(ctx EvalContext) (interface{}, error) { + cfg := *n.Config + + // If we have an Input configuration set, then merge that in + if input := ctx.ProviderInput(n.Provider); input != nil { + // "input" is a map of the subset of config values that were known + // during the input walk, set by EvalInputProvider. Note that + // in particular it does *not* include attributes that had + // computed values at input time; those appear *only* in + // "cfg" here. + rc, err := config.NewRawConfig(input) + if err != nil { + return nil, err + } + + merged := rc.Merge(cfg.raw) + cfg = NewResourceConfig(merged) } - var inputBody hcl.Body - inputConfig := ctx.ProviderInput(addr) - if len(inputConfig) > 0 { - inputBody = configs.SynthBody("", inputConfig) - } - - switch { - case configBody != nil && inputBody != nil: - log.Printf("[TRACE] buildProviderConfig for %s: merging explicit config and input", addr) - // Note that the inputBody is the _base_ here, because configs.MergeBodies - // expects the base have all of the required fields, while these are - // forced to be optional for the override. The input process should - // guarantee that we have a value for each of the required arguments and - // that in practice the sets of attributes in each body will be - // disjoint. - return configs.MergeBodies(inputBody, configBody) - case configBody != nil: - log.Printf("[TRACE] buildProviderConfig for %s: using explicit config only", addr) - return configBody - case inputBody != nil: - log.Printf("[TRACE] buildProviderConfig for %s: using input only", addr) - return inputBody - default: - log.Printf("[TRACE] buildProviderConfig for %s: no configuration at all", addr) - return hcl.EmptyBody() - } + *n.Output = cfg + return nil, nil } // EvalConfigProvider is an EvalNode implementation that configures // a provider that is already initialized and retrieved. type EvalConfigProvider struct { - Addr addrs.ProviderConfig - Provider *providers.Interface - Config *configs.Provider + Provider string + Config **ResourceConfig } func (n *EvalConfigProvider) Eval(ctx EvalContext) (interface{}, error) { - if n.Provider == nil { - return nil, fmt.Errorf("EvalConfigProvider Provider is nil") - } - - var diags tfdiags.Diagnostics - provider := *n.Provider - config := n.Config - - configBody := buildProviderConfig(ctx, n.Addr, config) - - resp := provider.GetSchema() - diags = diags.Append(resp.Diagnostics) - if diags.HasErrors() { - return nil, diags.NonFatalErr() - } - - configSchema := resp.Provider.Block - configVal, configBody, evalDiags := ctx.EvaluateBlock(configBody, configSchema, nil, EvalDataForNoInstanceKey) - diags = diags.Append(evalDiags) - if evalDiags.HasErrors() { - return nil, diags.NonFatalErr() - } - - configDiags := ctx.ConfigureProvider(n.Addr, configVal) - configDiags = configDiags.InConfigBody(configBody) - - return nil, configDiags.ErrWithWarnings() + return nil, ctx.ConfigureProvider(n.Provider, *n.Config) } // EvalInitProvider is an EvalNode implementation that initializes a provider @@ -89,59 +53,85 @@ func (n *EvalConfigProvider) Eval(ctx EvalContext) (interface{}, error) { // EvalGetProvider node. type EvalInitProvider struct { TypeName string - Addr addrs.ProviderConfig + Name string } func (n *EvalInitProvider) Eval(ctx EvalContext) (interface{}, error) { - return ctx.InitProvider(n.TypeName, n.Addr) + return ctx.InitProvider(n.TypeName, n.Name) } // EvalCloseProvider is an EvalNode implementation that closes provider // connections that aren't needed anymore. type EvalCloseProvider struct { - Addr addrs.ProviderConfig + Name string } func (n *EvalCloseProvider) Eval(ctx EvalContext) (interface{}, error) { - ctx.CloseProvider(n.Addr) + ctx.CloseProvider(n.Name) return nil, nil } // EvalGetProvider is an EvalNode implementation that retrieves an already // initialized provider instance for the given name. -// -// Unlike most eval nodes, this takes an _absolute_ provider configuration, -// because providers can be passed into and inherited between modules. -// Resource nodes must therefore know the absolute path of the provider they -// will use, which is usually accomplished by implementing -// interface GraphNodeProviderConsumer. type EvalGetProvider struct { - Addr addrs.AbsProviderConfig - Output *providers.Interface - - // If non-nil, Schema will be updated after eval to refer to the - // schema of the provider. - Schema **ProviderSchema + Name string + Output *ResourceProvider } func (n *EvalGetProvider) Eval(ctx EvalContext) (interface{}, error) { - if n.Addr.ProviderConfig.Type == "" { - // Should never happen - panic("EvalGetProvider used with uninitialized provider configuration address") - } - - result := ctx.Provider(n.Addr) + result := ctx.Provider(n.Name) if result == nil { - return nil, fmt.Errorf("provider %s not initialized", n.Addr) + return nil, fmt.Errorf("provider %s not initialized", n.Name) } if n.Output != nil { *n.Output = result } - if n.Schema != nil { - *n.Schema = ctx.ProviderSchema(n.Addr) + return nil, nil +} + +// EvalInputProvider is an EvalNode implementation that asks for input +// for the given provider configurations. +type EvalInputProvider struct { + Name string + Provider *ResourceProvider + Config **ResourceConfig +} + +func (n *EvalInputProvider) Eval(ctx EvalContext) (interface{}, error) { + rc := *n.Config + orig := rc.DeepCopy() + + // Wrap the input into a namespace + input := &PrefixUIInput{ + IdPrefix: fmt.Sprintf("provider.%s", n.Name), + QueryPrefix: fmt.Sprintf("provider.%s.", n.Name), + UIInput: ctx.Input(), } + // Go through each provider and capture the input necessary + // to satisfy it. + config, err := (*n.Provider).Input(input, rc) + if err != nil { + return nil, fmt.Errorf( + "Error configuring %s: %s", n.Name, err) + } + + // We only store values that have changed through Input. + // The goal is to cache cache input responses, not to provide a complete + // config for other providers. + confMap := make(map[string]interface{}) + if config != nil && len(config.Config) > 0 { + // any values that weren't in the original ResourcConfig will be cached + for k, v := range config.Config { + if _, ok := orig.Config[k]; !ok { + confMap[k] = v + } + } + } + + ctx.SetProviderInput(n.Name, confMap) + return nil, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/eval_provisioner.go index bc6b5cc7..89579c05 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_provisioner.go @@ -2,9 +2,6 @@ package terraform import ( "fmt" - - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/provisioners" ) // EvalInitProvisioner is an EvalNode implementation that initializes a provisioner @@ -33,8 +30,7 @@ func (n *EvalCloseProvisioner) Eval(ctx EvalContext) (interface{}, error) { // initialized provisioner instance for the given name. type EvalGetProvisioner struct { Name string - Output *provisioners.Interface - Schema **configschema.Block + Output *ResourceProvisioner } func (n *EvalGetProvisioner) Eval(ctx EvalContext) (interface{}, error) { @@ -47,9 +43,5 @@ func (n *EvalGetProvisioner) Eval(ctx EvalContext) (interface{}, error) { *n.Output = result } - if n.Schema != nil { - *n.Schema = ctx.ProvisionerSchema(n.Name) - } - return result, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_read_data.go b/vendor/github.com/hashicorp/terraform/terraform/eval_read_data.go index d89d02ba..fb85a284 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_read_data.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_read_data.go @@ -2,439 +2,105 @@ package terraform import ( "fmt" - "log" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/plans/objchange" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) -// EvalReadData is an EvalNode implementation that deals with the main part -// of the data resource lifecycle: either actually reading from the data source -// or generating a plan to do so. -type EvalReadData struct { - Addr addrs.ResourceInstance - Config *configs.Resource - Dependencies []addrs.Referenceable - Provider *providers.Interface - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - - // Planned is set when dealing with data resources that were deferred to - // the apply walk, to let us see what was planned. If this is set, the - // evaluation of the config is required to produce a wholly-known - // configuration which is consistent with the partial object included - // in this planned change. - Planned **plans.ResourceInstanceChange - - // ForcePlanRead, if true, overrides the usual behavior of immediately - // reading from the data source where possible, instead forcing us to - // _always_ generate a plan. This is used during the plan walk, since we - // mustn't actually apply anything there. (The resulting state doesn't - // get persisted) - ForcePlanRead bool - - // The result from this EvalNode has a few different possibilities - // depending on the input: - // - If Planned is nil then we assume we're aiming to _produce_ the plan, - // and so the following two outcomes are possible: - // - OutputChange.Action is plans.NoOp and OutputState is the complete - // result of reading from the data source. This is the easy path. - // - OutputChange.Action is plans.Read and OutputState is a planned - // object placeholder (states.ObjectPlanned). In this case, the - // returned change must be recorded in the overral changeset and - // eventually passed to another instance of this struct during the - // apply walk. - // - If Planned is non-nil then we assume we're aiming to complete a - // planned read from an earlier plan walk. In this case the only possible - // non-error outcome is to set Output.Action (if non-nil) to a plans.NoOp - // change and put the complete resulting state in OutputState, ready to - // be saved in the overall state and used for expression evaluation. - OutputChange **plans.ResourceInstanceChange - OutputValue *cty.Value - OutputConfigValue *cty.Value - OutputState **states.ResourceInstanceObject -} - -func (n *EvalReadData) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - log.Printf("[TRACE] EvalReadData: working on %s", absAddr) - - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - return nil, fmt.Errorf("provider schema not available for %s", n.Addr) - } - - var diags tfdiags.Diagnostics - var change *plans.ResourceInstanceChange - var configVal cty.Value - - // TODO: Do we need to handle Delete changes here? EvalReadDataDiff and - // EvalReadDataApply did, but it seems like we should handle that via a - // separate mechanism since it boils down to just deleting the object from - // the state... and we do that on every plan anyway, forcing the data - // resource to re-read. - - config := *n.Config - provider := *n.Provider - providerSchema := *n.ProviderSchema - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider %q does not support data source %q", n.ProviderAddr.ProviderConfig.Type, n.Addr.Resource.Type) - } - - // We'll always start by evaluating the configuration. What we do after - // that will depend on the evaluation result along with what other inputs - // we were given. - objTy := schema.ImpliedType() - priorVal := cty.NullVal(objTy) // for data resources, prior is always null because we start fresh every time - - keyData := EvalDataForInstanceKey(n.Addr.Key) - - var configDiags tfdiags.Diagnostics - configVal, _, configDiags = ctx.EvaluateBlock(config.Config, schema, nil, keyData) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } - - proposedNewVal := objchange.PlannedDataResourceObject(schema, configVal) - - // If our configuration contains any unknown values then we must defer the - // read to the apply phase by producing a "Read" change for this resource, - // and a placeholder value for it in the state. - if n.ForcePlanRead || !configVal.IsWhollyKnown() { - // If the configuration is still unknown when we're applying a planned - // change then that indicates a bug in Terraform, since we should have - // everything resolved by now. - if n.Planned != nil && *n.Planned != nil { - return nil, fmt.Errorf( - "configuration for %s still contains unknown values during apply (this is a bug in Terraform; please report it!)", - absAddr, - ) - } - if n.ForcePlanRead { - log.Printf("[TRACE] EvalReadData: %s configuration is fully known, but we're forcing a read plan to be created", absAddr) - } else { - log.Printf("[TRACE] EvalReadData: %s configuration not fully known yet, so deferring to apply phase", absAddr) - } - - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreDiff(absAddr, states.CurrentGen, priorVal, proposedNewVal) - }) - if err != nil { - return nil, err - } - - change = &plans.ResourceInstanceChange{ - Addr: absAddr, - ProviderAddr: n.ProviderAddr, - Change: plans.Change{ - Action: plans.Read, - Before: priorVal, - After: proposedNewVal, - }, - } - - err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostDiff(absAddr, states.CurrentGen, change.Action, priorVal, proposedNewVal) - }) - if err != nil { - return nil, err - } - - if n.OutputChange != nil { - *n.OutputChange = change - } - if n.OutputValue != nil { - *n.OutputValue = change.After - } - if n.OutputConfigValue != nil { - *n.OutputConfigValue = configVal - } - if n.OutputState != nil { - state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectPlanned, // because the partial value in the plan must be used for now - Dependencies: n.Dependencies, - } - *n.OutputState = state - } - - return nil, diags.ErrWithWarnings() - } - - if n.Planned != nil && *n.Planned != nil && (*n.Planned).Action != plans.Read { - // If any other action gets in here then that's always a bug; this - // EvalNode only deals with reading. - return nil, fmt.Errorf( - "invalid action %s for %s: only Read is supported (this is a bug in Terraform; please report it!)", - (*n.Planned).Action, absAddr, - ) - } - - // If we get down here then our configuration is complete and we're read - // to actually call the provider to read the data. - log.Printf("[TRACE] EvalReadData: %s configuration is complete, so reading from provider", absAddr) - - err := ctx.Hook(func(h Hook) (HookAction, error) { - // We don't have a state yet, so we'll just give the hook an - // empty one to work with. - return h.PreRefresh(absAddr, states.CurrentGen, cty.NullVal(cty.DynamicPseudoType)) - }) - if err != nil { - return nil, err - } - - resp := provider.ReadDataSource(providers.ReadDataSourceRequest{ - TypeName: n.Addr.Resource.Type, - Config: configVal, - }) - diags = diags.Append(resp.Diagnostics.InConfigBody(n.Config.Config)) - if diags.HasErrors() { - return nil, diags.Err() - } - newVal := resp.State - if newVal == cty.NilVal { - // This can happen with incompletely-configured mocks. We'll allow it - // and treat it as an alias for a properly-typed null value. - newVal = cty.NullVal(schema.ImpliedType()) - } - - for _, err := range newVal.Type().TestConformance(schema.ImpliedType()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q produced an invalid value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() - } - - if newVal.IsNull() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced null object", - fmt.Sprintf( - "Provider %q produced a null value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, - ), - )) - } - if !newVal.IsWhollyKnown() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q produced a value for %s that is not wholly known.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, - ), - )) - - // We'll still save the object, but we need to eliminate any unknown - // values first because we can't serialize them in the state file. - // Note that this may cause set elements to be coalesced if they - // differed only by having unknown values, but we don't worry about - // that here because we're saving the value only for inspection - // purposes; the error we added above will halt the graph walk. - newVal = cty.UnknownAsNull(newVal) - } - - // Since we've completed the read, we actually have no change to make, but - // we'll produce a NoOp one anyway to preserve the usual flow of the - // plan phase and allow it to produce a complete plan. - change = &plans.ResourceInstanceChange{ - Addr: absAddr, - ProviderAddr: n.ProviderAddr, - Change: plans.Change{ - Action: plans.NoOp, - Before: newVal, - After: newVal, - }, - } - state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectReady, // because we completed the read from the provider - Dependencies: n.Dependencies, - } - - err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostRefresh(absAddr, states.CurrentGen, change.Before, newVal) - }) - if err != nil { - return nil, err - } - - if n.OutputChange != nil { - *n.OutputChange = change - } - if n.OutputValue != nil { - *n.OutputValue = change.After - } - if n.OutputConfigValue != nil { - *n.OutputConfigValue = configVal - } - if n.OutputState != nil { - *n.OutputState = state - } - - return nil, diags.ErrWithWarnings() -} - // EvalReadDataDiff is an EvalNode implementation that executes a data // resource's ReadDataDiff method to discover what attributes it exports. type EvalReadDataDiff struct { - Addr addrs.ResourceInstance - Config *configs.Resource - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - - Output **plans.ResourceInstanceChange - OutputValue *cty.Value - OutputConfigValue *cty.Value - OutputState **states.ResourceInstanceObject + Provider *ResourceProvider + Output **InstanceDiff + OutputState **InstanceState + Config **ResourceConfig + Info *InstanceInfo // Set Previous when re-evaluating diff during apply, to ensure that // the "Destroy" flag is preserved. - Previous **plans.ResourceInstanceChange + Previous **InstanceDiff } func (n *EvalReadDataDiff) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - return nil, fmt.Errorf("provider schema not available for %s", n.Addr) - } - - var diags tfdiags.Diagnostics - var change *plans.ResourceInstanceChange - var configVal cty.Value - - if n.Previous != nil && *n.Previous != nil && (*n.Previous).Action == plans.Delete { - // If we're re-diffing for a diff that was already planning to - // destroy, then we'll just continue with that plan. - - nullVal := cty.NullVal(cty.DynamicPseudoType) - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreDiff(absAddr, states.CurrentGen, nullVal, nullVal) - }) - if err != nil { - return nil, err - } - - change = &plans.ResourceInstanceChange{ - Addr: absAddr, - ProviderAddr: n.ProviderAddr, - Change: plans.Change{ - Action: plans.Delete, - Before: nullVal, - After: nullVal, - }, - } - } else { - config := *n.Config - providerSchema := *n.ProviderSchema - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support data source %q", n.Addr.Resource.Type) - } - - objTy := schema.ImpliedType() - priorVal := cty.NullVal(objTy) // for data resources, prior is always null because we start fresh every time - - keyData := EvalDataForInstanceKey(n.Addr.Key) - - var configDiags tfdiags.Diagnostics - configVal, _, configDiags = ctx.EvaluateBlock(config.Config, schema, nil, keyData) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } - - proposedNewVal := objchange.ProposedNewObject(schema, priorVal, configVal) - - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreDiff(absAddr, states.CurrentGen, priorVal, proposedNewVal) - }) - if err != nil { - return nil, err - } - - change = &plans.ResourceInstanceChange{ - Addr: absAddr, - ProviderAddr: n.ProviderAddr, - Change: plans.Change{ - Action: plans.Read, - Before: priorVal, - After: proposedNewVal, - }, - } - } + // TODO: test err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostDiff(absAddr, states.CurrentGen, change.Action, change.Before, change.After) + return h.PreDiff(n.Info, nil) }) if err != nil { return nil, err } - if n.Output != nil { - *n.Output = change + var diff *InstanceDiff + + if n.Previous != nil && *n.Previous != nil && (*n.Previous).GetDestroy() { + // If we're re-diffing for a diff that was already planning to + // destroy, then we'll just continue with that plan. + diff = &InstanceDiff{Destroy: true} + } else { + provider := *n.Provider + config := *n.Config + + var err error + diff, err = provider.ReadDataDiff(n.Info, config) + if err != nil { + return nil, err + } + if diff == nil { + diff = new(InstanceDiff) + } + + // if id isn't explicitly set then it's always computed, because we're + // always "creating a new resource". + diff.init() + if _, ok := diff.Attributes["id"]; !ok { + diff.SetAttribute("id", &ResourceAttrDiff{ + Old: "", + NewComputed: true, + RequiresNew: true, + Type: DiffAttrOutput, + }) + } } - if n.OutputValue != nil { - *n.OutputValue = change.After - } - if n.OutputConfigValue != nil { - *n.OutputConfigValue = configVal + + err = ctx.Hook(func(h Hook) (HookAction, error) { + return h.PostDiff(n.Info, diff) + }) + if err != nil { + return nil, err } + *n.Output = diff + if n.OutputState != nil { - state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectReady, - } + state := &InstanceState{} *n.OutputState = state + + // Apply the diff to the returned state, so the state includes + // any attribute values that are not computed. + if !diff.Empty() && n.OutputState != nil { + *n.OutputState = state.MergeDiff(diff) + } } - return nil, diags.ErrWithWarnings() + return nil, nil } // EvalReadDataApply is an EvalNode implementation that executes a data // resource's ReadDataApply method to read data from the data source. type EvalReadDataApply struct { - Addr addrs.ResourceInstance - Provider *providers.Interface - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - Output **states.ResourceInstanceObject - Config *configs.Resource - Change **plans.ResourceInstanceChange - StateReferences []addrs.Referenceable + Provider *ResourceProvider + Output **InstanceState + Diff **InstanceDiff + Info *InstanceInfo } func (n *EvalReadDataApply) Eval(ctx EvalContext) (interface{}, error) { + // TODO: test provider := *n.Provider - change := *n.Change - providerSchema := *n.ProviderSchema - absAddr := n.Addr.Absolute(ctx.Path()) - - var diags tfdiags.Diagnostics + diff := *n.Diff // If the diff is for *destroying* this resource then we'll // just drop its state and move on, since data resources don't // support an actual "destroy" action. - if change != nil && change.Action == plans.Delete { + if diff != nil && diff.GetDestroy() { if n.Output != nil { *n.Output = nil } @@ -447,56 +113,27 @@ func (n *EvalReadDataApply) Eval(ctx EvalContext) (interface{}, error) { err := ctx.Hook(func(h Hook) (HookAction, error) { // We don't have a state yet, so we'll just give the hook an // empty one to work with. - return h.PreRefresh(absAddr, states.CurrentGen, cty.NullVal(cty.DynamicPseudoType)) + return h.PreRefresh(n.Info, &InstanceState{}) }) if err != nil { return nil, err } - resp := provider.ReadDataSource(providers.ReadDataSourceRequest{ - TypeName: n.Addr.Resource.Type, - Config: change.After, - }) - diags = diags.Append(resp.Diagnostics.InConfigBody(n.Config.Config)) - if diags.HasErrors() { - return nil, diags.Err() - } - - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support data source %q", n.Addr.Resource.Type) - } - - newVal := resp.State - for _, err := range newVal.Type().TestConformance(schema.ImpliedType()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q planned an invalid value for %s. The result could not be saved.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() + state, err := provider.ReadDataApply(n.Info, diff) + if err != nil { + return nil, fmt.Errorf("%s: %s", n.Info.Id, err) } err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostRefresh(absAddr, states.CurrentGen, change.Before, newVal) + return h.PostRefresh(n.Info, state) }) if err != nil { return nil, err } if n.Output != nil { - *n.Output = &states.ResourceInstanceObject{ - Value: newVal, - Status: states.ObjectReady, - Dependencies: n.StateReferences, - } + *n.Output = state } - return nil, diags.ErrWithWarnings() + return nil, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_refresh.go b/vendor/github.com/hashicorp/terraform/terraform/eval_refresh.go index ec3822ce..fa2b8126 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_refresh.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_refresh.go @@ -3,102 +3,53 @@ package terraform import ( "fmt" "log" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // EvalRefresh is an EvalNode implementation that does a refresh for // a resource. type EvalRefresh struct { - Addr addrs.ResourceInstance - ProviderAddr addrs.AbsProviderConfig - Provider *providers.Interface - ProviderSchema **ProviderSchema - State **states.ResourceInstanceObject - Output **states.ResourceInstanceObject + Provider *ResourceProvider + State **InstanceState + Info *InstanceInfo + Output **InstanceState } // TODO: test func (n *EvalRefresh) Eval(ctx EvalContext) (interface{}, error) { + provider := *n.Provider state := *n.State - absAddr := n.Addr.Absolute(ctx.Path()) - - var diags tfdiags.Diagnostics // If we have no state, we don't do any refreshing if state == nil { - log.Printf("[DEBUG] refresh: %s: no state, so not refreshing", n.Addr.Absolute(ctx.Path())) - return nil, diags.ErrWithWarnings() - } - - schema, _ := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) + log.Printf("[DEBUG] refresh: %s: no state, not refreshing", n.Info.Id) + return nil, nil } // Call pre-refresh hook err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreRefresh(absAddr, states.CurrentGen, state.Value) + return h.PreRefresh(n.Info, state) }) if err != nil { - return nil, diags.ErrWithWarnings() + return nil, err } // Refresh! - priorVal := state.Value - req := providers.ReadResourceRequest{ - TypeName: n.Addr.Resource.Type, - PriorState: priorVal, + state, err = provider.Refresh(n.Info, state) + if err != nil { + return nil, fmt.Errorf("%s: %s", n.Info.Id, err.Error()) } - provider := *n.Provider - resp := provider.ReadResource(req) - diags = diags.Append(resp.Diagnostics) - if diags.HasErrors() { - return nil, diags.Err() - } - - if resp.NewState == cty.NilVal { - // This ought not to happen in real cases since it's not possible to - // send NilVal over the plugin RPC channel, but it can come up in - // tests due to sloppy mocking. - panic("new state is cty.NilVal") - } - - for _, err := range schema.ImpliedType().TestConformance(resp.NewState.Type()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q planned an invalid value for %s: %s during refresh.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, tfdiags.FormatError(err), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() - } - - newState := state.DeepCopy() - newState.Value = resp.NewState - // Call post-refresh hook err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostRefresh(absAddr, states.CurrentGen, priorVal, newState.Value) + return h.PostRefresh(n.Info, state) }) if err != nil { return nil, err } if n.Output != nil { - *n.Output = newState + *n.Output = state } - return nil, diags.ErrWithWarnings() + return nil, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_resource.go b/vendor/github.com/hashicorp/terraform/terraform/eval_resource.go new file mode 100644 index 00000000..5eca6782 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_resource.go @@ -0,0 +1,13 @@ +package terraform + +// EvalInstanceInfo is an EvalNode implementation that fills in the +// InstanceInfo as much as it can. +type EvalInstanceInfo struct { + Info *InstanceInfo +} + +// TODO: test +func (n *EvalInstanceInfo) Eval(ctx EvalContext) (interface{}, error) { + n.Info.ModulePath = ctx.Path() + return nil, nil +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_sequence.go b/vendor/github.com/hashicorp/terraform/terraform/eval_sequence.go index 3485e4f1..82d81782 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_sequence.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_sequence.go @@ -1,37 +1,22 @@ package terraform -import ( - "github.com/hashicorp/terraform/tfdiags" -) - // EvalSequence is an EvalNode that evaluates in sequence. type EvalSequence struct { Nodes []EvalNode } func (n *EvalSequence) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - for _, n := range n.Nodes { if n == nil { continue } if _, err := EvalRaw(n, ctx); err != nil { - if _, isEarlyExit := err.(EvalEarlyExitError); isEarlyExit { - // In this path we abort early, losing any non-error - // diagnostics we saw earlier. - return nil, err - } - diags = diags.Append(err) - if diags.HasErrors() { - // Halt if we get some errors, but warnings are okay. - break - } + return nil, err } } - return nil, diags.ErrWithWarnings() + return nil, nil } // EvalNodeFilterable impl. diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_state.go b/vendor/github.com/hashicorp/terraform/terraform/eval_state.go index d506ce3f..11826907 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_state.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_state.go @@ -2,149 +2,91 @@ package terraform import ( "fmt" - "log" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // EvalReadState is an EvalNode implementation that reads the -// current object for a specific instance in the state. +// primary InstanceState for a specific resource out of the state. type EvalReadState struct { - // Addr is the address of the instance to read state for. - Addr addrs.ResourceInstance - - // ProviderSchema is the schema for the provider given in Provider. - ProviderSchema **ProviderSchema - - // Provider is the provider that will subsequently perform actions on - // the the state object. This is used to perform any schema upgrades - // that might be required to prepare the stored data for use. - Provider *providers.Interface - - // Output will be written with a pointer to the retrieved object. - Output **states.ResourceInstanceObject + Name string + Output **InstanceState } func (n *EvalReadState) Eval(ctx EvalContext) (interface{}, error) { - if n.Provider == nil || *n.Provider == nil { - panic("EvalReadState used with no Provider object") - } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - panic("EvalReadState used with no ProviderSchema object") - } - - absAddr := n.Addr.Absolute(ctx.Path()) - log.Printf("[TRACE] EvalReadState: reading state for %s", absAddr) - - src := ctx.State().ResourceInstanceObject(absAddr, states.CurrentGen) - if src == nil { - // Presumably we only have deposed objects, then. - log.Printf("[TRACE] EvalReadState: no state present for %s", absAddr) - return nil, nil - } - - schema, currentVersion := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Shouldn't happen since we should've failed long ago if no schema is present - return nil, fmt.Errorf("no schema available for %s while reading state; this is a bug in Terraform and should be reported", absAddr) - } - var diags tfdiags.Diagnostics - src, diags = UpgradeResourceState(absAddr, *n.Provider, src, schema, currentVersion) - if diags.HasErrors() { - // Note that we don't have any channel to return warnings here. We'll - // accept that for now since warnings during a schema upgrade would - // be pretty weird anyway, since this operation is supposed to seem - // invisible to the user. - return nil, diags.Err() - } - - obj, err := src.Decode(schema.ImpliedType()) - if err != nil { - return nil, err - } - - if n.Output != nil { - *n.Output = obj - } - return obj, nil + return readInstanceFromState(ctx, n.Name, n.Output, func(rs *ResourceState) (*InstanceState, error) { + return rs.Primary, nil + }) } // EvalReadStateDeposed is an EvalNode implementation that reads the // deposed InstanceState for a specific resource out of the state type EvalReadStateDeposed struct { - // Addr is the address of the instance to read state for. - Addr addrs.ResourceInstance - - // Key identifies which deposed object we will read. - Key states.DeposedKey - - // ProviderSchema is the schema for the provider given in Provider. - ProviderSchema **ProviderSchema - - // Provider is the provider that will subsequently perform actions on - // the the state object. This is used to perform any schema upgrades - // that might be required to prepare the stored data for use. - Provider *providers.Interface - - // Output will be written with a pointer to the retrieved object. - Output **states.ResourceInstanceObject + Name string + Output **InstanceState + // Index indicates which instance in the Deposed list to target, or -1 for + // the last item. + Index int } func (n *EvalReadStateDeposed) Eval(ctx EvalContext) (interface{}, error) { - if n.Provider == nil || *n.Provider == nil { - panic("EvalReadStateDeposed used with no Provider object") - } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - panic("EvalReadStateDeposed used with no ProviderSchema object") - } + return readInstanceFromState(ctx, n.Name, n.Output, func(rs *ResourceState) (*InstanceState, error) { + // Get the index. If it is negative, then we get the last one + idx := n.Index + if idx < 0 { + idx = len(rs.Deposed) - 1 + } + if idx >= 0 && idx < len(rs.Deposed) { + return rs.Deposed[idx], nil + } else { + return nil, fmt.Errorf("bad deposed index: %d, for resource: %#v", idx, rs) + } + }) +} - key := n.Key - if key == states.NotDeposed { - return nil, fmt.Errorf("EvalReadStateDeposed used with no instance key; this is a bug in Terraform and should be reported") - } - absAddr := n.Addr.Absolute(ctx.Path()) - log.Printf("[TRACE] EvalReadStateDeposed: reading state for %s deposed object %s", absAddr, n.Key) +// Does the bulk of the work for the various flavors of ReadState eval nodes. +// Each node just provides a reader function to get from the ResourceState to the +// InstanceState, and this takes care of all the plumbing. +func readInstanceFromState( + ctx EvalContext, + resourceName string, + output **InstanceState, + readerFn func(*ResourceState) (*InstanceState, error), +) (*InstanceState, error) { + state, lock := ctx.State() - src := ctx.State().ResourceInstanceObject(absAddr, key) - if src == nil { - // Presumably we only have deposed objects, then. - log.Printf("[TRACE] EvalReadStateDeposed: no state present for %s deposed object %s", absAddr, n.Key) + // Get a read lock so we can access this instance + lock.RLock() + defer lock.RUnlock() + + // Look for the module state. If we don't have one, then it doesn't matter. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { return nil, nil } - schema, currentVersion := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Shouldn't happen since we should've failed long ago if no schema is present - return nil, fmt.Errorf("no schema available for %s while reading state; this is a bug in Terraform and should be reported", absAddr) - } - var diags tfdiags.Diagnostics - src, diags = UpgradeResourceState(absAddr, *n.Provider, src, schema, currentVersion) - if diags.HasErrors() { - // Note that we don't have any channel to return warnings here. We'll - // accept that for now since warnings during a schema upgrade would - // be pretty weird anyway, since this operation is supposed to seem - // invisible to the user. - return nil, diags.Err() + // Look for the resource state. If we don't have one, then it is okay. + rs := mod.Resources[resourceName] + if rs == nil { + return nil, nil } - obj, err := src.Decode(schema.ImpliedType()) + // Use the delegate function to get the instance state from the resource state + is, err := readerFn(rs) if err != nil { return nil, err } - if n.Output != nil { - *n.Output = obj + + // Write the result to the output pointer + if output != nil { + *output = is } - return obj, nil + + return is, nil } -// EvalRequireState is an EvalNode implementation that exits early if the given -// object is null. +// EvalRequireState is an EvalNode implementation that early exits +// if the state doesn't have an ID. type EvalRequireState struct { - State **states.ResourceInstanceObject + State **InstanceState } func (n *EvalRequireState) Eval(ctx EvalContext) (interface{}, error) { @@ -153,7 +95,7 @@ func (n *EvalRequireState) Eval(ctx EvalContext) (interface{}, error) { } state := *n.State - if state == nil || state.Value.IsNull() { + if state == nil || state.ID == "" { return nil, EvalEarlyExitError{} } @@ -165,14 +107,12 @@ func (n *EvalRequireState) Eval(ctx EvalContext) (interface{}, error) { type EvalUpdateStateHook struct{} func (n *EvalUpdateStateHook) Eval(ctx EvalContext) (interface{}, error) { - // In principle we could grab the lock here just long enough to take a - // deep copy and then pass that to our hooks below, but we'll instead - // hold the hook for the duration to avoid the potential confusing - // situation of us racing to call PostStateUpdate concurrently with - // different state snapshots. - stateSync := ctx.State() - state := stateSync.Lock().DeepCopy() - defer stateSync.Unlock() + state, lock := ctx.State() + + // Get a full lock. Even calling something like WriteState can modify + // (prune) the state, so we need the full lock. + lock.Lock() + defer lock.Unlock() // Call the hook err := ctx.Hook(func(h Hook) (HookAction, error) { @@ -185,285 +125,171 @@ func (n *EvalUpdateStateHook) Eval(ctx EvalContext) (interface{}, error) { return nil, nil } -// EvalWriteState is an EvalNode implementation that saves the given object -// as the current object for the selected resource instance. +// EvalWriteState is an EvalNode implementation that writes the +// primary InstanceState for a specific resource into the state. type EvalWriteState struct { - // Addr is the address of the instance to read state for. - Addr addrs.ResourceInstance - - // State is the object state to save. - State **states.ResourceInstanceObject - - // ProviderSchema is the schema for the provider given in ProviderAddr. - ProviderSchema **ProviderSchema - - // ProviderAddr is the address of the provider configuration that - // produced the given object. - ProviderAddr addrs.AbsProviderConfig + Name string + ResourceType string + Provider string + Dependencies []string + State **InstanceState } func (n *EvalWriteState) Eval(ctx EvalContext) (interface{}, error) { - if n.State == nil { - // Note that a pointer _to_ nil is valid here, indicating the total - // absense of an object as we'd see during destroy. - panic("EvalWriteState used with no ResourceInstanceObject") - } - - absAddr := n.Addr.Absolute(ctx.Path()) - state := ctx.State() - - if n.ProviderAddr.ProviderConfig.Type == "" { - return nil, fmt.Errorf("failed to write state for %s, missing provider type", absAddr) - } - - obj := *n.State - if obj == nil || obj.Value.IsNull() { - // No need to encode anything: we'll just write it directly. - state.SetResourceInstanceCurrent(absAddr, nil, n.ProviderAddr) - log.Printf("[TRACE] EvalWriteState: removing state object for %s", absAddr) - return nil, nil - } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - // Should never happen, unless our state object is nil - panic("EvalWriteState used with pointer to nil ProviderSchema object") - } - - if obj != nil { - log.Printf("[TRACE] EvalWriteState: writing current state object for %s", absAddr) - } else { - log.Printf("[TRACE] EvalWriteState: removing current state object for %s", absAddr) - } - - schema, currentVersion := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // It shouldn't be possible to get this far in any real scenario - // without a schema, but we might end up here in contrived tests that - // fail to set up their world properly. - return nil, fmt.Errorf("failed to encode %s in state: no resource type schema available", absAddr) - } - src, err := obj.Encode(schema.ImpliedType(), currentVersion) - if err != nil { - return nil, fmt.Errorf("failed to encode %s in state: %s", absAddr, err) - } - - state.SetResourceInstanceCurrent(absAddr, src, n.ProviderAddr) - return nil, nil + return writeInstanceToState(ctx, n.Name, n.ResourceType, n.Provider, n.Dependencies, + func(rs *ResourceState) error { + rs.Primary = *n.State + return nil + }, + ) } // EvalWriteStateDeposed is an EvalNode implementation that writes // an InstanceState out to the Deposed list of a resource in the state. type EvalWriteStateDeposed struct { - // Addr is the address of the instance to read state for. - Addr addrs.ResourceInstance - - // Key indicates which deposed object to write to. - Key states.DeposedKey - - // State is the object state to save. - State **states.ResourceInstanceObject - - // ProviderSchema is the schema for the provider given in ProviderAddr. - ProviderSchema **ProviderSchema - - // ProviderAddr is the address of the provider configuration that - // produced the given object. - ProviderAddr addrs.AbsProviderConfig + Name string + ResourceType string + Provider string + Dependencies []string + State **InstanceState + // Index indicates which instance in the Deposed list to target, or -1 to append. + Index int } func (n *EvalWriteStateDeposed) Eval(ctx EvalContext) (interface{}, error) { - if n.State == nil { - // Note that a pointer _to_ nil is valid here, indicating the total - // absense of an object as we'd see during destroy. - panic("EvalWriteStateDeposed used with no ResourceInstanceObject") + return writeInstanceToState(ctx, n.Name, n.ResourceType, n.Provider, n.Dependencies, + func(rs *ResourceState) error { + if n.Index == -1 { + rs.Deposed = append(rs.Deposed, *n.State) + } else { + rs.Deposed[n.Index] = *n.State + } + return nil + }, + ) +} + +// Pulls together the common tasks of the EvalWriteState nodes. All the args +// are passed directly down from the EvalNode along with a `writer` function +// which is yielded the *ResourceState and is responsible for writing an +// InstanceState to the proper field in the ResourceState. +func writeInstanceToState( + ctx EvalContext, + resourceName string, + resourceType string, + provider string, + dependencies []string, + writerFn func(*ResourceState) error, +) (*InstanceState, error) { + state, lock := ctx.State() + if state == nil { + return nil, fmt.Errorf("cannot write state to nil state") } - absAddr := n.Addr.Absolute(ctx.Path()) - key := n.Key - state := ctx.State() + // Get a write lock so we can access this instance + lock.Lock() + defer lock.Unlock() - if key == states.NotDeposed { - // should never happen - return nil, fmt.Errorf("can't save deposed object for %s without a deposed key; this is a bug in Terraform that should be reported", absAddr) + // Look for the module state. If we don't have one, create it. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { + mod = state.AddModule(ctx.Path()) } - obj := *n.State - if obj == nil { - // No need to encode anything: we'll just write it directly. - state.SetResourceInstanceDeposed(absAddr, key, nil, n.ProviderAddr) - log.Printf("[TRACE] EvalWriteStateDeposed: removing state object for %s deposed %s", absAddr, key) - return nil, nil + // Look for the resource state. + rs := mod.Resources[resourceName] + if rs == nil { + rs = &ResourceState{} + rs.init() + mod.Resources[resourceName] = rs } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - // Should never happen, unless our state object is nil - panic("EvalWriteStateDeposed used with no ProviderSchema object") + rs.Type = resourceType + rs.Dependencies = dependencies + rs.Provider = provider + + if err := writerFn(rs); err != nil { + return nil, err } - schema, currentVersion := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // It shouldn't be possible to get this far in any real scenario - // without a schema, but we might end up here in contrived tests that - // fail to set up their world properly. - return nil, fmt.Errorf("failed to encode %s in state: no resource type schema available", absAddr) - } - src, err := obj.Encode(schema.ImpliedType(), currentVersion) - if err != nil { - return nil, fmt.Errorf("failed to encode %s in state: %s", absAddr, err) - } - - log.Printf("[TRACE] EvalWriteStateDeposed: writing state object for %s deposed %s", absAddr, key) - state.SetResourceInstanceDeposed(absAddr, key, src, n.ProviderAddr) return nil, nil } -// EvalDeposeState is an EvalNode implementation that moves the current object -// for the given instance to instead be a deposed object, leaving the instance -// with no current object. -// This is used at the beginning of a create-before-destroy replace action so -// that the create can create while preserving the old state of the -// to-be-destroyed object. +// EvalDeposeState is an EvalNode implementation that takes the primary +// out of a state and makes it Deposed. This is done at the beginning of +// create-before-destroy calls so that the create can create while preserving +// the old state of the to-be-destroyed resource. type EvalDeposeState struct { - Addr addrs.ResourceInstance - - // ForceKey, if a value other than states.NotDeposed, will be used as the - // key for the newly-created deposed object that results from this action. - // If set to states.NotDeposed (the zero value), a new unique key will be - // allocated. - ForceKey states.DeposedKey - - // OutputKey, if non-nil, will be written with the deposed object key that - // was generated for the object. This can then be passed to - // EvalUndeposeState.Key so it knows which deposed instance to forget. - OutputKey *states.DeposedKey + Name string } // TODO: test func (n *EvalDeposeState) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - state := ctx.State() + state, lock := ctx.State() - var key states.DeposedKey - if n.ForceKey == states.NotDeposed { - key = state.DeposeResourceInstanceObject(absAddr) - } else { - key = n.ForceKey - state.DeposeResourceInstanceObjectForceKey(absAddr, key) - } - log.Printf("[TRACE] EvalDeposeState: prior object for %s now deposed with key %s", absAddr, key) + // Get a read lock so we can access this instance + lock.RLock() + defer lock.RUnlock() - if n.OutputKey != nil { - *n.OutputKey = key + // Look for the module state. If we don't have one, then it doesn't matter. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { + return nil, nil } + // Look for the resource state. If we don't have one, then it is okay. + rs := mod.Resources[n.Name] + if rs == nil { + return nil, nil + } + + // If we don't have a primary, we have nothing to depose + if rs.Primary == nil { + return nil, nil + } + + // Depose + rs.Deposed = append(rs.Deposed, rs.Primary) + rs.Primary = nil + return nil, nil } -// EvalMaybeRestoreDeposedObject is an EvalNode implementation that will -// restore a particular deposed object of the specified resource instance -// to be the "current" object if and only if the instance doesn't currently -// have a current object. -// -// This is intended for use when the create leg of a create before destroy -// fails with no partial new object: if we didn't take any action, the user -// would be left in the unfortunate situation of having no current object -// and the previously-workign object now deposed. This EvalNode causes a -// better outcome by restoring things to how they were before the replace -// operation began. -// -// The create operation may have produced a partial result even though it -// failed and it's important that we don't "forget" that state, so in that -// situation the prior object remains deposed and the partial new object -// remains the current object, allowing the situation to hopefully be -// improved in a subsequent run. -type EvalMaybeRestoreDeposedObject struct { - Addr addrs.ResourceInstance - - // Key is a pointer to the deposed object key that should be forgotten - // from the state, which must be non-nil. - Key *states.DeposedKey +// EvalUndeposeState is an EvalNode implementation that reads the +// InstanceState for a specific resource out of the state. +type EvalUndeposeState struct { + Name string + State **InstanceState } // TODO: test -func (n *EvalMaybeRestoreDeposedObject) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - dk := *n.Key - state := ctx.State() +func (n *EvalUndeposeState) Eval(ctx EvalContext) (interface{}, error) { + state, lock := ctx.State() - restored := state.MaybeRestoreResourceInstanceDeposed(absAddr, dk) - if restored { - log.Printf("[TRACE] EvalMaybeRestoreDeposedObject: %s deposed object %s was restored as the current object", absAddr, dk) - } else { - log.Printf("[TRACE] EvalMaybeRestoreDeposedObject: %s deposed object %s remains deposed", absAddr, dk) + // Get a read lock so we can access this instance + lock.RLock() + defer lock.RUnlock() + + // Look for the module state. If we don't have one, then it doesn't matter. + mod := state.ModuleByPath(ctx.Path()) + if mod == nil { + return nil, nil } - - return nil, nil -} - -// EvalWriteResourceState is an EvalNode implementation that ensures that -// a suitable resource-level state record is present in the state, if that's -// required for the "each mode" of that resource. -// -// This is important primarily for the situation where count = 0, since this -// eval is the only change we get to set the resource "each mode" to list -// in that case, allowing expression evaluation to see it as a zero-element -// list rather than as not set at all. -type EvalWriteResourceState struct { - Addr addrs.Resource - Config *configs.Resource - ProviderAddr addrs.AbsProviderConfig -} - -// TODO: test -func (n *EvalWriteResourceState) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - absAddr := n.Addr.Absolute(ctx.Path()) - state := ctx.State() - - count, countDiags := evaluateResourceCountExpression(n.Config.Count, ctx) - diags = diags.Append(countDiags) - if countDiags.HasErrors() { - return nil, diags.Err() - } - - // Currently we ony support NoEach and EachList, because for_each support - // is not fully wired up across Terraform. Once for_each support is added, - // we'll need to handle that here too, setting states.EachMap if the - // assigned expression is a map. - eachMode := states.NoEach - if count >= 0 { // -1 signals "count not set" - eachMode = states.EachList - } - - // This method takes care of all of the business logic of updating this - // while ensuring that any existing instances are preserved, etc. - state.SetResourceMeta(absAddr, eachMode, n.ProviderAddr) - - return nil, nil -} - -// EvalForgetResourceState is an EvalNode implementation that prunes out an -// empty resource-level state for a given resource address, or produces an -// error if it isn't empty after all. -// -// This should be the last action taken for a resource that has been removed -// from the configuration altogether, to clean up the leftover husk of the -// resource in the state after other EvalNodes have destroyed and removed -// all of the instances and instance objects beneath it. -type EvalForgetResourceState struct { - Addr addrs.Resource -} - -func (n *EvalForgetResourceState) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - state := ctx.State() - - pruned := state.RemoveResourceIfEmpty(absAddr) - if !pruned { - // If this produces an error, it indicates a bug elsewhere in Terraform - // -- probably missing graph nodes, graph edges, or - // incorrectly-implemented evaluation steps. - return nil, fmt.Errorf("orphan resource %s still has a non-empty state after apply; this is a bug in Terraform", absAddr) - } - log.Printf("[TRACE] EvalForgetResourceState: Pruned husk of %s from state", absAddr) + + // Look for the resource state. If we don't have one, then it is okay. + rs := mod.Resources[n.Name] + if rs == nil { + return nil, nil + } + + // If we don't have any desposed resource, then we don't have anything to do + if len(rs.Deposed) == 0 { + return nil, nil + } + + // Undepose + idx := len(rs.Deposed) - 1 + rs.Primary = rs.Deposed[idx] + rs.Deposed[idx] = *n.State return nil, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_state_upgrade.go b/vendor/github.com/hashicorp/terraform/terraform/eval_state_upgrade.go deleted file mode 100644 index e78cc206..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_state_upgrade.go +++ /dev/null @@ -1,104 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" -) - -// UpgradeResourceState will, if necessary, run the provider-defined upgrade -// logic against the given state object to make it compliant with the -// current schema version. This is a no-op if the given state object is -// already at the latest version. -// -// If any errors occur during upgrade, error diagnostics are returned. In that -// case it is not safe to proceed with using the original state object. -func UpgradeResourceState(addr addrs.AbsResourceInstance, provider providers.Interface, src *states.ResourceInstanceObjectSrc, currentSchema *configschema.Block, currentVersion uint64) (*states.ResourceInstanceObjectSrc, tfdiags.Diagnostics) { - if src.SchemaVersion == currentVersion { - // No upgrading required, then. - return src, nil - } - if addr.Resource.Resource.Mode != addrs.ManagedResourceMode { - // We only do state upgrading for managed resources. - return src, nil - } - - providerType := addr.Resource.Resource.DefaultProviderConfig().Type - if src.SchemaVersion > currentVersion { - log.Printf("[TRACE] UpgradeResourceState: can't downgrade state for %s from version %d to %d", addr, src.SchemaVersion, currentVersion) - var diags tfdiags.Diagnostics - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Resource instance managed by newer provider version", - // This is not a very good error message, but we don't retain enough - // information in state to give good feedback on what provider - // version might be required here. :( - fmt.Sprintf("The current state of %s was created by a newer provider version than is currently selected. Upgrade the %s provider to work with this state.", addr, providerType), - )) - return nil, diags - } - - // If we get down here then we need to upgrade the state, with the - // provider's help. - // If this state was originally created by a version of Terraform prior to - // v0.12, this also includes translating from legacy flatmap to new-style - // representation, since only the provider has enough information to - // understand a flatmap built against an older schema. - log.Printf("[TRACE] UpgradeResourceState: upgrading state for %s from version %d to %d using provider %q", addr, src.SchemaVersion, currentVersion, providerType) - - req := providers.UpgradeResourceStateRequest{ - TypeName: addr.Resource.Resource.Type, - - // TODO: The internal schema version representations are all using - // uint64 instead of int64, but unsigned integers aren't friendly - // to all protobuf target languages so in practice we use int64 - // on the wire. In future we will change all of our internal - // representations to int64 too. - Version: int64(src.SchemaVersion), - } - - if len(src.AttrsJSON) != 0 { - req.RawStateJSON = src.AttrsJSON - } else { - req.RawStateFlatmap = src.AttrsFlat - } - - resp := provider.UpgradeResourceState(req) - diags := resp.Diagnostics - if diags.HasErrors() { - return nil, diags - } - - // After upgrading, the new value must conform to the current schema. When - // going over RPC this is actually already ensured by the - // marshaling/unmarshaling of the new value, but we'll check it here - // anyway for robustness, e.g. for in-process providers. - newValue := resp.UpgradedState - if errs := newValue.Type().TestConformance(currentSchema.ImpliedType()); len(errs) > 0 { - for _, err := range errs { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource state upgrade", - fmt.Sprintf("The %s provider upgraded the state for %s from a previous version, but produced an invalid result: %s.", providerType, addr, tfdiags.FormatError(err)), - )) - } - return nil, diags - } - - new, err := src.CompleteUpgrade(newValue, currentSchema.ImpliedType(), uint64(currentVersion)) - if err != nil { - // We already checked for type conformance above, so getting into this - // codepath should be rare and is probably a bug somewhere under CompleteUpgrade. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to encode result of resource state upgrade", - fmt.Sprintf("Failed to encode state for %s after resource schema upgrade: %s.", addr, tfdiags.FormatError(err)), - )) - } - return new, diags -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_validate.go b/vendor/github.com/hashicorp/terraform/terraform/eval_validate.go index a7e62561..3e5a84ce 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_validate.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_validate.go @@ -2,164 +2,126 @@ package terraform import ( "fmt" - "log" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/gocty" + "github.com/hashicorp/terraform/config" + "github.com/mitchellh/mapstructure" ) +// EvalValidateError is the error structure returned if there were +// validation errors. +type EvalValidateError struct { + Warnings []string + Errors []error +} + +func (e *EvalValidateError) Error() string { + return fmt.Sprintf("Warnings: %s. Errors: %s", e.Warnings, e.Errors) +} + // EvalValidateCount is an EvalNode implementation that validates // the count of a resource. type EvalValidateCount struct { - Resource *configs.Resource + Resource *config.Resource } // TODO: test func (n *EvalValidateCount) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics var count int + var errs []error var err error - - val, valDiags := ctx.EvaluateExpr(n.Resource.Count, cty.Number, nil) - diags = diags.Append(valDiags) - if valDiags.HasErrors() { - goto RETURN - } - if val.IsNull() || !val.IsKnown() { + if _, err := ctx.Interpolate(n.Resource.RawCount, nil); err != nil { + errs = append(errs, fmt.Errorf( + "Failed to interpolate count: %s", err)) goto RETURN } - err = gocty.FromCtyValue(val, &count) + count, err = n.Resource.Count() if err != nil { - // The EvaluateExpr call above already guaranteed us a number value, - // so if we end up here then we have something that is out of range - // for an int, and the error message will include a description of - // the valid range. - rawVal := val.AsBigFloat() - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count value", - Detail: fmt.Sprintf("The number %s is not a valid count value: %s.", rawVal, err), - Subject: n.Resource.Count.Range().Ptr(), - }) - } else if count < 0 { - rawVal := val.AsBigFloat() - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count value", - Detail: fmt.Sprintf("The number %s is not a valid count value: count must not be negative.", rawVal), - Subject: n.Resource.Count.Range().Ptr(), - }) + // If we can't get the count during validation, then + // just replace it with the number 1. + c := n.Resource.RawCount.Config() + c[n.Resource.RawCount.Key] = "1" + count = 1 + } + err = nil + + if count < 0 { + errs = append(errs, fmt.Errorf( + "Count is less than zero: %d", count)) } RETURN: - return nil, diags.NonFatalErr() + if len(errs) != 0 { + err = &EvalValidateError{ + Errors: errs, + } + } + return nil, err } // EvalValidateProvider is an EvalNode implementation that validates -// a provider configuration. +// the configuration of a resource. type EvalValidateProvider struct { - Addr addrs.ProviderConfig - Provider *providers.Interface - Config *configs.Provider + Provider *ResourceProvider + Config **ResourceConfig } func (n *EvalValidateProvider) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics provider := *n.Provider + config := *n.Config - configBody := buildProviderConfig(ctx, n.Addr, n.Config) - - resp := provider.GetSchema() - diags = diags.Append(resp.Diagnostics) - if diags.HasErrors() { - return nil, diags.NonFatalErr() + warns, errs := provider.Validate(config) + if len(warns) == 0 && len(errs) == 0 { + return nil, nil } - configSchema := resp.Provider.Block - if configSchema == nil { - // Should never happen in real code, but often comes up in tests where - // mock schemas are being used that tend to be incomplete. - log.Printf("[WARN] EvalValidateProvider: no config schema is available for %s, so using empty schema", n.Addr) - configSchema = &configschema.Block{} + return nil, &EvalValidateError{ + Warnings: warns, + Errors: errs, } - - configVal, configBody, evalDiags := ctx.EvaluateBlock(configBody, configSchema, nil, EvalDataForNoInstanceKey) - diags = diags.Append(evalDiags) - if evalDiags.HasErrors() { - return nil, diags.NonFatalErr() - } - - req := providers.PrepareProviderConfigRequest{ - Config: configVal, - } - - validateResp := provider.PrepareProviderConfig(req) - diags = diags.Append(validateResp.Diagnostics) - - return nil, diags.NonFatalErr() } // EvalValidateProvisioner is an EvalNode implementation that validates -// the configuration of a provisioner belonging to a resource. +// the configuration of a resource. type EvalValidateProvisioner struct { - ResourceAddr addrs.Resource - Provisioner *provisioners.Interface - Schema **configschema.Block - Config *configs.Provisioner - ConnConfig *configs.Connection - ResourceHasCount bool + Provisioner *ResourceProvisioner + Config **ResourceConfig + ConnConfig **ResourceConfig } func (n *EvalValidateProvisioner) Eval(ctx EvalContext) (interface{}, error) { provisioner := *n.Provisioner config := *n.Config - schema := *n.Schema - - var diags tfdiags.Diagnostics + var warns []string + var errs []error { // Validate the provisioner's own config first - - configVal, _, configDiags := n.evaluateBlock(ctx, config.Config, schema) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } - - if configVal == cty.NilVal { - // Should never happen for a well-behaved EvaluateBlock implementation - return nil, fmt.Errorf("EvaluateBlock returned nil value") - } - - req := provisioners.ValidateProvisionerConfigRequest{ - Config: configVal, - } - - resp := provisioner.ValidateProvisionerConfig(req) - diags = diags.Append(resp.Diagnostics) + w, e := provisioner.Validate(config) + warns = append(warns, w...) + errs = append(errs, e...) } { // Now validate the connection config, which might either be from // the provisioner block itself or inherited from the resource's // shared connection info. - connDiags := n.validateConnConfig(ctx, n.ConnConfig, n.ResourceAddr) - diags = diags.Append(connDiags) + w, e := n.validateConnConfig(*n.ConnConfig) + warns = append(warns, w...) + errs = append(errs, e...) } - return nil, diags.NonFatalErr() + if len(warns) == 0 && len(errs) == 0 { + return nil, nil + } + + return nil, &EvalValidateError{ + Warnings: warns, + Errors: errs, + } } -func (n *EvalValidateProvisioner) validateConnConfig(ctx EvalContext, config *configs.Connection, self addrs.Referenceable) tfdiags.Diagnostics { +func (n *EvalValidateProvisioner) validateConnConfig(connConfig *ResourceConfig) (warns []string, errs []error) { // We can't comprehensively validate the connection config since its // final structure is decided by the communicator and we can't instantiate // that until we have a complete instance state. However, we *can* catch @@ -167,379 +129,103 @@ func (n *EvalValidateProvisioner) validateConnConfig(ctx EvalContext, config *co // typos early rather than waiting until we actually try to run one of // the resource's provisioners. - var diags tfdiags.Diagnostics + type connConfigSuperset struct { + // All attribute types are interface{} here because at this point we + // may still have unresolved interpolation expressions, which will + // appear as strings regardless of the final goal type. - if config == nil || config.Config == nil { - // No block to validate - return diags - } - - // We evaluate here just by evaluating the block and returning any - // diagnostics we get, since evaluation alone is enough to check for - // extraneous arguments and incorrectly-typed arguments. - _, _, configDiags := n.evaluateBlock(ctx, config.Config, connectionBlockSupersetSchema) - diags = diags.Append(configDiags) - - return diags -} - -func (n *EvalValidateProvisioner) evaluateBlock(ctx EvalContext, body hcl.Body, schema *configschema.Block) (cty.Value, hcl.Body, tfdiags.Diagnostics) { - keyData := EvalDataForNoInstanceKey - selfAddr := n.ResourceAddr.Instance(addrs.NoKey) - - if n.ResourceHasCount { - // For a resource that has count, we allow count.index but don't - // know at this stage what it will return. - keyData = InstanceKeyEvalData{ - CountIndex: cty.UnknownVal(cty.Number), - } - - // "self" can't point to an unknown key, but we'll force it to be - // key 0 here, which should return an unknown value of the - // expected type since none of these elements are known at this - // point anyway. - selfAddr = n.ResourceAddr.Instance(addrs.IntKey(0)) - } - - return ctx.EvaluateBlock(body, schema, selfAddr, keyData) -} - -// connectionBlockSupersetSchema is a schema representing the superset of all -// possible arguments for "connection" blocks across all supported connection -// types. -// -// This currently lives here because we've not yet updated our communicator -// subsystem to be aware of schema itself. Once that is done, we can remove -// this and use a type-specific schema from the communicator to validate -// exactly what is expected for a given connection type. -var connectionBlockSupersetSchema = &configschema.Block{ - Attributes: map[string]*configschema.Attribute{ - // NOTE: "type" is not included here because it's treated special - // by the config loader and stored away in a separate field. - - // Common attributes for both connection types - "host": { - Type: cty.String, - Required: true, - }, - "type": { - Type: cty.String, - Optional: true, - }, - "user": { - Type: cty.String, - Optional: true, - }, - "password": { - Type: cty.String, - Optional: true, - }, - "port": { - Type: cty.String, - Optional: true, - }, - "timeout": { - Type: cty.String, - Optional: true, - }, - "script_path": { - Type: cty.String, - Optional: true, - }, + Type interface{} `mapstructure:"type"` + User interface{} `mapstructure:"user"` + Password interface{} `mapstructure:"password"` + Host interface{} `mapstructure:"host"` + Port interface{} `mapstructure:"port"` + Timeout interface{} `mapstructure:"timeout"` + ScriptPath interface{} `mapstructure:"script_path"` // For type=ssh only (enforced in ssh communicator) - "private_key": { - Type: cty.String, - Optional: true, - }, - "certificate": { - Type: cty.String, - Optional: true, - }, - "host_key": { - Type: cty.String, - Optional: true, - }, - "agent": { - Type: cty.Bool, - Optional: true, - }, - "agent_identity": { - Type: cty.String, - Optional: true, - }, - "bastion_host": { - Type: cty.String, - Optional: true, - }, - "bastion_host_key": { - Type: cty.String, - Optional: true, - }, - "bastion_port": { - Type: cty.Number, - Optional: true, - }, - "bastion_user": { - Type: cty.String, - Optional: true, - }, - "bastion_password": { - Type: cty.String, - Optional: true, - }, - "bastion_private_key": { - Type: cty.String, - Optional: true, - }, + PrivateKey interface{} `mapstructure:"private_key"` + HostKey interface{} `mapstructure:"host_key"` + Agent interface{} `mapstructure:"agent"` + BastionHost interface{} `mapstructure:"bastion_host"` + BastionHostKey interface{} `mapstructure:"bastion_host_key"` + BastionPort interface{} `mapstructure:"bastion_port"` + BastionUser interface{} `mapstructure:"bastion_user"` + BastionPassword interface{} `mapstructure:"bastion_password"` + BastionPrivateKey interface{} `mapstructure:"bastion_private_key"` + AgentIdentity interface{} `mapstructure:"agent_identity"` // For type=winrm only (enforced in winrm communicator) - "https": { - Type: cty.Bool, - Optional: true, - }, - "insecure": { - Type: cty.Bool, - Optional: true, - }, - "cacert": { - Type: cty.String, - Optional: true, - }, - "use_ntlm": { - Type: cty.Bool, - Optional: true, - }, - }, -} + HTTPS interface{} `mapstructure:"https"` + Insecure interface{} `mapstructure:"insecure"` + NTLM interface{} `mapstructure:"use_ntlm"` + CACert interface{} `mapstructure:"cacert"` + } -// connectionBlockSupersetSchema is a schema representing the superset of all -// possible arguments for "connection" blocks across all supported connection -// types. -// -// This currently lives here because we've not yet updated our communicator -// subsystem to be aware of schema itself. It's exported only for use in the -// configs/configupgrade package and should not be used from anywhere else. -// The caller may not modify any part of the returned schema data structure. -func ConnectionBlockSupersetSchema() *configschema.Block { - return connectionBlockSupersetSchema + var metadata mapstructure.Metadata + decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ + Metadata: &metadata, + Result: &connConfigSuperset{}, // result is disregarded; we only care about unused keys + }) + if err != nil { + // should never happen + errs = append(errs, err) + return + } + + if err := decoder.Decode(connConfig.Config); err != nil { + errs = append(errs, err) + return + } + + for _, attrName := range metadata.Unused { + errs = append(errs, fmt.Errorf("unknown 'connection' argument %q", attrName)) + } + return } // EvalValidateResource is an EvalNode implementation that validates // the configuration of a resource. type EvalValidateResource struct { - Addr addrs.Resource - Provider *providers.Interface - ProviderSchema **ProviderSchema - Config *configs.Resource + Provider *ResourceProvider + Config **ResourceConfig + ResourceName string + ResourceType string + ResourceMode config.ResourceMode // IgnoreWarnings means that warnings will not be passed through. This allows // "just-in-time" passes of validation to continue execution through warnings. IgnoreWarnings bool - - // ConfigVal, if non-nil, will be updated with the value resulting from - // evaluating the given configuration body. Since validation is performed - // very early, this value is likely to contain lots of unknown values, - // but its type will conform to the schema of the resource type associated - // with the resource instance being validated. - ConfigVal *cty.Value } func (n *EvalValidateResource) Eval(ctx EvalContext) (interface{}, error) { - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - return nil, fmt.Errorf("EvalValidateResource has nil schema for %s", n.Addr) - } - - var diags tfdiags.Diagnostics provider := *n.Provider cfg := *n.Config - schema := *n.ProviderSchema - mode := cfg.Mode - - keyData := EvalDataForNoInstanceKey - if n.Config.Count != nil { - // If the config block has count, we'll evaluate with an unknown - // number as count.index so we can still type check even though - // we won't expand count until the plan phase. - keyData = InstanceKeyEvalData{ - CountIndex: cty.UnknownVal(cty.Number), - } - - // Basic type-checking of the count argument. More complete validation - // of this will happen when we DynamicExpand during the plan walk. - countDiags := n.validateCount(ctx, n.Config.Count) - diags = diags.Append(countDiags) - } - - for _, traversal := range n.Config.DependsOn { - ref, refDiags := addrs.ParseRef(traversal) - diags = diags.Append(refDiags) - if len(ref.Remaining) != 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid depends_on reference", - Detail: "References in depends_on must be to a whole object (resource, etc), not to an attribute of an object.", - Subject: ref.Remaining.SourceRange().Ptr(), - }) - } - - // The ref must also refer to something that exists. To test that, - // we'll just eval it and count on the fact that our evaluator will - // detect references to non-existent objects. - if !diags.HasErrors() { - scope := ctx.EvaluationScope(nil, EvalDataForNoInstanceKey) - if scope != nil { // sometimes nil in tests, due to incomplete mocks - _, refDiags = scope.EvalReference(ref, cty.DynamicPseudoType) - diags = diags.Append(refDiags) - } - } - } - + var warns []string + var errs []error // Provider entry point varies depending on resource mode, because // managed resources and data resources are two distinct concepts // in the provider abstraction. - switch mode { - case addrs.ManagedResourceMode: - schema, _ := schema.SchemaForResourceType(mode, cfg.Type) - if schema == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource type", - Detail: fmt.Sprintf("The provider %s does not support resource type %q.", cfg.ProviderConfigAddr(), cfg.Type), - Subject: &cfg.TypeRange, - }) - return nil, diags.Err() - } - - configVal, _, valDiags := ctx.EvaluateBlock(cfg.Config, schema, nil, keyData) - diags = diags.Append(valDiags) - if valDiags.HasErrors() { - return nil, diags.Err() - } - - if cfg.Managed != nil { // can be nil only in tests with poorly-configured mocks - for _, traversal := range cfg.Managed.IgnoreChanges { - moreDiags := schema.StaticValidateTraversal(traversal) - diags = diags.Append(moreDiags) - } - } - - req := providers.ValidateResourceTypeConfigRequest{ - TypeName: cfg.Type, - Config: configVal, - } - - resp := provider.ValidateResourceTypeConfig(req) - diags = diags.Append(resp.Diagnostics.InConfigBody(cfg.Config)) - - if n.ConfigVal != nil { - *n.ConfigVal = configVal - } - - case addrs.DataResourceMode: - schema, _ := schema.SchemaForResourceType(mode, cfg.Type) - if schema == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid data source", - Detail: fmt.Sprintf("The provider %s does not support data source %q.", cfg.ProviderConfigAddr(), cfg.Type), - Subject: &cfg.TypeRange, - }) - return nil, diags.Err() - } - - configVal, _, valDiags := ctx.EvaluateBlock(cfg.Config, schema, nil, keyData) - diags = diags.Append(valDiags) - if valDiags.HasErrors() { - return nil, diags.Err() - } - - req := providers.ValidateDataSourceConfigRequest{ - TypeName: cfg.Type, - Config: configVal, - } - - resp := provider.ValidateDataSourceConfig(req) - diags = diags.Append(resp.Diagnostics.InConfigBody(cfg.Config)) + switch n.ResourceMode { + case config.ManagedResourceMode: + warns, errs = provider.ValidateResource(n.ResourceType, cfg) + case config.DataResourceMode: + warns, errs = provider.ValidateDataSource(n.ResourceType, cfg) } - if n.IgnoreWarnings { - // If we _only_ have warnings then we'll return nil. - if diags.HasErrors() { - return nil, diags.NonFatalErr() - } + // If the resource name doesn't match the name regular + // expression, show an error. + if !config.NameRegexp.Match([]byte(n.ResourceName)) { + errs = append(errs, fmt.Errorf( + "%s: resource name can only contain letters, numbers, "+ + "dashes, and underscores.", n.ResourceName)) + } + + if (len(warns) == 0 || n.IgnoreWarnings) && len(errs) == 0 { return nil, nil - } else { - // We'll return an error if there are any diagnostics at all, even if - // some of them are warnings. - return nil, diags.NonFatalErr() + } + + return nil, &EvalValidateError{ + Warnings: warns, + Errors: errs, } } - -func (n *EvalValidateResource) validateCount(ctx EvalContext, expr hcl.Expression) tfdiags.Diagnostics { - if expr == nil { - return nil - } - - var diags tfdiags.Diagnostics - - countVal, countDiags := ctx.EvaluateExpr(expr, cty.Number, nil) - diags = diags.Append(countDiags) - if diags.HasErrors() { - return diags - } - - if countVal.IsNull() { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is null. An integer is required.`, - Subject: expr.Range().Ptr(), - }) - return diags - } - - var err error - countVal, err = convert.Convert(countVal, cty.Number) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err), - Subject: expr.Range().Ptr(), - }) - return diags - } - - // If the value isn't known then that's the best we can do for now, but - // we'll check more thoroughly during the plan walk. - if !countVal.IsKnown() { - return diags - } - - // If we _do_ know the value, then we can do a few more checks here. - var count int - err = gocty.FromCtyValue(countVal, &count) - if err != nil { - // Isn't a whole number, etc. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err), - Subject: expr.Range().Ptr(), - }) - return diags - } - - if count < 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is unsuitable: count cannot be negative.`, - Subject: expr.Range().Ptr(), - }) - return diags - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_validate_selfref.go b/vendor/github.com/hashicorp/terraform/terraform/eval_validate_selfref.go index edd604fa..ae4436a2 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_validate_selfref.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_validate_selfref.go @@ -3,65 +3,72 @@ package terraform import ( "fmt" - "github.com/hashicorp/hcl2/hcl" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/lang" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config" ) -// EvalValidateSelfRef is an EvalNode implementation that checks to ensure that -// expressions within a particular referencable block do not reference that -// same block. -type EvalValidateSelfRef struct { - Addr addrs.Referenceable - Config hcl.Body - ProviderSchema **ProviderSchema +// EvalValidateResourceSelfRef is an EvalNode implementation that validates that +// a configuration doesn't contain a reference to the resource itself. +// +// This must be done prior to interpolating configuration in order to avoid +// any infinite loop scenarios. +type EvalValidateResourceSelfRef struct { + Addr **ResourceAddress + Config **config.RawConfig } -func (n *EvalValidateSelfRef) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - addr := n.Addr +func (n *EvalValidateResourceSelfRef) Eval(ctx EvalContext) (interface{}, error) { + addr := *n.Addr + conf := *n.Config - addrStrs := make([]string, 0, 1) - addrStrs = append(addrStrs, addr.String()) - switch tAddr := addr.(type) { - case addrs.ResourceInstance: - // A resource instance may not refer to its containing resource either. - addrStrs = append(addrStrs, tAddr.ContainingResource().String()) - } + // Go through the variables and find self references + var errs []error + for k, raw := range conf.Variables { + rv, ok := raw.(*config.ResourceVariable) + if !ok { + continue + } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - return nil, fmt.Errorf("provider schema unavailable while validating %s for self-references; this is a bug in Terraform and should be reported", addr) - } + // Build an address from the variable + varAddr := &ResourceAddress{ + Path: addr.Path, + Mode: rv.Mode, + Type: rv.Type, + Name: rv.Name, + Index: rv.Index, + InstanceType: TypePrimary, + } - providerSchema := *n.ProviderSchema - var schema *configschema.Block - switch tAddr := addr.(type) { - case addrs.Resource: - schema, _ = providerSchema.SchemaForResourceAddr(tAddr) - case addrs.ResourceInstance: - schema, _ = providerSchema.SchemaForResourceAddr(tAddr.ContainingResource()) - } + // If the variable access is a multi-access (*), then we just + // match the index so that we'll match our own addr if everything + // else matches. + if rv.Multi && rv.Index == -1 { + varAddr.Index = addr.Index + } - if schema == nil { - return nil, fmt.Errorf("no schema available for %s to validate for self-references; this is a bug in Terraform and should be reported", addr) - } + // This is a weird thing where ResourceAddres has index "-1" when + // index isn't set at all. This means index "0" for resource access. + // So, if we have this scenario, just set our varAddr to -1 so it + // matches. + if addr.Index == -1 && varAddr.Index == 0 { + varAddr.Index = -1 + } - refs, _ := lang.ReferencesInBlock(n.Config, schema) - for _, ref := range refs { - for _, addrStr := range addrStrs { - if ref.Subject.String() == addrStr { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Self-referential block", - Detail: fmt.Sprintf("Configuration for %s may not refer to itself.", addrStr), - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - } + // If the addresses match, then this is a self reference + if varAddr.Equals(addr) && varAddr.Index == addr.Index { + errs = append(errs, fmt.Errorf( + "%s: self reference not allowed: %q", + addr, k)) } } - return nil, diags.NonFatalErr() + // If no errors, no errors! + if len(errs) == 0 { + return nil, nil + } + + // Wrap the errors in the proper wrapper so we can handle validation + // formatting properly upstream. + return nil, &EvalValidateError{ + Errors: errs, + } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_variable.go b/vendor/github.com/hashicorp/terraform/terraform/eval_variable.go index 68adf764..e39a33c2 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_variable.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_variable.go @@ -4,17 +4,12 @@ import ( "fmt" "log" "reflect" + "strconv" "strings" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/configs" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/config/module" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" + "github.com/hashicorp/terraform/helper/hilmapstructure" ) // EvalTypeCheckVariable is an EvalNode which ensures that the variable @@ -98,88 +93,166 @@ func (n *EvalTypeCheckVariable) Eval(ctx EvalContext) (interface{}, error) { return nil, nil } -// EvalSetModuleCallArguments is an EvalNode implementation that sets values -// for arguments of a child module call, for later retrieval during -// expression evaluation. -type EvalSetModuleCallArguments struct { - Module addrs.ModuleCallInstance - Values map[string]cty.Value +// EvalSetVariables is an EvalNode implementation that sets the variables +// explicitly for interpolation later. +type EvalSetVariables struct { + Module *string + Variables map[string]interface{} } // TODO: test -func (n *EvalSetModuleCallArguments) Eval(ctx EvalContext) (interface{}, error) { - ctx.SetModuleCallArguments(n.Module, n.Values) +func (n *EvalSetVariables) Eval(ctx EvalContext) (interface{}, error) { + ctx.SetVariables(*n.Module, n.Variables) return nil, nil } -// EvalModuleCallArgument is an EvalNode implementation that produces the value -// for a particular variable as will be used by a child module instance. -// -// The result is written into the map given in Values, with its key -// set to the local name of the variable, disregarding the module instance -// address. Any existing values in that map are deleted first. This weird -// interface is a result of trying to be convenient for use with -// EvalContext.SetModuleCallArguments, which expects a map to merge in with -// any existing arguments. -type EvalModuleCallArgument struct { - Addr addrs.InputVariable - Config *configs.Variable - Expr hcl.Expression - - // If this flag is set, any diagnostics are discarded and this operation - // will always succeed, though may produce an unknown value in the - // event of an error. - IgnoreDiagnostics bool - - Values map[string]cty.Value +// EvalVariableBlock is an EvalNode implementation that evaluates the +// given configuration, and uses the final values as a way to set the +// mapping. +type EvalVariableBlock struct { + Config **ResourceConfig + VariableValues map[string]interface{} } -func (n *EvalModuleCallArgument) Eval(ctx EvalContext) (interface{}, error) { +func (n *EvalVariableBlock) Eval(ctx EvalContext) (interface{}, error) { // Clear out the existing mapping - for k := range n.Values { - delete(n.Values, k) + for k, _ := range n.VariableValues { + delete(n.VariableValues, k) } - wantType := n.Config.Type - name := n.Addr.Name - expr := n.Expr + // Get our configuration + rc := *n.Config + for k, v := range rc.Config { + vKind := reflect.ValueOf(v).Type().Kind() - if expr == nil { - // Should never happen, but we'll bail out early here rather than - // crash in case it does. We set no value at all in this case, - // making a subsequent call to EvalContext.SetModuleCallArguments - // a no-op. - log.Printf("[ERROR] attempt to evaluate %s with nil expression", n.Addr.String()) - return nil, nil + switch vKind { + case reflect.Slice: + var vSlice []interface{} + if err := hilmapstructure.WeakDecode(v, &vSlice); err == nil { + n.VariableValues[k] = vSlice + continue + } + case reflect.Map: + var vMap map[string]interface{} + if err := hilmapstructure.WeakDecode(v, &vMap); err == nil { + n.VariableValues[k] = vMap + continue + } + default: + var vString string + if err := hilmapstructure.WeakDecode(v, &vString); err == nil { + n.VariableValues[k] = vString + continue + } + } + + return nil, fmt.Errorf("Variable value for %s is not a string, list or map type", k) } - val, diags := ctx.EvaluateExpr(expr, cty.DynamicPseudoType, nil) - - // We intentionally passed DynamicPseudoType to EvaluateExpr above because - // now we can do our own local type conversion and produce an error message - // with better context if it fails. - var convErr error - val, convErr = convert.Convert(val, wantType) - if convErr != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid value for module argument", - Detail: fmt.Sprintf( - "The given value is not suitable for child module variable %q defined at %s: %s.", - name, n.Config.DeclRange.String(), convErr, - ), - Subject: expr.Range().Ptr(), - }) - // We'll return a placeholder unknown value to avoid producing - // redundant downstream errors. - val = cty.UnknownVal(wantType) + for _, path := range rc.ComputedKeys { + log.Printf("[DEBUG] Setting Unknown Variable Value for computed key: %s", path) + err := n.setUnknownVariableValueForPath(path) + if err != nil { + return nil, err + } } - n.Values[name] = val - if n.IgnoreDiagnostics { - return nil, nil + return nil, nil +} + +func (n *EvalVariableBlock) setUnknownVariableValueForPath(path string) error { + pathComponents := strings.Split(path, ".") + + if len(pathComponents) < 1 { + return fmt.Errorf("No path comoponents in %s", path) } - return nil, diags.ErrWithWarnings() + + if len(pathComponents) == 1 { + // Special case the "top level" since we know the type + if _, ok := n.VariableValues[pathComponents[0]]; !ok { + n.VariableValues[pathComponents[0]] = config.UnknownVariableValue + } + return nil + } + + // Otherwise find the correct point in the tree and then set to unknown + var current interface{} = n.VariableValues[pathComponents[0]] + for i := 1; i < len(pathComponents); i++ { + switch tCurrent := current.(type) { + case []interface{}: + index, err := strconv.Atoi(pathComponents[i]) + if err != nil { + return fmt.Errorf("Cannot convert %s to slice index in path %s", + pathComponents[i], path) + } + current = tCurrent[index] + case []map[string]interface{}: + index, err := strconv.Atoi(pathComponents[i]) + if err != nil { + return fmt.Errorf("Cannot convert %s to slice index in path %s", + pathComponents[i], path) + } + current = tCurrent[index] + case map[string]interface{}: + if val, hasVal := tCurrent[pathComponents[i]]; hasVal { + current = val + continue + } + + tCurrent[pathComponents[i]] = config.UnknownVariableValue + break + } + } + + return nil +} + +// EvalCoerceMapVariable is an EvalNode implementation that recognizes a +// specific ambiguous HCL parsing situation and resolves it. In HCL parsing, a +// bare map literal is indistinguishable from a list of maps w/ one element. +// +// We take all the same inputs as EvalTypeCheckVariable above, since we need +// both the target type and the proposed value in order to properly coerce. +type EvalCoerceMapVariable struct { + Variables map[string]interface{} + ModulePath []string + ModuleTree *module.Tree +} + +// Eval implements the EvalNode interface. See EvalCoerceMapVariable for +// details. +func (n *EvalCoerceMapVariable) Eval(ctx EvalContext) (interface{}, error) { + currentTree := n.ModuleTree + for _, pathComponent := range n.ModulePath[1:] { + currentTree = currentTree.Children()[pathComponent] + } + targetConfig := currentTree.Config() + + prototypes := make(map[string]config.VariableType) + for _, variable := range targetConfig.Variables { + prototypes[variable.Name] = variable.Type() + } + + for name, declaredType := range prototypes { + if declaredType != config.VariableTypeMap { + continue + } + + proposedValue, ok := n.Variables[name] + if !ok { + continue + } + + if list, ok := proposedValue.([]interface{}); ok && len(list) == 1 { + if m, ok := list[0].(map[string]interface{}); ok { + log.Printf("[DEBUG] EvalCoerceMapVariable: "+ + "Coercing single element list into map: %#v", m) + n.Variables[name] = m + } + } + } + + return nil, nil } // hclTypeName returns the name of the type that would represent this value in diff --git a/vendor/github.com/hashicorp/terraform/terraform/evaltree_provider.go b/vendor/github.com/hashicorp/terraform/terraform/evaltree_provider.go index 6b4df67a..0c3da48f 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/evaltree_provider.go +++ b/vendor/github.com/hashicorp/terraform/terraform/evaltree_provider.go @@ -1,34 +1,48 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/providers" + "strings" + + "github.com/hashicorp/terraform/config" ) // ProviderEvalTree returns the evaluation tree for initializing and // configuring providers. -func ProviderEvalTree(n *NodeApplyableProvider, config *configs.Provider) EvalNode { - var provider providers.Interface +func ProviderEvalTree(n *NodeApplyableProvider, config *config.ProviderConfig) EvalNode { + var provider ResourceProvider + var resourceConfig *ResourceConfig - addr := n.Addr - relAddr := addr.ProviderConfig + typeName := strings.SplitN(n.NameValue, ".", 2)[0] seq := make([]EvalNode, 0, 5) seq = append(seq, &EvalInitProvider{ - TypeName: relAddr.Type, - Addr: addr.ProviderConfig, + TypeName: typeName, + Name: n.Name(), }) // Input stuff seq = append(seq, &EvalOpFilter{ - Ops: []walkOperation{walkImport}, + Ops: []walkOperation{walkInput, walkImport}, Node: &EvalSequence{ Nodes: []EvalNode{ &EvalGetProvider{ - Addr: addr, + Name: n.Name(), Output: &provider, }, + &EvalInterpolateProvider{ + Config: config, + Output: &resourceConfig, + }, + &EvalBuildProviderConfig{ + Provider: n.NameValue, + Config: &resourceConfig, + Output: &resourceConfig, + }, + &EvalInputProvider{ + Name: n.NameValue, + Provider: &provider, + Config: &resourceConfig, + }, }, }, }) @@ -38,13 +52,21 @@ func ProviderEvalTree(n *NodeApplyableProvider, config *configs.Provider) EvalNo Node: &EvalSequence{ Nodes: []EvalNode{ &EvalGetProvider{ - Addr: addr, + Name: n.Name(), Output: &provider, }, + &EvalInterpolateProvider{ + Config: config, + Output: &resourceConfig, + }, + &EvalBuildProviderConfig{ + Provider: n.NameValue, + Config: &resourceConfig, + Output: &resourceConfig, + }, &EvalValidateProvider{ - Addr: relAddr, Provider: &provider, - Config: config, + Config: &resourceConfig, }, }, }, @@ -56,9 +78,18 @@ func ProviderEvalTree(n *NodeApplyableProvider, config *configs.Provider) EvalNo Node: &EvalSequence{ Nodes: []EvalNode{ &EvalGetProvider{ - Addr: addr, + Name: n.Name(), Output: &provider, }, + &EvalInterpolateProvider{ + Config: config, + Output: &resourceConfig, + }, + &EvalBuildProviderConfig{ + Provider: n.NameValue, + Config: &resourceConfig, + Output: &resourceConfig, + }, }, }, }) @@ -70,9 +101,8 @@ func ProviderEvalTree(n *NodeApplyableProvider, config *configs.Provider) EvalNo Node: &EvalSequence{ Nodes: []EvalNode{ &EvalConfigProvider{ - Addr: relAddr, - Provider: &provider, - Config: config, + Provider: n.Name(), + Config: &resourceConfig, }, }, }, @@ -83,6 +113,6 @@ func ProviderEvalTree(n *NodeApplyableProvider, config *configs.Provider) EvalNo // CloseProviderEvalTree returns the evaluation tree for closing // provider connections that aren't needed anymore. -func CloseProviderEvalTree(addr addrs.AbsProviderConfig) EvalNode { - return &EvalCloseProvider{Addr: addr.ProviderConfig} +func CloseProviderEvalTree(n string) EvalNode { + return &EvalCloseProvider{Name: n} } diff --git a/vendor/github.com/hashicorp/terraform/terraform/evaluate.go b/vendor/github.com/hashicorp/terraform/terraform/evaluate.go deleted file mode 100644 index 38fe8767..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/evaluate.go +++ /dev/null @@ -1,916 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - "os" - "path/filepath" - "strconv" - "sync" - - "github.com/agext/levenshtein" - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/lang" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" -) - -// Evaluator provides the necessary contextual data for evaluating expressions -// for a particular walk operation. -type Evaluator struct { - // Operation defines what type of operation this evaluator is being used - // for. - Operation walkOperation - - // Meta is contextual metadata about the current operation. - Meta *ContextMeta - - // Config is the root node in the configuration tree. - Config *configs.Config - - // VariableValues is a map from variable names to their associated values, - // within the module indicated by ModulePath. VariableValues is modified - // concurrently, and so it must be accessed only while holding - // VariableValuesLock. - // - // The first map level is string representations of addr.ModuleInstance - // values, while the second level is variable names. - VariableValues map[string]map[string]cty.Value - VariableValuesLock *sync.Mutex - - // Schemas is a repository of all of the schemas we should need to - // evaluate expressions. This must be constructed by the caller to - // include schemas for all of the providers, resource types, data sources - // and provisioners used by the given configuration and state. - // - // This must not be mutated during evaluation. - Schemas *Schemas - - // State is the current state, embedded in a wrapper that ensures that - // it can be safely accessed and modified concurrently. - State *states.SyncState - - // Changes is the set of proposed changes, embedded in a wrapper that - // ensures they can be safely accessed and modified concurrently. - Changes *plans.ChangesSync -} - -// Scope creates an evaluation scope for the given module path and optional -// resource. -// -// If the "self" argument is nil then the "self" object is not available -// in evaluated expressions. Otherwise, it behaves as an alias for the given -// address. -func (e *Evaluator) Scope(data lang.Data, self addrs.Referenceable) *lang.Scope { - return &lang.Scope{ - Data: data, - SelfAddr: self, - PureOnly: e.Operation != walkApply && e.Operation != walkDestroy, - BaseDir: ".", // Always current working directory for now. - } -} - -// evaluationStateData is an implementation of lang.Data that resolves -// references primarily (but not exclusively) using information from a State. -type evaluationStateData struct { - Evaluator *Evaluator - - // ModulePath is the path through the dynamic module tree to the module - // that references will be resolved relative to. - ModulePath addrs.ModuleInstance - - // InstanceKeyData describes the values, if any, that are accessible due - // to repetition of a containing object using "count" or "for_each" - // arguments. (It is _not_ used for the for_each inside "dynamic" blocks, - // since the user specifies in that case which variable name to locally - // shadow.) - InstanceKeyData InstanceKeyEvalData - - // Operation records the type of walk the evaluationStateData is being used - // for. - Operation walkOperation -} - -// InstanceKeyEvalData is used during evaluation to specify which values, -// if any, should be produced for count.index, each.key, and each.value. -type InstanceKeyEvalData struct { - // CountIndex is the value for count.index, or cty.NilVal if evaluating - // in a context where the "count" argument is not active. - // - // For correct operation, this should always be of type cty.Number if not - // nil. - CountIndex cty.Value - - // EachKey and EachValue are the values for each.key and each.value - // respectively, or cty.NilVal if evaluating in a context where the - // "for_each" argument is not active. These must either both be set - // or neither set. - // - // For correct operation, EachKey must always be either of type cty.String - // or cty.Number if not nil. - EachKey, EachValue cty.Value -} - -// EvalDataForInstanceKey constructs a suitable InstanceKeyEvalData for -// evaluating in a context that has the given instance key. -func EvalDataForInstanceKey(key addrs.InstanceKey) InstanceKeyEvalData { - // At the moment we don't actually implement for_each, so we only - // ever populate CountIndex. - // (When we implement for_each later we may need to reorganize this some, - // so that we can resolve the ambiguity that an int key may either be - // a count.index or an each.key where for_each is over a list.) - - var countIdx cty.Value - if intKey, ok := key.(addrs.IntKey); ok { - countIdx = cty.NumberIntVal(int64(intKey)) - } - - return InstanceKeyEvalData{ - CountIndex: countIdx, - } -} - -// EvalDataForNoInstanceKey is a value of InstanceKeyData that sets no instance -// key values at all, suitable for use in contexts where no keyed instance -// is relevant. -var EvalDataForNoInstanceKey = InstanceKeyEvalData{} - -// evaluationStateData must implement lang.Data -var _ lang.Data = (*evaluationStateData)(nil) - -func (d *evaluationStateData) GetCountAttr(addr addrs.CountAttr, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - switch addr.Name { - - case "index": - idxVal := d.InstanceKeyData.CountIndex - if idxVal == cty.NilVal { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to "count" in non-counted context`, - Detail: fmt.Sprintf(`The "count" object can be used only in "resource" and "data" blocks, and only when the "count" argument is set.`), - Subject: rng.ToHCL().Ptr(), - }) - return cty.UnknownVal(cty.Number), diags - } - return idxVal, diags - - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "count" attribute`, - Detail: fmt.Sprintf(`The "count" object does not have an attribute named %q. The only supported attribute is count.index, which is the index of each instance of a resource block that has the "count" argument set.`, addr.Name), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } -} - -func (d *evaluationStateData) GetInputVariable(addr addrs.InputVariable, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // First we'll make sure the requested value is declared in configuration, - // so we can produce a nice message if not. - moduleConfig := d.Evaluator.Config.DescendentForInstance(d.ModulePath) - if moduleConfig == nil { - // should never happen, since we can't be evaluating in a module - // that wasn't mentioned in configuration. - panic(fmt.Sprintf("input variable read from %s, which has no configuration", d.ModulePath)) - } - - config := moduleConfig.Module.Variables[addr.Name] - if config == nil { - var suggestions []string - for k := range moduleConfig.Module.Variables { - suggestions = append(suggestions, k) - } - suggestion := nameSuggestion(addr.Name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } else { - suggestion = fmt.Sprintf(" This variable can be declared with a variable %q {} block.", addr.Name) - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared input variable`, - Detail: fmt.Sprintf(`An input variable with the name %q has not been declared.%s`, addr.Name, suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - wantType := cty.DynamicPseudoType - if config.Type != cty.NilType { - wantType = config.Type - } - - d.Evaluator.VariableValuesLock.Lock() - defer d.Evaluator.VariableValuesLock.Unlock() - - moduleAddrStr := d.ModulePath.String() - vals := d.Evaluator.VariableValues[moduleAddrStr] - if vals == nil { - return cty.UnknownVal(wantType), diags - } - - val, isSet := vals[addr.Name] - if !isSet { - if config.Default != cty.NilVal { - return config.Default, diags - } - return cty.UnknownVal(wantType), diags - } - - var err error - val, err = convert.Convert(val, wantType) - if err != nil { - // We should never get here because this problem should've been caught - // during earlier validation, but we'll do something reasonable anyway. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Incorrect variable type`, - Detail: fmt.Sprintf(`The resolved value of variable %q is not appropriate: %s.`, addr.Name, err), - Subject: &config.DeclRange, - }) - // Stub out our return value so that the semantic checker doesn't - // produce redundant downstream errors. - val = cty.UnknownVal(wantType) - } - - return val, diags -} - -func (d *evaluationStateData) GetLocalValue(addr addrs.LocalValue, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // First we'll make sure the requested value is declared in configuration, - // so we can produce a nice message if not. - moduleConfig := d.Evaluator.Config.DescendentForInstance(d.ModulePath) - if moduleConfig == nil { - // should never happen, since we can't be evaluating in a module - // that wasn't mentioned in configuration. - panic(fmt.Sprintf("local value read from %s, which has no configuration", d.ModulePath)) - } - - config := moduleConfig.Module.Locals[addr.Name] - if config == nil { - var suggestions []string - for k := range moduleConfig.Module.Locals { - suggestions = append(suggestions, k) - } - suggestion := nameSuggestion(addr.Name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared local value`, - Detail: fmt.Sprintf(`A local value with the name %q has not been declared.%s`, addr.Name, suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - val := d.Evaluator.State.LocalValue(addr.Absolute(d.ModulePath)) - if val == cty.NilVal { - // Not evaluated yet? - val = cty.DynamicVal - } - - return val, diags -} - -func (d *evaluationStateData) GetModuleInstance(addr addrs.ModuleCallInstance, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // Output results live in the module that declares them, which is one of - // the child module instances of our current module path. - moduleAddr := addr.ModuleInstance(d.ModulePath) - - // We'll consult the configuration to see what output names we are - // expecting, so we can ensure the resulting object is of the expected - // type even if our data is incomplete for some reason. - moduleConfig := d.Evaluator.Config.DescendentForInstance(moduleAddr) - if moduleConfig == nil { - // should never happen, since this should've been caught during - // static validation. - panic(fmt.Sprintf("output value read from %s, which has no configuration", moduleAddr)) - } - outputConfigs := moduleConfig.Module.Outputs - - vals := map[string]cty.Value{} - for n := range outputConfigs { - addr := addrs.OutputValue{Name: n}.Absolute(moduleAddr) - - // If a pending change is present in our current changeset then its value - // takes priority over what's in state. (It will usually be the same but - // will differ if the new value is unknown during planning.) - if changeSrc := d.Evaluator.Changes.GetOutputChange(addr); changeSrc != nil { - change, err := changeSrc.Decode() - if err != nil { - // This should happen only if someone has tampered with a plan - // file, so we won't bother with a pretty error for it. - diags = diags.Append(fmt.Errorf("planned change for %s could not be decoded: %s", addr, err)) - vals[n] = cty.DynamicVal - continue - } - // We care only about the "after" value, which is the value this output - // will take on after the plan is applied. - vals[n] = change.After - } else { - os := d.Evaluator.State.OutputValue(addr) - if os == nil { - // Not evaluated yet? - vals[n] = cty.DynamicVal - continue - } - vals[n] = os.Value - } - } - return cty.ObjectVal(vals), diags -} - -func (d *evaluationStateData) GetModuleInstanceOutput(addr addrs.ModuleCallOutput, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // Output results live in the module that declares them, which is one of - // the child module instances of our current module path. - absAddr := addr.AbsOutputValue(d.ModulePath) - moduleAddr := absAddr.Module - - // First we'll consult the configuration to see if an output of this - // name is declared at all. - moduleConfig := d.Evaluator.Config.DescendentForInstance(moduleAddr) - if moduleConfig == nil { - // this doesn't happen in normal circumstances due to our validation - // pass, but it can turn up in some unusual situations, like in the - // "terraform console" repl where arbitrary expressions can be - // evaluated. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared module`, - Detail: fmt.Sprintf(`The configuration contains no %s.`, moduleAddr), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - config := moduleConfig.Module.Outputs[addr.Name] - if config == nil { - var suggestions []string - for k := range moduleConfig.Module.Outputs { - suggestions = append(suggestions, k) - } - suggestion := nameSuggestion(addr.Name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared output value`, - Detail: fmt.Sprintf(`An output value with the name %q has not been declared in %s.%s`, addr.Name, moduleDisplayAddr(moduleAddr), suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - // If a pending change is present in our current changeset then its value - // takes priority over what's in state. (It will usually be the same but - // will differ if the new value is unknown during planning.) - if changeSrc := d.Evaluator.Changes.GetOutputChange(absAddr); changeSrc != nil { - change, err := changeSrc.Decode() - if err != nil { - // This should happen only if someone has tampered with a plan - // file, so we won't bother with a pretty error for it. - diags = diags.Append(fmt.Errorf("planned change for %s could not be decoded: %s", absAddr, err)) - return cty.DynamicVal, diags - } - // We care only about the "after" value, which is the value this output - // will take on after the plan is applied. - return change.After, diags - } - - os := d.Evaluator.State.OutputValue(absAddr) - if os == nil { - // Not evaluated yet? - return cty.DynamicVal, diags - } - - return os.Value, diags -} - -func (d *evaluationStateData) GetPathAttr(addr addrs.PathAttr, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - switch addr.Name { - - case "cwd": - wd, err := os.Getwd() - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Failed to get working directory`, - Detail: fmt.Sprintf(`The value for path.cwd cannot be determined due to a system error: %s`, err), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - return cty.StringVal(filepath.ToSlash(wd)), diags - - case "module": - moduleConfig := d.Evaluator.Config.DescendentForInstance(d.ModulePath) - if moduleConfig == nil { - // should never happen, since we can't be evaluating in a module - // that wasn't mentioned in configuration. - panic(fmt.Sprintf("module.path read from module %s, which has no configuration", d.ModulePath)) - } - sourceDir := moduleConfig.Module.SourceDir - return cty.StringVal(filepath.ToSlash(sourceDir)), diags - - case "root": - sourceDir := d.Evaluator.Config.Module.SourceDir - return cty.StringVal(filepath.ToSlash(sourceDir)), diags - - default: - suggestion := nameSuggestion(addr.Name, []string{"cwd", "module", "root"}) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "path" attribute`, - Detail: fmt.Sprintf(`The "path" object does not have an attribute named %q.%s`, addr.Name, suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } -} - -func (d *evaluationStateData) GetResourceInstance(addr addrs.ResourceInstance, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // Although we are giving a ResourceInstance address here, if it has - // a key of addrs.NoKey then it might actually be a request for all of - // the instances of a particular resource. The reference resolver can't - // resolve the ambiguity itself, so we must do it in here. - - // First we'll consult the configuration to see if an resource of this - // name is declared at all. - moduleAddr := d.ModulePath - moduleConfig := d.Evaluator.Config.DescendentForInstance(moduleAddr) - if moduleConfig == nil { - // should never happen, since we can't be evaluating in a module - // that wasn't mentioned in configuration. - panic(fmt.Sprintf("resource value read from %s, which has no configuration", moduleAddr)) - } - - config := moduleConfig.Module.ResourceByAddr(addr.ContainingResource()) - if config == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared resource`, - Detail: fmt.Sprintf(`A resource %q %q has not been declared in %s`, addr.Resource.Type, addr.Resource.Name, moduleDisplayAddr(moduleAddr)), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - // First we'll find the state for the resource as a whole, and decide - // from there whether we're going to interpret the given address as a - // resource or a resource instance address. - rs := d.Evaluator.State.Resource(addr.ContainingResource().Absolute(d.ModulePath)) - - if rs == nil { - schema := d.getResourceSchema(addr.ContainingResource(), config.ProviderConfigAddr().Absolute(d.ModulePath)) - - // If it doesn't exist at all then we can't reliably determine whether - // single-instance or whole-resource interpretation was intended, but - // we can decide this partially... - if addr.Key != addrs.NoKey { - // If there's an instance key then the user must be intending - // single-instance interpretation, and so we can return a - // properly-typed unknown value to help with type checking. - return cty.UnknownVal(schema.ImpliedType()), diags - } - - // otherwise we must return DynamicVal so that both interpretations - // can proceed without generating errors, and we'll deal with this - // in a later step where more information is gathered. - // (In practice we should only end up here during the validate walk, - // since later walks should have at least partial states populated - // for all resources in the configuration.) - return cty.DynamicVal, diags - } - - // Break out early during validation, because resource may not be expanded - // yet and indexed references may show up as invalid. - if d.Operation == walkValidate { - return cty.DynamicVal, diags - } - - schema := d.getResourceSchema(addr.ContainingResource(), rs.ProviderConfig) - - // If we are able to automatically convert to the "right" type of instance - // key for this each mode then we'll do so, to match with how we generally - // treat values elsewhere in the language. This allows code below to - // assume that any possible conversions have already been dealt with and - // just worry about validation. - key := d.coerceInstanceKey(addr.Key, rs.EachMode) - - multi := false - - switch rs.EachMode { - case states.NoEach: - if key != addrs.NoKey { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource index", - Detail: fmt.Sprintf("Resource %s does not have either \"count\" or \"for_each\" set, so it cannot be indexed.", addr.ContainingResource()), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - case states.EachList: - multi = key == addrs.NoKey - if _, ok := addr.Key.(addrs.IntKey); !multi && !ok { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource index", - Detail: fmt.Sprintf("Resource %s must be indexed with a number value.", addr.ContainingResource()), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - case states.EachMap: - multi = key == addrs.NoKey - if _, ok := addr.Key.(addrs.IntKey); !multi && !ok { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource index", - Detail: fmt.Sprintf("Resource %s must be indexed with a string value.", addr.ContainingResource()), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - } - - if !multi { - log.Printf("[TRACE] GetResourceInstance: %s is a single instance", addr) - is := rs.Instance(key) - if is == nil { - return cty.UnknownVal(schema.ImpliedType()), diags - } - return d.getResourceInstanceSingle(addr, rng, is, config, rs.ProviderConfig) - } - - log.Printf("[TRACE] GetResourceInstance: %s has multiple keyed instances", addr) - return d.getResourceInstancesAll(addr.ContainingResource(), rng, config, rs, rs.ProviderConfig) -} - -func (d *evaluationStateData) getResourceInstanceSingle(addr addrs.ResourceInstance, rng tfdiags.SourceRange, is *states.ResourceInstance, config *configs.Resource, providerAddr addrs.AbsProviderConfig) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - schema := d.getResourceSchema(addr.ContainingResource(), providerAddr) - if schema == nil { - // This shouldn't happen, since validation before we get here should've - // taken care of it, but we'll show a reasonable error message anyway. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Missing resource type schema`, - Detail: fmt.Sprintf("No schema is available for %s in %s. This is a bug in Terraform and should be reported.", addr, providerAddr), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - ty := schema.ImpliedType() - if is == nil || is.Current == nil { - // Assume we're dealing with an instance that hasn't been created yet. - return cty.UnknownVal(ty), diags - } - - if is.Current.Status == states.ObjectPlanned { - // If there's a pending change for this instance in our plan, we'll prefer - // that. This is important because the state can't represent unknown values - // and so its data is inaccurate when changes are pending. - if change := d.Evaluator.Changes.GetResourceInstanceChange(addr.Absolute(d.ModulePath), states.CurrentGen); change != nil { - val, err := change.After.Decode(ty) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in plan", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", addr.Absolute(d.ModulePath), err), - Subject: &config.DeclRange, - }) - return cty.UnknownVal(ty), diags - } - return val, diags - } else { - // If the object is in planned status then we should not - // get here, since we should've found a pending value - // in the plan above instead. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing pending object in plan", - Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", addr), - Subject: &config.DeclRange, - }) - return cty.UnknownVal(ty), diags - } - } - - ios, err := is.Current.Decode(ty) - if err != nil { - // This shouldn't happen, since by the time we get here - // we should've upgraded the state data already. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in state", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", addr.Absolute(d.ModulePath), err), - Subject: &config.DeclRange, - }) - return cty.UnknownVal(ty), diags - } - - return ios.Value, diags -} - -func (d *evaluationStateData) getResourceInstancesAll(addr addrs.Resource, rng tfdiags.SourceRange, config *configs.Resource, rs *states.Resource, providerAddr addrs.AbsProviderConfig) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - schema := d.getResourceSchema(addr, providerAddr) - if schema == nil { - // This shouldn't happen, since validation before we get here should've - // taken care of it, but we'll show a reasonable error message anyway. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Missing resource type schema`, - Detail: fmt.Sprintf("No schema is available for %s in %s. This is a bug in Terraform and should be reported.", addr, providerAddr), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - switch rs.EachMode { - - case states.EachList: - // We need to infer the length of our resulting tuple by searching - // for the max IntKey in our instances map. - length := 0 - for k := range rs.Instances { - if ik, ok := k.(addrs.IntKey); ok { - if int(ik) >= length { - length = int(ik) + 1 - } - } - } - - vals := make([]cty.Value, length) - for i := 0; i < length; i++ { - ty := schema.ImpliedType() - key := addrs.IntKey(i) - is, exists := rs.Instances[key] - if exists { - instAddr := addr.Instance(key).Absolute(d.ModulePath) - - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. - if is.Current.Status == states.ObjectPlanned { - if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { - val, err := change.After.Decode(ty) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in plan", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[i] = val - continue - } else { - // If the object is in planned status then we should not - // get here, since we should've found a pending value - // in the plan above instead. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing pending object in plan", - Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", instAddr), - Subject: &config.DeclRange, - }) - continue - } - } - - ios, err := is.Current.Decode(ty) - if err != nil { - // This shouldn't happen, since by the time we get here - // we should've upgraded the state data already. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in state", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[i] = ios.Value - } else { - // There shouldn't normally be "gaps" in our list but we'll - // allow it under the assumption that we're in a weird situation - // where e.g. someone has run "terraform state mv" to reorder - // a list and left a hole behind. - vals[i] = cty.UnknownVal(schema.ImpliedType()) - } - } - - // We use a tuple rather than a list here because resource schemas may - // include dynamically-typed attributes, which will then cause each - // instance to potentially have a different runtime type even though - // they all conform to the static schema. - return cty.TupleVal(vals), diags - - case states.EachMap: - ty := schema.ImpliedType() - vals := make(map[string]cty.Value, len(rs.Instances)) - for k, is := range rs.Instances { - if sk, ok := k.(addrs.StringKey); ok { - instAddr := addr.Instance(k).Absolute(d.ModulePath) - - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. - if is.Current.Status == states.ObjectPlanned { - if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { - val, err := change.After.Decode(ty) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in plan", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[string(sk)] = val - continue - } else { - // If the object is in planned status then we should not - // get here, since we should've found a pending value - // in the plan above instead. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing pending object in plan", - Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", instAddr), - Subject: &config.DeclRange, - }) - continue - } - } - - ios, err := is.Current.Decode(ty) - if err != nil { - // This shouldn't happen, since by the time we get here - // we should've upgraded the state data already. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in state", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[string(sk)] = ios.Value - } - } - - // We use an object rather than a map here because resource schemas may - // include dynamically-typed attributes, which will then cause each - // instance to potentially have a different runtime type even though - // they all conform to the static schema. - return cty.ObjectVal(vals), diags - - default: - // Should never happen since caller should deal with other modes - panic(fmt.Sprintf("unsupported EachMode %s", rs.EachMode)) - } -} - -func (d *evaluationStateData) getResourceSchema(addr addrs.Resource, providerAddr addrs.AbsProviderConfig) *configschema.Block { - providerType := providerAddr.ProviderConfig.Type - schemas := d.Evaluator.Schemas - schema, _ := schemas.ResourceTypeConfig(providerType, addr.Mode, addr.Type) - return schema -} - -// coerceInstanceKey attempts to convert the given key to the type expected -// for the given EachMode. -// -// If the key is already of the correct type or if it cannot be converted then -// it is returned verbatim. If conversion is required and possible, the -// converted value is returned. Callers should not try to determine if -// conversion was possible, should instead just check if the result is of -// the expected type. -func (d *evaluationStateData) coerceInstanceKey(key addrs.InstanceKey, mode states.EachMode) addrs.InstanceKey { - if key == addrs.NoKey { - // An absent key can't be converted - return key - } - - switch mode { - case states.NoEach: - // No conversions possible at all - return key - case states.EachMap: - if intKey, isInt := key.(addrs.IntKey); isInt { - return addrs.StringKey(strconv.Itoa(int(intKey))) - } - return key - case states.EachList: - if strKey, isStr := key.(addrs.StringKey); isStr { - i, err := strconv.Atoi(string(strKey)) - if err != nil { - return key - } - return addrs.IntKey(i) - } - return key - default: - return key - } -} - -func (d *evaluationStateData) GetTerraformAttr(addr addrs.TerraformAttr, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - switch addr.Name { - - case "workspace": - workspaceName := d.Evaluator.Meta.Env - return cty.StringVal(workspaceName), diags - - case "env": - // Prior to Terraform 0.12 there was an attribute "env", which was - // an alias name for "workspace". This was deprecated and is now - // removed. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "terraform" attribute`, - Detail: `The terraform.env attribute was deprecated in v0.10 and removed in v0.12. The "state environment" concept was rename to "workspace" in v0.12, and so the workspace name can now be accessed using the terraform.workspace attribute.`, - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "terraform" attribute`, - Detail: fmt.Sprintf(`The "terraform" object does not have an attribute named %q. The only supported attribute is terraform.workspace, the name of the currently-selected workspace.`, addr.Name), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } -} - -// nameSuggestion tries to find a name from the given slice of suggested names -// that is close to the given name and returns it if found. If no suggestion -// is close enough, returns the empty string. -// -// The suggestions are tried in order, so earlier suggestions take precedence -// if the given string is similar to two or more suggestions. -// -// This function is intended to be used with a relatively-small number of -// suggestions. It's not optimized for hundreds or thousands of them. -func nameSuggestion(given string, suggestions []string) string { - for _, suggestion := range suggestions { - dist := levenshtein.Distance(given, suggestion, nil) - if dist < 3 { // threshold determined experimentally - return suggestion - } - } - return "" -} - -// moduleDisplayAddr returns a string describing the given module instance -// address that is appropriate for returning to users in situations where the -// root module is possible. Specifically, it returns "the root module" if the -// root module instance is given, or a string representation of the module -// address otherwise. -func moduleDisplayAddr(addr addrs.ModuleInstance) string { - switch { - case addr.IsRoot(): - return "the root module" - default: - return addr.String() - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/evaluate_valid.go b/vendor/github.com/hashicorp/terraform/terraform/evaluate_valid.go deleted file mode 100644 index 4255102d..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/evaluate_valid.go +++ /dev/null @@ -1,299 +0,0 @@ -package terraform - -import ( - "fmt" - "sort" - - "github.com/hashicorp/hcl2/hcl" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/helper/didyoumean" - "github.com/hashicorp/terraform/tfdiags" -) - -// StaticValidateReferences checks the given references against schemas and -// other statically-checkable rules, producing error diagnostics if any -// problems are found. -// -// If this method returns errors for a particular reference then evaluating -// that reference is likely to generate a very similar error, so callers should -// not run this method and then also evaluate the source expression(s) and -// merge the two sets of diagnostics together, since this will result in -// confusing redundant errors. -// -// This method can find more errors than can be found by evaluating an -// expression with a partially-populated scope, since it checks the referenced -// names directly against the schema rather than relying on evaluation errors. -// -// The result may include warning diagnostics if, for example, deprecated -// features are referenced. -func (d *evaluationStateData) StaticValidateReferences(refs []*addrs.Reference, self addrs.Referenceable) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - for _, ref := range refs { - moreDiags := d.staticValidateReference(ref, self) - diags = diags.Append(moreDiags) - } - return diags -} - -func (d *evaluationStateData) staticValidateReference(ref *addrs.Reference, self addrs.Referenceable) tfdiags.Diagnostics { - modCfg := d.Evaluator.Config.DescendentForInstance(d.ModulePath) - if modCfg == nil { - // This is a bug in the caller rather than a problem with the - // reference, but rather than crashing out here in an unhelpful way - // we'll just ignore it and trust a different layer to catch it. - return nil - } - - if ref.Subject == addrs.Self { - // The "self" address is a special alias for the address given as - // our self parameter here, if present. - if self == nil { - var diags tfdiags.Diagnostics - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "self" reference`, - // This detail message mentions some current practice that - // this codepath doesn't really "know about". If the "self" - // object starts being supported in more contexts later then - // we'll need to adjust this message. - Detail: `The "self" object is not available in this context. This object can be used only in resource provisioner and connection blocks.`, - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - return diags - } - - synthRef := *ref // shallow copy - synthRef.Subject = self - ref = &synthRef - } - - switch addr := ref.Subject.(type) { - - // For static validation we validate both resource and resource instance references the same way. - // We mostly disregard the index, though we do some simple validation of - // its _presence_ in staticValidateSingleResourceReference and - // staticValidateMultiResourceReference respectively. - case addrs.Resource: - var diags tfdiags.Diagnostics - diags = diags.Append(d.staticValidateSingleResourceReference(modCfg, addr, ref.Remaining, ref.SourceRange)) - diags = diags.Append(d.staticValidateResourceReference(modCfg, addr, ref.Remaining, ref.SourceRange)) - return diags - case addrs.ResourceInstance: - var diags tfdiags.Diagnostics - diags = diags.Append(d.staticValidateMultiResourceReference(modCfg, addr, ref.Remaining, ref.SourceRange)) - diags = diags.Append(d.staticValidateResourceReference(modCfg, addr.ContainingResource(), ref.Remaining, ref.SourceRange)) - return diags - - // We also handle all module call references the same way, disregarding index. - case addrs.ModuleCall: - return d.staticValidateModuleCallReference(modCfg, addr, ref.Remaining, ref.SourceRange) - case addrs.ModuleCallInstance: - return d.staticValidateModuleCallReference(modCfg, addr.Call, ref.Remaining, ref.SourceRange) - case addrs.ModuleCallOutput: - // This one is a funny one because we will take the output name referenced - // and use it to fake up a "remaining" that would make sense for the - // module call itself, rather than for the specific output, and then - // we can just re-use our static module call validation logic. - remain := make(hcl.Traversal, len(ref.Remaining)+1) - copy(remain[1:], ref.Remaining) - remain[0] = hcl.TraverseAttr{ - Name: addr.Name, - - // Using the whole reference as the source range here doesn't exactly - // match how HCL would normally generate an attribute traversal, - // but is close enough for our purposes. - SrcRange: ref.SourceRange.ToHCL(), - } - return d.staticValidateModuleCallReference(modCfg, addr.Call.Call, remain, ref.SourceRange) - - default: - // Anything else we'll just permit through without any static validation - // and let it be caught during dynamic evaluation, in evaluate.go . - return nil - } -} - -func (d *evaluationStateData) staticValidateSingleResourceReference(modCfg *configs.Config, addr addrs.Resource, remain hcl.Traversal, rng tfdiags.SourceRange) tfdiags.Diagnostics { - // If we have at least one step in "remain" and this resource has - // "count" set then we know for sure this in invalid because we have - // something like: - // aws_instance.foo.bar - // ...when we really need - // aws_instance.foo[count.index].bar - - // It is _not_ safe to do this check when remain is empty, because that - // would also match aws_instance.foo[count.index].bar due to `count.index` - // not being statically-resolvable as part of a reference, and match - // direct references to the whole aws_instance.foo tuple. - if len(remain) == 0 { - return nil - } - - var diags tfdiags.Diagnostics - - cfg := modCfg.Module.ResourceByAddr(addr) - if cfg == nil { - // We'll just bail out here and catch this in our subsequent call to - // staticValidateResourceReference, then. - return diags - } - - if cfg.Count != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Missing resource instance key`, - Detail: fmt.Sprintf("Because %s has \"count\" set, its attributes must be accessed on specific instances.\n\nFor example, to correlate with indices of a referring resource, use:\n %s[count.index]", addr, addr), - Subject: rng.ToHCL().Ptr(), - }) - } - if cfg.ForEach != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Missing resource instance key`, - Detail: fmt.Sprintf("Because %s has \"for_each\" set, its attributes must be accessed on specific instances.\n\nFor example, to correlate with indices of a referring resource, use:\n %s[each.key]", addr, addr), - Subject: rng.ToHCL().Ptr(), - }) - } - - return diags -} - -func (d *evaluationStateData) staticValidateMultiResourceReference(modCfg *configs.Config, addr addrs.ResourceInstance, remain hcl.Traversal, rng tfdiags.SourceRange) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - cfg := modCfg.Module.ResourceByAddr(addr.ContainingResource()) - if cfg == nil { - // We'll just bail out here and catch this in our subsequent call to - // staticValidateResourceReference, then. - return diags - } - - if addr.Key == addrs.NoKey { - // This is a different path into staticValidateSingleResourceReference - return d.staticValidateSingleResourceReference(modCfg, addr.ContainingResource(), remain, rng) - } else { - if cfg.Count == nil && cfg.ForEach == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Unexpected resource instance key`, - Detail: fmt.Sprintf(`Because %s does not have "count" or "for_each" set, references to it must not include an index key. Remove the bracketed index to refer to the single instance of this resource.`, addr.ContainingResource()), - Subject: rng.ToHCL().Ptr(), - }) - } - } - - return diags -} - -func (d *evaluationStateData) staticValidateResourceReference(modCfg *configs.Config, addr addrs.Resource, remain hcl.Traversal, rng tfdiags.SourceRange) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - var modeAdjective string - switch addr.Mode { - case addrs.ManagedResourceMode: - modeAdjective = "managed" - case addrs.DataResourceMode: - modeAdjective = "data" - default: - // should never happen - modeAdjective = "" - } - - cfg := modCfg.Module.ResourceByAddr(addr) - if cfg == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared resource`, - Detail: fmt.Sprintf(`A %s resource %q %q has not been declared in %s.`, modeAdjective, addr.Type, addr.Name, moduleConfigDisplayAddr(modCfg.Path)), - Subject: rng.ToHCL().Ptr(), - }) - return diags - } - - // Normally accessing this directly is wrong because it doesn't take into - // account provider inheritance, etc but it's okay here because we're only - // paying attention to the type anyway. - providerType := cfg.ProviderConfigAddr().Type - schema, _ := d.Evaluator.Schemas.ResourceTypeConfig(providerType, addr.Mode, addr.Type) - - if schema == nil { - // Prior validation should've taken care of a resource block with an - // unsupported type, so we should never get here but we'll handle it - // here anyway for robustness. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid resource type`, - Detail: fmt.Sprintf(`A %s resource type %q is not supported by provider %q.`, modeAdjective, addr.Type, providerType), - Subject: rng.ToHCL().Ptr(), - }) - return diags - } - - // As a special case we'll detect attempts to access an attribute called - // "count" and produce a special error for it, since versions of Terraform - // prior to v0.12 offered this as a weird special case that we can no - // longer support. - if len(remain) > 0 { - if step, ok := remain[0].(hcl.TraverseAttr); ok && step.Name == "count" { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid resource count attribute`, - Detail: fmt.Sprintf(`The special "count" attribute is no longer supported after Terraform v0.12. Instead, use length(%s) to count resource instances.`, addr), - Subject: rng.ToHCL().Ptr(), - }) - return diags - } - } - - // If we got this far then we'll try to validate the remaining traversal - // steps against our schema. - moreDiags := schema.StaticValidateTraversal(remain) - diags = diags.Append(moreDiags) - - return diags -} - -func (d *evaluationStateData) staticValidateModuleCallReference(modCfg *configs.Config, addr addrs.ModuleCall, remain hcl.Traversal, rng tfdiags.SourceRange) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - // For now, our focus here is just in testing that the referenced module - // call exists. All other validation is deferred until evaluation time. - _, exists := modCfg.Module.ModuleCalls[addr.Name] - if !exists { - var suggestions []string - for name := range modCfg.Module.ModuleCalls { - suggestions = append(suggestions, name) - } - sort.Strings(suggestions) - suggestion := didyoumean.NameSuggestion(addr.Name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared module`, - Detail: fmt.Sprintf(`No module call named %q is declared in %s.%s`, addr.Name, moduleConfigDisplayAddr(modCfg.Path), suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return diags - } - - return diags -} - -// moduleConfigDisplayAddr returns a string describing the given module -// address that is appropriate for returning to users in situations where the -// root module is possible. Specifically, it returns "the root module" if the -// root module instance is given, or a string representation of the module -// address otherwise. -func moduleConfigDisplayAddr(addr addrs.Module) string { - switch { - case addr.IsRoot(): - return "the root module" - default: - return addr.String() - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph.go b/vendor/github.com/hashicorp/terraform/terraform/graph.go index 58d45a7b..735ec4ec 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph.go @@ -3,14 +3,18 @@ package terraform import ( "fmt" "log" - - "github.com/hashicorp/terraform/tfdiags" - - "github.com/hashicorp/terraform/addrs" + "runtime/debug" + "strings" "github.com/hashicorp/terraform/dag" ) +// RootModuleName is the name given to the root module implicitly. +const RootModuleName = "root" + +// RootModulePath is the path for the root module. +var RootModulePath = []string{RootModuleName} + // Graph represents the graph that Terraform uses to represent resources // and their dependencies. type Graph struct { @@ -19,7 +23,9 @@ type Graph struct { dag.AcyclicGraph // Path is the path in the module tree that this Graph represents. - Path addrs.ModuleInstance + // The root is represented by a single element list containing + // RootModuleName + Path []string // debugName is a name for reference in the debug output. This is usually // to indicate what topmost builder was, and if this graph is a shadow or @@ -34,42 +40,71 @@ func (g *Graph) DirectedGraph() dag.Grapher { // Walk walks the graph with the given walker for callbacks. The graph // will be walked with full parallelism, so the walker should expect // to be called in concurrently. -func (g *Graph) Walk(walker GraphWalker) tfdiags.Diagnostics { +func (g *Graph) Walk(walker GraphWalker) error { return g.walk(walker) } -func (g *Graph) walk(walker GraphWalker) tfdiags.Diagnostics { +func (g *Graph) walk(walker GraphWalker) error { // The callbacks for enter/exiting a graph ctx := walker.EnterPath(g.Path) defer walker.ExitPath(g.Path) // Get the path for logs - path := ctx.Path().String() + path := strings.Join(ctx.Path(), ".") + + // Determine if our walker is a panic wrapper + panicwrap, ok := walker.(GraphWalkerPanicwrapper) + if !ok { + panicwrap = nil // just to be sure + } debugName := "walk-graph.json" if g.debugName != "" { debugName = g.debugName + "-" + debugName } + debugBuf := dbug.NewFileWriter(debugName) + g.SetDebugWriter(debugBuf) + defer debugBuf.Close() + // Walk the graph. var walkFn dag.WalkFunc - walkFn = func(v dag.Vertex) (diags tfdiags.Diagnostics) { - log.Printf("[TRACE] vertex %q: starting visit (%T)", dag.VertexName(v), v) + walkFn = func(v dag.Vertex) (rerr error) { + log.Printf("[TRACE] vertex '%s.%s': walking", path, dag.VertexName(v)) g.DebugVisitInfo(v, g.debugName) + // If we have a panic wrap GraphWalker and a panic occurs, recover + // and call that. We ensure the return value is an error, however, + // so that future nodes are not called. defer func() { - log.Printf("[TRACE] vertex %q: visit complete", dag.VertexName(v)) + // If no panicwrap, do nothing + if panicwrap == nil { + return + } + + // If no panic, do nothing + err := recover() + if err == nil { + return + } + + // Modify the return value to show the error + rerr = fmt.Errorf("vertex %q captured panic: %s\n\n%s", + dag.VertexName(v), err, debug.Stack()) + + // Call the panic wrapper + panicwrap.Panic(v, err) }() walker.EnterVertex(v) - defer walker.ExitVertex(v, diags) + defer walker.ExitVertex(v, rerr) // vertexCtx is the context that we use when evaluating. This // is normally the context of our graph but can be overridden // with a GraphNodeSubPath impl. vertexCtx := ctx if pn, ok := v.(GraphNodeSubPath); ok && len(pn.Path()) > 0 { - vertexCtx = walker.EnterPath(pn.Path()) + vertexCtx = walker.EnterPath(normalizeModulePath(pn.Path())) defer walker.ExitPath(pn.Path()) } @@ -77,64 +112,60 @@ func (g *Graph) walk(walker GraphWalker) tfdiags.Diagnostics { if ev, ok := v.(GraphNodeEvalable); ok { tree := ev.EvalTree() if tree == nil { - panic(fmt.Sprintf("%q (%T): nil eval tree", dag.VertexName(v), v)) + panic(fmt.Sprintf( + "%s.%s (%T): nil eval tree", path, dag.VertexName(v), v)) } // Allow the walker to change our tree if needed. Eval, // then callback with the output. - log.Printf("[TRACE] vertex %q: evaluating", dag.VertexName(v)) + log.Printf("[TRACE] vertex '%s.%s': evaluating", path, dag.VertexName(v)) g.DebugVertexInfo(v, fmt.Sprintf("evaluating %T(%s)", v, path)) tree = walker.EnterEvalTree(v, tree) output, err := Eval(tree, vertexCtx) - diags = diags.Append(walker.ExitEvalTree(v, output, err)) - if diags.HasErrors() { + if rerr = walker.ExitEvalTree(v, output, err); rerr != nil { return } } // If the node is dynamically expanded, then expand it if ev, ok := v.(GraphNodeDynamicExpandable); ok { - log.Printf("[TRACE] vertex %q: expanding dynamic subgraph", dag.VertexName(v)) + log.Printf( + "[TRACE] vertex '%s.%s': expanding/walking dynamic subgraph", + path, + dag.VertexName(v)) g.DebugVertexInfo(v, fmt.Sprintf("expanding %T(%s)", v, path)) g, err := ev.DynamicExpand(vertexCtx) if err != nil { - diags = diags.Append(err) + rerr = err return } if g != nil { // Walk the subgraph - log.Printf("[TRACE] vertex %q: entering dynamic subgraph", dag.VertexName(v)) - subDiags := g.walk(walker) - diags = diags.Append(subDiags) - if subDiags.HasErrors() { - log.Printf("[TRACE] vertex %q: dynamic subgraph encountered errors", dag.VertexName(v)) + if rerr = g.walk(walker); rerr != nil { return } - log.Printf("[TRACE] vertex %q: dynamic subgraph completed successfully", dag.VertexName(v)) - } else { - log.Printf("[TRACE] vertex %q: produced no dynamic subgraph", dag.VertexName(v)) } } // If the node has a subgraph, then walk the subgraph if sn, ok := v.(GraphNodeSubgraph); ok { - log.Printf("[TRACE] vertex %q: entering static subgraph", dag.VertexName(v)) + log.Printf( + "[TRACE] vertex '%s.%s': walking subgraph", + path, + dag.VertexName(v)) g.DebugVertexInfo(v, fmt.Sprintf("subgraph: %T(%s)", v, path)) - subDiags := sn.Subgraph().(*Graph).walk(walker) - if subDiags.HasErrors() { - log.Printf("[TRACE] vertex %q: static subgraph encountered errors", dag.VertexName(v)) + if rerr = sn.Subgraph().(*Graph).walk(walker); rerr != nil { return } - log.Printf("[TRACE] vertex %q: static subgraph completed successfully", dag.VertexName(v)) } - return + return nil } return g.AcyclicGraph.Walk(walkFn) diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder.go index 66b21f30..6374bb90 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder.go @@ -4,10 +4,6 @@ import ( "fmt" "log" "strings" - - "github.com/hashicorp/terraform/tfdiags" - - "github.com/hashicorp/terraform/addrs" ) // GraphBuilder is an interface that can be implemented and used with @@ -16,7 +12,7 @@ type GraphBuilder interface { // Build builds the graph for the given module path. It is up to // the interface implementation whether this build should expand // the graph or not. - Build(addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) + Build(path []string) (*Graph, error) } // BasicGraphBuilder is a GraphBuilder that builds a graph out of a @@ -29,16 +25,21 @@ type BasicGraphBuilder struct { Name string } -func (b *BasicGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics +func (b *BasicGraphBuilder) Build(path []string) (*Graph, error) { g := &Graph{Path: path} - var lastStepStr string + debugName := "graph.json" + if b.Name != "" { + debugName = b.Name + "-" + debugName + } + debugBuf := dbug.NewFileWriter(debugName) + g.SetDebugWriter(debugBuf) + defer debugBuf.Close() + for _, step := range b.Steps { if step == nil { continue } - log.Printf("[TRACE] Executing graph transform %T", step) stepName := fmt.Sprintf("%T", step) dot := strings.LastIndex(stepName, ".") @@ -55,20 +56,12 @@ func (b *BasicGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Di } debugOp.End(errMsg) - if thisStepStr := g.StringWithNodeTypes(); thisStepStr != lastStepStr { - log.Printf("[TRACE] Completed graph transform %T with new graph:\n%s------", step, thisStepStr) - lastStepStr = thisStepStr - } else { - log.Printf("[TRACE] Completed graph transform %T (no changes)", step) - } + log.Printf( + "[TRACE] Graph after step %T:\n\n%s", + step, g.StringWithNodeTypes()) if err != nil { - if nf, isNF := err.(tfdiags.NonFatalError); isNF { - diags = diags.Append(nf.Diagnostics) - } else { - diags = diags.Append(err) - return g, diags - } + return g, err } } @@ -76,10 +69,9 @@ func (b *BasicGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Di if b.Validate { if err := g.Validate(); err != nil { log.Printf("[ERROR] Graph validation failed. Graph:\n\n%s", g.String()) - diags = diags.Append(err) - return nil, diags + return nil, err } } - return g, diags + return g, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_apply.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_apply.go index 7182dd7d..0c2b2332 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_apply.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_apply.go @@ -1,12 +1,8 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // ApplyGraphBuilder implements GraphBuilder and is responsible for building @@ -17,28 +13,26 @@ import ( // that aren't explicitly in the diff. There are other scenarios where the // diff can be deviated, so this is just one layer of protection. type ApplyGraphBuilder struct { - // Config is the configuration tree that the diff was built from. - Config *configs.Config + // Module is the root module for the graph to build. + Module *module.Tree - // Changes describes the changes that we need apply. - Changes *plans.Changes + // Diff is the diff to apply. + Diff *Diff // State is the current state - State *states.State + State *State - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory + // Providers is the list of providers supported. + Providers []string - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas + // Provisioners is the list of provisioners supported. + Provisioners []string // Targets are resources to target. This is only required to make sure // unnecessary outputs aren't included in the apply graph. The plan // builder successfully handles targeting resources. In the future, // outputs should go into the diff so that this is unnecessary. - Targets []addrs.Targetable + Targets []string // DisableReduce, if true, will not reduce the graph. Great for testing. DisableReduce bool @@ -51,7 +45,7 @@ type ApplyGraphBuilder struct { } // See GraphBuilder -func (b *ApplyGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { +func (b *ApplyGraphBuilder) Build(path []string) (*Graph, error) { return (&BasicGraphBuilder{ Steps: b.Steps(), Validate: b.Validate, @@ -74,99 +68,53 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { } } - concreteOrphanResource := func(a *NodeAbstractResource) dag.Vertex { - return &NodeDestroyResource{ - NodeAbstractResource: a, - } - } - - concreteResourceInstance := func(a *NodeAbstractResourceInstance) dag.Vertex { - return &NodeApplyableResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - steps := []GraphTransformer{ - // Creates all the resources represented in the config. During apply, - // we use this just to ensure that the whole-resource metadata is - // updated to reflect things such as whether the count argument is - // set in config, or which provider configuration manages each resource. - &ConfigTransformer{ - Concrete: concreteResource, - Config: b.Config, - }, - - // Creates all the resource instances represented in the diff, along - // with dependency edges against the whole-resource nodes added by - // ConfigTransformer above. + // Creates all the nodes represented in the diff. &DiffTransformer{ - Concrete: concreteResourceInstance, - State: b.State, - Changes: b.Changes, - }, + Concrete: concreteResource, - // Creates extra cleanup nodes for any entire resources that are - // no longer present in config, so we can make sure we clean up the - // leftover empty resource states after the instances have been - // destroyed. - // (We don't track this particular type of change in the plan because - // it's just cleanup of our own state object, and so doesn't effect - // any real remote objects or consumable outputs.) - &OrphanResourceTransformer{ - Concrete: concreteOrphanResource, - Config: b.Config, - State: b.State, + Diff: b.Diff, + Module: b.Module, + State: b.State, }, // Create orphan output nodes - &OrphanOutputTransformer{Config: b.Config, State: b.State}, + &OrphanOutputTransformer{Module: b.Module, State: b.State}, // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, + &AttachResourceConfigTransformer{Module: b.Module}, // Attach the state &AttachStateTransformer{State: b.State}, + // add providers + TransformProviders(b.Providers, concreteProvider, b.Module), + // Destruction ordering - &DestroyEdgeTransformer{ - Config: b.Config, - State: b.State, - Schemas: b.Schemas, - }, + &DestroyEdgeTransformer{Module: b.Module, State: b.State}, GraphTransformIf( func() bool { return !b.Destroy }, - &CBDEdgeTransformer{ - Config: b.Config, - State: b.State, - Schemas: b.Schemas, - }, + &CBDEdgeTransformer{Module: b.Module, State: b.State}, ), // Provisioner-related transformations - &MissingProvisionerTransformer{Provisioners: b.Components.ResourceProvisioners()}, + &MissingProvisionerTransformer{Provisioners: b.Provisioners}, &ProvisionerTransformer{}, // Add root variables - &RootVariableTransformer{Config: b.Config}, + &RootVariableTransformer{Module: b.Module}, // Add the local values - &LocalTransformer{Config: b.Config}, + &LocalTransformer{Module: b.Module}, // Add the outputs - &OutputTransformer{Config: b.Config}, + &OutputTransformer{Module: b.Module}, // Add module variables - &ModuleVariableTransformer{Config: b.Config}, - - // add providers - TransformProviders(b.Components.ResourceProviders(), concreteProvider, b.Config), + &ModuleVariableTransformer{Module: b.Module}, // Remove modules no longer present in the config - &RemovedModuleTransformer{Config: b.Config, State: b.State}, - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, + &RemovedModuleTransformer{Module: b.Module, State: b.State}, // Connect references so ordering is correct &ReferenceTransformer{}, @@ -187,9 +135,7 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { ), // Add the node to fix the state count boundaries - &CountBoundaryTransformer{ - Config: b.Config, - }, + &CountBoundaryTransformer{}, // Target &TargetsTransformer{Targets: b.Targets}, diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_destroy_plan.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_destroy_plan.go index a6047a9b..014b348e 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_destroy_plan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_destroy_plan.go @@ -1,11 +1,8 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // DestroyPlanGraphBuilder implements GraphBuilder and is responsible for @@ -14,29 +11,21 @@ import ( // Planning a pure destroy operation is simple because we can ignore most // ordering configuration and simply reverse the state. type DestroyPlanGraphBuilder struct { - // Config is the configuration tree to build the plan from. - Config *configs.Config + // Module is the root module for the graph to build. + Module *module.Tree // State is the current state - State *states.State - - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas + State *State // Targets are resources to target - Targets []addrs.Targetable + Targets []string // Validate will do structural validation of the graph. Validate bool } // See GraphBuilder -func (b *DestroyPlanGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { +func (b *DestroyPlanGraphBuilder) Build(path []string) (*Graph, error) { return (&BasicGraphBuilder{ Steps: b.Steps(), Validate: b.Validate, @@ -46,44 +35,25 @@ func (b *DestroyPlanGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdi // See GraphBuilder func (b *DestroyPlanGraphBuilder) Steps() []GraphTransformer { - concreteResourceInstance := func(a *NodeAbstractResourceInstance) dag.Vertex { - return &NodePlanDestroyableResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - concreteResourceInstanceDeposed := func(a *NodeAbstractResourceInstance, key states.DeposedKey) dag.Vertex { - return &NodePlanDeposedResourceInstanceObject{ - NodeAbstractResourceInstance: a, - DeposedKey: key, - } - } - - concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{ - NodeAbstractProvider: a, + concreteResource := func(a *NodeAbstractResource) dag.Vertex { + return &NodePlanDestroyableResource{ + NodeAbstractResource: a, } } steps := []GraphTransformer{ - // Creates nodes for the resource instances tracked in the state. + // Creates all the nodes represented in the state. &StateTransformer{ - ConcreteCurrent: concreteResourceInstance, - ConcreteDeposed: concreteResourceInstanceDeposed, - State: b.State, + Concrete: concreteResource, + State: b.State, }, // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, - - TransformProviders(b.Components.ResourceProviders(), concreteProvider, b.Config), + &AttachResourceConfigTransformer{Module: b.Module}, // Destruction ordering. We require this only so that // targeting below will prune the correct things. - &DestroyEdgeTransformer{ - Config: b.Config, - State: b.State, - Schemas: b.Schemas, - }, + &DestroyEdgeTransformer{Module: b.Module, State: b.State}, // Target. Note we don't set "Destroy: true" here since we already // created proper destroy ordering. diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_eval.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_eval.go deleted file mode 100644 index eb6c897b..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_eval.go +++ /dev/null @@ -1,108 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" -) - -// EvalGraphBuilder implements GraphBuilder and constructs a graph suitable -// for evaluating in-memory values (input variables, local values, output -// values) in the state without any other side-effects. -// -// This graph is used only in weird cases, such as the "terraform console" -// CLI command, where we need to evaluate expressions against the state -// without taking any other actions. -// -// The generated graph will include nodes for providers, resources, etc -// just to allow indirect dependencies to be resolved, but these nodes will -// not take any actions themselves since we assume that their parts of the -// state, if any, are already complete. -// -// Although the providers are never configured, they must still be available -// in order to obtain schema information used for type checking, etc. -type EvalGraphBuilder struct { - // Config is the configuration tree. - Config *configs.Config - - // State is the current state - State *states.State - - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas -} - -// See GraphBuilder -func (b *EvalGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - return (&BasicGraphBuilder{ - Steps: b.Steps(), - Validate: true, - Name: "EvalGraphBuilder", - }).Build(path) -} - -// See GraphBuilder -func (b *EvalGraphBuilder) Steps() []GraphTransformer { - concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeEvalableProvider{ - NodeAbstractProvider: a, - } - } - - steps := []GraphTransformer{ - // Creates all the data resources that aren't in the state. This will also - // add any orphans from scaling in as destroy nodes. - &ConfigTransformer{ - Concrete: nil, // just use the abstract type - Config: b.Config, - Unique: true, - }, - - // Attach the state - &AttachStateTransformer{State: b.State}, - - // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, - - // Add root variables - &RootVariableTransformer{Config: b.Config}, - - // Add the local values - &LocalTransformer{Config: b.Config}, - - // Add the outputs - &OutputTransformer{Config: b.Config}, - - // Add module variables - &ModuleVariableTransformer{Config: b.Config}, - - TransformProviders(b.Components.ResourceProviders(), concreteProvider, b.Config), - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, - - // Connect so that the references are ready for targeting. We'll - // have to connect again later for providers and so on. - &ReferenceTransformer{}, - - // Although we don't configure providers, we do still start them up - // to get their schemas, and so we must shut them down again here. - &CloseProviderTransformer{}, - - // Single root - &RootTransformer{}, - - // Remove redundant edges to simplify the graph. - &TransitiveReductionTransformer{}, - } - - return steps -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_import.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_import.go index 7b0e39f4..07a1eaf8 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_import.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_import.go @@ -1,10 +1,8 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/tfdiags" ) // ImportGraphBuilder implements GraphBuilder and is responsible for building @@ -14,19 +12,15 @@ type ImportGraphBuilder struct { // ImportTargets are the list of resources to import. ImportTargets []*ImportTarget - // Module is a configuration to build the graph from. See ImportOpts.Config. - Config *configs.Config + // Module is the module to add to the graph. See ImportOpts.Module. + Module *module.Tree - // Components is the factory for our available plugin components. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas + // Providers is the list of providers supported. + Providers []string } // Build builds the graph according to the steps returned by Steps. -func (b *ImportGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { +func (b *ImportGraphBuilder) Build(path []string) (*Graph, error) { return (&BasicGraphBuilder{ Steps: b.Steps(), Validate: true, @@ -39,9 +33,9 @@ func (b *ImportGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.D func (b *ImportGraphBuilder) Steps() []GraphTransformer { // Get the module. If we don't have one, we just use an empty tree // so that the transform still works but does nothing. - config := b.Config - if config == nil { - config = configs.NewEmptyConfig() + mod := b.Module + if mod == nil { + mod = module.NewEmptyTree() } // Custom factory for creating providers. @@ -53,36 +47,16 @@ func (b *ImportGraphBuilder) Steps() []GraphTransformer { steps := []GraphTransformer{ // Create all our resources from the configuration and state - &ConfigTransformer{Config: config}, + &ConfigTransformer{Module: mod}, // Add the import steps &ImportStateTransformer{Targets: b.ImportTargets}, - // Add root variables - &RootVariableTransformer{Config: b.Config}, - - TransformProviders(b.Components.ResourceProviders(), concreteProvider, config), + TransformProviders(b.Providers, concreteProvider, mod), // This validates that the providers only depend on variables &ImportProviderValidateTransformer{}, - // Add the local values - &LocalTransformer{Config: b.Config}, - - // Add the outputs - &OutputTransformer{Config: b.Config}, - - // Add module variables - &ModuleVariableTransformer{Config: b.Config}, - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, - - // Connect so that the references are ready for targeting. We'll - // have to connect again later for providers and so on. - &ReferenceTransformer{}, - // Close opened plugin connections &CloseProviderTransformer{}, diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_input.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_input.go new file mode 100644 index 00000000..0df48cdb --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_input.go @@ -0,0 +1,27 @@ +package terraform + +import ( + "github.com/hashicorp/terraform/dag" +) + +// InputGraphBuilder creates the graph for the input operation. +// +// Unlike other graph builders, this is a function since it currently modifies +// and is based on the PlanGraphBuilder. The PlanGraphBuilder passed in will be +// modified and should not be used for any other operations. +func InputGraphBuilder(p *PlanGraphBuilder) GraphBuilder { + // We're going to customize the concrete functions + p.CustomConcrete = true + + // Set the provider to the normal provider. This will ask for input. + p.ConcreteProvider = func(a *NodeAbstractProvider) dag.Vertex { + return &NodeApplyableProvider{ + NodeAbstractProvider: a, + } + } + + // We purposely don't set any more concrete fields since the remainder + // should be no-ops. + + return p +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_plan.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_plan.go index 17adfd27..f8dd0fc9 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_plan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_plan.go @@ -3,11 +3,8 @@ package terraform import ( "sync" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // PlanGraphBuilder implements GraphBuilder and is responsible for building @@ -22,22 +19,20 @@ import ( // create-before-destroy can be completely ignored. // type PlanGraphBuilder struct { - // Config is the configuration tree to build a plan from. - Config *configs.Config + // Module is the root module for the graph to build. + Module *module.Tree // State is the current state - State *states.State + State *State - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory + // Providers is the list of providers supported. + Providers []string - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas + // Provisioners is the list of provisioners supported. + Provisioners []string // Targets are resources to target - Targets []addrs.Targetable + Targets []string // DisableReduce, if true, will not reduce the graph. Great for testing. DisableReduce bool @@ -51,13 +46,13 @@ type PlanGraphBuilder struct { CustomConcrete bool ConcreteProvider ConcreteProviderNodeFunc ConcreteResource ConcreteResourceNodeFunc - ConcreteResourceOrphan ConcreteResourceInstanceNodeFunc + ConcreteResourceOrphan ConcreteResourceNodeFunc once sync.Once } // See GraphBuilder -func (b *PlanGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { +func (b *PlanGraphBuilder) Build(path []string) (*Graph, error) { return (&BasicGraphBuilder{ Steps: b.Steps(), Validate: b.Validate, @@ -69,82 +64,66 @@ func (b *PlanGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Dia func (b *PlanGraphBuilder) Steps() []GraphTransformer { b.once.Do(b.init) - concreteResourceInstanceDeposed := func(a *NodeAbstractResourceInstance, key states.DeposedKey) dag.Vertex { - return &NodePlanDeposedResourceInstanceObject{ - NodeAbstractResourceInstance: a, - DeposedKey: key, - } - } - steps := []GraphTransformer{ // Creates all the resources represented in the config &ConfigTransformer{ Concrete: b.ConcreteResource, - Config: b.Config, + Module: b.Module, }, // Add the local values - &LocalTransformer{Config: b.Config}, + &LocalTransformer{Module: b.Module}, // Add the outputs - &OutputTransformer{Config: b.Config}, + &OutputTransformer{Module: b.Module}, // Add orphan resources - &OrphanResourceInstanceTransformer{ + &OrphanResourceTransformer{ Concrete: b.ConcreteResourceOrphan, State: b.State, - Config: b.Config, - }, - - // We also need nodes for any deposed instance objects present in the - // state, so we can plan to destroy them. (This intentionally - // skips creating nodes for _current_ objects, since ConfigTransformer - // created nodes that will do that during DynamicExpand.) - &StateTransformer{ - ConcreteDeposed: concreteResourceInstanceDeposed, - State: b.State, + Module: b.Module, }, // Create orphan output nodes &OrphanOutputTransformer{ - Config: b.Config, + Module: b.Module, State: b.State, }, // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, + &AttachResourceConfigTransformer{Module: b.Module}, // Attach the state &AttachStateTransformer{State: b.State}, // Add root variables - &RootVariableTransformer{Config: b.Config}, + &RootVariableTransformer{Module: b.Module}, - &MissingProvisionerTransformer{Provisioners: b.Components.ResourceProvisioners()}, - &ProvisionerTransformer{}, + TransformProviders(b.Providers, b.ConcreteProvider, b.Module), + + // Provisioner-related transformations. Only add these if requested. + GraphTransformIf( + func() bool { return b.Provisioners != nil }, + GraphTransformMulti( + &MissingProvisionerTransformer{Provisioners: b.Provisioners}, + &ProvisionerTransformer{}, + ), + ), // Add module variables &ModuleVariableTransformer{ - Config: b.Config, + Module: b.Module, }, - TransformProviders(b.Components.ResourceProviders(), b.ConcreteProvider, b.Config), - // Remove modules no longer present in the config - &RemovedModuleTransformer{Config: b.Config, State: b.State}, - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, + &RemovedModuleTransformer{Module: b.Module, State: b.State}, // Connect so that the references are ready for targeting. We'll // have to connect again later for providers and so on. &ReferenceTransformer{}, // Add the node to fix the state count boundaries - &CountBoundaryTransformer{ - Config: b.Config, - }, + &CountBoundaryTransformer{}, // Target &TargetsTransformer{ @@ -157,10 +136,6 @@ func (b *PlanGraphBuilder) Steps() []GraphTransformer { IgnoreIndices: true, }, - // Detect when create_before_destroy must be forced on for a particular - // node due to dependency edges, to avoid graph cycles during apply. - &ForcedCBDTransformer{}, - // Close opened plugin connections &CloseProviderTransformer{}, &CloseProvisionerTransformer{}, @@ -192,13 +167,15 @@ func (b *PlanGraphBuilder) init() { b.ConcreteResource = func(a *NodeAbstractResource) dag.Vertex { return &NodePlannableResource{ - NodeAbstractResource: a, + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: a, + }, } } - b.ConcreteResourceOrphan = func(a *NodeAbstractResourceInstance) dag.Vertex { - return &NodePlannableResourceInstanceOrphan{ - NodeAbstractResourceInstance: a, + b.ConcreteResourceOrphan = func(a *NodeAbstractResource) dag.Vertex { + return &NodePlannableResourceOrphan{ + NodeAbstractResource: a, } } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_refresh.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_refresh.go index 0342cdbe..9638d4c8 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_refresh.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_refresh.go @@ -3,11 +3,8 @@ package terraform import ( "log" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" ) @@ -24,22 +21,17 @@ import ( // create-before-destroy can be completely ignored. // type RefreshGraphBuilder struct { - // Config is the configuration tree. - Config *configs.Config + // Module is the root module for the graph to build. + Module *module.Tree - // State is the prior state - State *states.State + // State is the current state + State *State - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas + // Providers is the list of providers supported. + Providers []string // Targets are resources to target - Targets []addrs.Targetable + Targets []string // DisableReduce, if true, will not reduce the graph. Great for testing. DisableReduce bool @@ -49,7 +41,7 @@ type RefreshGraphBuilder struct { } // See GraphBuilder -func (b *RefreshGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { +func (b *RefreshGraphBuilder) Build(path []string) (*Graph, error) { return (&BasicGraphBuilder{ Steps: b.Steps(), Validate: b.Validate, @@ -68,27 +60,23 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { concreteManagedResource := func(a *NodeAbstractResource) dag.Vertex { return &NodeRefreshableManagedResource{ - NodeAbstractResource: a, + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: a, + }, } } - concreteManagedResourceInstance := func(a *NodeAbstractResourceInstance) dag.Vertex { + concreteManagedResourceInstance := func(a *NodeAbstractResource) dag.Vertex { return &NodeRefreshableManagedResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - - concreteResourceInstanceDeposed := func(a *NodeAbstractResourceInstance, key states.DeposedKey) dag.Vertex { - // The "Plan" node type also handles refreshing behavior. - return &NodePlanDeposedResourceInstanceObject{ - NodeAbstractResourceInstance: a, - DeposedKey: key, + NodeAbstractResource: a, } } concreteDataResource := func(a *NodeAbstractResource) dag.Vertex { return &NodeRefreshableDataResource{ - NodeAbstractResource: a, + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: a, + }, } } @@ -100,13 +88,13 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { if b.State.HasResources() { return &ConfigTransformer{ Concrete: concreteManagedResource, - Config: b.Config, + Module: b.Module, Unique: true, ModeFilter: true, - Mode: addrs.ManagedResourceMode, + Mode: config.ManagedResourceMode, } } - log.Println("[TRACE] No managed resources in state during refresh; skipping managed resource transformer") + log.Println("[TRACE] No managed resources in state during refresh, skipping managed resource transformer") return nil }(), @@ -114,53 +102,40 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { // add any orphans from scaling in as destroy nodes. &ConfigTransformer{ Concrete: concreteDataResource, - Config: b.Config, + Module: b.Module, Unique: true, ModeFilter: true, - Mode: addrs.DataResourceMode, + Mode: config.DataResourceMode, }, // Add any fully-orphaned resources from config (ones that have been // removed completely, not ones that are just orphaned due to a scaled-in // count. - &OrphanResourceInstanceTransformer{ + &OrphanResourceTransformer{ Concrete: concreteManagedResourceInstance, State: b.State, - Config: b.Config, - }, - - // We also need nodes for any deposed instance objects present in the - // state, so we can check if they still exist. (This intentionally - // skips creating nodes for _current_ objects, since ConfigTransformer - // created nodes that will do that during DynamicExpand.) - &StateTransformer{ - ConcreteDeposed: concreteResourceInstanceDeposed, - State: b.State, + Module: b.Module, }, // Attach the state &AttachStateTransformer{State: b.State}, // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, + &AttachResourceConfigTransformer{Module: b.Module}, // Add root variables - &RootVariableTransformer{Config: b.Config}, + &RootVariableTransformer{Module: b.Module}, + + TransformProviders(b.Providers, concreteProvider, b.Module), // Add the local values - &LocalTransformer{Config: b.Config}, + &LocalTransformer{Module: b.Module}, // Add the outputs - &OutputTransformer{Config: b.Config}, + &OutputTransformer{Module: b.Module}, // Add module variables - &ModuleVariableTransformer{Config: b.Config}, - - TransformProviders(b.Components.ResourceProviders(), concreteProvider, b.Config), - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, + &ModuleVariableTransformer{Module: b.Module}, // Connect so that the references are ready for targeting. We'll // have to connect again later for providers and so on. diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_validate.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_validate.go index 1881f95f..645ec7be 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_validate.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_validate.go @@ -23,7 +23,9 @@ func ValidateGraphBuilder(p *PlanGraphBuilder) GraphBuilder { p.ConcreteResource = func(a *NodeAbstractResource) dag.Vertex { return &NodeValidatableResource{ - NodeAbstractResource: a, + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: a, + }, } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_interface_subgraph.go b/vendor/github.com/hashicorp/terraform/terraform/graph_interface_subgraph.go index 768590fb..2897eb54 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_interface_subgraph.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_interface_subgraph.go @@ -1,11 +1,7 @@ package terraform -import ( - "github.com/hashicorp/terraform/addrs" -) - // GraphNodeSubPath says that a node is part of a graph with a // different path, and the context should be adjusted accordingly. type GraphNodeSubPath interface { - Path() addrs.ModuleInstance + Path() []string } diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_walk.go b/vendor/github.com/hashicorp/terraform/terraform/graph_walk.go index e980e0c6..34ce6f64 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_walk.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_walk.go @@ -1,32 +1,60 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/tfdiags" ) // GraphWalker is an interface that can be implemented that when used // with Graph.Walk will invoke the given callbacks under certain events. type GraphWalker interface { - EnterPath(addrs.ModuleInstance) EvalContext - ExitPath(addrs.ModuleInstance) + EnterPath([]string) EvalContext + ExitPath([]string) EnterVertex(dag.Vertex) - ExitVertex(dag.Vertex, tfdiags.Diagnostics) + ExitVertex(dag.Vertex, error) EnterEvalTree(dag.Vertex, EvalNode) EvalNode - ExitEvalTree(dag.Vertex, interface{}, error) tfdiags.Diagnostics + ExitEvalTree(dag.Vertex, interface{}, error) error } +// GrpahWalkerPanicwrapper can be optionally implemented to catch panics +// that occur while walking the graph. This is not generally recommended +// since panics should crash Terraform and result in a bug report. However, +// this is particularly useful for situations like the shadow graph where +// you don't ever want to cause a panic. +type GraphWalkerPanicwrapper interface { + GraphWalker + + // Panic is called when a panic occurs. This will halt the panic from + // propogating so if the walker wants it to crash still it should panic + // again. This is called from within a defer so runtime/debug.Stack can + // be used to get the stack trace of the panic. + Panic(dag.Vertex, interface{}) +} + +// GraphWalkerPanicwrap wraps an existing Graphwalker to wrap and swallow +// the panics. This doesn't lose the panics since the panics are still +// returned as errors as part of a graph walk. +func GraphWalkerPanicwrap(w GraphWalker) GraphWalkerPanicwrapper { + return &graphWalkerPanicwrapper{ + GraphWalker: w, + } +} + +type graphWalkerPanicwrapper struct { + GraphWalker +} + +func (graphWalkerPanicwrapper) Panic(dag.Vertex, interface{}) {} + // NullGraphWalker is a GraphWalker implementation that does nothing. // This can be embedded within other GraphWalker implementations for easily // implementing all the required functions. type NullGraphWalker struct{} -func (NullGraphWalker) EnterPath(addrs.ModuleInstance) EvalContext { return new(MockEvalContext) } -func (NullGraphWalker) ExitPath(addrs.ModuleInstance) {} +func (NullGraphWalker) EnterPath([]string) EvalContext { return new(MockEvalContext) } +func (NullGraphWalker) ExitPath([]string) {} func (NullGraphWalker) EnterVertex(dag.Vertex) {} -func (NullGraphWalker) ExitVertex(dag.Vertex, tfdiags.Diagnostics) {} +func (NullGraphWalker) ExitVertex(dag.Vertex, error) {} func (NullGraphWalker) EnterEvalTree(v dag.Vertex, n EvalNode) EvalNode { return n } -func (NullGraphWalker) ExitEvalTree(dag.Vertex, interface{}, error) tfdiags.Diagnostics { +func (NullGraphWalker) ExitEvalTree(dag.Vertex, interface{}, error) error { return nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_walk_context.go b/vendor/github.com/hashicorp/terraform/terraform/graph_walk_context.go index 03c192a8..89f376e5 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_walk_context.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_walk_context.go @@ -2,19 +2,12 @@ package terraform import ( "context" + "fmt" "log" "sync" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" + "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // ContextGraphWalker is the GraphWalker implementation used with the @@ -23,56 +16,54 @@ type ContextGraphWalker struct { NullGraphWalker // Configurable values - Context *Context - State *states.SyncState // Used for safe concurrent access to state - Changes *plans.ChangesSync // Used for safe concurrent writes to changes - Operation walkOperation - StopContext context.Context - RootVariableValues InputValues + Context *Context + Operation walkOperation + StopContext context.Context - // This is an output. Do not set this, nor read it while a graph walk - // is in progress. - NonFatalDiagnostics tfdiags.Diagnostics + // Outputs, do not set these. Do not read these while the graph + // is being walked. + ValidationWarnings []string + ValidationErrors []error - errorLock sync.Mutex - once sync.Once - contexts map[string]*BuiltinEvalContext - contextLock sync.Mutex - variableValues map[string]map[string]cty.Value - variableValuesLock sync.Mutex - providerCache map[string]providers.Interface - providerSchemas map[string]*ProviderSchema - providerLock sync.Mutex - provisionerCache map[string]provisioners.Interface - provisionerSchemas map[string]*configschema.Block - provisionerLock sync.Mutex + errorLock sync.Mutex + once sync.Once + contexts map[string]*BuiltinEvalContext + contextLock sync.Mutex + interpolaterVars map[string]map[string]interface{} + interpolaterVarLock sync.Mutex + providerCache map[string]ResourceProvider + providerLock sync.Mutex + provisionerCache map[string]ResourceProvisioner + provisionerLock sync.Mutex } -func (w *ContextGraphWalker) EnterPath(path addrs.ModuleInstance) EvalContext { +func (w *ContextGraphWalker) EnterPath(path []string) EvalContext { w.once.Do(w.init) w.contextLock.Lock() defer w.contextLock.Unlock() // If we already have a context for this path cached, use that - key := path.String() + key := PathCacheKey(path) if ctx, ok := w.contexts[key]; ok { return ctx } - // Our evaluator shares some locks with the main context and the walker - // so that we can safely run multiple evaluations at once across - // different modules. - evaluator := &Evaluator{ - Meta: w.Context.meta, - Config: w.Context.config, - Operation: w.Operation, - State: w.State, - Changes: w.Changes, - Schemas: w.Context.schemas, - VariableValues: w.variableValues, - VariableValuesLock: &w.variableValuesLock, + // Setup the variables for this interpolater + variables := make(map[string]interface{}) + if len(path) <= 1 { + for k, v := range w.Context.variables { + variables[k] = v + } } + w.interpolaterVarLock.Lock() + if m, ok := w.interpolaterVars[key]; ok { + for k, v := range m { + variables[k] = v + } + } + w.interpolaterVars[key] = variables + w.interpolaterVarLock.Unlock() ctx := &BuiltinEvalContext{ StopContext: w.StopContext, @@ -80,17 +71,26 @@ func (w *ContextGraphWalker) EnterPath(path addrs.ModuleInstance) EvalContext { Hooks: w.Context.hooks, InputValue: w.Context.uiInput, Components: w.Context.components, - Schemas: w.Context.schemas, ProviderCache: w.providerCache, ProviderInputConfig: w.Context.providerInputConfig, ProviderLock: &w.providerLock, ProvisionerCache: w.provisionerCache, ProvisionerLock: &w.provisionerLock, - ChangesValue: w.Changes, - StateValue: w.State, - Evaluator: evaluator, - VariableValues: w.variableValues, - VariableValuesLock: &w.variableValuesLock, + DiffValue: w.Context.diff, + DiffLock: &w.Context.diffLock, + StateValue: w.Context.state, + StateLock: &w.Context.stateLock, + Interpolater: &Interpolater{ + Operation: w.Operation, + Meta: w.Context.meta, + Module: w.Context.module, + State: w.Context.state, + StateLock: &w.Context.stateLock, + VariableValues: variables, + VariableValuesLock: &w.interpolaterVarLock, + }, + InterpolaterVars: w.interpolaterVars, + InterpolaterVarLock: &w.interpolaterVarLock, } w.contexts[key] = ctx @@ -98,7 +98,8 @@ func (w *ContextGraphWalker) EnterPath(path addrs.ModuleInstance) EvalContext { } func (w *ContextGraphWalker) EnterEvalTree(v dag.Vertex, n EvalNode) EvalNode { - log.Printf("[TRACE] [%s] Entering eval tree: %s", w.Operation, dag.VertexName(v)) + log.Printf("[TRACE] [%s] Entering eval tree: %s", + w.Operation, dag.VertexName(v)) // Acquire a lock on the semaphore w.Context.parallelSem.Acquire() @@ -108,8 +109,10 @@ func (w *ContextGraphWalker) EnterEvalTree(v dag.Vertex, n EvalNode) EvalNode { return EvalFilter(n, EvalNodeFilterOp(w.Operation)) } -func (w *ContextGraphWalker) ExitEvalTree(v dag.Vertex, output interface{}, err error) tfdiags.Diagnostics { - log.Printf("[TRACE] [%s] Exiting eval tree: %s", w.Operation, dag.VertexName(v)) +func (w *ContextGraphWalker) ExitEvalTree( + v dag.Vertex, output interface{}, err error) error { + log.Printf("[TRACE] [%s] Exiting eval tree: %s", + w.Operation, dag.VertexName(v)) // Release the semaphore w.Context.parallelSem.Release() @@ -122,36 +125,30 @@ func (w *ContextGraphWalker) ExitEvalTree(v dag.Vertex, output interface{}, err w.errorLock.Lock() defer w.errorLock.Unlock() - // If the error is non-fatal then we'll accumulate its diagnostics in our - // non-fatal list, rather than returning it directly, so that the graph - // walk can continue. - if nferr, ok := err.(tfdiags.NonFatalError); ok { - log.Printf("[WARN] %s: %s", dag.VertexName(v), nferr) - w.NonFatalDiagnostics = w.NonFatalDiagnostics.Append(nferr.Diagnostics) - return nil + // Try to get a validation error out of it. If its not a validation + // error, then just record the normal error. + verr, ok := err.(*EvalValidateError) + if !ok { + return err } - // Otherwise, we'll let our usual diagnostics machinery figure out how to - // unpack this as one or more diagnostic messages and return that. If we - // get down here then the returned diagnostics will contain at least one - // error, causing the graph walk to halt. - var diags tfdiags.Diagnostics - diags = diags.Append(err) - return diags + for _, msg := range verr.Warnings { + w.ValidationWarnings = append( + w.ValidationWarnings, + fmt.Sprintf("%s: %s", dag.VertexName(v), msg)) + } + for _, e := range verr.Errors { + w.ValidationErrors = append( + w.ValidationErrors, + errwrap.Wrapf(fmt.Sprintf("%s: {{err}}", dag.VertexName(v)), e)) + } + + return nil } func (w *ContextGraphWalker) init() { - w.contexts = make(map[string]*BuiltinEvalContext) - w.providerCache = make(map[string]providers.Interface) - w.providerSchemas = make(map[string]*ProviderSchema) - w.provisionerCache = make(map[string]provisioners.Interface) - w.provisionerSchemas = make(map[string]*configschema.Block) - w.variableValues = make(map[string]map[string]cty.Value) - - // Populate root module variable values. Other modules will be populated - // during the graph walk. - w.variableValues[""] = make(map[string]cty.Value) - for k, iv := range w.RootVariableValues { - w.variableValues[""][k] = iv.Value - } + w.contexts = make(map[string]*BuiltinEvalContext, 5) + w.providerCache = make(map[string]ResourceProvider, 5) + w.provisionerCache = make(map[string]ResourceProvisioner, 5) + w.interpolaterVars = make(map[string]map[string]interface{}, 5) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_walk_operation.go b/vendor/github.com/hashicorp/terraform/terraform/graph_walk_operation.go index a3756e76..3fb37481 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_walk_operation.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_walk_operation.go @@ -7,6 +7,7 @@ type walkOperation byte const ( walkInvalid walkOperation = iota + walkInput walkApply walkPlan walkPlanDestroy @@ -14,5 +15,4 @@ const ( walkValidate walkDestroy walkImport - walkEval // used just to prepare EvalContext for expression evaluation, with no other actions ) diff --git a/vendor/github.com/hashicorp/terraform/terraform/graphtype_string.go b/vendor/github.com/hashicorp/terraform/terraform/graphtype_string.go index 855ef7b1..95ef4e94 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graphtype_string.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graphtype_string.go @@ -4,9 +4,9 @@ package terraform import "strconv" -const _GraphType_name = "GraphTypeInvalidGraphTypeLegacyGraphTypeRefreshGraphTypePlanGraphTypePlanDestroyGraphTypeApplyGraphTypeValidateGraphTypeEval" +const _GraphType_name = "GraphTypeInvalidGraphTypeLegacyGraphTypeRefreshGraphTypePlanGraphTypePlanDestroyGraphTypeApplyGraphTypeInputGraphTypeValidate" -var _GraphType_index = [...]uint8{0, 16, 31, 47, 60, 80, 94, 111, 124} +var _GraphType_index = [...]uint8{0, 16, 31, 47, 60, 80, 94, 108, 125} func (i GraphType) String() string { if i >= GraphType(len(_GraphType_index)-1) { diff --git a/vendor/github.com/hashicorp/terraform/terraform/hook.go b/vendor/github.com/hashicorp/terraform/terraform/hook.go index c0bb23ab..ab11e8ee 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/hook.go +++ b/vendor/github.com/hashicorp/terraform/terraform/hook.go @@ -1,14 +1,5 @@ package terraform -import ( - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" -) - // HookAction is an enum of actions that can be taken as a result of a hook // callback. This allows you to modify the behavior of Terraform at runtime. type HookAction byte @@ -30,56 +21,42 @@ const ( // NilHook into your struct, which implements all of the interface but does // nothing. Then, override only the functions you want to implement. type Hook interface { - // PreApply and PostApply are called before and after an action for a - // single instance is applied. The error argument in PostApply is the + // PreApply and PostApply are called before and after a single + // resource is applied. The error argument in PostApply is the // error, if any, that was returned from the provider Apply call itself. - PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) - PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (HookAction, error) + PreApply(*InstanceInfo, *InstanceState, *InstanceDiff) (HookAction, error) + PostApply(*InstanceInfo, *InstanceState, error) (HookAction, error) - // PreDiff and PostDiff are called before and after a provider is given - // the opportunity to customize the proposed new state to produce the - // planned new state. - PreDiff(addr addrs.AbsResourceInstance, gen states.Generation, priorState, proposedNewState cty.Value) (HookAction, error) - PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) + // PreDiff and PostDiff are called before and after a single resource + // resource is diffed. + PreDiff(*InstanceInfo, *InstanceState) (HookAction, error) + PostDiff(*InstanceInfo, *InstanceDiff) (HookAction, error) - // The provisioning hooks signal both the overall start end end of - // provisioning for a particular instance and of each of the individual - // configured provisioners for each instance. The sequence of these - // for a given instance might look something like this: + // Provisioning hooks // - // PreProvisionInstance(aws_instance.foo[1], ...) - // PreProvisionInstanceStep(aws_instance.foo[1], "file") - // PostProvisionInstanceStep(aws_instance.foo[1], "file", nil) - // PreProvisionInstanceStep(aws_instance.foo[1], "remote-exec") - // ProvisionOutput(aws_instance.foo[1], "remote-exec", "Installing foo...") - // ProvisionOutput(aws_instance.foo[1], "remote-exec", "Configuring bar...") - // PostProvisionInstanceStep(aws_instance.foo[1], "remote-exec", nil) - // PostProvisionInstance(aws_instance.foo[1], ...) - // - // ProvisionOutput is called with output sent back by the provisioners. - // This will be called multiple times as output comes in, with each call - // representing one line of output. It cannot control whether the - // provisioner continues running. - PreProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) - PostProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) - PreProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string) (HookAction, error) - PostProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string, err error) (HookAction, error) - ProvisionOutput(addr addrs.AbsResourceInstance, typeName string, line string) + // All should be self-explanatory. ProvisionOutput is called with + // output sent back by the provisioners. This will be called multiple + // times as output comes in, but each call should represent a line of + // output. The ProvisionOutput method cannot control whether the + // hook continues running. + PreProvisionResource(*InstanceInfo, *InstanceState) (HookAction, error) + PostProvisionResource(*InstanceInfo, *InstanceState) (HookAction, error) + PreProvision(*InstanceInfo, string) (HookAction, error) + PostProvision(*InstanceInfo, string, error) (HookAction, error) + ProvisionOutput(*InstanceInfo, string, string) // PreRefresh and PostRefresh are called before and after a single // resource state is refreshed, respectively. - PreRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value) (HookAction, error) - PostRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value, newState cty.Value) (HookAction, error) + PreRefresh(*InstanceInfo, *InstanceState) (HookAction, error) + PostRefresh(*InstanceInfo, *InstanceState) (HookAction, error) + + // PostStateUpdate is called after the state is updated. + PostStateUpdate(*State) (HookAction, error) // PreImportState and PostImportState are called before and after - // (respectively) each state import operation for a given resource address. - PreImportState(addr addrs.AbsResourceInstance, importID string) (HookAction, error) - PostImportState(addr addrs.AbsResourceInstance, imported []providers.ImportedResource) (HookAction, error) - - // PostStateUpdate is called each time the state is updated. It receives - // a deep copy of the state, which it may therefore access freely without - // any need for locks to protect from concurrent writes from the caller. - PostStateUpdate(new *states.State) (HookAction, error) + // a single resource's state is being improted. + PreImportState(*InstanceInfo, string) (HookAction, error) + PostImportState(*InstanceInfo, []*InstanceState) (HookAction, error) } // NilHook is a Hook implementation that does nothing. It exists only to @@ -87,60 +64,59 @@ type Hook interface { // and only implement the functions you are interested in. type NilHook struct{} -var _ Hook = (*NilHook)(nil) - -func (*NilHook) PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { +func (*NilHook) PreApply(*InstanceInfo, *InstanceState, *InstanceDiff) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (HookAction, error) { +func (*NilHook) PostApply(*InstanceInfo, *InstanceState, error) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PreDiff(addr addrs.AbsResourceInstance, gen states.Generation, priorState, proposedNewState cty.Value) (HookAction, error) { +func (*NilHook) PreDiff(*InstanceInfo, *InstanceState) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { +func (*NilHook) PostDiff(*InstanceInfo, *InstanceDiff) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PreProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { +func (*NilHook) PreProvisionResource(*InstanceInfo, *InstanceState) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PostProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { +func (*NilHook) PostProvisionResource(*InstanceInfo, *InstanceState) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PreProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string) (HookAction, error) { +func (*NilHook) PreProvision(*InstanceInfo, string) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PostProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string, err error) (HookAction, error) { +func (*NilHook) PostProvision(*InstanceInfo, string, error) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) ProvisionOutput(addr addrs.AbsResourceInstance, typeName string, line string) { +func (*NilHook) ProvisionOutput( + *InstanceInfo, string, string) { } -func (*NilHook) PreRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value) (HookAction, error) { +func (*NilHook) PreRefresh(*InstanceInfo, *InstanceState) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PostRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value, newState cty.Value) (HookAction, error) { +func (*NilHook) PostRefresh(*InstanceInfo, *InstanceState) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PreImportState(addr addrs.AbsResourceInstance, importID string) (HookAction, error) { +func (*NilHook) PreImportState(*InstanceInfo, string) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PostImportState(addr addrs.AbsResourceInstance, imported []providers.ImportedResource) (HookAction, error) { +func (*NilHook) PostImportState(*InstanceInfo, []*InstanceState) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PostStateUpdate(new *states.State) (HookAction, error) { +func (*NilHook) PostStateUpdate(*State) (HookAction, error) { return HookActionContinue, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/hook_mock.go b/vendor/github.com/hashicorp/terraform/terraform/hook_mock.go index 6efa3196..0e464006 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/hook_mock.go +++ b/vendor/github.com/hashicorp/terraform/terraform/hook_mock.go @@ -1,274 +1,245 @@ package terraform -import ( - "sync" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" -) +import "sync" // MockHook is an implementation of Hook that can be used for tests. // It records all of its function calls. type MockHook struct { sync.Mutex - PreApplyCalled bool - PreApplyAddr addrs.AbsResourceInstance - PreApplyGen states.Generation - PreApplyAction plans.Action - PreApplyPriorState cty.Value - PreApplyPlannedState cty.Value - PreApplyReturn HookAction - PreApplyError error + PreApplyCalled bool + PreApplyInfo *InstanceInfo + PreApplyDiff *InstanceDiff + PreApplyState *InstanceState + PreApplyReturn HookAction + PreApplyError error PostApplyCalled bool - PostApplyAddr addrs.AbsResourceInstance - PostApplyGen states.Generation - PostApplyNewState cty.Value + PostApplyInfo *InstanceInfo + PostApplyState *InstanceState PostApplyError error PostApplyReturn HookAction PostApplyReturnError error - PostApplyFn func(addrs.AbsResourceInstance, states.Generation, cty.Value, error) (HookAction, error) + PostApplyFn func(*InstanceInfo, *InstanceState, error) (HookAction, error) - PreDiffCalled bool - PreDiffAddr addrs.AbsResourceInstance - PreDiffGen states.Generation - PreDiffPriorState cty.Value - PreDiffProposedState cty.Value - PreDiffReturn HookAction - PreDiffError error + PreDiffCalled bool + PreDiffInfo *InstanceInfo + PreDiffState *InstanceState + PreDiffReturn HookAction + PreDiffError error - PostDiffCalled bool - PostDiffAddr addrs.AbsResourceInstance - PostDiffGen states.Generation - PostDiffAction plans.Action - PostDiffPriorState cty.Value - PostDiffPlannedState cty.Value - PostDiffReturn HookAction - PostDiffError error + PostDiffCalled bool + PostDiffInfo *InstanceInfo + PostDiffDiff *InstanceDiff + PostDiffReturn HookAction + PostDiffError error - PreProvisionInstanceCalled bool - PreProvisionInstanceAddr addrs.AbsResourceInstance - PreProvisionInstanceState cty.Value - PreProvisionInstanceReturn HookAction - PreProvisionInstanceError error + PreProvisionResourceCalled bool + PreProvisionResourceInfo *InstanceInfo + PreProvisionInstanceState *InstanceState + PreProvisionResourceReturn HookAction + PreProvisionResourceError error - PostProvisionInstanceCalled bool - PostProvisionInstanceAddr addrs.AbsResourceInstance - PostProvisionInstanceState cty.Value - PostProvisionInstanceReturn HookAction - PostProvisionInstanceError error + PostProvisionResourceCalled bool + PostProvisionResourceInfo *InstanceInfo + PostProvisionInstanceState *InstanceState + PostProvisionResourceReturn HookAction + PostProvisionResourceError error - PreProvisionInstanceStepCalled bool - PreProvisionInstanceStepAddr addrs.AbsResourceInstance - PreProvisionInstanceStepProvisionerType string - PreProvisionInstanceStepReturn HookAction - PreProvisionInstanceStepError error + PreProvisionCalled bool + PreProvisionInfo *InstanceInfo + PreProvisionProvisionerId string + PreProvisionReturn HookAction + PreProvisionError error - PostProvisionInstanceStepCalled bool - PostProvisionInstanceStepAddr addrs.AbsResourceInstance - PostProvisionInstanceStepProvisionerType string - PostProvisionInstanceStepErrorArg error - PostProvisionInstanceStepReturn HookAction - PostProvisionInstanceStepError error + PostProvisionCalled bool + PostProvisionInfo *InstanceInfo + PostProvisionProvisionerId string + PostProvisionErrorArg error + PostProvisionReturn HookAction + PostProvisionError error - ProvisionOutputCalled bool - ProvisionOutputAddr addrs.AbsResourceInstance - ProvisionOutputProvisionerType string - ProvisionOutputMessage string + ProvisionOutputCalled bool + ProvisionOutputInfo *InstanceInfo + ProvisionOutputProvisionerId string + ProvisionOutputMessage string - PreRefreshCalled bool - PreRefreshAddr addrs.AbsResourceInstance - PreRefreshGen states.Generation - PreRefreshPriorState cty.Value - PreRefreshReturn HookAction - PreRefreshError error + PostRefreshCalled bool + PostRefreshInfo *InstanceInfo + PostRefreshState *InstanceState + PostRefreshReturn HookAction + PostRefreshError error - PostRefreshCalled bool - PostRefreshAddr addrs.AbsResourceInstance - PostRefreshGen states.Generation - PostRefreshPriorState cty.Value - PostRefreshNewState cty.Value - PostRefreshReturn HookAction - PostRefreshError error + PreRefreshCalled bool + PreRefreshInfo *InstanceInfo + PreRefreshState *InstanceState + PreRefreshReturn HookAction + PreRefreshError error PreImportStateCalled bool - PreImportStateAddr addrs.AbsResourceInstance - PreImportStateID string + PreImportStateInfo *InstanceInfo + PreImportStateId string PreImportStateReturn HookAction PreImportStateError error - PostImportStateCalled bool - PostImportStateAddr addrs.AbsResourceInstance - PostImportStateNewStates []providers.ImportedResource - PostImportStateReturn HookAction - PostImportStateError error + PostImportStateCalled bool + PostImportStateInfo *InstanceInfo + PostImportStateState []*InstanceState + PostImportStateReturn HookAction + PostImportStateError error PostStateUpdateCalled bool - PostStateUpdateState *states.State + PostStateUpdateState *State PostStateUpdateReturn HookAction PostStateUpdateError error } -var _ Hook = (*MockHook)(nil) - -func (h *MockHook) PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { +func (h *MockHook) PreApply(n *InstanceInfo, s *InstanceState, d *InstanceDiff) (HookAction, error) { h.Lock() defer h.Unlock() h.PreApplyCalled = true - h.PreApplyAddr = addr - h.PreApplyGen = gen - h.PreApplyAction = action - h.PreApplyPriorState = priorState - h.PreApplyPlannedState = plannedNewState + h.PreApplyInfo = n + h.PreApplyDiff = d + h.PreApplyState = s return h.PreApplyReturn, h.PreApplyError } -func (h *MockHook) PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (HookAction, error) { +func (h *MockHook) PostApply(n *InstanceInfo, s *InstanceState, e error) (HookAction, error) { h.Lock() defer h.Unlock() h.PostApplyCalled = true - h.PostApplyAddr = addr - h.PostApplyGen = gen - h.PostApplyNewState = newState - h.PostApplyError = err + h.PostApplyInfo = n + h.PostApplyState = s + h.PostApplyError = e if h.PostApplyFn != nil { - return h.PostApplyFn(addr, gen, newState, err) + return h.PostApplyFn(n, s, e) } return h.PostApplyReturn, h.PostApplyReturnError } -func (h *MockHook) PreDiff(addr addrs.AbsResourceInstance, gen states.Generation, priorState, proposedNewState cty.Value) (HookAction, error) { +func (h *MockHook) PreDiff(n *InstanceInfo, s *InstanceState) (HookAction, error) { h.Lock() defer h.Unlock() h.PreDiffCalled = true - h.PreDiffAddr = addr - h.PreDiffGen = gen - h.PreDiffPriorState = priorState - h.PreDiffProposedState = proposedNewState + h.PreDiffInfo = n + h.PreDiffState = s return h.PreDiffReturn, h.PreDiffError } -func (h *MockHook) PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { +func (h *MockHook) PostDiff(n *InstanceInfo, d *InstanceDiff) (HookAction, error) { h.Lock() defer h.Unlock() h.PostDiffCalled = true - h.PostDiffAddr = addr - h.PostDiffGen = gen - h.PostDiffAction = action - h.PostDiffPriorState = priorState - h.PostDiffPlannedState = plannedNewState + h.PostDiffInfo = n + h.PostDiffDiff = d return h.PostDiffReturn, h.PostDiffError } -func (h *MockHook) PreProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { +func (h *MockHook) PreProvisionResource(n *InstanceInfo, s *InstanceState) (HookAction, error) { h.Lock() defer h.Unlock() - h.PreProvisionInstanceCalled = true - h.PreProvisionInstanceAddr = addr - h.PreProvisionInstanceState = state - return h.PreProvisionInstanceReturn, h.PreProvisionInstanceError + h.PreProvisionResourceCalled = true + h.PreProvisionResourceInfo = n + h.PreProvisionInstanceState = s + return h.PreProvisionResourceReturn, h.PreProvisionResourceError } -func (h *MockHook) PostProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { +func (h *MockHook) PostProvisionResource(n *InstanceInfo, s *InstanceState) (HookAction, error) { h.Lock() defer h.Unlock() - h.PostProvisionInstanceCalled = true - h.PostProvisionInstanceAddr = addr - h.PostProvisionInstanceState = state - return h.PostProvisionInstanceReturn, h.PostProvisionInstanceError + h.PostProvisionResourceCalled = true + h.PostProvisionResourceInfo = n + h.PostProvisionInstanceState = s + return h.PostProvisionResourceReturn, h.PostProvisionResourceError } -func (h *MockHook) PreProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string) (HookAction, error) { +func (h *MockHook) PreProvision(n *InstanceInfo, provId string) (HookAction, error) { h.Lock() defer h.Unlock() - h.PreProvisionInstanceStepCalled = true - h.PreProvisionInstanceStepAddr = addr - h.PreProvisionInstanceStepProvisionerType = typeName - return h.PreProvisionInstanceStepReturn, h.PreProvisionInstanceStepError + h.PreProvisionCalled = true + h.PreProvisionInfo = n + h.PreProvisionProvisionerId = provId + return h.PreProvisionReturn, h.PreProvisionError } -func (h *MockHook) PostProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string, err error) (HookAction, error) { +func (h *MockHook) PostProvision(n *InstanceInfo, provId string, err error) (HookAction, error) { h.Lock() defer h.Unlock() - h.PostProvisionInstanceStepCalled = true - h.PostProvisionInstanceStepAddr = addr - h.PostProvisionInstanceStepProvisionerType = typeName - h.PostProvisionInstanceStepErrorArg = err - return h.PostProvisionInstanceStepReturn, h.PostProvisionInstanceStepError + h.PostProvisionCalled = true + h.PostProvisionInfo = n + h.PostProvisionProvisionerId = provId + h.PostProvisionErrorArg = err + return h.PostProvisionReturn, h.PostProvisionError } -func (h *MockHook) ProvisionOutput(addr addrs.AbsResourceInstance, typeName string, line string) { +func (h *MockHook) ProvisionOutput( + n *InstanceInfo, + provId string, + msg string) { h.Lock() defer h.Unlock() h.ProvisionOutputCalled = true - h.ProvisionOutputAddr = addr - h.ProvisionOutputProvisionerType = typeName - h.ProvisionOutputMessage = line + h.ProvisionOutputInfo = n + h.ProvisionOutputProvisionerId = provId + h.ProvisionOutputMessage = msg } -func (h *MockHook) PreRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value) (HookAction, error) { +func (h *MockHook) PreRefresh(n *InstanceInfo, s *InstanceState) (HookAction, error) { h.Lock() defer h.Unlock() h.PreRefreshCalled = true - h.PreRefreshAddr = addr - h.PreRefreshGen = gen - h.PreRefreshPriorState = priorState + h.PreRefreshInfo = n + h.PreRefreshState = s return h.PreRefreshReturn, h.PreRefreshError } -func (h *MockHook) PostRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value, newState cty.Value) (HookAction, error) { +func (h *MockHook) PostRefresh(n *InstanceInfo, s *InstanceState) (HookAction, error) { h.Lock() defer h.Unlock() h.PostRefreshCalled = true - h.PostRefreshAddr = addr - h.PostRefreshPriorState = priorState - h.PostRefreshNewState = newState + h.PostRefreshInfo = n + h.PostRefreshState = s return h.PostRefreshReturn, h.PostRefreshError } -func (h *MockHook) PreImportState(addr addrs.AbsResourceInstance, importID string) (HookAction, error) { +func (h *MockHook) PreImportState(info *InstanceInfo, id string) (HookAction, error) { h.Lock() defer h.Unlock() h.PreImportStateCalled = true - h.PreImportStateAddr = addr - h.PreImportStateID = importID + h.PreImportStateInfo = info + h.PreImportStateId = id return h.PreImportStateReturn, h.PreImportStateError } -func (h *MockHook) PostImportState(addr addrs.AbsResourceInstance, imported []providers.ImportedResource) (HookAction, error) { +func (h *MockHook) PostImportState(info *InstanceInfo, s []*InstanceState) (HookAction, error) { h.Lock() defer h.Unlock() h.PostImportStateCalled = true - h.PostImportStateAddr = addr - h.PostImportStateNewStates = imported + h.PostImportStateInfo = info + h.PostImportStateState = s return h.PostImportStateReturn, h.PostImportStateError } -func (h *MockHook) PostStateUpdate(new *states.State) (HookAction, error) { +func (h *MockHook) PostStateUpdate(s *State) (HookAction, error) { h.Lock() defer h.Unlock() h.PostStateUpdateCalled = true - h.PostStateUpdateState = new + h.PostStateUpdateState = s return h.PostStateUpdateReturn, h.PostStateUpdateError } diff --git a/vendor/github.com/hashicorp/terraform/terraform/hook_stop.go b/vendor/github.com/hashicorp/terraform/terraform/hook_stop.go index 811fb337..104d0098 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/hook_stop.go +++ b/vendor/github.com/hashicorp/terraform/terraform/hook_stop.go @@ -2,13 +2,6 @@ package terraform import ( "sync/atomic" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" ) // stopHook is a private Hook implementation that Terraform uses to @@ -17,69 +10,63 @@ type stopHook struct { stop uint32 } -var _ Hook = (*stopHook)(nil) - -func (h *stopHook) PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { +func (h *stopHook) PreApply(*InstanceInfo, *InstanceState, *InstanceDiff) (HookAction, error) { return h.hook() } -func (h *stopHook) PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (HookAction, error) { +func (h *stopHook) PostApply(*InstanceInfo, *InstanceState, error) (HookAction, error) { return h.hook() } -func (h *stopHook) PreDiff(addr addrs.AbsResourceInstance, gen states.Generation, priorState, proposedNewState cty.Value) (HookAction, error) { +func (h *stopHook) PreDiff(*InstanceInfo, *InstanceState) (HookAction, error) { return h.hook() } -func (h *stopHook) PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { +func (h *stopHook) PostDiff(*InstanceInfo, *InstanceDiff) (HookAction, error) { return h.hook() } -func (h *stopHook) PreProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { +func (h *stopHook) PreProvisionResource(*InstanceInfo, *InstanceState) (HookAction, error) { return h.hook() } -func (h *stopHook) PostProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { +func (h *stopHook) PostProvisionResource(*InstanceInfo, *InstanceState) (HookAction, error) { return h.hook() } -func (h *stopHook) PreProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string) (HookAction, error) { +func (h *stopHook) PreProvision(*InstanceInfo, string) (HookAction, error) { return h.hook() } -func (h *stopHook) PostProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string, err error) (HookAction, error) { +func (h *stopHook) PostProvision(*InstanceInfo, string, error) (HookAction, error) { return h.hook() } -func (h *stopHook) ProvisionOutput(addr addrs.AbsResourceInstance, typeName string, line string) { +func (h *stopHook) ProvisionOutput(*InstanceInfo, string, string) { } -func (h *stopHook) PreRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value) (HookAction, error) { +func (h *stopHook) PreRefresh(*InstanceInfo, *InstanceState) (HookAction, error) { return h.hook() } -func (h *stopHook) PostRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value, newState cty.Value) (HookAction, error) { +func (h *stopHook) PostRefresh(*InstanceInfo, *InstanceState) (HookAction, error) { return h.hook() } -func (h *stopHook) PreImportState(addr addrs.AbsResourceInstance, importID string) (HookAction, error) { +func (h *stopHook) PreImportState(*InstanceInfo, string) (HookAction, error) { return h.hook() } -func (h *stopHook) PostImportState(addr addrs.AbsResourceInstance, imported []providers.ImportedResource) (HookAction, error) { +func (h *stopHook) PostImportState(*InstanceInfo, []*InstanceState) (HookAction, error) { return h.hook() } -func (h *stopHook) PostStateUpdate(new *states.State) (HookAction, error) { +func (h *stopHook) PostStateUpdate(*State) (HookAction, error) { return h.hook() } func (h *stopHook) hook() (HookAction, error) { if h.Stopped() { - // FIXME: This should really return an error since stopping partway - // through is not a successful run-to-completion, but we'll need to - // introduce that cautiously since existing automation solutions may - // be depending on this behavior. return HookActionHalt, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/interpolate.go b/vendor/github.com/hashicorp/terraform/terraform/interpolate.go index 26c18575..4f4e178c 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/interpolate.go +++ b/vendor/github.com/hashicorp/terraform/terraform/interpolate.go @@ -45,7 +45,65 @@ type InterpolationScope struct { func (i *Interpolater) Values( scope *InterpolationScope, vars map[string]config.InterpolatedVariable) (map[string]ast.Variable, error) { - return nil, fmt.Errorf("type Interpolator is no longer supported; use the evaluator API instead") + if scope == nil { + scope = &InterpolationScope{} + } + + result := make(map[string]ast.Variable, len(vars)) + + // Copy the default variables + if i.Module != nil && scope != nil { + mod := i.Module + if len(scope.Path) > 1 { + mod = i.Module.Child(scope.Path[1:]) + } + for _, v := range mod.Config().Variables { + // Set default variables + if v.Default == nil { + continue + } + + n := fmt.Sprintf("var.%s", v.Name) + variable, err := hil.InterfaceToVariable(v.Default) + if err != nil { + return nil, fmt.Errorf("invalid default map value for %s: %v", v.Name, v.Default) + } + + result[n] = variable + } + } + + for n, rawV := range vars { + var err error + switch v := rawV.(type) { + case *config.CountVariable: + err = i.valueCountVar(scope, n, v, result) + case *config.ModuleVariable: + err = i.valueModuleVar(scope, n, v, result) + case *config.PathVariable: + err = i.valuePathVar(scope, n, v, result) + case *config.ResourceVariable: + err = i.valueResourceVar(scope, n, v, result) + case *config.SelfVariable: + err = i.valueSelfVar(scope, n, v, result) + case *config.SimpleVariable: + err = i.valueSimpleVar(scope, n, v, result) + case *config.TerraformVariable: + err = i.valueTerraformVar(scope, n, v, result) + case *config.LocalVariable: + err = i.valueLocalVar(scope, n, v, result) + case *config.UserVariable: + err = i.valueUserVar(scope, n, v, result) + default: + err = fmt.Errorf("%s: unknown variable type: %T", n, rawV) + } + + if err != nil { + return nil, err + } + } + + return result, nil } func (i *Interpolater) valueCountVar( @@ -95,7 +153,7 @@ func (i *Interpolater) valueModuleVar( defer i.StateLock.RUnlock() // Get the module where we're looking for the value - mod := i.State.ModuleByPath(normalizeModulePath(path)) + mod := i.State.ModuleByPath(path) if mod == nil { // If the module doesn't exist, then we can return an empty string. // This happens usually only in Refresh() when we haven't populated @@ -199,13 +257,13 @@ func (i *Interpolater) valueResourceVar( } if variable == nil { - // During the refresh walk we tolerate missing variables because + // During the input walk we tolerate missing variables because // we haven't yet had a chance to refresh state, so dynamic data may // not yet be complete. // If it truly is missing, we'll catch it on a later walk. // This applies only to graph nodes that interpolate during the - // refresh walk, e.g. providers. - if i.Operation == walkRefresh { + // config walk, e.g. providers. + if i.Operation == walkInput || i.Operation == walkRefresh { result[n] = unknownVariable() return nil } @@ -307,7 +365,7 @@ func (i *Interpolater) valueLocalVar( } // Get the relevant module - module := i.State.ModuleByPath(normalizeModulePath(scope.Path)) + module := i.State.ModuleByPath(scope.Path) if module == nil { result[n] = unknownVariable() return nil @@ -526,7 +584,10 @@ MISSING: // // For a Destroy, we're also fine with computed values, since our goal is // only to get destroy nodes for existing resources. - if i.Operation == walkRefresh || i.Operation == walkPlanDestroy { + // + // For an input walk, computed values are okay to return because we're only + // looking for missing variables to prompt the user for. + if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkInput { return &unknownVariable, nil } @@ -546,6 +607,13 @@ func (i *Interpolater) computeResourceMultiVariable( unknownVariable := unknownVariable() + // If we're only looking for input, we don't need to expand a + // multi-variable. This prevents us from encountering things that should be + // known but aren't because the state has yet to be refreshed. + if i.Operation == walkInput { + return &unknownVariable, nil + } + // Get the information about this resource variable, and verify // that it exists and such. module, cr, err := i.resourceVariableInfo(scope, v) @@ -627,7 +695,7 @@ func (i *Interpolater) computeResourceMultiVariable( // // For an input walk, computed values are okay to return because we're only // looking for missing variables to prompt the user for. - if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkDestroy { + if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkDestroy || i.Operation == walkInput { return &unknownVariable, nil } @@ -708,7 +776,7 @@ func (i *Interpolater) resourceVariableInfo( } // Get the relevant module - module := i.State.ModuleByPath(normalizeModulePath(scope.Path)) + module := i.State.ModuleByPath(scope.Path) return module, cr, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/module_dependencies.go b/vendor/github.com/hashicorp/terraform/terraform/module_dependencies.go index 66a68c7d..4594cb60 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/module_dependencies.go +++ b/vendor/github.com/hashicorp/terraform/terraform/module_dependencies.go @@ -1,135 +1,84 @@ package terraform import ( - version "github.com/hashicorp/go-version" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/moduledeps" "github.com/hashicorp/terraform/plugin/discovery" - "github.com/hashicorp/terraform/states" ) -// ConfigTreeDependencies returns the dependencies of the tree of modules -// described by the given configuration and state. +// ModuleTreeDependencies returns the dependencies of the tree of modules +// described by the given configuration tree and state. // // Both configuration and state are required because there can be resources // implied by instances in the state that no longer exist in config. -func ConfigTreeDependencies(root *configs.Config, state *states.State) *moduledeps.Module { +// +// This function will panic if any invalid version constraint strings are +// present in the configuration. This is guaranteed not to happen for any +// configuration that has passed a call to Config.Validate(). +func ModuleTreeDependencies(root *module.Tree, state *State) *moduledeps.Module { // First we walk the configuration tree to build the overall structure // and capture the explicit/implicit/inherited provider dependencies. - deps := configTreeConfigDependencies(root, nil) + deps := moduleTreeConfigDependencies(root, nil) // Next we walk over the resources in the state to catch any additional // dependencies created by existing resources that are no longer in config. // Most things we find in state will already be present in 'deps', but // we're interested in the rare thing that isn't. - configTreeMergeStateDependencies(deps, state) + moduleTreeMergeStateDependencies(deps, state) return deps } -func configTreeConfigDependencies(root *configs.Config, inheritProviders map[string]*configs.Provider) *moduledeps.Module { +func moduleTreeConfigDependencies(root *module.Tree, inheritProviders map[string]*config.ProviderConfig) *moduledeps.Module { if root == nil { // If no config is provided, we'll make a synthetic root. // This isn't necessarily correct if we're called with a nil that // *isn't* at the root, but in practice that can never happen. return &moduledeps.Module{ - Name: "root", - Providers: make(moduledeps.Providers), + Name: "root", } } - name := "root" - if len(root.Path) != 0 { - name = root.Path[len(root.Path)-1] - } - ret := &moduledeps.Module{ - Name: name, + Name: root.Name(), } - module := root.Module + cfg := root.Config() + providerConfigs := cfg.ProviderConfigsByFullName() // Provider dependencies { - providers := make(moduledeps.Providers) + providers := make(moduledeps.Providers, len(providerConfigs)) - // The main way to declare a provider dependency is explicitly inside - // the "terraform" block, which allows declaring a requirement without - // also creating a configuration. - for fullName, constraints := range module.ProviderRequirements { + // Any providerConfigs elements are *explicit* provider dependencies, + // which is the only situation where the user might provide an actual + // version constraint. We'll take care of these first. + for fullName, pCfg := range providerConfigs { inst := moduledeps.ProviderInstance(fullName) - - // The handling here is a bit fiddly because the moduledeps package - // was designed around the legacy (pre-0.12) configuration model - // and hasn't yet been revised to handle the new model. As a result, - // we need to do some translation here. - // FIXME: Eventually we should adjust the underlying model so we - // can also retain the source location of each constraint, for - // more informative output from the "terraform providers" command. - var rawConstraints version.Constraints - for _, constraint := range constraints { - rawConstraints = append(rawConstraints, constraint.Required...) + versionSet := discovery.AllVersions + if pCfg.Version != "" { + versionSet = discovery.ConstraintStr(pCfg.Version).MustParse() } - discoConstraints := discovery.NewConstraints(rawConstraints) - providers[inst] = moduledeps.ProviderDependency{ - Constraints: discoConstraints, + Constraints: versionSet, Reason: moduledeps.ProviderDependencyExplicit, } } - // Provider configurations can also include version constraints, - // allowing for more terse declaration in situations where both a - // configuration and a constraint are defined in the same module. - for fullName, pCfg := range module.ProviderConfigs { - inst := moduledeps.ProviderInstance(fullName) - discoConstraints := discovery.AllVersions - if pCfg.Version.Required != nil { - discoConstraints = discovery.NewConstraints(pCfg.Version.Required) - } - if existing, exists := providers[inst]; exists { - existing.Constraints = existing.Constraints.Append(discoConstraints) - } else { - providers[inst] = moduledeps.ProviderDependency{ - Constraints: discoConstraints, - Reason: moduledeps.ProviderDependencyExplicit, - } - } - } - // Each resource in the configuration creates an *implicit* provider // dependency, though we'll only record it if there isn't already // an explicit dependency on the same provider. - for _, rc := range module.ManagedResources { - addr := rc.ProviderConfigAddr() - inst := moduledeps.ProviderInstance(addr.StringCompact()) + for _, rc := range cfg.Resources { + fullName := rc.ProviderFullName() + inst := moduledeps.ProviderInstance(fullName) if _, exists := providers[inst]; exists { // Explicit dependency already present continue } reason := moduledeps.ProviderDependencyImplicit - if _, inherited := inheritProviders[addr.StringCompact()]; inherited { - reason = moduledeps.ProviderDependencyInherited - } - - providers[inst] = moduledeps.ProviderDependency{ - Constraints: discovery.AllVersions, - Reason: reason, - } - } - for _, rc := range module.DataResources { - addr := rc.ProviderConfigAddr() - inst := moduledeps.ProviderInstance(addr.StringCompact()) - if _, exists := providers[inst]; exists { - // Explicit dependency already present - continue - } - - reason := moduledeps.ProviderDependencyImplicit - if _, inherited := inheritProviders[addr.String()]; inherited { + if _, inherited := inheritProviders[fullName]; inherited { reason = moduledeps.ProviderDependencyInherited } @@ -142,31 +91,31 @@ func configTreeConfigDependencies(root *configs.Config, inheritProviders map[str ret.Providers = providers } - childInherit := make(map[string]*configs.Provider) + childInherit := make(map[string]*config.ProviderConfig) for k, v := range inheritProviders { childInherit[k] = v } - for k, v := range module.ProviderConfigs { + for k, v := range providerConfigs { childInherit[k] = v } - for _, c := range root.Children { - ret.Children = append(ret.Children, configTreeConfigDependencies(c, childInherit)) + for _, c := range root.Children() { + ret.Children = append(ret.Children, moduleTreeConfigDependencies(c, childInherit)) } return ret } -func configTreeMergeStateDependencies(root *moduledeps.Module, state *states.State) { +func moduleTreeMergeStateDependencies(root *moduledeps.Module, state *State) { if state == nil { return } - findModule := func(path addrs.ModuleInstance) *moduledeps.Module { + findModule := func(path []string) *moduledeps.Module { module := root - for _, step := range path { + for _, name := range path[1:] { // skip initial "root" var next *moduledeps.Module for _, cm := range module.Children { - if cm.Name == step.Name { + if cm.Name == name { next = cm break } @@ -175,8 +124,7 @@ func configTreeMergeStateDependencies(root *moduledeps.Module, state *states.Sta if next == nil { // If we didn't find a next node, we'll need to make one next = &moduledeps.Module{ - Name: step.Name, - Providers: make(moduledeps.Providers), + Name: name, } module.Children = append(module.Children, next) } @@ -187,11 +135,15 @@ func configTreeMergeStateDependencies(root *moduledeps.Module, state *states.Sta } for _, ms := range state.Modules { - module := findModule(ms.Addr) + module := findModule(ms.Path) - for _, rs := range ms.Resources { - inst := moduledeps.ProviderInstance(rs.ProviderConfig.ProviderConfig.StringCompact()) + for _, is := range ms.Resources { + fullName := config.ResourceProviderFullName(is.Type, is.Provider) + inst := moduledeps.ProviderInstance(fullName) if _, exists := module.Providers[inst]; !exists { + if module.Providers == nil { + module.Providers = make(moduledeps.Providers) + } module.Providers[inst] = moduledeps.ProviderDependency{ Constraints: discovery.AllVersions, Reason: moduledeps.ProviderDependencyFromState, @@ -199,4 +151,5 @@ func configTreeMergeStateDependencies(root *moduledeps.Module, state *states.Sta } } } + } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_count_boundary.go b/vendor/github.com/hashicorp/terraform/terraform/node_count_boundary.go index e4952039..bd32c79f 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_count_boundary.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_count_boundary.go @@ -1,22 +1,14 @@ package terraform -import ( - "github.com/hashicorp/terraform/configs" -) - -// NodeCountBoundary fixes up any transitions between "each modes" in objects -// saved in state, such as switching from NoEach to EachInt. -type NodeCountBoundary struct { - Config *configs.Config -} +// NodeCountBoundary fixes any "count boundarie" in the state: resources +// that are named "foo.0" when they should be named "foo" +type NodeCountBoundary struct{} func (n *NodeCountBoundary) Name() string { - return "meta.count-boundary (EachMode fixup)" + return "meta.count-boundary (count boundary fixup)" } // GraphNodeEvalable func (n *NodeCountBoundary) EvalTree() EvalNode { - return &EvalCountFixZeroOneBoundaryGlobal{ - Config: n.Config, - } + return &EvalCountFixZeroOneBoundaryGlobal{} } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_data_destroy.go b/vendor/github.com/hashicorp/terraform/terraform/node_data_destroy.go index 6ba39904..e32cea88 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_data_destroy.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_data_destroy.go @@ -1,40 +1,22 @@ package terraform -import ( - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" -) - -// NodeDestroyableDataResourceInstance represents a resource that is "destroyable": -// it is ready to be destroyed. -type NodeDestroyableDataResourceInstance struct { - *NodeAbstractResourceInstance +// NodeDestroyableDataResource represents a resource that is "plannable": +// it is ready to be planned in order to create a diff. +type NodeDestroyableDataResource struct { + *NodeAbstractResource } // GraphNodeEvalable -func (n *NodeDestroyableDataResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() +func (n *NodeDestroyableDataResource) EvalTree() EvalNode { + addr := n.NodeAbstractResource.Addr - var providerSchema *ProviderSchema - // We don't need the provider, but we're calling EvalGetProvider to load the - // schema. - var provider providers.Interface + // stateId is the ID to put into the state + stateId := addr.stateId() // Just destroy it. - var state *states.ResourceInstanceObject - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalWriteState{ - Addr: addr.Resource, - State: &state, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - }, - }, + var state *InstanceState + return &EvalWriteState{ + Name: stateId, + State: &state, // state is nil here } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_data_refresh.go b/vendor/github.com/hashicorp/terraform/terraform/node_data_refresh.go index a086214d..d5ca641a 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_data_refresh.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_data_refresh.go @@ -2,66 +2,46 @@ package terraform import ( "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" ) -// NodeRefreshableDataResource represents a resource that is "refreshable". +// NodeRefreshableDataResource represents a resource that is "plannable": +// it is ready to be planned in order to create a diff. type NodeRefreshableDataResource struct { - *NodeAbstractResource + *NodeAbstractCountResource } -var ( - _ GraphNodeSubPath = (*NodeRefreshableDataResource)(nil) - _ GraphNodeDynamicExpandable = (*NodeRefreshableDataResource)(nil) - _ GraphNodeReferenceable = (*NodeRefreshableDataResource)(nil) - _ GraphNodeReferencer = (*NodeRefreshableDataResource)(nil) - _ GraphNodeResource = (*NodeRefreshableDataResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeRefreshableDataResource)(nil) -) - // GraphNodeDynamicExpandable func (n *NodeRefreshableDataResource) DynamicExpand(ctx EvalContext) (*Graph, error) { - var diags tfdiags.Diagnostics + // Grab the state which we read + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() - count, countDiags := evaluateResourceCountExpression(n.Config.Count, ctx) - diags = diags.Append(countDiags) - if countDiags.HasErrors() { - return nil, diags.Err() + // Expand the resource count which must be available by now from EvalTree + count, err := n.Config.Count() + if err != nil { + return nil, err } - // Next we need to potentially rename an instance address in the state - // if we're transitioning whether "count" is set at all. - fixResourceCountSetTransition(ctx, n.ResourceAddr(), count != -1) - - // Our graph transformers require access to the full state, so we'll - // temporarily lock it while we work on this. - state := ctx.State().Lock() - defer ctx.State().Unlock() - // The concrete resource factory we'll use - concreteResource := func(a *NodeAbstractResourceInstance) dag.Vertex { + concreteResource := func(a *NodeAbstractResource) dag.Vertex { // Add the config and state since we don't do that via transforms a.Config = n.Config a.ResolvedProvider = n.ResolvedProvider return &NodeRefreshableDataResourceInstance{ - NodeAbstractResourceInstance: a, + NodeAbstractResource: a, } } // We also need a destroyable resource for orphans that are a result of a // scaled-in count. - concreteResourceDestroyable := func(a *NodeAbstractResourceInstance) dag.Vertex { - // Add the config and provider since we don't do that via transforms + concreteResourceDestroyable := func(a *NodeAbstractResource) dag.Vertex { + // Add the config since we don't do that via transforms a.Config = n.Config - a.ResolvedProvider = n.ResolvedProvider - return &NodeDestroyableDataResourceInstance{ - NodeAbstractResourceInstance: a, + return &NodeDestroyableDataResource{ + NodeAbstractResource: a, } } @@ -70,7 +50,6 @@ func (n *NodeRefreshableDataResource) DynamicExpand(ctx EvalContext) (*Graph, er // Expand the count. &ResourceCountTransformer{ Concrete: concreteResource, - Schema: n.Schema, Count: count, Addr: n.ResourceAddr(), }, @@ -88,7 +67,7 @@ func (n *NodeRefreshableDataResource) DynamicExpand(ctx EvalContext) (*Graph, er &AttachStateTransformer{State: state}, // Targeting - &TargetsTransformer{Targets: n.Targets}, + &TargetsTransformer{ParsedTargets: n.Targets}, // Connect references so ordering is correct &ReferenceTransformer{}, @@ -104,118 +83,139 @@ func (n *NodeRefreshableDataResource) DynamicExpand(ctx EvalContext) (*Graph, er Name: "NodeRefreshableDataResource", } - graph, diags := b.Build(ctx.Path()) - return graph, diags.ErrWithWarnings() + return b.Build(ctx.Path()) } -// NodeRefreshableDataResourceInstance represents a single resource instance +// NodeRefreshableDataResourceInstance represents a _single_ resource instance // that is refreshable. type NodeRefreshableDataResourceInstance struct { - *NodeAbstractResourceInstance + *NodeAbstractResource } // GraphNodeEvalable func (n *NodeRefreshableDataResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() + addr := n.NodeAbstractResource.Addr - // These variables are the state for the eval sequence below, and are - // updated through pointers. - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - var configVal cty.Value + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: addr.Type, + } + + // Get the state if we have it, if not we build it + rs := n.ResourceState + if rs == nil { + rs = &ResourceState{ + Provider: n.ResolvedProvider, + } + } + + // If the config isn't empty we update the state + if n.Config != nil { + rs = &ResourceState{ + Type: n.Config.Type, + Provider: n.Config.Provider, + Dependencies: n.StateReferences(), + } + } + + // Build the resource for eval + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } + + // Declare a bunch of variables that are used for state during + // evaluation. Most of this are written to by-address below. + var config *ResourceConfig + var diff *InstanceDiff + var provider ResourceProvider + var state *InstanceState return &EvalSequence{ Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - // Always destroy the existing state first, since we must // make sure that values from a previous read will not // get interpolated if we end up needing to defer our // loading until apply time. &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, // a pointer to nil, here - ProviderSchema: &providerSchema, + Name: stateId, + ResourceType: rs.Type, + Provider: n.ResolvedProvider, + Dependencies: rs.Dependencies, + State: &state, // state is nil here }, + &EvalInterpolate{ + Config: n.Config.RawConfig.Copy(), + Resource: resource, + Output: &config, + }, + + // The rest of this pass can proceed only if there are no + // computed values in our config. + // (If there are, we'll deal with this during the plan and + // apply phases.) &EvalIf{ If: func(ctx EvalContext) (bool, error) { + if config.ComputedKeys != nil && len(config.ComputedKeys) > 0 { + return true, EvalEarlyExitError{} + } + // If the config explicitly has a depends_on for this // data source, assume the intention is to prevent - // refreshing ahead of that dependency, and therefore - // we need to deal with this resource during the apply - // phase.. + // refreshing ahead of that dependency. if len(n.Config.DependsOn) > 0 { return true, EvalEarlyExitError{} } return true, nil }, + Then: EvalNoop{}, }, - // EvalReadData will _attempt_ to read the data source, but may - // generate an incomplete planned object if the configuration - // includes values that won't be known until apply. - &EvalReadData{ - Addr: addr.Resource, - Config: n.Config, - Dependencies: n.StateReferences(), - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - OutputChange: &change, - OutputConfigValue: &configVal, - OutputState: &state, + // The remainder of this pass is the same as running + // a "plan" pass immediately followed by an "apply" pass, + // populating the state early so it'll be available to + // provider configurations that need this data during + // refresh/plan. + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, }, - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - return (*state).Status != states.ObjectPlanned, nil - }, - Then: &EvalSequence{ - Nodes: []EvalNode{ - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - ProviderSchema: &providerSchema, - }, - &EvalUpdateStateHook{}, - }, - }, - Else: &EvalSequence{ - // We can't deal with this yet, so we'll repeat this step - // during the plan walk to produce a planned change to read - // this during the apply walk. However, we do still need to - // save the generated change and partial state so that - // results from it can be included in other data resources - // or provider configurations during the refresh walk. - // (The planned object we save in the state here will be - // pruned out at the end of the refresh walk, returning - // it back to being unset again for subsequent walks.) - Nodes: []EvalNode{ - &EvalWriteDiff{ - Addr: addr.Resource, - Change: &change, - ProviderSchema: &providerSchema, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - ProviderSchema: &providerSchema, - }, - }, - }, + &EvalReadDataDiff{ + Info: info, + Config: &config, + Provider: &provider, + Output: &diff, + OutputState: &state, }, + + &EvalReadDataApply{ + Info: info, + Diff: &diff, + Provider: &provider, + Output: &state, + }, + + &EvalWriteState{ + Name: stateId, + ResourceType: rs.Type, + Provider: n.ResolvedProvider, + Dependencies: rs.Dependencies, + State: &state, + }, + + &EvalUpdateStateHook{}, }, } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_local.go b/vendor/github.com/hashicorp/terraform/terraform/node_local.go index 591eb305..d3872226 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_local.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_local.go @@ -1,10 +1,10 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/lang" + "fmt" + "strings" + + "github.com/hashicorp/terraform/config" ) // NodeLocal represents a named local value in a particular module. @@ -12,26 +12,22 @@ import ( // Local value nodes only have one operation, common to all walk types: // evaluate the result and place it in state. type NodeLocal struct { - Addr addrs.AbsLocalValue - Config *configs.Local + PathValue []string + Config *config.Local } -var ( - _ GraphNodeSubPath = (*NodeLocal)(nil) - _ RemovableIfNotTargeted = (*NodeLocal)(nil) - _ GraphNodeReferenceable = (*NodeLocal)(nil) - _ GraphNodeReferencer = (*NodeLocal)(nil) - _ GraphNodeEvalable = (*NodeLocal)(nil) - _ dag.GraphNodeDotter = (*NodeLocal)(nil) -) - func (n *NodeLocal) Name() string { - return n.Addr.String() + result := fmt.Sprintf("local.%s", n.Config.Name) + if len(n.PathValue) > 1 { + result = fmt.Sprintf("%s.%s", modulePrefixStr(n.PathValue), result) + } + + return result } // GraphNodeSubPath -func (n *NodeLocal) Path() addrs.ModuleInstance { - return n.Addr.Module +func (n *NodeLocal) Path() []string { + return n.PathValue } // RemovableIfNotTargeted @@ -40,31 +36,31 @@ func (n *NodeLocal) RemoveIfNotTargeted() bool { } // GraphNodeReferenceable -func (n *NodeLocal) ReferenceableAddrs() []addrs.Referenceable { - return []addrs.Referenceable{n.Addr.LocalValue} +func (n *NodeLocal) ReferenceableName() []string { + name := fmt.Sprintf("local.%s", n.Config.Name) + return []string{name} } // GraphNodeReferencer -func (n *NodeLocal) References() []*addrs.Reference { - refs, _ := lang.ReferencesInExpr(n.Config.Expr) - return appendResourceDestroyReferences(refs) +func (n *NodeLocal) References() []string { + var result []string + result = append(result, ReferencesFromConfig(n.Config.RawConfig)...) + for _, v := range result { + split := strings.Split(v, "/") + for i, s := range split { + split[i] = s + ".destroy" + } + + result = append(result, strings.Join(split, "/")) + } + + return result } // GraphNodeEvalable func (n *NodeLocal) EvalTree() EvalNode { return &EvalLocal{ - Addr: n.Addr.LocalValue, - Expr: n.Config.Expr, - } -} - -// dag.GraphNodeDotter impl. -func (n *NodeLocal) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, + Name: n.Config.Name, + Value: n.Config.RawConfig, } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_module_removed.go b/vendor/github.com/hashicorp/terraform/terraform/node_module_removed.go index cb55a1a8..bb3e5ee1 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_module_removed.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_module_removed.go @@ -2,80 +2,76 @@ package terraform import ( "fmt" - - "github.com/hashicorp/terraform/addrs" + "log" + "reflect" ) // NodeModuleRemoved represents a module that is no longer in the // config. type NodeModuleRemoved struct { - Addr addrs.ModuleInstance + PathValue []string } -var ( - _ GraphNodeSubPath = (*NodeModuleRemoved)(nil) - _ GraphNodeEvalable = (*NodeModuleRemoved)(nil) - _ GraphNodeReferencer = (*NodeModuleRemoved)(nil) - _ GraphNodeReferenceOutside = (*NodeModuleRemoved)(nil) -) - func (n *NodeModuleRemoved) Name() string { - return fmt.Sprintf("%s (removed)", n.Addr.String()) + return fmt.Sprintf("%s (removed)", modulePrefixStr(n.PathValue)) } // GraphNodeSubPath -func (n *NodeModuleRemoved) Path() addrs.ModuleInstance { - return n.Addr +func (n *NodeModuleRemoved) Path() []string { + return n.PathValue } // GraphNodeEvalable func (n *NodeModuleRemoved) EvalTree() EvalNode { return &EvalOpFilter{ Ops: []walkOperation{walkRefresh, walkApply, walkDestroy}, - Node: &EvalCheckModuleRemoved{ - Addr: n.Addr, + Node: &EvalDeleteModule{ + PathValue: n.PathValue, }, } } -func (n *NodeModuleRemoved) ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) { - // Our "References" implementation indicates that this node depends on - // the call to the module it represents, which implicitly depends on - // everything inside the module. That reference must therefore be - // interpreted in terms of our parent module. - return n.Addr, n.Addr.Parent() +func (n *NodeModuleRemoved) ReferenceGlobal() bool { + return true } -func (n *NodeModuleRemoved) References() []*addrs.Reference { - // We depend on the call to the module we represent, because that - // implicitly then depends on everything inside that module. - // Our ReferenceOutside implementation causes this to be interpreted - // within the parent module. +func (n *NodeModuleRemoved) References() []string { + return []string{modulePrefixStr(n.PathValue)} +} - _, call := n.Addr.CallInstance() - return []*addrs.Reference{ - { - Subject: call, +// EvalDeleteModule is an EvalNode implementation that removes an empty module +// entry from the state. +type EvalDeleteModule struct { + PathValue []string +} - // No source range here, because there's nothing reasonable for - // us to return. - }, +func (n *EvalDeleteModule) Eval(ctx EvalContext) (interface{}, error) { + state, lock := ctx.State() + if state == nil { + return nil, nil } -} -// EvalCheckModuleRemoved is an EvalNode implementation that verifies that -// a module has been removed from the state as expected. -type EvalCheckModuleRemoved struct { - Addr addrs.ModuleInstance -} + // Get a write lock so we can access this instance + lock.Lock() + defer lock.Unlock() -func (n *EvalCheckModuleRemoved) Eval(ctx EvalContext) (interface{}, error) { - mod := ctx.State().Module(n.Addr) - if mod != nil { - // If we get here then that indicates a bug either in the states - // module or in an earlier step of the graph walk, since we should've - // pruned out the module when the last resource was removed from it. - return nil, fmt.Errorf("leftover module %s in state that should have been removed; this is a bug in Terraform and should be reported", n.Addr) + // Make sure we have a clean state + // Destroyed resources aren't deleted, they're written with an ID of "". + state.prune() + + // find the module and delete it + for i, m := range state.Modules { + if reflect.DeepEqual(m.Path, n.PathValue) { + if !m.Empty() { + // a targeted apply may leave module resources even without a config, + // so just log this and return. + log.Printf("[DEBUG] cannot remove module %s, not empty", modulePrefixStr(n.PathValue)) + break + } + state.Modules = append(state.Modules[:i], state.Modules[i+1:]...) + break + } } + return nil, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_module_variable.go b/vendor/github.com/hashicorp/terraform/terraform/node_module_variable.go index aca5a6a3..66ff7d5e 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_module_variable.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_module_variable.go @@ -1,43 +1,40 @@ package terraform import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/lang" - "github.com/zclconf/go-cty/cty" + "fmt" + + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" ) // NodeApplyableModuleVariable represents a module variable input during // the apply step. type NodeApplyableModuleVariable struct { - Addr addrs.AbsInputVariableInstance - Config *configs.Variable // Config is the var in the config - Expr hcl.Expression // Expr is the value expression given in the call + PathValue []string + Config *config.Variable // Config is the var in the config + Value *config.RawConfig // Value is the value that is set + + Module *module.Tree // Antiquated, want to remove } -// Ensure that we are implementing all of the interfaces we think we are -// implementing. -var ( - _ GraphNodeSubPath = (*NodeApplyableModuleVariable)(nil) - _ RemovableIfNotTargeted = (*NodeApplyableModuleVariable)(nil) - _ GraphNodeReferenceOutside = (*NodeApplyableModuleVariable)(nil) - _ GraphNodeReferenceable = (*NodeApplyableModuleVariable)(nil) - _ GraphNodeReferencer = (*NodeApplyableModuleVariable)(nil) - _ GraphNodeEvalable = (*NodeApplyableModuleVariable)(nil) - _ dag.GraphNodeDotter = (*NodeApplyableModuleVariable)(nil) -) - func (n *NodeApplyableModuleVariable) Name() string { - return n.Addr.String() + result := fmt.Sprintf("var.%s", n.Config.Name) + if len(n.PathValue) > 1 { + result = fmt.Sprintf("%s.%s", modulePrefixStr(n.PathValue), result) + } + + return result } // GraphNodeSubPath -func (n *NodeApplyableModuleVariable) Path() addrs.ModuleInstance { - // We execute in the parent scope (above our own module) because - // expressions in our value are resolved in that context. - return n.Addr.Module.Parent() +func (n *NodeApplyableModuleVariable) Path() []string { + // We execute in the parent scope (above our own module) so that + // we can access the proper interpolations. + if len(n.PathValue) > 2 { + return n.PathValue[:len(n.PathValue)-1] + } + + return rootModulePath } // RemovableIfNotTargeted @@ -47,96 +44,95 @@ func (n *NodeApplyableModuleVariable) RemoveIfNotTargeted() bool { return true } -// GraphNodeReferenceOutside implementation -func (n *NodeApplyableModuleVariable) ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) { - - // Module input variables have their value expressions defined in the - // context of their calling (parent) module, and so references from - // a node of this type should be resolved in the parent module instance. - referencePath = n.Addr.Module.Parent() - - // Input variables are _referenced_ from their own module, though. - selfPath = n.Addr.Module - - return // uses named return values +// GraphNodeReferenceGlobal +func (n *NodeApplyableModuleVariable) ReferenceGlobal() bool { + // We have to create fully qualified references because we cross + // boundaries here: our ReferenceableName is in one path and our + // References are from another path. + return true } // GraphNodeReferenceable -func (n *NodeApplyableModuleVariable) ReferenceableAddrs() []addrs.Referenceable { - return []addrs.Referenceable{n.Addr.Variable} +func (n *NodeApplyableModuleVariable) ReferenceableName() []string { + return []string{n.Name()} } // GraphNodeReferencer -func (n *NodeApplyableModuleVariable) References() []*addrs.Reference { - - // If we have no value expression, we cannot depend on anything. - if n.Expr == nil { +func (n *NodeApplyableModuleVariable) References() []string { + // If we have no value set, we depend on nothing + if n.Value == nil { return nil } - // Variables in the root don't depend on anything, because their values - // are gathered prior to the graph walk and recorded in the context. - if len(n.Addr.Module) == 0 { + // Can't depend on anything if we're in the root + if len(n.PathValue) < 2 { return nil } - // Otherwise, we depend on anything referenced by our value expression. - // We ignore diagnostics here under the assumption that we'll re-eval - // all these things later and catch them then; for our purposes here, - // we only care about valid references. - // - // Due to our GraphNodeReferenceOutside implementation, the addresses - // returned by this function are interpreted in the _parent_ module from - // where our associated variable was declared, which is correct because - // our value expression is assigned within a "module" block in the parent - // module. - refs, _ := lang.ReferencesInExpr(n.Expr) - return refs + // Otherwise, we depend on anything that is in our value, but + // specifically in the namespace of the parent path. + // Create the prefix based on the path + var prefix string + if p := n.Path(); len(p) > 0 { + prefix = modulePrefixStr(p) + } + + result := ReferencesFromConfig(n.Value) + return modulePrefixList(result, prefix) } // GraphNodeEvalable func (n *NodeApplyableModuleVariable) EvalTree() EvalNode { // If we have no value, do nothing - if n.Expr == nil { + if n.Value == nil { return &EvalNoop{} } // Otherwise, interpolate the value of this variable and set it // within the variables mapping. - vals := make(map[string]cty.Value) - - _, call := n.Addr.Module.CallInstance() + var config *ResourceConfig + variables := make(map[string]interface{}) return &EvalSequence{ Nodes: []EvalNode{ + &EvalOpFilter{ + Ops: []walkOperation{walkInput}, + Node: &EvalInterpolate{ + Config: n.Value, + Output: &config, + ContinueOnErr: true, + }, + }, &EvalOpFilter{ Ops: []walkOperation{walkRefresh, walkPlan, walkApply, walkDestroy, walkValidate}, - Node: &EvalModuleCallArgument{ - Addr: n.Addr.Variable, - Config: n.Config, - Expr: n.Expr, - Values: vals, - - IgnoreDiagnostics: false, + Node: &EvalInterpolate{ + Config: n.Value, + Output: &config, }, }, - &EvalSetModuleCallArguments{ - Module: call, - Values: vals, + &EvalVariableBlock{ + Config: &config, + VariableValues: variables, + }, + + &EvalCoerceMapVariable{ + Variables: variables, + ModulePath: n.PathValue, + ModuleTree: n.Module, + }, + + &EvalTypeCheckVariable{ + Variables: variables, + ModulePath: n.PathValue, + ModuleTree: n.Module, + }, + + &EvalSetVariables{ + Module: &n.PathValue[len(n.PathValue)-1], + Variables: variables, }, }, } } - -// dag.GraphNodeDotter impl. -func (n *NodeApplyableModuleVariable) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_output.go b/vendor/github.com/hashicorp/terraform/terraform/node_output.go index bb3d0653..83e9925a 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_output.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_output.go @@ -2,38 +2,31 @@ package terraform import ( "fmt" + "strings" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/lang" ) // NodeApplyableOutput represents an output that is "applyable": // it is ready to be applied. type NodeApplyableOutput struct { - Addr addrs.AbsOutputValue - Config *configs.Output // Config is the output in the config + PathValue []string + Config *config.Output // Config is the output in the config } -var ( - _ GraphNodeSubPath = (*NodeApplyableOutput)(nil) - _ RemovableIfNotTargeted = (*NodeApplyableOutput)(nil) - _ GraphNodeTargetDownstream = (*NodeApplyableOutput)(nil) - _ GraphNodeReferenceable = (*NodeApplyableOutput)(nil) - _ GraphNodeReferencer = (*NodeApplyableOutput)(nil) - _ GraphNodeReferenceOutside = (*NodeApplyableOutput)(nil) - _ GraphNodeEvalable = (*NodeApplyableOutput)(nil) - _ dag.GraphNodeDotter = (*NodeApplyableOutput)(nil) -) - func (n *NodeApplyableOutput) Name() string { - return n.Addr.String() + result := fmt.Sprintf("output.%s", n.Config.Name) + if len(n.PathValue) > 1 { + result = fmt.Sprintf("%s.%s", modulePrefixStr(n.PathValue), result) + } + + return result } // GraphNodeSubPath -func (n *NodeApplyableOutput) Path() addrs.ModuleInstance { - return n.Addr.Module +func (n *NodeApplyableOutput) Path() []string { + return n.PathValue } // RemovableIfNotTargeted @@ -51,64 +44,27 @@ func (n *NodeApplyableOutput) TargetDownstream(targetedDeps, untargetedDeps *dag return true } -func referenceOutsideForOutput(addr addrs.AbsOutputValue) (selfPath, referencePath addrs.ModuleInstance) { - - // Output values have their expressions resolved in the context of the - // module where they are defined. - referencePath = addr.Module - - // ...but they are referenced in the context of their calling module. - selfPath = addr.Module.Parent() - - return // uses named return values - -} - -// GraphNodeReferenceOutside implementation -func (n *NodeApplyableOutput) ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) { - return referenceOutsideForOutput(n.Addr) -} - -func referenceableAddrsForOutput(addr addrs.AbsOutputValue) []addrs.Referenceable { - // An output in the root module can't be referenced at all. - if addr.Module.IsRoot() { - return nil - } - - // Otherwise, we can be referenced via a reference to our output name - // on the parent module's call, or via a reference to the entire call. - // e.g. module.foo.bar or just module.foo . - // Note that our ReferenceOutside method causes these addresses to be - // relative to the calling module, not the module where the output - // was declared. - _, outp := addr.ModuleCallOutput() - _, call := addr.Module.CallInstance() - return []addrs.Referenceable{outp, call} - -} - // GraphNodeReferenceable -func (n *NodeApplyableOutput) ReferenceableAddrs() []addrs.Referenceable { - return referenceableAddrsForOutput(n.Addr) -} - -func referencesForOutput(c *configs.Output) []*addrs.Reference { - impRefs, _ := lang.ReferencesInExpr(c.Expr) - expRefs, _ := lang.References(c.DependsOn) - l := len(impRefs) + len(expRefs) - if l == 0 { - return nil - } - refs := make([]*addrs.Reference, 0, l) - refs = append(refs, impRefs...) - refs = append(refs, expRefs...) - return refs - +func (n *NodeApplyableOutput) ReferenceableName() []string { + name := fmt.Sprintf("output.%s", n.Config.Name) + return []string{name} } // GraphNodeReferencer -func (n *NodeApplyableOutput) References() []*addrs.Reference { - return appendResourceDestroyReferences(referencesForOutput(n.Config)) +func (n *NodeApplyableOutput) References() []string { + var result []string + result = append(result, n.Config.DependsOn...) + result = append(result, ReferencesFromConfig(n.Config.RawConfig)...) + for _, v := range result { + split := strings.Split(v, "/") + for i, s := range split { + split[i] = s + ".destroy" + } + + result = append(result, strings.Join(split, "/")) + } + + return result } // GraphNodeEvalable @@ -116,24 +72,24 @@ func (n *NodeApplyableOutput) EvalTree() EvalNode { return &EvalSequence{ Nodes: []EvalNode{ &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkPlan, walkApply, walkValidate, walkDestroy, walkPlanDestroy}, + // Don't let interpolation errors stop Input, since it happens + // before Refresh. + Ops: []walkOperation{walkInput}, Node: &EvalWriteOutput{ - Addr: n.Addr.OutputValue, - Sensitive: n.Config.Sensitive, - Expr: n.Config.Expr, + Name: n.Config.Name, + Sensitive: n.Config.Sensitive, + Value: n.Config.RawConfig, + ContinueOnErr: true, + }, + }, + &EvalOpFilter{ + Ops: []walkOperation{walkRefresh, walkPlan, walkApply, walkValidate, walkDestroy, walkPlanDestroy}, + Node: &EvalWriteOutput{ + Name: n.Config.Name, + Sensitive: n.Config.Sensitive, + Value: n.Config.RawConfig, }, }, - }, - } -} - -// dag.GraphNodeDotter impl. -func (n *NodeApplyableOutput) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", }, } } @@ -141,26 +97,22 @@ func (n *NodeApplyableOutput) DotNode(name string, opts *dag.DotOpts) *dag.DotNo // NodeDestroyableOutput represents an output that is "destroybale": // its application will remove the output from the state. type NodeDestroyableOutput struct { - Addr addrs.AbsOutputValue - Config *configs.Output // Config is the output in the config + PathValue []string + Config *config.Output // Config is the output in the config } -var ( - _ GraphNodeSubPath = (*NodeDestroyableOutput)(nil) - _ RemovableIfNotTargeted = (*NodeDestroyableOutput)(nil) - _ GraphNodeTargetDownstream = (*NodeDestroyableOutput)(nil) - _ GraphNodeReferencer = (*NodeDestroyableOutput)(nil) - _ GraphNodeEvalable = (*NodeDestroyableOutput)(nil) - _ dag.GraphNodeDotter = (*NodeDestroyableOutput)(nil) -) - func (n *NodeDestroyableOutput) Name() string { - return fmt.Sprintf("%s (destroy)", n.Addr.String()) + result := fmt.Sprintf("output.%s (destroy)", n.Config.Name) + if len(n.PathValue) > 1 { + result = fmt.Sprintf("%s.%s", modulePrefixStr(n.PathValue), result) + } + + return result } // GraphNodeSubPath -func (n *NodeDestroyableOutput) Path() addrs.ModuleInstance { - return n.Addr.Module +func (n *NodeDestroyableOutput) Path() []string { + return n.PathValue } // RemovableIfNotTargeted @@ -177,24 +129,25 @@ func (n *NodeDestroyableOutput) TargetDownstream(targetedDeps, untargetedDeps *d } // GraphNodeReferencer -func (n *NodeDestroyableOutput) References() []*addrs.Reference { - return referencesForOutput(n.Config) +func (n *NodeDestroyableOutput) References() []string { + var result []string + result = append(result, n.Config.DependsOn...) + result = append(result, ReferencesFromConfig(n.Config.RawConfig)...) + for _, v := range result { + split := strings.Split(v, "/") + for i, s := range split { + split[i] = s + ".destroy" + } + + result = append(result, strings.Join(split, "/")) + } + + return result } // GraphNodeEvalable func (n *NodeDestroyableOutput) EvalTree() EvalNode { return &EvalDeleteOutput{ - Addr: n.Addr.OutputValue, - } -} - -// dag.GraphNodeDotter impl. -func (n *NodeDestroyableOutput) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, + Name: n.Config.Name, } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_output_orphan.go b/vendor/github.com/hashicorp/terraform/terraform/node_output_orphan.go index 518b8aa0..0fd1554a 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_output_orphan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_output_orphan.go @@ -2,39 +2,31 @@ package terraform import ( "fmt" - - "github.com/hashicorp/terraform/addrs" ) // NodeOutputOrphan represents an output that is an orphan. type NodeOutputOrphan struct { - Addr addrs.AbsOutputValue + OutputName string + PathValue []string } -var ( - _ GraphNodeSubPath = (*NodeOutputOrphan)(nil) - _ GraphNodeReferenceable = (*NodeOutputOrphan)(nil) - _ GraphNodeReferenceOutside = (*NodeOutputOrphan)(nil) - _ GraphNodeEvalable = (*NodeOutputOrphan)(nil) -) - func (n *NodeOutputOrphan) Name() string { - return fmt.Sprintf("%s (orphan)", n.Addr.String()) -} + result := fmt.Sprintf("output.%s (orphan)", n.OutputName) + if len(n.PathValue) > 1 { + result = fmt.Sprintf("%s.%s", modulePrefixStr(n.PathValue), result) + } -// GraphNodeReferenceOutside implementation -func (n *NodeOutputOrphan) ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) { - return referenceOutsideForOutput(n.Addr) + return result } // GraphNodeReferenceable -func (n *NodeOutputOrphan) ReferenceableAddrs() []addrs.Referenceable { - return referenceableAddrsForOutput(n.Addr) +func (n *NodeOutputOrphan) ReferenceableName() []string { + return []string{"output." + n.OutputName} } // GraphNodeSubPath -func (n *NodeOutputOrphan) Path() addrs.ModuleInstance { - return n.Addr.Module +func (n *NodeOutputOrphan) Path() []string { + return n.PathValue } // GraphNodeEvalable @@ -42,7 +34,7 @@ func (n *NodeOutputOrphan) EvalTree() EvalNode { return &EvalOpFilter{ Ops: []walkOperation{walkRefresh, walkApply, walkDestroy}, Node: &EvalDeleteOutput{ - Addr: n.Addr.OutputValue, + Name: n.OutputName, }, } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_provider_abstract.go b/vendor/github.com/hashicorp/terraform/terraform/node_provider_abstract.go index a0cdcfe0..9e490f7b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_provider_abstract.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_provider_abstract.go @@ -1,10 +1,10 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/configs/configschema" + "fmt" + "strings" + "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/dag" ) @@ -15,33 +15,37 @@ type ConcreteProviderNodeFunc func(*NodeAbstractProvider) dag.Vertex // NodeAbstractProvider represents a provider that has no associated operations. // It registers all the common interfaces across operations for providers. type NodeAbstractProvider struct { - Addr addrs.AbsProviderConfig + NameValue string + PathValue []string // The fields below will be automatically set using the Attach // interfaces if you're running those transforms, but also be explicitly // set if you already have that information. - Config *configs.Provider - Schema *configschema.Block + Config *config.ProviderConfig } -var ( - _ GraphNodeSubPath = (*NodeAbstractProvider)(nil) - _ RemovableIfNotTargeted = (*NodeAbstractProvider)(nil) - _ GraphNodeReferencer = (*NodeAbstractProvider)(nil) - _ GraphNodeProvider = (*NodeAbstractProvider)(nil) - _ GraphNodeAttachProvider = (*NodeAbstractProvider)(nil) - _ GraphNodeAttachProviderConfigSchema = (*NodeAbstractProvider)(nil) - _ dag.GraphNodeDotter = (*NodeAbstractProvider)(nil) -) +func ResolveProviderName(name string, path []string) string { + if strings.Contains(name, "provider.") { + // already resolved + return name + } + + name = fmt.Sprintf("provider.%s", name) + if len(path) >= 1 { + name = fmt.Sprintf("%s.%s", modulePrefixStr(path), name) + } + + return name +} func (n *NodeAbstractProvider) Name() string { - return n.Addr.String() + return ResolveProviderName(n.NameValue, n.PathValue) } // GraphNodeSubPath -func (n *NodeAbstractProvider) Path() addrs.ModuleInstance { - return n.Addr.Module +func (n *NodeAbstractProvider) Path() []string { + return n.PathValue } // RemovableIfNotTargeted @@ -52,21 +56,21 @@ func (n *NodeAbstractProvider) RemoveIfNotTargeted() bool { } // GraphNodeReferencer -func (n *NodeAbstractProvider) References() []*addrs.Reference { - if n.Config == nil || n.Schema == nil { +func (n *NodeAbstractProvider) References() []string { + if n.Config == nil { return nil } - return ReferencesFromConfig(n.Config.Config, n.Schema) + return ReferencesFromConfig(n.Config.RawConfig) } // GraphNodeProvider -func (n *NodeAbstractProvider) ProviderAddr() addrs.AbsProviderConfig { - return n.Addr +func (n *NodeAbstractProvider) ProviderName() string { + return n.NameValue } // GraphNodeProvider -func (n *NodeAbstractProvider) ProviderConfig() *configs.Provider { +func (n *NodeAbstractProvider) ProviderConfig() *config.ProviderConfig { if n.Config == nil { return nil } @@ -75,15 +79,10 @@ func (n *NodeAbstractProvider) ProviderConfig() *configs.Provider { } // GraphNodeAttachProvider -func (n *NodeAbstractProvider) AttachProvider(c *configs.Provider) { +func (n *NodeAbstractProvider) AttachProvider(c *config.ProviderConfig) { n.Config = c } -// GraphNodeAttachProviderConfigSchema impl. -func (n *NodeAbstractProvider) AttachProviderConfigSchema(schema *configschema.Block) { - n.Schema = schema -} - // GraphNodeDotter impl. func (n *NodeAbstractProvider) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { return &dag.DotNode{ diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_provider_disabled.go b/vendor/github.com/hashicorp/terraform/terraform/node_provider_disabled.go index 30d8813a..a00bc46f 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_provider_disabled.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_provider_disabled.go @@ -2,8 +2,6 @@ package terraform import ( "fmt" - - "github.com/hashicorp/terraform/dag" ) // NodeDisabledProvider represents a provider that is disabled. A disabled @@ -13,15 +11,24 @@ type NodeDisabledProvider struct { *NodeAbstractProvider } -var ( - _ GraphNodeSubPath = (*NodeDisabledProvider)(nil) - _ RemovableIfNotTargeted = (*NodeDisabledProvider)(nil) - _ GraphNodeReferencer = (*NodeDisabledProvider)(nil) - _ GraphNodeProvider = (*NodeDisabledProvider)(nil) - _ GraphNodeAttachProvider = (*NodeDisabledProvider)(nil) - _ dag.GraphNodeDotter = (*NodeDisabledProvider)(nil) -) - func (n *NodeDisabledProvider) Name() string { return fmt.Sprintf("%s (disabled)", n.NodeAbstractProvider.Name()) } + +// GraphNodeEvalable +func (n *NodeDisabledProvider) EvalTree() EvalNode { + var resourceConfig *ResourceConfig + return &EvalSequence{ + Nodes: []EvalNode{ + &EvalInterpolateProvider{ + Config: n.ProviderConfig(), + Output: &resourceConfig, + }, + &EvalBuildProviderConfig{ + Provider: n.ProviderName(), + Config: &resourceConfig, + Output: &resourceConfig, + }, + }, + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_provider_eval.go b/vendor/github.com/hashicorp/terraform/terraform/node_provider_eval.go deleted file mode 100644 index 580e60cb..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/node_provider_eval.go +++ /dev/null @@ -1,20 +0,0 @@ -package terraform - -// NodeEvalableProvider represents a provider during an "eval" walk. -// This special provider node type just initializes a provider and -// fetches its schema, without configuring it or otherwise interacting -// with it. -type NodeEvalableProvider struct { - *NodeAbstractProvider -} - -// GraphNodeEvalable -func (n *NodeEvalableProvider) EvalTree() EvalNode { - addr := n.Addr - relAddr := addr.ProviderConfig - - return &EvalInitProvider{ - TypeName: relAddr.Type, - Addr: addr.ProviderConfig, - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/node_provisioner.go index 31ed1a8c..bb117c1d 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_provisioner.go @@ -3,7 +3,6 @@ package terraform import ( "fmt" - "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/config" ) @@ -11,7 +10,7 @@ import ( // It registers all the common interfaces across operations for providers. type NodeProvisioner struct { NameValue string - PathValue addrs.ModuleInstance + PathValue []string // The fields below will be automatically set using the Attach // interfaces if you're running those transforms, but also be explicitly @@ -20,23 +19,17 @@ type NodeProvisioner struct { Config *config.ProviderConfig } -var ( - _ GraphNodeSubPath = (*NodeProvisioner)(nil) - _ GraphNodeProvisioner = (*NodeProvisioner)(nil) - _ GraphNodeEvalable = (*NodeProvisioner)(nil) -) - func (n *NodeProvisioner) Name() string { result := fmt.Sprintf("provisioner.%s", n.NameValue) - if len(n.PathValue) > 0 { - result = fmt.Sprintf("%s.%s", n.PathValue.String(), result) + if len(n.PathValue) > 1 { + result = fmt.Sprintf("%s.%s", modulePrefixStr(n.PathValue), result) } return result } // GraphNodeSubPath -func (n *NodeProvisioner) Path() addrs.ModuleInstance { +func (n *NodeProvisioner) Path() []string { return n.PathValue } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract.go index 3a0570c5..73509c87 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract.go @@ -2,16 +2,10 @@ package terraform import ( "fmt" - "log" - "sort" + "strings" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/configs/configschema" + "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/lang" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) // ConcreteResourceNodeFunc is a callback type used to convert an @@ -22,420 +16,225 @@ type ConcreteResourceNodeFunc func(*NodeAbstractResource) dag.Vertex // The type of operation cannot be assumed, only that this node represents // the given resource. type GraphNodeResource interface { - ResourceAddr() addrs.AbsResource -} - -// ConcreteResourceInstanceNodeFunc is a callback type used to convert an -// abstract resource instance to a concrete one of some type. -type ConcreteResourceInstanceNodeFunc func(*NodeAbstractResourceInstance) dag.Vertex - -// GraphNodeResourceInstance is implemented by any nodes that represent -// a resource instance. A single resource may have multiple instances if, -// for example, the "count" or "for_each" argument is used for it in -// configuration. -type GraphNodeResourceInstance interface { - ResourceInstanceAddr() addrs.AbsResourceInstance + ResourceAddr() *ResourceAddress } // NodeAbstractResource represents a resource that has no associated // operations. It registers all the interfaces for a resource that common // across multiple operation types. type NodeAbstractResource struct { - Addr addrs.AbsResource // Addr is the address for this resource + Addr *ResourceAddress // Addr is the address for this resource // The fields below will be automatically set using the Attach // interfaces if you're running those transforms, but also be explicitly // set if you already have that information. - Schema *configschema.Block // Schema for processing the configuration body - SchemaVersion uint64 // Schema version of "Schema", as decided by the provider - Config *configs.Resource // Config is the resource in the config + Config *config.Resource // Config is the resource in the config + ResourceState *ResourceState // ResourceState is the ResourceState for this - ProvisionerSchemas map[string]*configschema.Block - - Targets []addrs.Targetable // Set from GraphNodeTargetable + Targets []ResourceAddress // Set from GraphNodeTargetable // The address of the provider this resource will use - ResolvedProvider addrs.AbsProviderConfig -} - -var ( - _ GraphNodeSubPath = (*NodeAbstractResource)(nil) - _ GraphNodeReferenceable = (*NodeAbstractResource)(nil) - _ GraphNodeReferencer = (*NodeAbstractResource)(nil) - _ GraphNodeProviderConsumer = (*NodeAbstractResource)(nil) - _ GraphNodeProvisionerConsumer = (*NodeAbstractResource)(nil) - _ GraphNodeResource = (*NodeAbstractResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeAbstractResource)(nil) - _ GraphNodeAttachResourceSchema = (*NodeAbstractResource)(nil) - _ GraphNodeAttachProvisionerSchema = (*NodeAbstractResource)(nil) - _ GraphNodeTargetable = (*NodeAbstractResource)(nil) - _ dag.GraphNodeDotter = (*NodeAbstractResource)(nil) -) - -// NewNodeAbstractResource creates an abstract resource graph node for -// the given absolute resource address. -func NewNodeAbstractResource(addr addrs.AbsResource) *NodeAbstractResource { - return &NodeAbstractResource{ - Addr: addr, - } -} - -// NodeAbstractResourceInstance represents a resource instance with no -// associated operations. It embeds NodeAbstractResource but additionally -// contains an instance key, used to identify one of potentially many -// instances that were created from a resource in configuration, e.g. using -// the "count" or "for_each" arguments. -type NodeAbstractResourceInstance struct { - NodeAbstractResource - InstanceKey addrs.InstanceKey - - // The fields below will be automatically set using the Attach - // interfaces if you're running those transforms, but also be explicitly - // set if you already have that information. - - ResourceState *states.Resource -} - -var ( - _ GraphNodeSubPath = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeProviderConsumer = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeProvisionerConsumer = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeResource = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeAttachResourceState = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeAttachResourceConfig = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeAttachResourceSchema = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeAttachProvisionerSchema = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeTargetable = (*NodeAbstractResourceInstance)(nil) - _ dag.GraphNodeDotter = (*NodeAbstractResourceInstance)(nil) -) - -// NewNodeAbstractResourceInstance creates an abstract resource instance graph -// node for the given absolute resource instance address. -func NewNodeAbstractResourceInstance(addr addrs.AbsResourceInstance) *NodeAbstractResourceInstance { - // Due to the fact that we embed NodeAbstractResource, the given address - // actually ends up split between the resource address in the embedded - // object and the InstanceKey field in our own struct. The - // ResourceInstanceAddr method will stick these back together again on - // request. - return &NodeAbstractResourceInstance{ - NodeAbstractResource: NodeAbstractResource{ - Addr: addr.ContainingResource(), - }, - InstanceKey: addr.Resource.Key, - } + ResolvedProvider string } func (n *NodeAbstractResource) Name() string { - return n.ResourceAddr().String() -} - -func (n *NodeAbstractResourceInstance) Name() string { - return n.ResourceInstanceAddr().String() + return n.Addr.String() } // GraphNodeSubPath -func (n *NodeAbstractResource) Path() addrs.ModuleInstance { - return n.Addr.Module +func (n *NodeAbstractResource) Path() []string { + return n.Addr.Path } // GraphNodeReferenceable -func (n *NodeAbstractResource) ReferenceableAddrs() []addrs.Referenceable { - return []addrs.Referenceable{n.Addr.Resource} -} - -// GraphNodeReferenceable -func (n *NodeAbstractResourceInstance) ReferenceableAddrs() []addrs.Referenceable { - addr := n.ResourceInstanceAddr() - return []addrs.Referenceable{ - addr.Resource, - - // A resource instance can also be referenced by the address of its - // containing resource, so that e.g. a reference to aws_instance.foo - // would match both aws_instance.foo[0] and aws_instance.foo[1]. - addr.ContainingResource().Resource, - } -} - -// GraphNodeReferencer -func (n *NodeAbstractResource) References() []*addrs.Reference { - // If we have a config then we prefer to use that. - if c := n.Config; c != nil { - var result []*addrs.Reference - - for _, traversal := range c.DependsOn { - ref, err := addrs.ParseRef(traversal) - if err != nil { - // We ignore this here, because this isn't a suitable place to return - // errors. This situation should be caught and rejected during - // validation. - log.Printf("[ERROR] Can't parse %#v from depends_on as reference: %s", traversal, err) - continue - } - - result = append(result, ref) - } - - if n.Schema == nil { - // Should never happens, but we'll log if it does so that we can - // see this easily when debugging. - log.Printf("[WARN] no schema is attached to %s, so config references cannot be detected", n.Name()) - } - - refs, _ := lang.ReferencesInExpr(c.Count) - result = append(result, refs...) - refs, _ = lang.ReferencesInBlock(c.Config, n.Schema) - result = append(result, refs...) - if c.Managed != nil { - for _, p := range c.Managed.Provisioners { - if p.When != configs.ProvisionerWhenCreate { - continue - } - if p.Connection != nil { - refs, _ = lang.ReferencesInBlock(p.Connection.Config, connectionBlockSupersetSchema) - result = append(result, refs...) - } - - schema := n.ProvisionerSchemas[p.Type] - if schema == nil { - log.Printf("[WARN] no schema for provisioner %q is attached to %s, so provisioner block references cannot be detected", p.Type, n.Name()) - } - refs, _ = lang.ReferencesInBlock(p.Config, schema) - result = append(result, refs...) - } - } - return result - } - - // Otherwise, we have no references. - return nil -} - -// GraphNodeReferencer -func (n *NodeAbstractResourceInstance) References() []*addrs.Reference { - // If we have a configuration attached then we'll delegate to our - // embedded abstract resource, which knows how to extract dependencies - // from configuration. +func (n *NodeAbstractResource) ReferenceableName() []string { + // We always are referenceable as "type.name" as long as + // we have a config or address. Determine what that value is. + var id string if n.Config != nil { - if n.Schema == nil { - // We'll produce a log message about this out here so that - // we can include the full instance address, since the equivalent - // message in NodeAbstractResource.References cannot see it. - log.Printf("[WARN] no schema is attached to %s, so config references cannot be detected", n.Name()) - return nil - } - return n.NodeAbstractResource.References() + id = n.Config.Id() + } else if n.Addr != nil { + addrCopy := n.Addr.Copy() + addrCopy.Path = nil // ReferenceTransformer handles paths + addrCopy.Index = -1 // We handle indexes below + id = addrCopy.String() + } else { + // No way to determine our type.name, just return + return nil } - // Otherwise, if we have state then we'll use the values stored in state - // as a fallback. - if rs := n.ResourceState; rs != nil { - if s := rs.Instance(n.InstanceKey); s != nil { - // State is still storing dependencies as old-style strings, so we'll - // need to do a little work here to massage this to the form we now - // want. - var result []*addrs.Reference - for _, addr := range s.Current.Dependencies { - if addr == nil { - // Should never happen; indicates a bug in the state loader - panic(fmt.Sprintf("dependencies for current object on %s contains nil address", n.ResourceInstanceAddr())) - } + var result []string - // This is a little weird: we need to manufacture an addrs.Reference - // with a fake range here because the state isn't something we can - // make source references into. - result = append(result, &addrs.Reference{ - Subject: addr, - SourceRange: tfdiags.SourceRange{ - Filename: "(state file)", - }, - }) - } - return result + // Always include our own ID. This is primarily for backwards + // compatibility with states that didn't yet support the more + // specific dep string. + result = append(result, id) + + // We represent all multi-access + result = append(result, fmt.Sprintf("%s.*", id)) + + // We represent either a specific number, or all numbers + suffix := "N" + if n.Addr != nil { + idx := n.Addr.Index + if idx == -1 { + idx = 0 } - } - // If we have neither config nor state then we have no references. - return nil + suffix = fmt.Sprintf("%d", idx) + } + result = append(result, fmt.Sprintf("%s.%s", id, suffix)) + + return result } -// converts an instance address to the legacy dotted notation -func dottedInstanceAddr(tr addrs.ResourceInstance) string { - // The legacy state format uses dot-separated instance keys, - // rather than bracketed as in our modern syntax. - var suffix string - switch tk := tr.Key.(type) { - case addrs.IntKey: - suffix = fmt.Sprintf(".%d", int(tk)) - case addrs.StringKey: - suffix = fmt.Sprintf(".%s", string(tk)) +// GraphNodeReferencer +func (n *NodeAbstractResource) References() []string { + // If we have a config, that is our source of truth + if c := n.Config; c != nil { + // Grab all the references + var result []string + result = append(result, c.DependsOn...) + result = append(result, ReferencesFromConfig(c.RawCount)...) + result = append(result, ReferencesFromConfig(c.RawConfig)...) + for _, p := range c.Provisioners { + if p.When == config.ProvisionerWhenCreate { + result = append(result, ReferencesFromConfig(p.ConnInfo)...) + result = append(result, ReferencesFromConfig(p.RawConfig)...) + } + } + + return uniqueStrings(result) } - return tr.Resource.String() + suffix + + // If we have state, that is our next source + if s := n.ResourceState; s != nil { + return s.Dependencies + } + + return nil } // StateReferences returns the dependencies to put into the state for // this resource. -func (n *NodeAbstractResourceInstance) StateReferences() []addrs.Referenceable { - selfAddrs := n.ReferenceableAddrs() +func (n *NodeAbstractResource) StateReferences() []string { + self := n.ReferenceableName() - // Since we don't include the source location references in our - // results from this method, we'll also filter out duplicates: - // there's no point in listing the same object twice without - // that additional context. - seen := map[string]struct{}{} - - // Pretend that we've already "seen" all of our own addresses so that we - // won't record self-references in the state. This can arise if, for - // example, a provisioner for a resource refers to the resource itself, - // which is valid (since provisioners always run after apply) but should - // not create an explicit dependency edge. - for _, selfAddr := range selfAddrs { - seen[selfAddr.String()] = struct{}{} - if riAddr, ok := selfAddr.(addrs.ResourceInstance); ok { - seen[riAddr.ContainingResource().String()] = struct{}{} - } - } + // Determine what our "prefix" is for checking for references to + // ourself. + addrCopy := n.Addr.Copy() + addrCopy.Index = -1 + selfPrefix := addrCopy.String() + "." depsRaw := n.References() - deps := make([]addrs.Referenceable, 0, len(depsRaw)) + deps := make([]string, 0, len(depsRaw)) for _, d := range depsRaw { - subj := d.Subject - if mco, isOutput := subj.(addrs.ModuleCallOutput); isOutput { - // For state dependencies, we simplify outputs to just refer - // to the module as a whole. It's not really clear why we do this, - // but this logic is preserved from before the 0.12 rewrite of - // this function. - subj = mco.Call - } - - k := subj.String() - if _, exists := seen[k]; exists { + // Ignore any variable dependencies + if strings.HasPrefix(d, "var.") { continue } - seen[k] = struct{}{} - switch tr := subj.(type) { - case addrs.ResourceInstance: - deps = append(deps, tr) - case addrs.Resource: - deps = append(deps, tr) - case addrs.ModuleCallInstance: - deps = append(deps, tr) - default: - // No other reference types are recorded in the state. - } - } - // We'll also sort them, since that'll avoid creating changes in the - // serialized state that make no semantic difference. - sort.Slice(deps, func(i, j int) bool { - // Simple string-based sort because we just care about consistency, - // not user-friendliness. - return deps[i].String() < deps[j].String() - }) + // If this has a backup ref, ignore those for now. The old state + // file never contained those and I'd rather store the rich types we + // add in the future. + if idx := strings.IndexRune(d, '/'); idx != -1 { + d = d[:idx] + } + + // If we're referencing ourself, then ignore it + found := false + for _, s := range self { + if d == s { + found = true + } + } + if found { + continue + } + + // If this is a reference to ourself and a specific index, we keep + // it. For example, if this resource is "foo.bar" and the reference + // is "foo.bar.0" then we keep it exact. Otherwise, we strip it. + if strings.HasSuffix(d, ".0") && !strings.HasPrefix(d, selfPrefix) { + d = d[:len(d)-2] + } + + // This is sad. The dependencies are currently in the format of + // "module.foo.bar" (the full field). This strips the field off. + if strings.HasPrefix(d, "module.") { + parts := strings.SplitN(d, ".", 3) + d = strings.Join(parts[0:2], ".") + } + + deps = append(deps, d) + } return deps } -func (n *NodeAbstractResource) SetProvider(p addrs.AbsProviderConfig) { +func (n *NodeAbstractResource) SetProvider(p string) { n.ResolvedProvider = p } // GraphNodeProviderConsumer -func (n *NodeAbstractResource) ProvidedBy() (addrs.AbsProviderConfig, bool) { +func (n *NodeAbstractResource) ProvidedBy() string { // If we have a config we prefer that above all else if n.Config != nil { - relAddr := n.Config.ProviderConfigAddr() - return relAddr.Absolute(n.Path()), false - } - - // Use our type and containing module path to guess a provider configuration address - return n.Addr.Resource.DefaultProviderConfig().Absolute(n.Addr.Module), false -} - -// GraphNodeProviderConsumer -func (n *NodeAbstractResourceInstance) ProvidedBy() (addrs.AbsProviderConfig, bool) { - // If we have a config we prefer that above all else - if n.Config != nil { - relAddr := n.Config.ProviderConfigAddr() - return relAddr.Absolute(n.Path()), false + return resourceProvider(n.Config.Type, n.Config.Provider) } // If we have state, then we will use the provider from there - if n.ResourceState != nil { - // An address from the state must match exactly, since we must ensure - // we refresh/destroy a resource with the same provider configuration - // that created it. - return n.ResourceState.ProviderConfig, true + if n.ResourceState != nil && n.ResourceState.Provider != "" { + return n.ResourceState.Provider } - // Use our type and containing module path to guess a provider configuration address - return n.Addr.Resource.DefaultProviderConfig().Absolute(n.Path()), false + // Use our type + return resourceProvider(n.Addr.Type, "") } // GraphNodeProvisionerConsumer func (n *NodeAbstractResource) ProvisionedBy() []string { // If we have no configuration, then we have no provisioners - if n.Config == nil || n.Config.Managed == nil { + if n.Config == nil { return nil } // Build the list of provisioners we need based on the configuration. // It is okay to have duplicates here. - result := make([]string, len(n.Config.Managed.Provisioners)) - for i, p := range n.Config.Managed.Provisioners { + result := make([]string, len(n.Config.Provisioners)) + for i, p := range n.Config.Provisioners { result[i] = p.Type } return result } -// GraphNodeProvisionerConsumer -func (n *NodeAbstractResource) AttachProvisionerSchema(name string, schema *configschema.Block) { - if n.ProvisionerSchemas == nil { - n.ProvisionerSchemas = make(map[string]*configschema.Block) - } - n.ProvisionerSchemas[name] = schema -} - -// GraphNodeResource -func (n *NodeAbstractResource) ResourceAddr() addrs.AbsResource { +// GraphNodeResource, GraphNodeAttachResourceState +func (n *NodeAbstractResource) ResourceAddr() *ResourceAddress { return n.Addr } -// GraphNodeResourceInstance -func (n *NodeAbstractResourceInstance) ResourceInstanceAddr() addrs.AbsResourceInstance { - return n.NodeAbstractResource.Addr.Instance(n.InstanceKey) -} - // GraphNodeAddressable, TODO: remove, used by target, should unify func (n *NodeAbstractResource) ResourceAddress() *ResourceAddress { - return NewLegacyResourceAddress(n.Addr) + return n.ResourceAddr() } // GraphNodeTargetable -func (n *NodeAbstractResource) SetTargets(targets []addrs.Targetable) { +func (n *NodeAbstractResource) SetTargets(targets []ResourceAddress) { n.Targets = targets } // GraphNodeAttachResourceState -func (n *NodeAbstractResourceInstance) AttachResourceState(s *states.Resource) { +func (n *NodeAbstractResource) AttachResourceState(s *ResourceState) { n.ResourceState = s } // GraphNodeAttachResourceConfig -func (n *NodeAbstractResource) AttachResourceConfig(c *configs.Resource) { +func (n *NodeAbstractResource) AttachResourceConfig(c *config.Resource) { n.Config = c } -// GraphNodeAttachResourceSchema impl -func (n *NodeAbstractResource) AttachResourceSchema(schema *configschema.Block, version uint64) { - n.Schema = schema - n.SchemaVersion = version -} - // GraphNodeDotter impl. func (n *NodeAbstractResource) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { return &dag.DotNode{ diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract_count.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract_count.go new file mode 100644 index 00000000..573570d8 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract_count.go @@ -0,0 +1,50 @@ +package terraform + +// NodeAbstractCountResource should be embedded instead of NodeAbstractResource +// if the resource has a `count` value that needs to be expanded. +// +// The embedder should implement `DynamicExpand` to process the count. +type NodeAbstractCountResource struct { + *NodeAbstractResource + + // Validate, if true, will perform the validation for the count. + // This should only be turned on for the "validate" operation. + Validate bool +} + +// GraphNodeEvalable +func (n *NodeAbstractCountResource) EvalTree() EvalNode { + // We only check if the count is computed if we're not validating. + // If we're validating we allow computed counts since they just turn + // into more computed values. + var evalCountCheckComputed EvalNode + if !n.Validate { + evalCountCheckComputed = &EvalCountCheckComputed{Resource: n.Config} + } + + return &EvalSequence{ + Nodes: []EvalNode{ + // The EvalTree for a plannable resource primarily involves + // interpolating the count since it can contain variables + // we only just received access to. + // + // With the interpolated count, we can then DynamicExpand + // into the proper number of instances. + &EvalInterpolate{Config: n.Config.RawCount}, + + // Check if the count is computed + evalCountCheckComputed, + + // If validation is enabled, perform the validation + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + return n.Validate, nil + }, + + Then: &EvalValidateCount{Resource: n.Config}, + }, + + &EvalCountFixZeroOneBoundary{Resource: n.Config}, + }, + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply.go index 3e2fff3a..40ee1cf2 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply.go @@ -1,71 +1,400 @@ package terraform import ( - "log" + "fmt" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/lang" + "github.com/hashicorp/terraform/config" ) // NodeApplyableResource represents a resource that is "applyable": -// it may need to have its record in the state adjusted to match configuration. -// -// Unlike in the plan walk, this resource node does not DynamicExpand. Instead, -// it should be inserted into the same graph as any instances of the nodes -// with dependency edges ensuring that the resource is evaluated before any -// of its instances, which will turn ensure that the whole-resource record -// in the state is suitably prepared to receive any updates to instances. +// it is ready to be applied and is represented by a diff. type NodeApplyableResource struct { *NodeAbstractResource } -var ( - _ GraphNodeResource = (*NodeApplyableResource)(nil) - _ GraphNodeEvalable = (*NodeApplyableResource)(nil) - _ GraphNodeProviderConsumer = (*NodeApplyableResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeApplyableResource)(nil) - _ GraphNodeReferencer = (*NodeApplyableResource)(nil) -) - -func (n *NodeApplyableResource) Name() string { - return n.NodeAbstractResource.Name() + " (prepare state)" +// GraphNodeCreator +func (n *NodeApplyableResource) CreateAddr() *ResourceAddress { + return n.NodeAbstractResource.Addr } -func (n *NodeApplyableResource) References() []*addrs.Reference { - if n.Config == nil { - log.Printf("[WARN] NodeApplyableResource %q: no configuration, so can't determine References", dag.VertexName(n)) - return nil +// GraphNodeReferencer, overriding NodeAbstractResource +func (n *NodeApplyableResource) References() []string { + result := n.NodeAbstractResource.References() + + // The "apply" side of a resource generally also depends on the + // destruction of its dependencies as well. For example, if a LB + // references a set of VMs with ${vm.foo.*.id}, then we must wait for + // the destruction so we get the newly updated list of VMs. + // + // The exception here is CBD. When CBD is set, we don't do this since + // it would create a cycle. By not creating a cycle, we require two + // applies since the first apply the creation step will use the OLD + // values (pre-destroy) and the second step will update. + // + // This is how Terraform behaved with "legacy" graphs (TF <= 0.7.x). + // We mimic that behavior here now and can improve upon it in the future. + // + // This behavior is tested in graph_build_apply_test.go to test ordering. + cbd := n.Config != nil && n.Config.Lifecycle.CreateBeforeDestroy + if !cbd { + // The "apply" side of a resource always depends on the destruction + // of all its dependencies in addition to the creation. + for _, v := range result { + result = append(result, v+".destroy") + } } - var result []*addrs.Reference - - // Since this node type only updates resource-level metadata, we only - // need to worry about the parts of the configuration that affect - // our "each mode": the count and for_each meta-arguments. - refs, _ := lang.ReferencesInExpr(n.Config.Count) - result = append(result, refs...) - refs, _ = lang.ReferencesInExpr(n.Config.ForEach) - result = append(result, refs...) - return result } // GraphNodeEvalable func (n *NodeApplyableResource) EvalTree() EvalNode { - addr := n.ResourceAddr() - config := n.Config - providerAddr := n.ResolvedProvider + addr := n.NodeAbstractResource.Addr - if config == nil { - // Nothing to do, then. - log.Printf("[TRACE] NodeApplyableResource: no configuration present for %s", addr) - return &EvalNoop{} + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: addr.Type, } - return &EvalWriteResourceState{ - Addr: addr.Resource, - Config: config, - ProviderAddr: providerAddr, + // Build the resource for eval + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } + + // Determine the dependencies for the state. + stateDeps := n.StateReferences() + + // Eval info is different depending on what kind of resource this is + switch n.Config.Mode { + case config.ManagedResourceMode: + return n.evalTreeManagedResource( + stateId, info, resource, stateDeps, + ) + case config.DataResourceMode: + return n.evalTreeDataResource( + stateId, info, resource, stateDeps) + default: + panic(fmt.Errorf("unsupported resource mode %s", n.Config.Mode)) + } +} + +func (n *NodeApplyableResource) evalTreeDataResource( + stateId string, info *InstanceInfo, + resource *Resource, stateDeps []string) EvalNode { + var provider ResourceProvider + var config *ResourceConfig + var diff *InstanceDiff + var state *InstanceState + + return &EvalSequence{ + Nodes: []EvalNode{ + // Build the instance info + &EvalInstanceInfo{ + Info: info, + }, + + // Get the saved diff for apply + &EvalReadDiff{ + Name: stateId, + Diff: &diff, + }, + + // Stop here if we don't actually have a diff + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + if diff == nil { + return true, EvalEarlyExitError{} + } + + if diff.GetAttributesLen() == 0 { + return true, EvalEarlyExitError{} + } + + return true, nil + }, + Then: EvalNoop{}, + }, + + // Normally we interpolate count as a preparation step before + // a DynamicExpand, but an apply graph has pre-expanded nodes + // and so the count would otherwise never be interpolated. + // + // This is redundant when there are multiple instances created + // from the same config (count > 1) but harmless since the + // underlying structures have mutexes to make this concurrency-safe. + // + // In most cases this isn't actually needed because we dealt with + // all of the counts during the plan walk, but we do it here + // for completeness because other code assumes that the + // final count is always available during interpolation. + // + // Here we are just populating the interpolated value in-place + // inside this RawConfig object, like we would in + // NodeAbstractCountResource. + &EvalInterpolate{ + Config: n.Config.RawCount, + ContinueOnErr: true, + }, + + // We need to re-interpolate the config here, rather than + // just using the diff's values directly, because we've + // potentially learned more variable values during the + // apply pass that weren't known when the diff was produced. + &EvalInterpolate{ + Config: n.Config.RawConfig.Copy(), + Resource: resource, + Output: &config, + }, + + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, + }, + + // Make a new diff with our newly-interpolated config. + &EvalReadDataDiff{ + Info: info, + Config: &config, + Previous: &diff, + Provider: &provider, + Output: &diff, + }, + + &EvalReadDataApply{ + Info: info, + Diff: &diff, + Provider: &provider, + Output: &state, + }, + + &EvalWriteState{ + Name: stateId, + ResourceType: n.Config.Type, + Provider: n.ResolvedProvider, + Dependencies: stateDeps, + State: &state, + }, + + // Clear the diff now that we've applied it, so + // later nodes won't see a diff that's now a no-op. + &EvalWriteDiff{ + Name: stateId, + Diff: nil, + }, + + &EvalUpdateStateHook{}, + }, + } +} + +func (n *NodeApplyableResource) evalTreeManagedResource( + stateId string, info *InstanceInfo, + resource *Resource, stateDeps []string) EvalNode { + // Declare a bunch of variables that are used for state during + // evaluation. Most of this are written to by-address below. + var provider ResourceProvider + var diff, diffApply *InstanceDiff + var state *InstanceState + var resourceConfig *ResourceConfig + var err error + var createNew bool + var createBeforeDestroyEnabled bool + + return &EvalSequence{ + Nodes: []EvalNode{ + // Build the instance info + &EvalInstanceInfo{ + Info: info, + }, + + // Get the saved diff for apply + &EvalReadDiff{ + Name: stateId, + Diff: &diffApply, + }, + + // We don't want to do any destroys + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + if diffApply == nil { + return true, EvalEarlyExitError{} + } + + if diffApply.GetDestroy() && diffApply.GetAttributesLen() == 0 { + return true, EvalEarlyExitError{} + } + + diffApply.SetDestroy(false) + return true, nil + }, + Then: EvalNoop{}, + }, + + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + destroy := false + if diffApply != nil { + destroy = diffApply.GetDestroy() || diffApply.RequiresNew() + } + + createBeforeDestroyEnabled = + n.Config.Lifecycle.CreateBeforeDestroy && + destroy + + return createBeforeDestroyEnabled, nil + }, + Then: &EvalDeposeState{ + Name: stateId, + }, + }, + + // Normally we interpolate count as a preparation step before + // a DynamicExpand, but an apply graph has pre-expanded nodes + // and so the count would otherwise never be interpolated. + // + // This is redundant when there are multiple instances created + // from the same config (count > 1) but harmless since the + // underlying structures have mutexes to make this concurrency-safe. + // + // In most cases this isn't actually needed because we dealt with + // all of the counts during the plan walk, but we need to do this + // in order to support interpolation of resource counts from + // apply-time-interpolated expressions, such as those in + // "provisioner" blocks. + // + // Here we are just populating the interpolated value in-place + // inside this RawConfig object, like we would in + // NodeAbstractCountResource. + &EvalInterpolate{ + Config: n.Config.RawCount, + ContinueOnErr: true, + }, + + &EvalInterpolate{ + Config: n.Config.RawConfig.Copy(), + Resource: resource, + Output: &resourceConfig, + }, + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, + }, + &EvalReadState{ + Name: stateId, + Output: &state, + }, + // Re-run validation to catch any errors we missed, e.g. type + // mismatches on computed values. + &EvalValidateResource{ + Provider: &provider, + Config: &resourceConfig, + ResourceName: n.Config.Name, + ResourceType: n.Config.Type, + ResourceMode: n.Config.Mode, + IgnoreWarnings: true, + }, + &EvalDiff{ + Info: info, + Config: &resourceConfig, + Resource: n.Config, + Provider: &provider, + Diff: &diffApply, + State: &state, + OutputDiff: &diffApply, + }, + + // Get the saved diff + &EvalReadDiff{ + Name: stateId, + Diff: &diff, + }, + + // Compare the diffs + &EvalCompareDiff{ + Info: info, + One: &diff, + Two: &diffApply, + }, + + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, + }, + &EvalReadState{ + Name: stateId, + Output: &state, + }, + // Call pre-apply hook + &EvalApplyPre{ + Info: info, + State: &state, + Diff: &diffApply, + }, + &EvalApply{ + Info: info, + State: &state, + Diff: &diffApply, + Provider: &provider, + Output: &state, + Error: &err, + CreateNew: &createNew, + }, + &EvalWriteState{ + Name: stateId, + ResourceType: n.Config.Type, + Provider: n.ResolvedProvider, + Dependencies: stateDeps, + State: &state, + }, + &EvalApplyProvisioners{ + Info: info, + State: &state, + Resource: n.Config, + InterpResource: resource, + CreateNew: &createNew, + Error: &err, + When: config.ProvisionerWhenCreate, + }, + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + return createBeforeDestroyEnabled && err != nil, nil + }, + Then: &EvalUndeposeState{ + Name: stateId, + State: &state, + }, + Else: &EvalWriteState{ + Name: stateId, + ResourceType: n.Config.Type, + Provider: n.ResolvedProvider, + Dependencies: stateDeps, + State: &state, + }, + }, + + // We clear the diff out here so that future nodes + // don't see a diff that is already complete. There + // is no longer a diff! + &EvalWriteDiff{ + Name: stateId, + Diff: nil, + }, + + &EvalApplyPost{ + Info: info, + State: &state, + Error: &err, + }, + &EvalUpdateStateHook{}, + }, } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply_instance.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply_instance.go deleted file mode 100644 index 4209605e..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply_instance.go +++ /dev/null @@ -1,411 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" -) - -// NodeApplyableResourceInstance represents a resource instance that is -// "applyable": it is ready to be applied and is represented by a diff. -// -// This node is for a specific instance of a resource. It will usually be -// accompanied in the graph by a NodeApplyableResource representing its -// containing resource, and should depend on that node to ensure that the -// state is properly prepared to receive changes to instances. -type NodeApplyableResourceInstance struct { - *NodeAbstractResourceInstance - - destroyNode GraphNodeDestroyerCBD - graphNodeDeposer // implementation of GraphNodeDeposer -} - -var ( - _ GraphNodeResource = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeCreator = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeDeposer = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeEvalable = (*NodeApplyableResourceInstance)(nil) -) - -// GraphNodeAttachDestroyer -func (n *NodeApplyableResourceInstance) AttachDestroyNode(d GraphNodeDestroyerCBD) { - n.destroyNode = d -} - -// createBeforeDestroy checks this nodes config status and the status af any -// companion destroy node for CreateBeforeDestroy. -func (n *NodeApplyableResourceInstance) createBeforeDestroy() bool { - cbd := false - - if n.Config != nil && n.Config.Managed != nil { - cbd = n.Config.Managed.CreateBeforeDestroy - } - - if n.destroyNode != nil { - cbd = cbd || n.destroyNode.CreateBeforeDestroy() - } - - return cbd -} - -// GraphNodeCreator -func (n *NodeApplyableResourceInstance) CreateAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr -} - -// GraphNodeReferencer, overriding NodeAbstractResourceInstance -func (n *NodeApplyableResourceInstance) References() []*addrs.Reference { - // Start with the usual resource instance implementation - ret := n.NodeAbstractResourceInstance.References() - - // Applying a resource must also depend on the destruction of any of its - // dependencies, since this may for example affect the outcome of - // evaluating an entire list of resources with "count" set (by reducing - // the count). - // - // However, we can't do this in create_before_destroy mode because that - // would create a dependency cycle. We make a compromise here of requiring - // changes to be updated across two applies in this case, since the first - // plan will use the old values. - if !n.createBeforeDestroy() { - for _, ref := range ret { - switch tr := ref.Subject.(type) { - case addrs.ResourceInstance: - newRef := *ref // shallow copy so we can mutate - newRef.Subject = tr.Phase(addrs.ResourceInstancePhaseDestroy) - newRef.Remaining = nil // can't access attributes of something being destroyed - ret = append(ret, &newRef) - case addrs.Resource: - newRef := *ref // shallow copy so we can mutate - newRef.Subject = tr.Phase(addrs.ResourceInstancePhaseDestroy) - newRef.Remaining = nil // can't access attributes of something being destroyed - ret = append(ret, &newRef) - } - } - } - - return ret -} - -// GraphNodeEvalable -func (n *NodeApplyableResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - // State still uses legacy-style internal ids, so we need to shim to get - // a suitable key to use. - stateId := NewLegacyResourceInstanceAddress(addr).stateId() - - // Determine the dependencies for the state. - stateDeps := n.StateReferences() - - // Eval info is different depending on what kind of resource this is - switch n.Config.Mode { - case addrs.ManagedResourceMode: - return n.evalTreeManagedResource(addr, stateId, stateDeps) - case addrs.DataResourceMode: - return n.evalTreeDataResource(addr, stateId, stateDeps) - default: - panic(fmt.Errorf("unsupported resource mode %s", n.Config.Mode)) - } -} - -func (n *NodeApplyableResourceInstance) evalTreeDataResource(addr addrs.AbsResourceInstance, stateId string, stateDeps []addrs.Referenceable) EvalNode { - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - // Get the saved diff for apply - &EvalReadDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, - }, - - // Stop early if we don't actually have a diff - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if change == nil { - return true, EvalEarlyExitError{} - } - return true, nil - }, - Then: EvalNoop{}, - }, - - // In this particular call to EvalReadData we include our planned - // change, which signals that we expect this read to complete fully - // with no unknown values; it'll produce an error if not. - &EvalReadData{ - Addr: addr.Resource, - Config: n.Config, - Dependencies: n.StateReferences(), - Planned: &change, // setting this indicates that the result must be complete - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - OutputState: &state, - }, - - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - - // Clear the diff now that we've applied it, so - // later nodes won't see a diff that's now a no-op. - &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: nil, - }, - - &EvalUpdateStateHook{}, - }, - } -} - -func (n *NodeApplyableResourceInstance) evalTreeManagedResource(addr addrs.AbsResourceInstance, stateId string, stateDeps []addrs.Referenceable) EvalNode { - // Declare a bunch of variables that are used for state during - // evaluation. Most of this are written to by-address below. - var provider providers.Interface - var providerSchema *ProviderSchema - var diff, diffApply *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - var err error - var createNew bool - var createBeforeDestroyEnabled bool - var configVal cty.Value - var deposedKey states.DeposedKey - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - // Get the saved diff for apply - &EvalReadDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &diffApply, - }, - - // We don't want to do any destroys - // (these are handled by NodeDestroyResourceInstance instead) - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if diffApply == nil { - return true, EvalEarlyExitError{} - } - if diffApply.Action == plans.Delete { - return true, EvalEarlyExitError{} - } - return true, nil - }, - Then: EvalNoop{}, - }, - - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - destroy := false - if diffApply != nil { - destroy = (diffApply.Action == plans.Delete || diffApply.Action.IsReplace()) - } - if destroy && n.createBeforeDestroy() { - createBeforeDestroyEnabled = true - } - return createBeforeDestroyEnabled, nil - }, - Then: &EvalDeposeState{ - Addr: addr.Resource, - ForceKey: n.PreallocatedDeposedKey, - OutputKey: &deposedKey, - }, - }, - - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - - // Get the saved diff - &EvalReadDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &diff, - }, - - // Make a new diff, in case we've learned new values in the state - // during apply which we can now incorporate. - &EvalDiff{ - Addr: addr.Resource, - Config: n.Config, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - PreviousDiff: &diff, - OutputChange: &diffApply, - OutputValue: &configVal, - OutputState: &state, - }, - - // Compare the diffs - &EvalCheckPlannedChange{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Planned: &diff, - Actual: &diffApply, - }, - - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - - &EvalReduceDiff{ - Addr: addr.Resource, - InChange: &diffApply, - Destroy: false, - OutChange: &diffApply, - }, - - // EvalReduceDiff may have simplified our planned change - // into a NoOp if it only requires destroying, since destroying - // is handled by NodeDestroyResourceInstance. - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if diffApply == nil || diffApply.Action == plans.NoOp { - return true, EvalEarlyExitError{} - } - return true, nil - }, - Then: EvalNoop{}, - }, - - // Call pre-apply hook - &EvalApplyPre{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - }, - &EvalApply{ - Addr: addr.Resource, - Config: n.Config, - Dependencies: n.StateReferences(), - State: &state, - Change: &diffApply, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Output: &state, - Error: &err, - CreateNew: &createNew, - }, - &EvalMaybeTainted{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - Error: &err, - StateOutput: &state, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - &EvalApplyProvisioners{ - Addr: addr.Resource, - State: &state, // EvalApplyProvisioners will skip if already tainted - ResourceConfig: n.Config, - CreateNew: &createNew, - Error: &err, - When: configs.ProvisionerWhenCreate, - }, - &EvalMaybeTainted{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - Error: &err, - StateOutput: &state, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - return createBeforeDestroyEnabled && err != nil, nil - }, - Then: &EvalMaybeRestoreDeposedObject{ - Addr: addr.Resource, - Key: &deposedKey, - }, - }, - - // We clear the diff out here so that future nodes - // don't see a diff that is already complete. There - // is no longer a diff! - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if !diff.Action.IsReplace() { - return true, nil - } - if !n.createBeforeDestroy() { - return true, nil - } - return false, nil - }, - Then: &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: nil, - }, - }, - - &EvalApplyPost{ - Addr: addr.Resource, - State: &state, - Error: &err, - }, - &EvalUpdateStateHook{}, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy.go index ca2267e4..657bbee7 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy.go @@ -2,114 +2,81 @@ package terraform import ( "fmt" - "log" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/states" + "github.com/hashicorp/terraform/config" ) -// NodeDestroyResourceInstance represents a resource instance that is to be -// destroyed. -type NodeDestroyResourceInstance struct { - *NodeAbstractResourceInstance - - // If DeposedKey is set to anything other than states.NotDeposed then - // this node destroys a deposed object of the associated instance - // rather than its current object. - DeposedKey states.DeposedKey - - CreateBeforeDestroyOverride *bool +// NodeDestroyResource represents a resource that is to be destroyed. +type NodeDestroyResource struct { + *NodeAbstractResource } -var ( - _ GraphNodeResource = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeDestroyer = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeDestroyerCBD = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeEvalable = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeProviderConsumer = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeProvisionerConsumer = (*NodeDestroyResourceInstance)(nil) -) - -func (n *NodeDestroyResourceInstance) Name() string { - if n.DeposedKey != states.NotDeposed { - return fmt.Sprintf("%s (destroy deposed %s)", n.ResourceInstanceAddr(), n.DeposedKey) - } - return n.ResourceInstanceAddr().String() + " (destroy)" +func (n *NodeDestroyResource) Name() string { + return n.NodeAbstractResource.Name() + " (destroy)" } // GraphNodeDestroyer -func (n *NodeDestroyResourceInstance) DestroyAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr +func (n *NodeDestroyResource) DestroyAddr() *ResourceAddress { + return n.Addr } // GraphNodeDestroyerCBD -func (n *NodeDestroyResourceInstance) CreateBeforeDestroy() bool { - if n.CreateBeforeDestroyOverride != nil { - return *n.CreateBeforeDestroyOverride - } - +func (n *NodeDestroyResource) CreateBeforeDestroy() bool { // If we have no config, we just assume no - if n.Config == nil || n.Config.Managed == nil { + if n.Config == nil { return false } - return n.Config.Managed.CreateBeforeDestroy + return n.Config.Lifecycle.CreateBeforeDestroy } // GraphNodeDestroyerCBD -func (n *NodeDestroyResourceInstance) ModifyCreateBeforeDestroy(v bool) error { - n.CreateBeforeDestroyOverride = &v +func (n *NodeDestroyResource) ModifyCreateBeforeDestroy(v bool) error { + // If we have no config, do nothing since it won't affect the + // create step anyways. + if n.Config == nil { + return nil + } + + // Set CBD to true + n.Config.Lifecycle.CreateBeforeDestroy = true + return nil } // GraphNodeReferenceable, overriding NodeAbstractResource -func (n *NodeDestroyResourceInstance) ReferenceableAddrs() []addrs.Referenceable { - normalAddrs := n.NodeAbstractResourceInstance.ReferenceableAddrs() - destroyAddrs := make([]addrs.Referenceable, len(normalAddrs)) +func (n *NodeDestroyResource) ReferenceableName() []string { + // We modify our referenceable name to have the suffix of ".destroy" + // since depending on the creation side doesn't necessarilly mean + // depending on destruction. + suffix := ".destroy" - phaseType := addrs.ResourceInstancePhaseDestroy + // If we're CBD, we also append "-cbd". This is because CBD will setup + // its own edges (in CBDEdgeTransformer). Depending on the "destroy" + // side generally doesn't mean depending on CBD as well. See GH-11349 if n.CreateBeforeDestroy() { - phaseType = addrs.ResourceInstancePhaseDestroyCBD + suffix += "-cbd" } - for i, normalAddr := range normalAddrs { - switch ta := normalAddr.(type) { - case addrs.Resource: - destroyAddrs[i] = ta.Phase(phaseType) - case addrs.ResourceInstance: - destroyAddrs[i] = ta.Phase(phaseType) - default: - destroyAddrs[i] = normalAddr - } + result := n.NodeAbstractResource.ReferenceableName() + for i, v := range result { + result[i] = v + suffix } - return destroyAddrs + return result } // GraphNodeReferencer, overriding NodeAbstractResource -func (n *NodeDestroyResourceInstance) References() []*addrs.Reference { +func (n *NodeDestroyResource) References() []string { // If we have a config, then we need to include destroy-time dependencies - if c := n.Config; c != nil && c.Managed != nil { - var result []*addrs.Reference - - // We include conn info and config for destroy time provisioners - // as dependencies that we have. - for _, p := range c.Managed.Provisioners { - schema := n.ProvisionerSchemas[p.Type] - - if p.When == configs.ProvisionerWhenDestroy { - if p.Connection != nil { - result = append(result, ReferencesFromConfig(p.Connection.Config, connectionBlockSupersetSchema)...) - } - result = append(result, ReferencesFromConfig(p.Config, schema)...) + if c := n.Config; c != nil { + var result []string + for _, p := range c.Provisioners { + // We include conn info and config for destroy time provisioners + // as dependencies that we have. + if p.When == config.ProvisionerWhenDestroy { + result = append(result, ReferencesFromConfig(p.ConnInfo)...) + result = append(result, ReferencesFromConfig(p.RawConfig)...) } } @@ -119,66 +86,117 @@ func (n *NodeDestroyResourceInstance) References() []*addrs.Reference { return nil } +// GraphNodeDynamicExpandable +func (n *NodeDestroyResource) DynamicExpand(ctx EvalContext) (*Graph, error) { + // If we have no config we do nothing + if n.Addr == nil { + return nil, nil + } + + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() + + // Start creating the steps + steps := make([]GraphTransformer, 0, 5) + + // We want deposed resources in the state to be destroyed + steps = append(steps, &DeposedTransformer{ + State: state, + View: n.Addr.stateId(), + ResolvedProvider: n.ResolvedProvider, + }) + + // Target + steps = append(steps, &TargetsTransformer{ + ParsedTargets: n.Targets, + }) + + // Always end with the root being added + steps = append(steps, &RootTransformer{}) + + // Build the graph + b := &BasicGraphBuilder{ + Steps: steps, + Name: "NodeResourceDestroy", + } + return b.Build(ctx.Path()) +} + // GraphNodeEvalable -func (n *NodeDestroyResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() +func (n *NodeDestroyResource) EvalTree() EvalNode { + // stateId is the ID to put into the state + stateId := n.Addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: n.Addr.Type, + uniqueExtra: "destroy", + } + + // Build the resource for eval + addr := n.Addr + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } // Get our state rs := n.ResourceState - var is *states.ResourceInstance - if rs != nil { - is = rs.Instance(n.InstanceKey) - } - if is == nil { - log.Printf("[WARN] NodeDestroyResourceInstance for %s with no state", addr) + if rs == nil { + rs = &ResourceState{ + Provider: n.ResolvedProvider, + } } - var changeApply *plans.ResourceInstanceChange - var provider providers.Interface - var providerSchema *ProviderSchema - var state *states.ResourceInstanceObject + var diffApply *InstanceDiff + var provider ResourceProvider + var state *InstanceState var err error return &EvalOpFilter{ Ops: []walkOperation{walkApply, walkDestroy}, Node: &EvalSequence{ Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - // Get the saved diff for apply &EvalReadDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &changeApply, + Name: stateId, + Diff: &diffApply, }, - &EvalReduceDiff{ - Addr: addr.Resource, - InChange: &changeApply, - Destroy: true, - OutChange: &changeApply, + // Filter the diff so we only get the destroy + &EvalFilterDiff{ + Diff: &diffApply, + Output: &diffApply, + Destroy: true, }, - // EvalReduceDiff may have simplified our planned change - // into a NoOp if it does not require destroying. + // If we're not destroying, then compare diffs &EvalIf{ If: func(ctx EvalContext) (bool, error) { - if changeApply == nil || changeApply.Action == plans.NoOp { - return true, EvalEarlyExitError{} + if diffApply != nil && diffApply.GetDestroy() { + return true, nil } - return true, nil + + return true, EvalEarlyExitError{} }, Then: EvalNoop{}, }, + // Load the instance info so we have the module path set + &EvalInstanceInfo{Info: info}, + + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, + }, &EvalReadState{ - Addr: addr.Resource, - Output: &state, - Provider: &provider, - ProviderSchema: &providerSchema, + Name: stateId, + Output: &state, }, &EvalRequireState{ State: &state, @@ -186,15 +204,15 @@ func (n *NodeDestroyResourceInstance) EvalTree() EvalNode { // Call pre-apply hook &EvalApplyPre{ - Addr: addr.Resource, - State: &state, - Change: &changeApply, + Info: info, + State: &state, + Diff: &diffApply, }, // Run destroy provisioners if not tainted &EvalIf{ If: func(ctx EvalContext) (bool, error) { - if state != nil && state.Status == states.ObjectTainted { + if state != nil && state.Tainted { return false, nil } @@ -202,11 +220,12 @@ func (n *NodeDestroyResourceInstance) EvalTree() EvalNode { }, Then: &EvalApplyProvisioners{ - Addr: addr.Resource, + Info: info, State: &state, - ResourceConfig: n.Config, + Resource: n.Config, + InterpResource: resource, Error: &err, - When: configs.ProvisionerWhenDestroy, + When: config.ProvisionerWhenDestroy, }, }, @@ -218,7 +237,7 @@ func (n *NodeDestroyResourceInstance) EvalTree() EvalNode { }, Then: &EvalApplyPost{ - Addr: addr.Resource, + Info: info, State: &state, Error: &err, }, @@ -227,38 +246,41 @@ func (n *NodeDestroyResourceInstance) EvalTree() EvalNode { // Make sure we handle data sources properly. &EvalIf{ If: func(ctx EvalContext) (bool, error) { - return addr.Resource.Resource.Mode == addrs.DataResourceMode, nil + if n.Addr == nil { + return false, fmt.Errorf("nil address") + } + + if n.Addr.Mode == config.DataResourceMode { + return true, nil + } + + return false, nil }, Then: &EvalReadDataApply{ - Addr: addr.Resource, - Config: n.Config, - Change: &changeApply, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Output: &state, + Info: info, + Diff: &diffApply, + Provider: &provider, + Output: &state, }, Else: &EvalApply{ - Addr: addr.Resource, - Config: nil, // No configuration because we are destroying - State: &state, - Change: &changeApply, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Output: &state, - Error: &err, + Info: info, + State: &state, + Diff: &diffApply, + Provider: &provider, + Output: &state, + Error: &err, }, }, &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, + Name: stateId, + ResourceType: n.Addr.Type, + Provider: n.ResolvedProvider, + Dependencies: rs.Dependencies, + State: &state, }, &EvalApplyPost{ - Addr: addr.Resource, + Info: info, State: &state, Error: &err, }, @@ -267,55 +289,3 @@ func (n *NodeDestroyResourceInstance) EvalTree() EvalNode { }, } } - -// NodeDestroyResourceInstance represents a resource that is to be destroyed. -// -// Destroying a resource is a state-only operation: it is the individual -// instances being destroyed that affects remote objects. During graph -// construction, NodeDestroyResource should always depend on any other node -// related to the given resource, since it's just a final cleanup to avoid -// leaving skeleton resource objects in state after their instances have -// all been destroyed. -type NodeDestroyResource struct { - *NodeAbstractResource -} - -var ( - _ GraphNodeResource = (*NodeDestroyResource)(nil) - _ GraphNodeReferenceable = (*NodeDestroyResource)(nil) - _ GraphNodeReferencer = (*NodeDestroyResource)(nil) - _ GraphNodeEvalable = (*NodeDestroyResource)(nil) -) - -func (n *NodeDestroyResource) Name() string { - return n.ResourceAddr().String() + " (clean up state)" -} - -// GraphNodeReferenceable, overriding NodeAbstractResource -func (n *NodeDestroyResource) ReferenceableAddrs() []addrs.Referenceable { - // NodeDestroyResource doesn't participate in references: the graph - // builder that created it should ensure directly that it already depends - // on every other node related to its resource, without relying on - // references. - return nil -} - -// GraphNodeReferencer, overriding NodeAbstractResource -func (n *NodeDestroyResource) References() []*addrs.Reference { - // NodeDestroyResource doesn't participate in references: the graph - // builder that created it should ensure directly that it already depends - // on every other node related to its resource, without relying on - // references. - return nil -} - -// GraphNodeEvalable -func (n *NodeDestroyResource) EvalTree() EvalNode { - // This EvalNode will produce an error if the resource isn't already - // empty by the time it is called, since it should just be pruning the - // leftover husk of a resource in state after all of the child instances - // and their objects were destroyed. - return &EvalForgetResourceState{ - Addr: n.ResourceAddr().Resource, - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy_deposed.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy_deposed.go deleted file mode 100644 index 67c46913..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy_deposed.go +++ /dev/null @@ -1,313 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" -) - -// ConcreteResourceInstanceDeposedNodeFunc is a callback type used to convert -// an abstract resource instance to a concrete one of some type that has -// an associated deposed object key. -type ConcreteResourceInstanceDeposedNodeFunc func(*NodeAbstractResourceInstance, states.DeposedKey) dag.Vertex - -type GraphNodeDeposedResourceInstanceObject interface { - DeposedInstanceObjectKey() states.DeposedKey -} - -// NodePlanDeposedResourceInstanceObject represents deposed resource -// instance objects during plan. These are distinct from the primary object -// for each resource instance since the only valid operation to do with them -// is to destroy them. -// -// This node type is also used during the refresh walk to ensure that the -// record of a deposed object is up-to-date before we plan to destroy it. -type NodePlanDeposedResourceInstanceObject struct { - *NodeAbstractResourceInstance - DeposedKey states.DeposedKey -} - -var ( - _ GraphNodeDeposedResourceInstanceObject = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeResource = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeResourceInstance = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeReferenceable = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeReferencer = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeEvalable = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeProviderConsumer = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeProvisionerConsumer = (*NodePlanDeposedResourceInstanceObject)(nil) -) - -func (n *NodePlanDeposedResourceInstanceObject) Name() string { - return fmt.Sprintf("%s (deposed %s)", n.ResourceInstanceAddr().String(), n.DeposedKey) -} - -func (n *NodePlanDeposedResourceInstanceObject) DeposedInstanceObjectKey() states.DeposedKey { - return n.DeposedKey -} - -// GraphNodeReferenceable implementation, overriding the one from NodeAbstractResourceInstance -func (n *NodePlanDeposedResourceInstanceObject) ReferenceableAddrs() []addrs.Referenceable { - // Deposed objects don't participate in references. - return nil -} - -// GraphNodeReferencer implementation, overriding the one from NodeAbstractResourceInstance -func (n *NodePlanDeposedResourceInstanceObject) References() []*addrs.Reference { - // We don't evaluate configuration for deposed objects, so they effectively - // make no references. - return nil -} - -// GraphNodeEvalable impl. -func (n *NodePlanDeposedResourceInstanceObject) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - var provider providers.Interface - var providerSchema *ProviderSchema - var state *states.ResourceInstanceObject - - seq := &EvalSequence{Nodes: make([]EvalNode, 0, 5)} - - // During the refresh walk we will ensure that our record of the deposed - // object is up-to-date. If it was already deleted outside of Terraform - // then this will remove it from state and thus avoid us planning a - // destroy for it during the subsequent plan walk. - seq.Nodes = append(seq.Nodes, &EvalOpFilter{ - Ops: []walkOperation{walkRefresh}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadStateDeposed{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - Key: n.DeposedKey, - Output: &state, - }, - &EvalRefresh{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - Provider: &provider, - ProviderSchema: &providerSchema, - State: &state, - Output: &state, - }, - &EvalWriteStateDeposed{ - Addr: addr.Resource, - Key: n.DeposedKey, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - }, - }, - }) - - // During the plan walk we always produce a planned destroy change, because - // destroying is the only supported action for deposed objects. - var change *plans.ResourceInstanceChange - seq.Nodes = append(seq.Nodes, &EvalOpFilter{ - Ops: []walkOperation{walkPlan, walkPlanDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadStateDeposed{ - Addr: addr.Resource, - Output: &state, - Key: n.DeposedKey, - Provider: &provider, - ProviderSchema: &providerSchema, - }, - &EvalDiffDestroy{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - DeposedKey: n.DeposedKey, - State: &state, - Output: &change, - }, - &EvalWriteDiff{ - Addr: addr.Resource, - DeposedKey: n.DeposedKey, - ProviderSchema: &providerSchema, - Change: &change, - }, - // Since deposed objects cannot be referenced by expressions - // elsewhere, we don't need to also record the planned new - // state in this case. - }, - }, - }) - - return seq -} - -// NodeDestroyDeposedResourceInstanceObject represents deposed resource -// instance objects during apply. Nodes of this type are inserted by -// DiffTransformer when the planned changeset contains "delete" changes for -// deposed instance objects, and its only supported operation is to destroy -// and then forget the associated object. -type NodeDestroyDeposedResourceInstanceObject struct { - *NodeAbstractResourceInstance - DeposedKey states.DeposedKey -} - -var ( - _ GraphNodeDeposedResourceInstanceObject = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeResource = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeResourceInstance = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeDestroyer = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeDestroyerCBD = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeReferenceable = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeReferencer = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeEvalable = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeProviderConsumer = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeProvisionerConsumer = (*NodeDestroyDeposedResourceInstanceObject)(nil) -) - -func (n *NodeDestroyDeposedResourceInstanceObject) Name() string { - return fmt.Sprintf("%s (destroy deposed %s)", n.Addr.String(), n.DeposedKey) -} - -func (n *NodeDestroyDeposedResourceInstanceObject) DeposedInstanceObjectKey() states.DeposedKey { - return n.DeposedKey -} - -// GraphNodeReferenceable implementation, overriding the one from NodeAbstractResourceInstance -func (n *NodeDestroyDeposedResourceInstanceObject) ReferenceableAddrs() []addrs.Referenceable { - // Deposed objects don't participate in references. - return nil -} - -// GraphNodeReferencer implementation, overriding the one from NodeAbstractResourceInstance -func (n *NodeDestroyDeposedResourceInstanceObject) References() []*addrs.Reference { - // We don't evaluate configuration for deposed objects, so they effectively - // make no references. - return nil -} - -// GraphNodeDestroyer -func (n *NodeDestroyDeposedResourceInstanceObject) DestroyAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr -} - -// GraphNodeDestroyerCBD -func (n *NodeDestroyDeposedResourceInstanceObject) CreateBeforeDestroy() bool { - // A deposed instance is always CreateBeforeDestroy by definition, since - // we use deposed only to handle create-before-destroy. - return true -} - -// GraphNodeDestroyerCBD -func (n *NodeDestroyDeposedResourceInstanceObject) ModifyCreateBeforeDestroy(v bool) error { - if !v { - // Should never happen: deposed instances are _always_ create_before_destroy. - return fmt.Errorf("can't deactivate create_before_destroy for a deposed instance") - } - return nil -} - -// GraphNodeEvalable impl. -func (n *NodeDestroyDeposedResourceInstanceObject) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - var provider providers.Interface - var providerSchema *ProviderSchema - var state *states.ResourceInstanceObject - var change *plans.ResourceInstanceChange - var err error - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadStateDeposed{ - Addr: addr.Resource, - Output: &state, - Key: n.DeposedKey, - Provider: &provider, - ProviderSchema: &providerSchema, - }, - &EvalDiffDestroy{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - Output: &change, - }, - // Call pre-apply hook - &EvalApplyPre{ - Addr: addr.Resource, - State: &state, - Change: &change, - }, - &EvalApply{ - Addr: addr.Resource, - Config: nil, // No configuration because we are destroying - State: &state, - Change: &change, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Output: &state, - Error: &err, - }, - // Always write the resource back to the state deposed... if it - // was successfully destroyed it will be pruned. If it was not, it will - // be caught on the next run. - &EvalWriteStateDeposed{ - Addr: addr.Resource, - Key: n.DeposedKey, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - &EvalApplyPost{ - Addr: addr.Resource, - State: &state, - Error: &err, - }, - &EvalReturnError{ - Error: &err, - }, - &EvalUpdateStateHook{}, - }, - } -} - -// GraphNodeDeposer is an optional interface implemented by graph nodes that -// might create a single new deposed object for a specific associated resource -// instance, allowing a caller to optionally pre-allocate a DeposedKey for -// it. -type GraphNodeDeposer interface { - // SetPreallocatedDeposedKey will be called during graph construction - // if a particular node must use a pre-allocated deposed key if/when it - // "deposes" the current object of its associated resource instance. - SetPreallocatedDeposedKey(key states.DeposedKey) -} - -// graphNodeDeposer is an embeddable implementation of GraphNodeDeposer. -// Embed it in a node type to get automatic support for it, and then access -// the field PreallocatedDeposedKey to access any pre-allocated key. -type graphNodeDeposer struct { - PreallocatedDeposedKey states.DeposedKey -} - -func (n *graphNodeDeposer) SetPreallocatedDeposedKey(key states.DeposedKey) { - n.PreallocatedDeposedKey = key -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go index 633c1c46..1afae7a0 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go @@ -1,119 +1,47 @@ package terraform import ( - "log" - "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/tfdiags" ) // NodePlannableResource represents a resource that is "plannable": // it is ready to be planned in order to create a diff. type NodePlannableResource struct { - *NodeAbstractResource - - // ForceCreateBeforeDestroy might be set via our GraphNodeDestroyerCBD - // during graph construction, if dependencies require us to force this - // on regardless of what the configuration says. - ForceCreateBeforeDestroy *bool -} - -var ( - _ GraphNodeSubPath = (*NodePlannableResource)(nil) - _ GraphNodeDestroyerCBD = (*NodePlannableResource)(nil) - _ GraphNodeDynamicExpandable = (*NodePlannableResource)(nil) - _ GraphNodeReferenceable = (*NodePlannableResource)(nil) - _ GraphNodeReferencer = (*NodePlannableResource)(nil) - _ GraphNodeResource = (*NodePlannableResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodePlannableResource)(nil) -) - -// GraphNodeEvalable -func (n *NodePlannableResource) EvalTree() EvalNode { - addr := n.ResourceAddr() - config := n.Config - - if config == nil { - // Nothing to do, then. - log.Printf("[TRACE] NodeApplyableResource: no configuration present for %s", addr) - return &EvalNoop{} - } - - // this ensures we can reference the resource even if the count is 0 - return &EvalWriteResourceState{ - Addr: addr.Resource, - Config: config, - ProviderAddr: n.ResolvedProvider, - } -} - -// GraphNodeDestroyerCBD -func (n *NodePlannableResource) CreateBeforeDestroy() bool { - if n.ForceCreateBeforeDestroy != nil { - return *n.ForceCreateBeforeDestroy - } - - // If we have no config, we just assume no - if n.Config == nil || n.Config.Managed == nil { - return false - } - - return n.Config.Managed.CreateBeforeDestroy -} - -// GraphNodeDestroyerCBD -func (n *NodePlannableResource) ModifyCreateBeforeDestroy(v bool) error { - n.ForceCreateBeforeDestroy = &v - return nil + *NodeAbstractCountResource } // GraphNodeDynamicExpandable func (n *NodePlannableResource) DynamicExpand(ctx EvalContext) (*Graph, error) { - var diags tfdiags.Diagnostics + // Grab the state which we read + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() - count, countDiags := evaluateResourceCountExpression(n.Config.Count, ctx) - diags = diags.Append(countDiags) - if countDiags.HasErrors() { - return nil, diags.Err() + // Expand the resource count which must be available by now from EvalTree + count, err := n.Config.Count() + if err != nil { + return nil, err } - // Next we need to potentially rename an instance address in the state - // if we're transitioning whether "count" is set at all. - fixResourceCountSetTransition(ctx, n.ResourceAddr(), count != -1) - - // Our graph transformers require access to the full state, so we'll - // temporarily lock it while we work on this. - state := ctx.State().Lock() - defer ctx.State().Unlock() - // The concrete resource factory we'll use - concreteResource := func(a *NodeAbstractResourceInstance) dag.Vertex { + concreteResource := func(a *NodeAbstractResource) dag.Vertex { // Add the config and state since we don't do that via transforms a.Config = n.Config a.ResolvedProvider = n.ResolvedProvider - a.Schema = n.Schema - a.ProvisionerSchemas = n.ProvisionerSchemas return &NodePlannableResourceInstance{ - NodeAbstractResourceInstance: a, - - // By the time we're walking, we've figured out whether we need - // to force on CreateBeforeDestroy due to dependencies on other - // nodes that have it. - ForceCreateBeforeDestroy: n.CreateBeforeDestroy(), + NodeAbstractResource: a, } } - // The concrete resource factory we'll use for orphans - concreteResourceOrphan := func(a *NodeAbstractResourceInstance) dag.Vertex { + // The concrete resource factory we'll use for oprhans + concreteResourceOrphan := func(a *NodeAbstractResource) dag.Vertex { // Add the config and state since we don't do that via transforms a.Config = n.Config a.ResolvedProvider = n.ResolvedProvider - a.Schema = n.Schema - a.ProvisionerSchemas = n.ProvisionerSchemas - return &NodePlannableResourceInstanceOrphan{ - NodeAbstractResourceInstance: a, + return &NodePlannableResourceOrphan{ + NodeAbstractResource: a, } } @@ -122,7 +50,6 @@ func (n *NodePlannableResource) DynamicExpand(ctx EvalContext) (*Graph, error) { // Expand the count. &ResourceCountTransformer{ Concrete: concreteResource, - Schema: n.Schema, Count: count, Addr: n.ResourceAddr(), }, @@ -139,7 +66,7 @@ func (n *NodePlannableResource) DynamicExpand(ctx EvalContext) (*Graph, error) { &AttachStateTransformer{State: state}, // Targeting - &TargetsTransformer{Targets: n.Targets}, + &TargetsTransformer{ParsedTargets: n.Targets}, // Connect references so ordering is correct &ReferenceTransformer{}, @@ -154,6 +81,5 @@ func (n *NodePlannableResource) DynamicExpand(ctx EvalContext) (*Graph, error) { Validate: true, Name: "NodePlannableResource", } - graph, diags := b.Build(ctx.Path()) - return graph, diags.ErrWithWarnings() + return b.Build(ctx.Path()) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_destroy.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_destroy.go index 38746f0d..9b02362b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_destroy.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_destroy.go @@ -1,87 +1,52 @@ package terraform -import ( - "fmt" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" -) - -// NodePlanDestroyableResourceInstance represents a resource that is ready -// to be planned for destruction. -type NodePlanDestroyableResourceInstance struct { - *NodeAbstractResourceInstance +// NodePlanDestroyableResource represents a resource that is "applyable": +// it is ready to be applied and is represented by a diff. +type NodePlanDestroyableResource struct { + *NodeAbstractResource } -var ( - _ GraphNodeSubPath = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeReferencer = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeDestroyer = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeResource = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeAttachResourceConfig = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeAttachResourceState = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeEvalable = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeProviderConsumer = (*NodePlanDestroyableResourceInstance)(nil) -) - // GraphNodeDestroyer -func (n *NodePlanDestroyableResourceInstance) DestroyAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr +func (n *NodePlanDestroyableResource) DestroyAddr() *ResourceAddress { + return n.Addr } // GraphNodeEvalable -func (n *NodePlanDestroyableResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() +func (n *NodePlanDestroyableResource) EvalTree() EvalNode { + addr := n.NodeAbstractResource.Addr + + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: addr.Type, + } // Declare a bunch of variables that are used for state during - // evaluation. These are written to by address in the EvalNodes we - // declare below. - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - - if n.ResolvedProvider.ProviderConfig.Type == "" { - // Should never happen; indicates that the graph was not constructed - // correctly since we didn't get our provider attached. - panic(fmt.Sprintf("%T %q was not assigned a resolved provider", n, dag.VertexName(n))) - } + // evaluation. Most of this are written to by-address below. + var diff *InstanceDiff + var state *InstanceState return &EvalSequence{ Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - + Name: stateId, Output: &state, }, &EvalDiffDestroy{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - Output: &change, + Info: info, + State: &state, + Output: &diff, }, &EvalCheckPreventDestroy{ - Addr: addr.Resource, - Config: n.Config, - Change: &change, + Resource: n.Config, + Diff: &diff, }, &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, + Name: stateId, + Diff: &diff, }, }, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_instance.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_instance.go index d69472f8..7d9fcddb 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_instance.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_instance.go @@ -3,182 +3,187 @@ package terraform import ( "fmt" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - - "github.com/hashicorp/terraform/addrs" - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/terraform/config" ) // NodePlannableResourceInstance represents a _single_ resource // instance that is plannable. This means this represents a single // count index, for example. type NodePlannableResourceInstance struct { - *NodeAbstractResourceInstance - ForceCreateBeforeDestroy bool + *NodeAbstractResource } -var ( - _ GraphNodeSubPath = (*NodePlannableResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodePlannableResourceInstance)(nil) - _ GraphNodeReferencer = (*NodePlannableResourceInstance)(nil) - _ GraphNodeResource = (*NodePlannableResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodePlannableResourceInstance)(nil) - _ GraphNodeAttachResourceConfig = (*NodePlannableResourceInstance)(nil) - _ GraphNodeAttachResourceState = (*NodePlannableResourceInstance)(nil) - _ GraphNodeEvalable = (*NodePlannableResourceInstance)(nil) -) - // GraphNodeEvalable func (n *NodePlannableResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() + addr := n.NodeAbstractResource.Addr - // State still uses legacy-style internal ids, so we need to shim to get - // a suitable key to use. - stateId := NewLegacyResourceInstanceAddress(addr).stateId() + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: addr.Type, + ModulePath: normalizeModulePath(addr.Path), + } + + // Build the resource for eval + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } // Determine the dependencies for the state. stateDeps := n.StateReferences() // Eval info is different depending on what kind of resource this is - switch addr.Resource.Resource.Mode { - case addrs.ManagedResourceMode: - return n.evalTreeManagedResource(addr, stateId, stateDeps) - case addrs.DataResourceMode: - return n.evalTreeDataResource(addr, stateId, stateDeps) + switch n.Config.Mode { + case config.ManagedResourceMode: + return n.evalTreeManagedResource( + stateId, info, resource, stateDeps, + ) + case config.DataResourceMode: + return n.evalTreeDataResource( + stateId, info, resource, stateDeps) default: panic(fmt.Errorf("unsupported resource mode %s", n.Config.Mode)) } } -func (n *NodePlannableResourceInstance) evalTreeDataResource(addr addrs.AbsResourceInstance, stateId string, stateDeps []addrs.Referenceable) EvalNode { - config := n.Config - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - var configVal cty.Value +func (n *NodePlannableResourceInstance) evalTreeDataResource( + stateId string, info *InstanceInfo, + resource *Resource, stateDeps []string) EvalNode { + var provider ResourceProvider + var config *ResourceConfig + var diff *InstanceDiff + var state *InstanceState return &EvalSequence{ Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - + Name: stateId, Output: &state, }, - // If we already have a non-planned state then we already dealt - // with this during the refresh walk and so we have nothing to do - // here. + // We need to re-interpolate the config here because some + // of the attributes may have become computed during + // earlier planning, due to other resources having + // "requires new resource" diffs. + &EvalInterpolate{ + Config: n.Config.RawConfig.Copy(), + Resource: resource, + Output: &config, + }, + &EvalIf{ If: func(ctx EvalContext) (bool, error) { - if state != nil && state.Status != states.ObjectPlanned { + computed := config.ComputedKeys != nil && len(config.ComputedKeys) > 0 + + // If the configuration is complete and we + // already have a state then we don't need to + // do any further work during apply, because we + // already populated the state during refresh. + if !computed && state != nil { return true, EvalEarlyExitError{} } + return true, nil }, Then: EvalNoop{}, }, - &EvalValidateSelfRef{ - Addr: addr.Resource, - Config: config.Config, - ProviderSchema: &providerSchema, + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, }, - &EvalReadData{ - Addr: addr.Resource, - Config: n.Config, - Dependencies: n.StateReferences(), - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - ForcePlanRead: true, // _always_ produce a Read change, even if the config seems ready - OutputChange: &change, - OutputValue: &configVal, - OutputState: &state, + &EvalReadDataDiff{ + Info: info, + Config: &config, + Provider: &provider, + Output: &diff, + OutputState: &state, }, &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, + Name: stateId, + ResourceType: n.Config.Type, + Provider: n.ResolvedProvider, + Dependencies: stateDeps, + State: &state, }, &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, + Name: stateId, + Diff: &diff, }, }, } } -func (n *NodePlannableResourceInstance) evalTreeManagedResource(addr addrs.AbsResourceInstance, stateId string, stateDeps []addrs.Referenceable) EvalNode { - config := n.Config - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject +func (n *NodePlannableResourceInstance) evalTreeManagedResource( + stateId string, info *InstanceInfo, + resource *Resource, stateDeps []string) EvalNode { + // Declare a bunch of variables that are used for state during + // evaluation. Most of this are written to by-address below. + var provider ResourceProvider + var diff *InstanceDiff + var state *InstanceState + var resourceConfig *ResourceConfig return &EvalSequence{ Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, + &EvalInterpolate{ + Config: n.Config.RawConfig.Copy(), + Resource: resource, + Output: &resourceConfig, }, - - &EvalReadState{ - Addr: addr.Resource, + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, + }, + // Re-run validation to catch any errors we missed, e.g. type + // mismatches on computed values. + &EvalValidateResource{ Provider: &provider, - ProviderSchema: &providerSchema, - + Config: &resourceConfig, + ResourceName: n.Config.Name, + ResourceType: n.Config.Type, + ResourceMode: n.Config.Mode, + IgnoreWarnings: true, + }, + &EvalReadState{ + Name: stateId, Output: &state, }, - - &EvalValidateSelfRef{ - Addr: addr.Resource, - Config: config.Config, - ProviderSchema: &providerSchema, - }, - &EvalDiff{ - Addr: addr.Resource, - Config: n.Config, - CreateBeforeDestroy: n.ForceCreateBeforeDestroy, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - OutputChange: &change, - OutputState: &state, + Name: stateId, + Info: info, + Config: &resourceConfig, + Resource: n.Config, + Provider: &provider, + State: &state, + OutputDiff: &diff, + OutputState: &state, }, &EvalCheckPreventDestroy{ - Addr: addr.Resource, - Config: n.Config, - Change: &change, + Resource: n.Config, + Diff: &diff, }, &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - ProviderSchema: &providerSchema, + Name: stateId, + ResourceType: n.Config.Type, + Provider: n.ResolvedProvider, + Dependencies: stateDeps, + State: &state, }, &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, + Name: stateId, + Diff: &diff, }, }, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_orphan.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_orphan.go index 84166949..73d6e41f 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_orphan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_orphan.go @@ -1,83 +1,53 @@ package terraform -import ( - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" -) - -// NodePlannableResourceInstanceOrphan represents a resource that is "applyable": +// NodePlannableResourceOrphan represents a resource that is "applyable": // it is ready to be applied and is represented by a diff. -type NodePlannableResourceInstanceOrphan struct { - *NodeAbstractResourceInstance +type NodePlannableResourceOrphan struct { + *NodeAbstractResource } -var ( - _ GraphNodeSubPath = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeReferenceable = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeReferencer = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeResource = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeResourceInstance = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeAttachResourceConfig = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeAttachResourceState = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeEvalable = (*NodePlannableResourceInstanceOrphan)(nil) -) - -var ( - _ GraphNodeEvalable = (*NodePlannableResourceInstanceOrphan)(nil) -) - -func (n *NodePlannableResourceInstanceOrphan) Name() string { - return n.ResourceInstanceAddr().String() + " (orphan)" +func (n *NodePlannableResourceOrphan) Name() string { + return n.NodeAbstractResource.Name() + " (orphan)" } // GraphNodeEvalable -func (n *NodePlannableResourceInstanceOrphan) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() +func (n *NodePlannableResourceOrphan) EvalTree() EvalNode { + addr := n.NodeAbstractResource.Addr + + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: addr.Type, + ModulePath: normalizeModulePath(addr.Path), + } // Declare a bunch of variables that are used for state during // evaluation. Most of this are written to by-address below. - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - var provider providers.Interface - var providerSchema *ProviderSchema + var diff *InstanceDiff + var state *InstanceState return &EvalSequence{ Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - + Name: stateId, Output: &state, }, &EvalDiffDestroy{ - Addr: addr.Resource, - State: &state, - ProviderAddr: n.ResolvedProvider, - Output: &change, - OutputState: &state, // Will point to a nil state after this complete, signalling destroyed + Info: info, + State: &state, + Output: &diff, }, &EvalCheckPreventDestroy{ - Addr: addr.Resource, - Config: n.Config, - Change: &change, + Resource: n.Config, + ResourceId: stateId, + Diff: &diff, }, &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, + Name: stateId, + Diff: &diff, }, }, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_refresh.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_refresh.go index 95060232..697bd494 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_refresh.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_refresh.go @@ -2,60 +2,38 @@ package terraform import ( "fmt" - "log" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/providers" - - "github.com/hashicorp/terraform/states" - - "github.com/hashicorp/terraform/addrs" + "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/tfdiags" ) // NodeRefreshableManagedResource represents a resource that is expanabled into // NodeRefreshableManagedResourceInstance. Resource count orphans are also added. type NodeRefreshableManagedResource struct { - *NodeAbstractResource + *NodeAbstractCountResource } -var ( - _ GraphNodeSubPath = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeDynamicExpandable = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeReferenceable = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeReferencer = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeResource = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeRefreshableManagedResource)(nil) -) - // GraphNodeDynamicExpandable func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, error) { - var diags tfdiags.Diagnostics + // Grab the state which we read + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() - count, countDiags := evaluateResourceCountExpression(n.Config.Count, ctx) - diags = diags.Append(countDiags) - if countDiags.HasErrors() { - return nil, diags.Err() + // Expand the resource count which must be available by now from EvalTree + count, err := n.Config.Count() + if err != nil { + return nil, err } - // Next we need to potentially rename an instance address in the state - // if we're transitioning whether "count" is set at all. - fixResourceCountSetTransition(ctx, n.ResourceAddr(), count != -1) - - // Our graph transformers require access to the full state, so we'll - // temporarily lock it while we work on this. - state := ctx.State().Lock() - defer ctx.State().Unlock() - // The concrete resource factory we'll use - concreteResource := func(a *NodeAbstractResourceInstance) dag.Vertex { + concreteResource := func(a *NodeAbstractResource) dag.Vertex { // Add the config and state since we don't do that via transforms a.Config = n.Config a.ResolvedProvider = n.ResolvedProvider return &NodeRefreshableManagedResourceInstance{ - NodeAbstractResourceInstance: a, + NodeAbstractResource: a, } } @@ -64,7 +42,6 @@ func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, // Expand the count. &ResourceCountTransformer{ Concrete: concreteResource, - Schema: n.Schema, Count: count, Addr: n.ResourceAddr(), }, @@ -82,7 +59,7 @@ func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, &AttachStateTransformer{State: state}, // Targeting - &TargetsTransformer{Targets: n.Targets}, + &TargetsTransformer{ParsedTargets: n.Targets}, // Connect references so ordering is correct &ReferenceTransformer{}, @@ -98,76 +75,66 @@ func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, Name: "NodeRefreshableManagedResource", } - graph, diags := b.Build(ctx.Path()) - return graph, diags.ErrWithWarnings() + return b.Build(ctx.Path()) } // NodeRefreshableManagedResourceInstance represents a resource that is "applyable": // it is ready to be applied and is represented by a diff. type NodeRefreshableManagedResourceInstance struct { - *NodeAbstractResourceInstance + *NodeAbstractResource } -var ( - _ GraphNodeSubPath = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeDestroyer = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeResource = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeAttachResourceConfig = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeAttachResourceState = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeEvalable = (*NodeRefreshableManagedResourceInstance)(nil) -) - // GraphNodeDestroyer -func (n *NodeRefreshableManagedResourceInstance) DestroyAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr +func (n *NodeRefreshableManagedResourceInstance) DestroyAddr() *ResourceAddress { + return n.Addr } // GraphNodeEvalable func (n *NodeRefreshableManagedResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - // Eval info is different depending on what kind of resource this is - switch addr.Resource.Resource.Mode { - case addrs.ManagedResourceMode: + switch mode := n.Addr.Mode; mode { + case config.ManagedResourceMode: if n.ResourceState == nil { - log.Printf("[TRACE] NodeRefreshableManagedResourceInstance: %s has no existing state to refresh", addr) return n.evalTreeManagedResourceNoState() } - log.Printf("[TRACE] NodeRefreshableManagedResourceInstance: %s will be refreshed", addr) return n.evalTreeManagedResource() - case addrs.DataResourceMode: + case config.DataResourceMode: // Get the data source node. If we don't have a configuration // then it is an orphan so we destroy it (remove it from the state). var dn GraphNodeEvalable if n.Config != nil { dn = &NodeRefreshableDataResourceInstance{ - NodeAbstractResourceInstance: n.NodeAbstractResourceInstance, + NodeAbstractResource: n.NodeAbstractResource, } } else { - dn = &NodeDestroyableDataResourceInstance{ - NodeAbstractResourceInstance: n.NodeAbstractResourceInstance, + dn = &NodeDestroyableDataResource{ + NodeAbstractResource: n.NodeAbstractResource, } } return dn.EvalTree() default: - panic(fmt.Errorf("unsupported resource mode %s", addr.Resource.Resource.Mode)) + panic(fmt.Errorf("unsupported resource mode %s", mode)) } } func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalNode { - addr := n.ResourceInstanceAddr() + addr := n.NodeAbstractResource.Addr + + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: addr.Type, + } // Declare a bunch of variables that are used for state during // evaluation. Most of this are written to by-address below. - var provider providers.Interface - var providerSchema *ProviderSchema - var state *states.ResourceInstanceObject + var provider ResourceProvider + var state *InstanceState // This happened during initial development. All known cases were // fixed and tested but as a sanity check let's assert here. @@ -183,33 +150,25 @@ func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalN return &EvalSequence{ Nodes: []EvalNode{ &EvalGetProvider{ - Addr: n.ResolvedProvider, + Name: n.ResolvedProvider, Output: &provider, - Schema: &providerSchema, }, - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - + Name: stateId, Output: &state, }, - &EvalRefresh{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - Provider: &provider, - ProviderSchema: &providerSchema, - State: &state, - Output: &state, + Info: info, + Provider: &provider, + State: &state, + Output: &state, }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, + Name: stateId, + ResourceType: n.ResourceState.Type, + Provider: n.ResolvedProvider, + Dependencies: n.ResourceState.Dependencies, + State: &state, }, }, } @@ -227,62 +186,80 @@ func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalN // plan, but nothing is done with the diff after it is created - it is dropped, // and its changes are not counted in the UI. func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResourceNoState() EvalNode { - addr := n.ResourceInstanceAddr() - // Declare a bunch of variables that are used for state during // evaluation. Most of this are written to by-address below. - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject + var provider ResourceProvider + var state *InstanceState + var resourceConfig *ResourceConfig + + addr := n.NodeAbstractResource.Addr + stateID := addr.stateId() + info := &InstanceInfo{ + Id: stateID, + Type: addr.Type, + ModulePath: normalizeModulePath(addr.Path), + } + + // Build the resource for eval + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } + + // Determine the dependencies for the state. + stateDeps := n.StateReferences() + + // n.Config can be nil if the config and state don't match + var raw *config.RawConfig + if n.Config != nil { + raw = n.Config.RawConfig.Copy() + } return &EvalSequence{ Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, + &EvalInterpolate{ + Config: raw, + Resource: resource, + Output: &resourceConfig, }, - - &EvalReadState{ - Addr: addr.Resource, + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, + }, + // Re-run validation to catch any errors we missed, e.g. type + // mismatches on computed values. + &EvalValidateResource{ Provider: &provider, - ProviderSchema: &providerSchema, - + Config: &resourceConfig, + ResourceName: n.Config.Name, + ResourceType: n.Config.Type, + ResourceMode: n.Config.Mode, + IgnoreWarnings: true, + }, + &EvalReadState{ + Name: stateID, Output: &state, }, - &EvalDiff{ - Addr: addr.Resource, - Config: n.Config, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - OutputChange: &change, - OutputState: &state, - Stub: true, + Name: stateID, + Info: info, + Config: &resourceConfig, + Resource: n.Config, + Provider: &provider, + State: &state, + OutputState: &state, + Stub: true, }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - - // We must also save the planned change, so that expressions in - // other nodes, such as provider configurations and data resources, - // can work with the planned new value. - // - // This depends on the fact that Context.Refresh creates a - // temporary new empty changeset for the duration of its graph - // walk, and so this recorded change will be discarded immediately - // after the refresh walk completes. - &EvalWriteDiff{ - Addr: addr.Resource, - Change: &change, - ProviderSchema: &providerSchema, + Name: stateID, + ResourceType: n.Config.Type, + Provider: n.ResolvedProvider, + Dependencies: stateDeps, + State: &state, }, }, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_validate.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_validate.go index c1e10a6b..0df223d9 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_validate.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_validate.go @@ -1,80 +1,158 @@ package terraform import ( - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/provisioners" - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/terraform/dag" ) // NodeValidatableResource represents a resource that is used for validation // only. type NodeValidatableResource struct { - *NodeAbstractResource + *NodeAbstractCountResource } -var ( - _ GraphNodeSubPath = (*NodeValidatableResource)(nil) - _ GraphNodeEvalable = (*NodeValidatableResource)(nil) - _ GraphNodeReferenceable = (*NodeValidatableResource)(nil) - _ GraphNodeReferencer = (*NodeValidatableResource)(nil) - _ GraphNodeResource = (*NodeValidatableResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeValidatableResource)(nil) -) - // GraphNodeEvalable func (n *NodeValidatableResource) EvalTree() EvalNode { - addr := n.ResourceAddr() - config := n.Config + // Ensure we're validating + c := n.NodeAbstractCountResource + c.Validate = true + return c.EvalTree() +} - // Declare the variables will be used are used to pass values along - // the evaluation sequence below. These are written to via pointers - // passed to the EvalNodes. - var provider providers.Interface - var providerSchema *ProviderSchema - var configVal cty.Value +// GraphNodeDynamicExpandable +func (n *NodeValidatableResource) DynamicExpand(ctx EvalContext) (*Graph, error) { + // Grab the state which we read + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() + + // Expand the resource count which must be available by now from EvalTree + count := 1 + if n.Config.RawCount.Value() != unknownValue() { + var err error + count, err = n.Config.Count() + if err != nil { + return nil, err + } + } + + // The concrete resource factory we'll use + concreteResource := func(a *NodeAbstractResource) dag.Vertex { + // Add the config and state since we don't do that via transforms + a.Config = n.Config + a.ResolvedProvider = n.ResolvedProvider + + return &NodeValidatableResourceInstance{ + NodeAbstractResource: a, + } + } + + // Start creating the steps + steps := []GraphTransformer{ + // Expand the count. + &ResourceCountTransformer{ + Concrete: concreteResource, + Count: count, + Addr: n.ResourceAddr(), + }, + + // Attach the state + &AttachStateTransformer{State: state}, + + // Targeting + &TargetsTransformer{ParsedTargets: n.Targets}, + + // Connect references so ordering is correct + &ReferenceTransformer{}, + + // Make sure there is a single root + &RootTransformer{}, + } + + // Build the graph + b := &BasicGraphBuilder{ + Steps: steps, + Validate: true, + Name: "NodeValidatableResource", + } + + return b.Build(ctx.Path()) +} + +// This represents a _single_ resource instance to validate. +type NodeValidatableResourceInstance struct { + *NodeAbstractResource +} + +// GraphNodeEvalable +func (n *NodeValidatableResourceInstance) EvalTree() EvalNode { + addr := n.NodeAbstractResource.Addr + + // Build the resource for eval + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } + + // Declare a bunch of variables that are used for state during + // evaluation. Most of this are written to by-address below. + var config *ResourceConfig + var provider ResourceProvider seq := &EvalSequence{ Nodes: []EvalNode{ + &EvalValidateResourceSelfRef{ + Addr: &addr, + Config: &n.Config.RawConfig, + }, &EvalGetProvider{ - Addr: n.ResolvedProvider, + Name: n.ResolvedProvider, Output: &provider, - Schema: &providerSchema, + }, + &EvalInterpolate{ + Config: n.Config.RawConfig.Copy(), + Resource: resource, + Output: &config, }, &EvalValidateResource{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - Config: config, - ConfigVal: &configVal, + Provider: &provider, + Config: &config, + ResourceName: n.Config.Name, + ResourceType: n.Config.Type, + ResourceMode: n.Config.Mode, }, }, } - if managed := n.Config.Managed; managed != nil { - hasCount := n.Config.Count != nil - - // Validate all the provisioners - for _, p := range managed.Provisioners { - var provisioner provisioners.Interface - var provisionerSchema *configschema.Block - seq.Nodes = append( - seq.Nodes, - &EvalGetProvisioner{ - Name: p.Type, - Output: &provisioner, - Schema: &provisionerSchema, - }, - &EvalValidateProvisioner{ - ResourceAddr: addr.Resource, - Provisioner: &provisioner, - Schema: &provisionerSchema, - Config: p, - ResourceHasCount: hasCount, - ConnConfig: p.Connection, - }, - ) - } + // Validate all the provisioners + for _, p := range n.Config.Provisioners { + var provisioner ResourceProvisioner + var connConfig *ResourceConfig + seq.Nodes = append( + seq.Nodes, + &EvalGetProvisioner{ + Name: p.Type, + Output: &provisioner, + }, + &EvalInterpolate{ + Config: p.RawConfig.Copy(), + Resource: resource, + Output: &config, + }, + &EvalInterpolate{ + Config: p.ConnInfo.Copy(), + Resource: resource, + Output: &connConfig, + }, + &EvalValidateProvisioner{ + Provisioner: &provisioner, + Config: &config, + ConnConfig: &connConfig, + }, + ) } return seq diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_root_variable.go b/vendor/github.com/hashicorp/terraform/terraform/node_root_variable.go index 1c302903..cb61a4e3 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_root_variable.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_root_variable.go @@ -1,44 +1,22 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/dag" + "fmt" + + "github.com/hashicorp/terraform/config" ) // NodeRootVariable represents a root variable input. type NodeRootVariable struct { - Addr addrs.InputVariable - Config *configs.Variable + Config *config.Variable } -var ( - _ GraphNodeSubPath = (*NodeRootVariable)(nil) - _ GraphNodeReferenceable = (*NodeRootVariable)(nil) - _ dag.GraphNodeDotter = (*NodeApplyableModuleVariable)(nil) -) - func (n *NodeRootVariable) Name() string { - return n.Addr.String() -} - -// GraphNodeSubPath -func (n *NodeRootVariable) Path() addrs.ModuleInstance { - return addrs.RootModuleInstance + result := fmt.Sprintf("var.%s", n.Config.Name) + return result } // GraphNodeReferenceable -func (n *NodeRootVariable) ReferenceableAddrs() []addrs.Referenceable { - return []addrs.Referenceable{n.Addr} -} - -// dag.GraphNodeDotter impl. -func (n *NodeRootVariable) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, - } +func (n *NodeRootVariable) ReferenceableName() []string { + return []string{n.Name()} } diff --git a/vendor/github.com/hashicorp/terraform/terraform/path.go b/vendor/github.com/hashicorp/terraform/terraform/path.go index 9757446b..51dd4122 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/path.go +++ b/vendor/github.com/hashicorp/terraform/terraform/path.go @@ -1,17 +1,10 @@ package terraform import ( - "fmt" - - "github.com/hashicorp/terraform/addrs" + "strings" ) -// PathObjectCacheKey is like PathCacheKey but includes an additional name -// to be included in the key, for module-namespaced objects. -// -// The result of this function is guaranteed unique for any distinct pair -// of path and name, but is not guaranteed to be in any particular format -// and in particular should never be shown to end-users. -func PathObjectCacheKey(path addrs.ModuleInstance, objectName string) string { - return fmt.Sprintf("%s|%s", path.String(), objectName) +// PathCacheKey returns a cache key for a module path. +func PathCacheKey(path []string) string { + return strings.Join(path, "|") } diff --git a/vendor/github.com/hashicorp/terraform/terraform/plan.go b/vendor/github.com/hashicorp/terraform/terraform/plan.go index af04c6cd..30db1950 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/plan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/plan.go @@ -3,13 +3,14 @@ package terraform import ( "bytes" "encoding/gob" + "errors" "fmt" "io" + "log" "sync" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" + "github.com/hashicorp/terraform/version" ) func init() { @@ -30,9 +31,9 @@ type Plan struct { // plan is applied. Diff *Diff - // Config represents the entire configuration that was present when this + // Module represents the entire configuration that was present when this // plan was created. - Config *configs.Config + Module *module.Tree // State is the Terraform state that was current when this plan was // created. @@ -43,7 +44,7 @@ type Plan struct { // Vars retains the variables that were set when creating the plan, so // that the same variables can be applied during apply. - Vars map[string]cty.Value + Vars map[string]interface{} // Targets, if non-empty, contains a set of resource address strings that // identify graph nodes that were selected as targets for plan. @@ -77,6 +78,64 @@ type Plan struct { once sync.Once } +// Context returns a Context with the data encapsulated in this plan. +// +// The following fields in opts are overridden by the plan: Config, +// Diff, Variables. +// +// If State is not provided, it is set from the plan. If it _is_ provided, +// it must be Equal to the state stored in plan, but may have a newer +// serial. +func (p *Plan) Context(opts *ContextOpts) (*Context, error) { + var err error + opts, err = p.contextOpts(opts) + if err != nil { + return nil, err + } + return NewContext(opts) +} + +// contextOpts mutates the given base ContextOpts in place to use input +// objects obtained from the receiving plan. +func (p *Plan) contextOpts(base *ContextOpts) (*ContextOpts, error) { + opts := base + + opts.Diff = p.Diff + opts.Module = p.Module + opts.Targets = p.Targets + opts.ProviderSHA256s = p.ProviderSHA256s + opts.Destroy = p.Destroy + + if opts.State == nil { + opts.State = p.State + } else if !opts.State.Equal(p.State) { + // Even if we're overriding the state, it should be logically equal + // to what's in plan. The only valid change to have made by the time + // we get here is to have incremented the serial. + // + // Due to the fact that serialization may change the representation of + // the state, there is little chance that these aren't actually equal. + // Log the error condition for reference, but continue with the state + // we have. + log.Println("[WARN] Plan state and ContextOpts state are not equal") + } + + thisVersion := version.String() + if p.TerraformVersion != "" && p.TerraformVersion != thisVersion { + return nil, fmt.Errorf( + "plan was created with a different version of Terraform (created with %s, but running %s)", + p.TerraformVersion, thisVersion, + ) + } + + opts.Variables = make(map[string]interface{}) + for k, v := range p.Vars { + opts.Variables[k] = v + } + + return opts, nil +} + func (p *Plan) String() string { buf := new(bytes.Buffer) buf.WriteString("DIFF:\n\n") @@ -99,7 +158,7 @@ func (p *Plan) init() { } if p.Vars == nil { - p.Vars = make(map[string]cty.Value) + p.Vars = make(map[string]interface{}) } }) } @@ -113,10 +172,63 @@ const planFormatVersion byte = 2 // ReadPlan reads a plan structure out of a reader in the format that // was written by WritePlan. func ReadPlan(src io.Reader) (*Plan, error) { - return nil, fmt.Errorf("terraform.ReadPlan is no longer in use; use planfile.Open instead") + var result *Plan + var err error + n := 0 + + // Verify the magic bytes + magic := make([]byte, len(planFormatMagic)) + for n < len(magic) { + n, err = src.Read(magic[n:]) + if err != nil { + return nil, fmt.Errorf("error while reading magic bytes: %s", err) + } + } + if string(magic) != planFormatMagic { + return nil, fmt.Errorf("not a valid plan file") + } + + // Verify the version is something we can read + var formatByte [1]byte + n, err = src.Read(formatByte[:]) + if err != nil { + return nil, err + } + if n != len(formatByte) { + return nil, errors.New("failed to read plan version byte") + } + + if formatByte[0] != planFormatVersion { + return nil, fmt.Errorf("unknown plan file version: %d", formatByte[0]) + } + + dec := gob.NewDecoder(src) + if err := dec.Decode(&result); err != nil { + return nil, err + } + + return result, nil } // WritePlan writes a plan somewhere in a binary format. func WritePlan(d *Plan, dst io.Writer) error { - return fmt.Errorf("terraform.WritePlan is no longer in use; use planfile.Create instead") + // Write the magic bytes so we can determine the file format later + n, err := dst.Write([]byte(planFormatMagic)) + if err != nil { + return err + } + if n != len(planFormatMagic) { + return errors.New("failed to write plan format magic bytes") + } + + // Write a version byte so we can iterate on version at some point + n, err = dst.Write([]byte{planFormatVersion}) + if err != nil { + return err + } + if n != 1 { + return errors.New("failed to write plan version byte") + } + + return gob.NewEncoder(dst).Encode(d) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/provider_mock.go b/vendor/github.com/hashicorp/terraform/terraform/provider_mock.go deleted file mode 100644 index 8c582408..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/provider_mock.go +++ /dev/null @@ -1,496 +0,0 @@ -package terraform - -import ( - "encoding/json" - "fmt" - "sync" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/hcl2shim" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/tfdiags" -) - -var _ providers.Interface = (*MockProvider)(nil) - -// MockProvider implements providers.Interface but mocks out all the -// calls for testing purposes. -type MockProvider struct { - sync.Mutex - - // Anything you want, in case you need to store extra data with the mock. - Meta interface{} - - GetSchemaCalled bool - GetSchemaReturn *ProviderSchema // This is using ProviderSchema directly rather than providers.GetSchemaResponse for compatibility with old tests - - PrepareProviderConfigCalled bool - PrepareProviderConfigResponse providers.PrepareProviderConfigResponse - PrepareProviderConfigRequest providers.PrepareProviderConfigRequest - PrepareProviderConfigFn func(providers.PrepareProviderConfigRequest) providers.PrepareProviderConfigResponse - - ValidateResourceTypeConfigCalled bool - ValidateResourceTypeConfigTypeName string - ValidateResourceTypeConfigResponse providers.ValidateResourceTypeConfigResponse - ValidateResourceTypeConfigRequest providers.ValidateResourceTypeConfigRequest - ValidateResourceTypeConfigFn func(providers.ValidateResourceTypeConfigRequest) providers.ValidateResourceTypeConfigResponse - - ValidateDataSourceConfigCalled bool - ValidateDataSourceConfigTypeName string - ValidateDataSourceConfigResponse providers.ValidateDataSourceConfigResponse - ValidateDataSourceConfigRequest providers.ValidateDataSourceConfigRequest - ValidateDataSourceConfigFn func(providers.ValidateDataSourceConfigRequest) providers.ValidateDataSourceConfigResponse - - UpgradeResourceStateCalled bool - UpgradeResourceStateTypeName string - UpgradeResourceStateResponse providers.UpgradeResourceStateResponse - UpgradeResourceStateRequest providers.UpgradeResourceStateRequest - UpgradeResourceStateFn func(providers.UpgradeResourceStateRequest) providers.UpgradeResourceStateResponse - - ConfigureCalled bool - ConfigureResponse providers.ConfigureResponse - ConfigureRequest providers.ConfigureRequest - ConfigureNewFn func(providers.ConfigureRequest) providers.ConfigureResponse // Named ConfigureNewFn so we can still have the legacy ConfigureFn declared below - - StopCalled bool - StopFn func() error - StopResponse error - - ReadResourceCalled bool - ReadResourceResponse providers.ReadResourceResponse - ReadResourceRequest providers.ReadResourceRequest - ReadResourceFn func(providers.ReadResourceRequest) providers.ReadResourceResponse - - PlanResourceChangeCalled bool - PlanResourceChangeResponse providers.PlanResourceChangeResponse - PlanResourceChangeRequest providers.PlanResourceChangeRequest - PlanResourceChangeFn func(providers.PlanResourceChangeRequest) providers.PlanResourceChangeResponse - - ApplyResourceChangeCalled bool - ApplyResourceChangeResponse providers.ApplyResourceChangeResponse - ApplyResourceChangeRequest providers.ApplyResourceChangeRequest - ApplyResourceChangeFn func(providers.ApplyResourceChangeRequest) providers.ApplyResourceChangeResponse - - ImportResourceStateCalled bool - ImportResourceStateResponse providers.ImportResourceStateResponse - ImportResourceStateRequest providers.ImportResourceStateRequest - ImportResourceStateFn func(providers.ImportResourceStateRequest) providers.ImportResourceStateResponse - // Legacy return type for existing tests, which will be shimmed into an - // ImportResourceStateResponse if set - ImportStateReturn []*InstanceState - - ReadDataSourceCalled bool - ReadDataSourceResponse providers.ReadDataSourceResponse - ReadDataSourceRequest providers.ReadDataSourceRequest - ReadDataSourceFn func(providers.ReadDataSourceRequest) providers.ReadDataSourceResponse - - CloseCalled bool - CloseError error - - // Legacy callbacks: if these are set, we will shim incoming calls for - // new-style methods to these old-fashioned terraform.ResourceProvider - // mock callbacks, for the benefit of older tests that were written against - // the old mock API. - ValidateFn func(c *ResourceConfig) (ws []string, es []error) - ConfigureFn func(c *ResourceConfig) error - DiffFn func(info *InstanceInfo, s *InstanceState, c *ResourceConfig) (*InstanceDiff, error) - ApplyFn func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) -} - -func (p *MockProvider) GetSchema() providers.GetSchemaResponse { - p.Lock() - defer p.Unlock() - p.GetSchemaCalled = true - return p.getSchema() -} - -func (p *MockProvider) getSchema() providers.GetSchemaResponse { - // This version of getSchema doesn't do any locking, so it's suitable to - // call from other methods of this mock as long as they are already - // holding the lock. - - ret := providers.GetSchemaResponse{ - Provider: providers.Schema{}, - DataSources: map[string]providers.Schema{}, - ResourceTypes: map[string]providers.Schema{}, - } - if p.GetSchemaReturn != nil { - ret.Provider.Block = p.GetSchemaReturn.Provider - for n, s := range p.GetSchemaReturn.DataSources { - ret.DataSources[n] = providers.Schema{ - Block: s, - } - } - for n, s := range p.GetSchemaReturn.ResourceTypes { - ret.ResourceTypes[n] = providers.Schema{ - Version: int64(p.GetSchemaReturn.ResourceTypeSchemaVersions[n]), - Block: s, - } - } - } - - return ret -} - -func (p *MockProvider) PrepareProviderConfig(r providers.PrepareProviderConfigRequest) providers.PrepareProviderConfigResponse { - p.Lock() - defer p.Unlock() - - p.PrepareProviderConfigCalled = true - p.PrepareProviderConfigRequest = r - if p.PrepareProviderConfigFn != nil { - return p.PrepareProviderConfigFn(r) - } - return p.PrepareProviderConfigResponse -} - -func (p *MockProvider) ValidateResourceTypeConfig(r providers.ValidateResourceTypeConfigRequest) providers.ValidateResourceTypeConfigResponse { - p.Lock() - defer p.Unlock() - - p.ValidateResourceTypeConfigCalled = true - p.ValidateResourceTypeConfigRequest = r - - if p.ValidateFn != nil { - resp := p.getSchema() - schema := resp.Provider.Block - rc := NewResourceConfigShimmed(r.Config, schema) - warns, errs := p.ValidateFn(rc) - ret := providers.ValidateResourceTypeConfigResponse{} - for _, warn := range warns { - ret.Diagnostics = ret.Diagnostics.Append(tfdiags.SimpleWarning(warn)) - } - for _, err := range errs { - ret.Diagnostics = ret.Diagnostics.Append(err) - } - } - if p.ValidateResourceTypeConfigFn != nil { - return p.ValidateResourceTypeConfigFn(r) - } - - return p.ValidateResourceTypeConfigResponse -} - -func (p *MockProvider) ValidateDataSourceConfig(r providers.ValidateDataSourceConfigRequest) providers.ValidateDataSourceConfigResponse { - p.Lock() - defer p.Unlock() - - p.ValidateDataSourceConfigCalled = true - p.ValidateDataSourceConfigRequest = r - - if p.ValidateDataSourceConfigFn != nil { - return p.ValidateDataSourceConfigFn(r) - } - - return p.ValidateDataSourceConfigResponse -} - -func (p *MockProvider) UpgradeResourceState(r providers.UpgradeResourceStateRequest) providers.UpgradeResourceStateResponse { - p.Lock() - defer p.Unlock() - - p.UpgradeResourceStateCalled = true - p.UpgradeResourceStateRequest = r - - if p.UpgradeResourceStateFn != nil { - return p.UpgradeResourceStateFn(r) - } - - return p.UpgradeResourceStateResponse -} - -func (p *MockProvider) Configure(r providers.ConfigureRequest) providers.ConfigureResponse { - p.Lock() - defer p.Unlock() - - p.ConfigureCalled = true - p.ConfigureRequest = r - - if p.ConfigureFn != nil { - resp := p.getSchema() - schema := resp.Provider.Block - rc := NewResourceConfigShimmed(r.Config, schema) - ret := providers.ConfigureResponse{} - - err := p.ConfigureFn(rc) - if err != nil { - ret.Diagnostics = ret.Diagnostics.Append(err) - } - return ret - } - if p.ConfigureNewFn != nil { - return p.ConfigureNewFn(r) - } - - return p.ConfigureResponse -} - -func (p *MockProvider) Stop() error { - // We intentionally don't lock in this one because the whole point of this - // method is to be called concurrently with another operation that can - // be cancelled. The provider itself is responsible for handling - // any concurrency concerns in this case. - - p.StopCalled = true - if p.StopFn != nil { - return p.StopFn() - } - - return p.StopResponse -} - -func (p *MockProvider) ReadResource(r providers.ReadResourceRequest) providers.ReadResourceResponse { - p.Lock() - defer p.Unlock() - - p.ReadResourceCalled = true - p.ReadResourceRequest = r - - if p.ReadResourceFn != nil { - return p.ReadResourceFn(r) - } - - // make sure the NewState fits the schema - newState, err := p.GetSchemaReturn.ResourceTypes[r.TypeName].CoerceValue(p.ReadResourceResponse.NewState) - if err != nil { - panic(err) - } - resp := p.ReadResourceResponse - resp.NewState = newState - - return resp -} - -func (p *MockProvider) PlanResourceChange(r providers.PlanResourceChangeRequest) providers.PlanResourceChangeResponse { - p.Lock() - defer p.Unlock() - - p.PlanResourceChangeCalled = true - p.PlanResourceChangeRequest = r - - if p.DiffFn != nil { - ps := p.getSchema() - if ps.ResourceTypes == nil || ps.ResourceTypes[r.TypeName].Block == nil { - return providers.PlanResourceChangeResponse{ - Diagnostics: tfdiags.Diagnostics(nil).Append(fmt.Printf("mock provider has no schema for resource type %s", r.TypeName)), - } - } - schema := ps.ResourceTypes[r.TypeName].Block - info := &InstanceInfo{ - Type: r.TypeName, - } - priorState := NewInstanceStateShimmedFromValue(r.PriorState, 0) - cfg := NewResourceConfigShimmed(r.Config, schema) - - legacyDiff, err := p.DiffFn(info, priorState, cfg) - - var res providers.PlanResourceChangeResponse - res.PlannedState = r.ProposedNewState - if err != nil { - res.Diagnostics = res.Diagnostics.Append(err) - } - if legacyDiff != nil { - newVal, err := legacyDiff.ApplyToValue(r.PriorState, schema) - if err != nil { - res.Diagnostics = res.Diagnostics.Append(err) - } - - res.PlannedState = newVal - - var requiresNew []string - for attr, d := range legacyDiff.Attributes { - if d.RequiresNew { - requiresNew = append(requiresNew, attr) - } - } - requiresReplace, err := hcl2shim.RequiresReplace(requiresNew, schema.ImpliedType()) - if err != nil { - res.Diagnostics = res.Diagnostics.Append(err) - } - res.RequiresReplace = requiresReplace - } - return res - } - if p.PlanResourceChangeFn != nil { - return p.PlanResourceChangeFn(r) - } - - return p.PlanResourceChangeResponse -} - -func (p *MockProvider) ApplyResourceChange(r providers.ApplyResourceChangeRequest) providers.ApplyResourceChangeResponse { - p.Lock() - p.ApplyResourceChangeCalled = true - p.ApplyResourceChangeRequest = r - p.Unlock() - - if p.ApplyFn != nil { - // ApplyFn is a special callback fashioned after our old provider - // interface, which expected to be given an actual diff rather than - // separate old/new values to apply. Therefore we need to approximate - // a diff here well enough that _most_ of our legacy ApplyFns in old - // tests still see the behavior they are expecting. New tests should - // not use this, and should instead use ApplyResourceChangeFn directly. - providerSchema := p.getSchema() - schema, ok := providerSchema.ResourceTypes[r.TypeName] - if !ok { - return providers.ApplyResourceChangeResponse{ - Diagnostics: tfdiags.Diagnostics(nil).Append(fmt.Errorf("no mocked schema available for resource type %s", r.TypeName)), - } - } - - info := &InstanceInfo{ - Type: r.TypeName, - } - - priorVal := r.PriorState - plannedVal := r.PlannedState - priorMap := hcl2shim.FlatmapValueFromHCL2(priorVal) - plannedMap := hcl2shim.FlatmapValueFromHCL2(plannedVal) - s := NewInstanceStateShimmedFromValue(priorVal, 0) - d := &InstanceDiff{ - Attributes: make(map[string]*ResourceAttrDiff), - } - if plannedMap == nil { // destroying, then - d.Destroy = true - // Destroy diffs don't have any attribute diffs - } else { - if priorMap == nil { // creating, then - // We'll just make an empty prior map to make things easier below. - priorMap = make(map[string]string) - } - - for k, new := range plannedMap { - old := priorMap[k] - newComputed := false - if new == config.UnknownVariableValue { - new = "" - newComputed = true - } - d.Attributes[k] = &ResourceAttrDiff{ - Old: old, - New: new, - NewComputed: newComputed, - Type: DiffAttrInput, // not generally used in tests, so just hard-coded - } - } - // Also need any attributes that were removed in "planned" - for k, old := range priorMap { - if _, ok := plannedMap[k]; ok { - continue - } - d.Attributes[k] = &ResourceAttrDiff{ - Old: old, - NewRemoved: true, - Type: DiffAttrInput, - } - } - } - newState, err := p.ApplyFn(info, s, d) - resp := providers.ApplyResourceChangeResponse{} - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - } - if newState != nil { - var newVal cty.Value - if newState != nil { - var err error - newVal, err = newState.AttrsAsObjectValue(schema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - } - } else { - // If apply returned a nil new state then that's the old way to - // indicate that the object was destroyed. Our new interface calls - // for that to be signalled as a null value. - newVal = cty.NullVal(schema.Block.ImpliedType()) - } - resp.NewState = newVal - } - - return resp - } - if p.ApplyResourceChangeFn != nil { - return p.ApplyResourceChangeFn(r) - } - - return p.ApplyResourceChangeResponse -} - -func (p *MockProvider) ImportResourceState(r providers.ImportResourceStateRequest) providers.ImportResourceStateResponse { - p.Lock() - defer p.Unlock() - - if p.ImportStateReturn != nil { - for _, is := range p.ImportStateReturn { - if is.Attributes == nil { - is.Attributes = make(map[string]string) - } - is.Attributes["id"] = is.ID - - typeName := is.Ephemeral.Type - // Use the requested type if the resource has no type of it's own. - // We still return the empty type, which will error, but this prevents a panic. - if typeName == "" { - typeName = r.TypeName - } - - schema := p.GetSchemaReturn.ResourceTypes[typeName] - if schema == nil { - panic("no schema found for " + typeName) - } - - private, err := json.Marshal(is.Meta) - if err != nil { - panic(err) - } - - state, err := hcl2shim.HCL2ValueFromFlatmap(is.Attributes, schema.ImpliedType()) - if err != nil { - panic(err) - } - - state, err = schema.CoerceValue(state) - if err != nil { - panic(err) - } - - p.ImportResourceStateResponse.ImportedResources = append( - p.ImportResourceStateResponse.ImportedResources, - providers.ImportedResource{ - TypeName: is.Ephemeral.Type, - State: state, - Private: private, - }) - } - } - - p.ImportResourceStateCalled = true - p.ImportResourceStateRequest = r - if p.ImportResourceStateFn != nil { - return p.ImportResourceStateFn(r) - } - - return p.ImportResourceStateResponse -} - -func (p *MockProvider) ReadDataSource(r providers.ReadDataSourceRequest) providers.ReadDataSourceResponse { - p.Lock() - defer p.Unlock() - - p.ReadDataSourceCalled = true - p.ReadDataSourceRequest = r - - if p.ReadDataSourceFn != nil { - return p.ReadDataSourceFn(r) - } - - return p.ReadDataSourceResponse -} - -func (p *MockProvider) Close() error { - p.CloseCalled = true - return p.CloseError -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/provisioner_mock.go b/vendor/github.com/hashicorp/terraform/terraform/provisioner_mock.go deleted file mode 100644 index f5958916..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/provisioner_mock.go +++ /dev/null @@ -1,154 +0,0 @@ -package terraform - -import ( - "fmt" - "sync" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform/provisioners" -) - -var _ provisioners.Interface = (*MockProvisioner)(nil) - -// MockProvisioner implements provisioners.Interface but mocks out all the -// calls for testing purposes. -type MockProvisioner struct { - sync.Mutex - // Anything you want, in case you need to store extra data with the mock. - Meta interface{} - - GetSchemaCalled bool - GetSchemaResponse provisioners.GetSchemaResponse - - ValidateProvisionerConfigCalled bool - ValidateProvisionerConfigRequest provisioners.ValidateProvisionerConfigRequest - ValidateProvisionerConfigResponse provisioners.ValidateProvisionerConfigResponse - ValidateProvisionerConfigFn func(provisioners.ValidateProvisionerConfigRequest) provisioners.ValidateProvisionerConfigResponse - - ProvisionResourceCalled bool - ProvisionResourceRequest provisioners.ProvisionResourceRequest - ProvisionResourceResponse provisioners.ProvisionResourceResponse - ProvisionResourceFn func(provisioners.ProvisionResourceRequest) provisioners.ProvisionResourceResponse - - StopCalled bool - StopResponse error - StopFn func() error - - CloseCalled bool - CloseResponse error - CloseFn func() error - - // Legacy callbacks: if these are set, we will shim incoming calls for - // new-style methods to these old-fashioned terraform.ResourceProvider - // mock callbacks, for the benefit of older tests that were written against - // the old mock API. - ApplyFn func(rs *InstanceState, c *ResourceConfig) error -} - -func (p *MockProvisioner) GetSchema() provisioners.GetSchemaResponse { - p.Lock() - defer p.Unlock() - - p.GetSchemaCalled = true - return p.getSchema() -} - -// getSchema is the implementation of GetSchema, which can be called from other -// methods on MockProvisioner that may already be holding the lock. -func (p *MockProvisioner) getSchema() provisioners.GetSchemaResponse { - return p.GetSchemaResponse -} - -func (p *MockProvisioner) ValidateProvisionerConfig(r provisioners.ValidateProvisionerConfigRequest) provisioners.ValidateProvisionerConfigResponse { - p.Lock() - defer p.Unlock() - - p.ValidateProvisionerConfigCalled = true - p.ValidateProvisionerConfigRequest = r - if p.ValidateProvisionerConfigFn != nil { - return p.ValidateProvisionerConfigFn(r) - } - return p.ValidateProvisionerConfigResponse -} - -func (p *MockProvisioner) ProvisionResource(r provisioners.ProvisionResourceRequest) provisioners.ProvisionResourceResponse { - p.Lock() - defer p.Unlock() - - p.ProvisionResourceCalled = true - p.ProvisionResourceRequest = r - if p.ApplyFn != nil { - if !r.Config.IsKnown() { - panic(fmt.Sprintf("cannot provision with unknown value: %#v", r.Config)) - } - - schema := p.getSchema() - rc := NewResourceConfigShimmed(r.Config, schema.Provisioner) - connVal := r.Connection - connMap := map[string]string{} - - if !connVal.IsNull() && connVal.IsKnown() { - for it := connVal.ElementIterator(); it.Next(); { - ak, av := it.Element() - name := ak.AsString() - - if !av.IsKnown() || av.IsNull() { - continue - } - - av, _ = convert.Convert(av, cty.String) - connMap[name] = av.AsString() - } - } - - // We no longer pass the full instance state to a provisioner, so we'll - // construct a partial one that should be good enough for what existing - // test mocks need. - is := &InstanceState{ - Ephemeral: EphemeralState{ - ConnInfo: connMap, - }, - } - var resp provisioners.ProvisionResourceResponse - err := p.ApplyFn(is, rc) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - } - return resp - } - if p.ProvisionResourceFn != nil { - fn := p.ProvisionResourceFn - p.Unlock() - return fn(r) - } - - return p.ProvisionResourceResponse -} - -func (p *MockProvisioner) Stop() error { - // We intentionally don't lock in this one because the whole point of this - // method is to be called concurrently with another operation that can - // be cancelled. The provisioner itself is responsible for handling - // any concurrency concerns in this case. - - p.StopCalled = true - if p.StopFn != nil { - return p.StopFn() - } - - return p.StopResponse -} - -func (p *MockProvisioner) Close() error { - p.Lock() - defer p.Unlock() - - p.CloseCalled = true - if p.CloseFn != nil { - return p.CloseFn() - } - - return p.CloseResponse -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/resource.go b/vendor/github.com/hashicorp/terraform/terraform/resource.go index 0991037b..2f5ebb5e 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/resource.go +++ b/vendor/github.com/hashicorp/terraform/terraform/resource.go @@ -2,20 +2,14 @@ package terraform import ( "fmt" - "log" "reflect" "sort" "strconv" "strings" + "github.com/hashicorp/terraform/config" "github.com/mitchellh/copystructure" "github.com/mitchellh/reflectwalk" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/hcl2shim" - "github.com/hashicorp/terraform/configs/configschema" ) // ResourceProvisionerConfig is used to pair a provisioner @@ -31,10 +25,9 @@ type ResourceProvisionerConfig struct { ConnInfo *config.RawConfig } -// Resource is a legacy way to identify a particular resource instance. -// -// New code should use addrs.ResourceInstance instead. This is still here -// only for codepaths that haven't been updated yet. +// Resource encapsulates a resource, its configuration, its provider, +// its current state, and potentially a desired diff from the state it +// wants to reach. type Resource struct { // These are all used by the new EvalNode stuff. Name string @@ -54,31 +47,6 @@ type Resource struct { Flags ResourceFlag } -// NewResource constructs a legacy Resource object from an -// addrs.ResourceInstance value. -// -// This is provided to shim to old codepaths that haven't been updated away -// from this type yet. Since this old type is not able to represent instances -// that have string keys, this function will panic if given a resource address -// that has a string key. -func NewResource(addr addrs.ResourceInstance) *Resource { - ret := &Resource{ - Name: addr.Resource.Name, - Type: addr.Resource.Type, - } - - if addr.Key != addrs.NoKey { - switch tk := addr.Key.(type) { - case addrs.IntKey: - ret.CountIndex = int(tk) - default: - panic(fmt.Errorf("resource instance with key %#v is not supported", addr.Key)) - } - } - - return ret -} - // ResourceKind specifies what kind of instance we're working with, whether // its a primary instance, a tainted instance, or an orphan. type ResourceFlag byte @@ -104,53 +72,20 @@ type InstanceInfo struct { uniqueExtra string } -// NewInstanceInfo constructs an InstanceInfo from an addrs.AbsResourceInstance. -// -// InstanceInfo is a legacy type, and uses of it should be gradually replaced -// by direct use of addrs.AbsResource or addrs.AbsResourceInstance as -// appropriate. -// -// The legacy InstanceInfo type cannot represent module instances with instance -// keys, so this function will panic if given such a path. Uses of this type -// should all be removed or replaced before implementing "count" and "for_each" -// arguments on modules in order to avoid such panics. -// -// This legacy type also cannot represent resource instances with string -// instance keys. It will panic if the given key is not either NoKey or an -// IntKey. -func NewInstanceInfo(addr addrs.AbsResourceInstance) *InstanceInfo { - // We need an old-style []string module path for InstanceInfo. - path := make([]string, len(addr.Module)) - for i, step := range addr.Module { - if step.InstanceKey != addrs.NoKey { - panic("NewInstanceInfo cannot convert module instance with key") - } - path[i] = step.Name +// HumanId is a unique Id that is human-friendly and useful for UI elements. +func (i *InstanceInfo) HumanId() string { + if i == nil { + return "" } - // This is a funny old meaning of "id" that is no longer current. It should - // not be used for anything users might see. Note that it does not include - // a representation of the resource mode, and so it's impossible to - // determine from an InstanceInfo alone whether it is a managed or data - // resource that is being referred to. - id := fmt.Sprintf("%s.%s", addr.Resource.Resource.Type, addr.Resource.Resource.Name) - if addr.Resource.Resource.Mode == addrs.DataResourceMode { - id = "data." + id - } - if addr.Resource.Key != addrs.NoKey { - switch k := addr.Resource.Key.(type) { - case addrs.IntKey: - id = id + fmt.Sprintf(".%d", int(k)) - default: - panic(fmt.Sprintf("NewInstanceInfo cannot convert resource instance with %T instance key", addr.Resource.Key)) - } + if len(i.ModulePath) <= 1 { + return i.Id } - return &InstanceInfo{ - Id: id, - ModulePath: path, - Type: addr.Resource.Resource.Type, - } + return fmt.Sprintf( + "module.%s.%s", + strings.Join(i.ModulePath[1:], "."), + i.Id) } // ResourceAddress returns the address of the resource that the receiver is describing. @@ -193,9 +128,18 @@ func (i *InstanceInfo) ResourceAddress() *ResourceAddress { return addr } -// ResourceConfig is a legacy type that was formerly used to represent -// interpolatable configuration blocks. It is now only used to shim to old -// APIs that still use this type, via NewResourceConfigShimmed. +func (i *InstanceInfo) uniqueId() string { + prefix := i.HumanId() + if v := i.uniqueExtra; v != "" { + prefix += " " + v + } + + return prefix +} + +// ResourceConfig holds the configuration given for a resource. This is +// done instead of a raw `map[string]interface{}` type so that rich +// methods can be added to it to make dealing with it easier. type ResourceConfig struct { ComputedKeys []string Raw map[string]interface{} @@ -211,112 +155,6 @@ func NewResourceConfig(c *config.RawConfig) *ResourceConfig { return result } -// NewResourceConfigShimmed wraps a cty.Value of object type in a legacy -// ResourceConfig object, so that it can be passed to older APIs that expect -// this wrapping. -// -// The returned ResourceConfig is already interpolated and cannot be -// re-interpolated. It is, therefore, useful only to functions that expect -// an already-populated ResourceConfig which they then treat as read-only. -// -// If the given value is not of an object type that conforms to the given -// schema then this function will panic. -func NewResourceConfigShimmed(val cty.Value, schema *configschema.Block) *ResourceConfig { - if !val.Type().IsObjectType() { - panic(fmt.Errorf("NewResourceConfigShimmed given %#v; an object type is required", val.Type())) - } - ret := &ResourceConfig{} - - legacyVal := hcl2shim.ConfigValueFromHCL2Block(val, schema) - if legacyVal != nil { - ret.Config = legacyVal - - // Now we need to walk through our structure and find any unknown values, - // producing the separate list ComputedKeys to represent these. We use the - // schema here so that we can preserve the expected invariant - // that an attribute is always either wholly known or wholly unknown, while - // a child block can be partially unknown. - ret.ComputedKeys = newResourceConfigShimmedComputedKeys(val, schema, "") - } else { - ret.Config = make(map[string]interface{}) - } - ret.Raw = ret.Config - - return ret -} - -// newResourceConfigShimmedComputedKeys finds all of the unknown values in the -// given object, which must conform to the given schema, returning them in -// the format that's expected for ResourceConfig.ComputedKeys. -func newResourceConfigShimmedComputedKeys(obj cty.Value, schema *configschema.Block, prefix string) []string { - var ret []string - ty := obj.Type() - - if schema == nil { - log.Printf("[WARN] NewResourceConfigShimmed: can't identify computed keys because no schema is available") - return nil - } - - for attrName := range schema.Attributes { - if !ty.HasAttribute(attrName) { - // Should never happen, but we'll tolerate it anyway - continue - } - - attrVal := obj.GetAttr(attrName) - if !attrVal.IsWhollyKnown() { - ret = append(ret, prefix+attrName) - } - } - - for typeName, blockS := range schema.BlockTypes { - if !ty.HasAttribute(typeName) { - // Should never happen, but we'll tolerate it anyway - continue - } - - blockVal := obj.GetAttr(typeName) - if blockVal.IsNull() || !blockVal.IsKnown() { - continue - } - - switch blockS.Nesting { - case configschema.NestingSingle: - keys := newResourceConfigShimmedComputedKeys(blockVal, &blockS.Block, fmt.Sprintf("%s%s.", prefix, typeName)) - ret = append(ret, keys...) - case configschema.NestingList, configschema.NestingSet: - // Producing computed keys items for sets is not really useful - // since they are not usefully addressable anyway, but we'll treat - // them like lists just so that ret.ComputedKeys accounts for them - // all. Our legacy system didn't support sets here anyway, so - // treating them as lists is the most accurate translation. Although - // set traversal isn't in any particular order, it is _stable_ as - // long as the list isn't mutated, and so we know we'll see the - // same order here as hcl2shim.ConfigValueFromHCL2 would've seen - // inside NewResourceConfigShimmed above. - i := 0 - for it := blockVal.ElementIterator(); it.Next(); i++ { - _, subVal := it.Element() - subPrefix := fmt.Sprintf("%s.%s%d.", typeName, prefix, i) - keys := newResourceConfigShimmedComputedKeys(subVal, &blockS.Block, subPrefix) - ret = append(ret, keys...) - } - case configschema.NestingMap: - for it := blockVal.ElementIterator(); it.Next(); { - subK, subVal := it.Element() - subPrefix := fmt.Sprintf("%s.%s%s.", typeName, prefix, subK.AsString()) - keys := newResourceConfigShimmedComputedKeys(subVal, &blockS.Block, subPrefix) - ret = append(ret, keys...) - } - default: - // Should never happen, since the above is exhaustive. - panic(fmt.Errorf("unsupported block nesting type %s", blockS.Nesting)) - } - } - - return ret -} - // DeepCopy performs a deep copy of the configuration. This makes it safe // to modify any of the structures that are part of the resource config without // affecting the original configuration. @@ -536,14 +374,6 @@ func (c *ResourceConfig) get( // refactor is complete. func (c *ResourceConfig) interpolateForce() { if c.raw == nil { - // If we don't have a lowercase "raw" but we _do_ have the uppercase - // Raw populated then this indicates that we're recieving a shim - // ResourceConfig created by NewResourceConfigShimmed, which is already - // fully evaluated and thus this function doesn't need to do anything. - if c.Raw != nil { - return - } - var err error c.raw, err = config.NewRawConfig(make(map[string]interface{})) if err != nil { diff --git a/vendor/github.com/hashicorp/terraform/terraform/resource_address.go b/vendor/github.com/hashicorp/terraform/terraform/resource_address.go index 156ecf5c..a64f5d84 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/resource_address.go +++ b/vendor/github.com/hashicorp/terraform/terraform/resource_address.go @@ -7,10 +7,8 @@ import ( "strconv" "strings" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" ) // ResourceAddress is a way of identifying an individual resource (or, @@ -111,47 +109,30 @@ func (r *ResourceAddress) WholeModuleAddress() *ResourceAddress { } } -// MatchesResourceConfig returns true if the receiver matches the given -// configuration resource within the given _static_ module path. Note that -// the module path in a resource address is a _dynamic_ module path, and -// multiple dynamic resource paths may map to a single static path if -// count and for_each are in use on module calls. +// MatchesConfig returns true if the receiver matches the given +// configuration resource within the given configuration module. // // Since resource configuration blocks represent all of the instances of // a multi-instance resource, the index of the address (if any) is not // considered. -func (r *ResourceAddress) MatchesResourceConfig(path addrs.Module, rc *configs.Resource) bool { +func (r *ResourceAddress) MatchesConfig(mod *module.Tree, rc *config.Resource) bool { if r.HasResourceSpec() { - // FIXME: Some ugliness while we are between worlds. Functionality - // in "addrs" should eventually replace this ResourceAddress idea - // completely, but for now we'll need to translate to the old - // way of representing resource modes. - switch r.Mode { - case config.ManagedResourceMode: - if rc.Mode != addrs.ManagedResourceMode { - return false - } - case config.DataResourceMode: - if rc.Mode != addrs.DataResourceMode { - return false - } - } - if r.Type != rc.Type || r.Name != rc.Name { + if r.Mode != rc.Mode || r.Type != rc.Type || r.Name != rc.Name { return false } } addrPath := r.Path + cfgPath := mod.Path() // normalize if len(addrPath) == 0 { addrPath = nil } - if len(path) == 0 { - path = nil + if len(cfgPath) == 0 { + cfgPath = nil } - rawPath := []string(path) - return reflect.DeepEqual(addrPath, rawPath) + return reflect.DeepEqual(addrPath, cfgPath) } // stateId returns the ID that this resource should be entered with @@ -289,144 +270,6 @@ func ParseResourceAddressForInstanceDiff(path []string, key string) (*ResourceAd return addr, nil } -// NewLegacyResourceAddress creates a ResourceAddress from a new-style -// addrs.AbsResource value. -// -// This is provided for shimming purposes so that we can still easily call into -// older functions that expect the ResourceAddress type. -func NewLegacyResourceAddress(addr addrs.AbsResource) *ResourceAddress { - ret := &ResourceAddress{ - Type: addr.Resource.Type, - Name: addr.Resource.Name, - } - - switch addr.Resource.Mode { - case addrs.ManagedResourceMode: - ret.Mode = config.ManagedResourceMode - case addrs.DataResourceMode: - ret.Mode = config.DataResourceMode - default: - panic(fmt.Errorf("cannot shim %s to legacy config.ResourceMode value", addr.Resource.Mode)) - } - - path := make([]string, len(addr.Module)) - for i, step := range addr.Module { - if step.InstanceKey != addrs.NoKey { - // At the time of writing this can't happen because we don't - // ket generate keyed module instances. This legacy codepath must - // be removed before we can support "count" and "for_each" for - // modules. - panic(fmt.Errorf("cannot shim module instance step with key %#v to legacy ResourceAddress.Path", step.InstanceKey)) - } - - path[i] = step.Name - } - ret.Path = path - ret.Index = -1 - - return ret -} - -// NewLegacyResourceInstanceAddress creates a ResourceAddress from a new-style -// addrs.AbsResource value. -// -// This is provided for shimming purposes so that we can still easily call into -// older functions that expect the ResourceAddress type. -func NewLegacyResourceInstanceAddress(addr addrs.AbsResourceInstance) *ResourceAddress { - ret := &ResourceAddress{ - Type: addr.Resource.Resource.Type, - Name: addr.Resource.Resource.Name, - } - - switch addr.Resource.Resource.Mode { - case addrs.ManagedResourceMode: - ret.Mode = config.ManagedResourceMode - case addrs.DataResourceMode: - ret.Mode = config.DataResourceMode - default: - panic(fmt.Errorf("cannot shim %s to legacy config.ResourceMode value", addr.Resource.Resource.Mode)) - } - - path := make([]string, len(addr.Module)) - for i, step := range addr.Module { - if step.InstanceKey != addrs.NoKey { - // At the time of writing this can't happen because we don't - // ket generate keyed module instances. This legacy codepath must - // be removed before we can support "count" and "for_each" for - // modules. - panic(fmt.Errorf("cannot shim module instance step with key %#v to legacy ResourceAddress.Path", step.InstanceKey)) - } - - path[i] = step.Name - } - ret.Path = path - - if addr.Resource.Key == addrs.NoKey { - ret.Index = -1 - } else if ik, ok := addr.Resource.Key.(addrs.IntKey); ok { - ret.Index = int(ik) - } else { - panic(fmt.Errorf("cannot shim resource instance with key %#v to legacy ResourceAddress.Index", addr.Resource.Key)) - } - - return ret -} - -// AbsResourceInstanceAddr converts the receiver, a legacy resource address, to -// the new resource address type addrs.AbsResourceInstance. -// -// This method can be used only on an address that has a resource specification. -// It will panic if called on a module-path-only ResourceAddress. Use -// method HasResourceSpec to check before calling, in contexts where it is -// unclear. -// -// addrs.AbsResourceInstance does not represent the "tainted" and "deposed" -// states, and so if these are present on the receiver then they are discarded. -// -// This is provided for shimming purposes so that we can easily adapt functions -// that are returning the legacy ResourceAddress type, for situations where -// the new type is required. -func (addr *ResourceAddress) AbsResourceInstanceAddr() addrs.AbsResourceInstance { - if !addr.HasResourceSpec() { - panic("AbsResourceInstanceAddr called on ResourceAddress with no resource spec") - } - - ret := addrs.AbsResourceInstance{ - Module: addr.ModuleInstanceAddr(), - Resource: addrs.ResourceInstance{ - Resource: addrs.Resource{ - Type: addr.Type, - Name: addr.Name, - }, - }, - } - - switch addr.Mode { - case config.ManagedResourceMode: - ret.Resource.Resource.Mode = addrs.ManagedResourceMode - case config.DataResourceMode: - ret.Resource.Resource.Mode = addrs.DataResourceMode - default: - panic(fmt.Errorf("cannot shim %s to addrs.ResourceMode value", addr.Mode)) - } - - if addr.Index != -1 { - ret.Resource.Key = addrs.IntKey(addr.Index) - } - - return ret -} - -// ModuleInstanceAddr returns the module path portion of the receiver as a -// addrs.ModuleInstance value. -func (addr *ResourceAddress) ModuleInstanceAddr() addrs.ModuleInstance { - path := make(addrs.ModuleInstance, len(addr.Path)) - for i, name := range addr.Path { - path[i] = addrs.ModuleInstanceStep{Name: name} - } - return path -} - // Contains returns true if and only if the given node is contained within // the receiver. // diff --git a/vendor/github.com/hashicorp/terraform/terraform/resource_provider.go b/vendor/github.com/hashicorp/terraform/terraform/resource_provider.go index 3455ad88..93fd14fc 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/resource_provider.go +++ b/vendor/github.com/hashicorp/terraform/terraform/resource_provider.go @@ -3,10 +3,8 @@ package terraform import ( "fmt" - "github.com/hashicorp/terraform/tfdiags" - + multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/plugin/discovery" - "github.com/hashicorp/terraform/providers" ) // ResourceProvider is an interface that must be implemented by any @@ -32,12 +30,13 @@ type ResourceProvider interface { // resource or data source has the SchemaAvailable flag set. GetSchema(*ProviderSchemaRequest) (*ProviderSchema, error) - // Input was used prior to v0.12 to ask the provider to prompt the user - // for input to complete the configuration. + // Input is called to ask the provider to ask the user for input + // for completing the configuration if necesarry. // - // From v0.12 onwards this method is never called because Terraform Core - // is able to handle the necessary input logic itself based on the - // schema returned from GetSchema. + // This may or may not be called, so resource provider writers shouldn't + // rely on this being available to set some default values for validate + // later. Example of a situation where this wouldn't be called is if + // the user is not using a TTY. Input(UIInput, *ResourceConfig) (*ResourceConfig, error) // Validate is called once at the beginning with the raw configuration @@ -171,6 +170,18 @@ type ResourceProvider interface { ReadDataApply(*InstanceInfo, *InstanceDiff) (*InstanceState, error) } +// ResourceProviderError may be returned when creating a Context if the +// required providers cannot be satisfied. This error can then be used to +// format a more useful message for the user. +type ResourceProviderError struct { + Errors []error +} + +func (e *ResourceProviderError) Error() string { + // use multierror to format the default output + return multierror.Append(nil, e.Errors...).Error() +} + // ResourceProviderCloser is an interface that providers that can close // connections that aren't needed anymore must implement. type ResourceProviderCloser interface { @@ -285,35 +296,13 @@ func ProviderHasDataSource(p ResourceProvider, n string) bool { // This should be called only with configurations that have passed calls // to config.Validate(), which ensures that all of the given version // constraints are valid. It will panic if any invalid constraints are present. -func resourceProviderFactories(resolver providers.Resolver, reqd discovery.PluginRequirements) (map[string]providers.Factory, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics +func resourceProviderFactories(resolver ResourceProviderResolver, reqd discovery.PluginRequirements) (map[string]ResourceProviderFactory, error) { ret, errs := resolver.ResolveProviders(reqd) if errs != nil { - diags = diags.Append( - tfdiags.Sourceless(tfdiags.Error, - "Could not satisfy plugin requirements", - errPluginInit, - ), - ) - - for _, err := range errs { - diags = diags.Append(err) + return nil, &ResourceProviderError{ + Errors: errs, } - - return nil, diags } return ret, nil } - -const errPluginInit = ` -Plugin reinitialization required. Please run "terraform init". - -Plugins are external binaries that Terraform uses to access and manipulate -resources. The configuration provided requires plugins which can't be located, -don't satisfy the version constraints, or are otherwise incompatible. - -Terraform automatically discovers provider requirements from your -configuration, including providers used in child modules. To see the -requirements and constraints from each module, run "terraform providers". -` diff --git a/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner.go index 2743dd7e..361ec1ec 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner.go @@ -1,21 +1,9 @@ package terraform -import ( - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/provisioners" -) - // ResourceProvisioner is an interface that must be implemented by any // resource provisioner: the thing that initializes resources in // a Terraform configuration. type ResourceProvisioner interface { - // GetConfigSchema returns the schema for the provisioner type's main - // configuration block. This is called prior to Validate to enable some - // basic structural validation to be performed automatically and to allow - // the configuration to be properly extracted from potentially-ambiguous - // configuration file formats. - GetConfigSchema() (*configschema.Block, error) - // Validate is called once at the beginning with the raw // configuration (no interpolation done) and can return a list of warnings // and/or errors. @@ -64,7 +52,3 @@ type ResourceProvisionerCloser interface { // ResourceProvisionerFactory is a function type that creates a new instance // of a resource provisioner. type ResourceProvisionerFactory func() (ResourceProvisioner, error) - -// ProvisionerFactory is a function type that creates a new instance -// of a provisioners.Interface. -type ProvisionerFactory = provisioners.Factory diff --git a/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner_mock.go b/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner_mock.go index 7b88cf73..f471a518 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner_mock.go +++ b/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner_mock.go @@ -1,10 +1,6 @@ package terraform -import ( - "sync" - - "github.com/hashicorp/terraform/configs/configschema" -) +import "sync" // MockResourceProvisioner implements ResourceProvisioner but mocks out all the // calls for testing purposes. @@ -13,10 +9,6 @@ type MockResourceProvisioner struct { // Anything you want, in case you need to store extra data with the mock. Meta interface{} - GetConfigSchemaCalled bool - GetConfigSchemaReturnSchema *configschema.Block - GetConfigSchemaReturnError error - ApplyCalled bool ApplyOutput UIOutput ApplyState *InstanceState @@ -35,13 +27,6 @@ type MockResourceProvisioner struct { StopReturnError error } -var _ ResourceProvisioner = (*MockResourceProvisioner)(nil) - -func (p *MockResourceProvisioner) GetConfigSchema() (*configschema.Block, error) { - p.GetConfigSchemaCalled = true - return p.GetConfigSchemaReturnSchema, p.GetConfigSchemaReturnError -} - func (p *MockResourceProvisioner) Validate(c *ResourceConfig) ([]string, []error) { p.Lock() defer p.Unlock() diff --git a/vendor/github.com/hashicorp/terraform/terraform/schemas.go b/vendor/github.com/hashicorp/terraform/terraform/schemas.go index 62991c82..ec46efcf 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/schemas.go +++ b/vendor/github.com/hashicorp/terraform/terraform/schemas.go @@ -1,239 +1,18 @@ package terraform import ( - "fmt" - "log" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config/configschema" ) -// Schemas is a container for various kinds of schema that Terraform needs -// during processing. type Schemas struct { - Providers map[string]*ProviderSchema - Provisioners map[string]*configschema.Block + Providers ProviderSchemas } -// ProviderSchema returns the entire ProviderSchema object that was produced -// by the plugin for the given provider, or nil if no such schema is available. +// ProviderSchemas is a map from provider names to provider schemas. // -// It's usually better to go use the more precise methods offered by type -// Schemas to handle this detail automatically. -func (ss *Schemas) ProviderSchema(typeName string) *ProviderSchema { - if ss.Providers == nil { - return nil - } - return ss.Providers[typeName] -} - -// ProviderConfig returns the schema for the provider configuration of the -// given provider type, or nil if no such schema is available. -func (ss *Schemas) ProviderConfig(typeName string) *configschema.Block { - ps := ss.ProviderSchema(typeName) - if ps == nil { - return nil - } - return ps.Provider -} - -// ResourceTypeConfig returns the schema for the configuration of a given -// resource type belonging to a given provider type, or nil of no such -// schema is available. -// -// In many cases the provider type is inferrable from the resource type name, -// but this is not always true because users can override the provider for -// a resource using the "provider" meta-argument. Therefore it's important to -// always pass the correct provider name, even though it many cases it feels -// redundant. -func (ss *Schemas) ResourceTypeConfig(providerType string, resourceMode addrs.ResourceMode, resourceType string) (block *configschema.Block, schemaVersion uint64) { - ps := ss.ProviderSchema(providerType) - if ps == nil || ps.ResourceTypes == nil { - return nil, 0 - } - return ps.SchemaForResourceType(resourceMode, resourceType) -} - -// ProvisionerConfig returns the schema for the configuration of a given -// provisioner, or nil of no such schema is available. -func (ss *Schemas) ProvisionerConfig(name string) *configschema.Block { - return ss.Provisioners[name] -} - -// LoadSchemas searches the given configuration, state and plan (any of which -// may be nil) for constructs that have an associated schema, requests the -// necessary schemas from the given component factory (which must _not_ be nil), -// and returns a single object representing all of the necessary schemas. -// -// If an error is returned, it may be a wrapped tfdiags.Diagnostics describing -// errors across multiple separate objects. Errors here will usually indicate -// either misbehavior on the part of one of the providers or of the provider -// protocol itself. When returned with errors, the returned schemas object is -// still valid but may be incomplete. -func LoadSchemas(config *configs.Config, state *states.State, components contextComponentFactory) (*Schemas, error) { - schemas := &Schemas{ - Providers: map[string]*ProviderSchema{}, - Provisioners: map[string]*configschema.Block{}, - } - var diags tfdiags.Diagnostics - - newDiags := loadProviderSchemas(schemas.Providers, config, state, components) - diags = diags.Append(newDiags) - newDiags = loadProvisionerSchemas(schemas.Provisioners, config, components) - diags = diags.Append(newDiags) - - return schemas, diags.Err() -} - -func loadProviderSchemas(schemas map[string]*ProviderSchema, config *configs.Config, state *states.State, components contextComponentFactory) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - ensure := func(typeName string) { - if _, exists := schemas[typeName]; exists { - return - } - - log.Printf("[TRACE] LoadSchemas: retrieving schema for provider type %q", typeName) - provider, err := components.ResourceProvider(typeName, "early/"+typeName) - if err != nil { - // We'll put a stub in the map so we won't re-attempt this on - // future calls. - schemas[typeName] = &ProviderSchema{} - diags = diags.Append( - fmt.Errorf("Failed to instantiate provider %q to obtain schema: %s", typeName, err), - ) - return - } - defer func() { - provider.Close() - }() - - resp := provider.GetSchema() - if resp.Diagnostics.HasErrors() { - // We'll put a stub in the map so we won't re-attempt this on - // future calls. - schemas[typeName] = &ProviderSchema{} - diags = diags.Append( - fmt.Errorf("Failed to retrieve schema from provider %q: %s", typeName, resp.Diagnostics.Err()), - ) - return - } - - s := &ProviderSchema{ - Provider: resp.Provider.Block, - ResourceTypes: make(map[string]*configschema.Block), - DataSources: make(map[string]*configschema.Block), - - ResourceTypeSchemaVersions: make(map[string]uint64), - } - - if resp.Provider.Version < 0 { - // We're not using the version numbers here yet, but we'll check - // for validity anyway in case we start using them in future. - diags = diags.Append( - fmt.Errorf("invalid negative schema version provider configuration for provider %q", typeName), - ) - } - - for t, r := range resp.ResourceTypes { - s.ResourceTypes[t] = r.Block - s.ResourceTypeSchemaVersions[t] = uint64(r.Version) - if r.Version < 0 { - diags = diags.Append( - fmt.Errorf("invalid negative schema version for resource type %s in provider %q", t, typeName), - ) - } - } - - for t, d := range resp.DataSources { - s.DataSources[t] = d.Block - if d.Version < 0 { - // We're not using the version numbers here yet, but we'll check - // for validity anyway in case we start using them in future. - diags = diags.Append( - fmt.Errorf("invalid negative schema version for data source %s in provider %q", t, typeName), - ) - } - } - - schemas[typeName] = s - } - - if config != nil { - for _, typeName := range config.ProviderTypes() { - ensure(typeName) - } - } - - if state != nil { - needed := providers.AddressedTypesAbs(state.ProviderAddrs()) - for _, typeName := range needed { - ensure(typeName) - } - } - - return diags -} - -func loadProvisionerSchemas(schemas map[string]*configschema.Block, config *configs.Config, components contextComponentFactory) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - ensure := func(name string) { - if _, exists := schemas[name]; exists { - return - } - - log.Printf("[TRACE] LoadSchemas: retrieving schema for provisioner %q", name) - provisioner, err := components.ResourceProvisioner(name, "early/"+name) - if err != nil { - // We'll put a stub in the map so we won't re-attempt this on - // future calls. - schemas[name] = &configschema.Block{} - diags = diags.Append( - fmt.Errorf("Failed to instantiate provisioner %q to obtain schema: %s", name, err), - ) - return - } - defer func() { - if closer, ok := provisioner.(ResourceProvisionerCloser); ok { - closer.Close() - } - }() - - resp := provisioner.GetSchema() - if resp.Diagnostics.HasErrors() { - // We'll put a stub in the map so we won't re-attempt this on - // future calls. - schemas[name] = &configschema.Block{} - diags = diags.Append( - fmt.Errorf("Failed to retrieve schema from provisioner %q: %s", name, resp.Diagnostics.Err()), - ) - return - } - - schemas[name] = resp.Provisioner - } - - if config != nil { - for _, rc := range config.Module.ManagedResources { - for _, pc := range rc.Managed.Provisioners { - ensure(pc.Type) - } - } - - // Must also visit our child modules, recursively. - for _, cc := range config.Children { - childDiags := loadProvisionerSchemas(schemas, cc, components) - diags = diags.Append(childDiags) - } - } - - return diags -} +// The names in this map are the direct plugin name (e.g. "aws") rather than +// any alias name (e.g. "aws.foo"), since. +type ProviderSchemas map[string]*ProviderSchema // ProviderSchema represents the schema for a provider's own configuration // and the configuration for some or all of its resources and data sources. @@ -245,29 +24,6 @@ type ProviderSchema struct { Provider *configschema.Block ResourceTypes map[string]*configschema.Block DataSources map[string]*configschema.Block - - ResourceTypeSchemaVersions map[string]uint64 -} - -// SchemaForResourceType attempts to find a schema for the given mode and type. -// Returns nil if no such schema is available. -func (ps *ProviderSchema) SchemaForResourceType(mode addrs.ResourceMode, typeName string) (schema *configschema.Block, version uint64) { - switch mode { - case addrs.ManagedResourceMode: - return ps.ResourceTypes[typeName], ps.ResourceTypeSchemaVersions[typeName] - case addrs.DataResourceMode: - // Data resources don't have schema versions right now, since state is discarded for each refresh - return ps.DataSources[typeName], 0 - default: - // Shouldn't happen, because the above cases are comprehensive. - return nil, 0 - } -} - -// SchemaForResourceAddr attempts to find a schema for the mode and type from -// the given resource address. Returns nil if no such schema is available. -func (ps *ProviderSchema) SchemaForResourceAddr(addr addrs.Resource) (schema *configschema.Block, version uint64) { - return ps.SchemaForResourceType(addr.Mode, addr.Type) } // ProviderSchemaRequest is used to describe to a ResourceProvider which diff --git a/vendor/github.com/hashicorp/terraform/terraform/semantics.go b/vendor/github.com/hashicorp/terraform/terraform/semantics.go new file mode 100644 index 00000000..20f1d8a2 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/semantics.go @@ -0,0 +1,132 @@ +package terraform + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/dag" +) + +// GraphSemanticChecker is the interface that semantic checks across +// the entire Terraform graph implement. +// +// The graph should NOT be modified by the semantic checker. +type GraphSemanticChecker interface { + Check(*dag.Graph) error +} + +// UnorderedSemanticCheckRunner is an implementation of GraphSemanticChecker +// that runs a list of SemanticCheckers against the vertices of the graph +// in no specified order. +type UnorderedSemanticCheckRunner struct { + Checks []SemanticChecker +} + +func (sc *UnorderedSemanticCheckRunner) Check(g *dag.Graph) error { + var err error + for _, v := range g.Vertices() { + for _, check := range sc.Checks { + if e := check.Check(g, v); e != nil { + err = multierror.Append(err, e) + } + } + } + + return err +} + +// SemanticChecker is the interface that semantic checks across the +// Terraform graph implement. Errors are accumulated. Even after an error +// is returned, child vertices in the graph will still be visited. +// +// The graph should NOT be modified by the semantic checker. +// +// The order in which vertices are visited is left unspecified, so the +// semantic checks should not rely on that. +type SemanticChecker interface { + Check(*dag.Graph, dag.Vertex) error +} + +// smcUserVariables does all the semantic checks to verify that the +// variables given satisfy the configuration itself. +func smcUserVariables(c *config.Config, vs map[string]interface{}) []error { + var errs []error + + cvs := make(map[string]*config.Variable) + for _, v := range c.Variables { + cvs[v.Name] = v + } + + // Check that all required variables are present + required := make(map[string]struct{}) + for _, v := range c.Variables { + if v.Required() { + required[v.Name] = struct{}{} + } + } + for k, _ := range vs { + delete(required, k) + } + if len(required) > 0 { + for k, _ := range required { + errs = append(errs, fmt.Errorf( + "Required variable not set: %s", k)) + } + } + + // Check that types match up + for name, proposedValue := range vs { + // Check for "map.key" fields. These stopped working with Terraform + // 0.7 but we do this to surface a better error message informing + // the user what happened. + if idx := strings.Index(name, "."); idx > 0 { + key := name[:idx] + if _, ok := cvs[key]; ok { + errs = append(errs, fmt.Errorf( + "%s: Overriding map keys with the format `name.key` is no "+ + "longer allowed. You may still override keys by setting "+ + "`name = { key = value }`. The maps will be merged. This "+ + "behavior appeared in 0.7.0.", name)) + continue + } + } + + schema, ok := cvs[name] + if !ok { + continue + } + + declaredType := schema.Type() + + switch declaredType { + case config.VariableTypeString: + switch proposedValue.(type) { + case string: + continue + } + case config.VariableTypeMap: + switch v := proposedValue.(type) { + case map[string]interface{}: + continue + case []map[string]interface{}: + // if we have a list of 1 map, it will get coerced later as needed + if len(v) == 1 { + continue + } + } + case config.VariableTypeList: + switch proposedValue.(type) { + case []interface{}: + continue + } + } + errs = append(errs, fmt.Errorf("variable %s should be type %s, got %s", + name, declaredType.Printable(), hclTypeName(proposedValue))) + } + + // TODO(mitchellh): variables that are unknown + + return errs +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/state.go b/vendor/github.com/hashicorp/terraform/terraform/state.go index 092b6907..04b14a65 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/state.go +++ b/vendor/github.com/hashicorp/terraform/terraform/state.go @@ -16,23 +16,12 @@ import ( "strings" "sync" - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - uuid "github.com/hashicorp/go-uuid" - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - "github.com/mitchellh/copystructure" - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform/addrs" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/go-uuid" + "github.com/hashicorp/go-version" "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/hcl2shim" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/tfdiags" + "github.com/mitchellh/copystructure" + tfversion "github.com/hashicorp/terraform/version" ) @@ -44,38 +33,26 @@ const ( // rootModulePath is the path of the root module var rootModulePath = []string{"root"} -// normalizeModulePath transforms a legacy module path (which may or may not -// have a redundant "root" label at the start of it) into an -// addrs.ModuleInstance representing the same module. -// -// For legacy reasons, different parts of Terraform disagree about whether the -// root module has the path []string{} or []string{"root"}, and so this -// function accepts both and trims off the "root". An implication of this is -// that it's not possible to actually have a module call in the root module -// that is itself named "root", since that would be ambiguous. -// // normalizeModulePath takes a raw module path and returns a path that // has the rootModulePath prepended to it. If I could go back in time I // would've never had a rootModulePath (empty path would be root). We can // still fix this but thats a big refactor that my branch doesn't make sense // for. Instead, this function normalizes paths. -func normalizeModulePath(p []string) addrs.ModuleInstance { - // FIXME: Remove this once everyone is using addrs.ModuleInstance. +func normalizeModulePath(p []string) []string { + k := len(rootModulePath) - if len(p) > 0 && p[0] == "root" { - p = p[1:] - } - - ret := make(addrs.ModuleInstance, len(p)) - for i, name := range p { - // For now we don't actually support modules with multiple instances - // identified by keys, so we just treat every path element as a - // step with no key. - ret[i] = addrs.ModuleInstanceStep{ - Name: name, + // If we already have a root module prefix, we're done + if len(p) >= len(rootModulePath) { + if reflect.DeepEqual(p[:k], rootModulePath) { + return p } } - return ret + + // None? Prefix it + result := make([]string, len(rootModulePath)+len(p)) + copy(result, rootModulePath) + copy(result[k:], p) + return result } // State keeps track of a snapshot state-of-the-world that Terraform @@ -161,43 +138,21 @@ func (s *State) children(path []string) []*ModuleState { // // This should be the preferred method to add module states since it // allows us to optimize lookups later as well as control sorting. -func (s *State) AddModule(path addrs.ModuleInstance) *ModuleState { +func (s *State) AddModule(path []string) *ModuleState { s.Lock() defer s.Unlock() return s.addModule(path) } -func (s *State) addModule(path addrs.ModuleInstance) *ModuleState { +func (s *State) addModule(path []string) *ModuleState { // check if the module exists first m := s.moduleByPath(path) if m != nil { return m } - // Lower the new-style address into a legacy-style address. - // This requires that none of the steps have instance keys, which is - // true for all addresses at the time of implementing this because - // "count" and "for_each" are not yet implemented for modules. - // For the purposes of state, the legacy address format also includes - // a redundant extra prefix element "root". It is important to include - // this because the "prune" method will remove any module that has a - // path length less than one, and other parts of the state code will - // trim off the first element indiscriminately. - legacyPath := make([]string, len(path)+1) - legacyPath[0] = "root" - for i, step := range path { - if step.InstanceKey != addrs.NoKey { - // FIXME: Once the rest of Terraform is ready to use count and - // for_each, remove all of this and just write the addrs.ModuleInstance - // value itself into the ModuleState. - panic("state cannot represent modules with count or for_each keys") - } - - legacyPath[i+1] = step.Name - } - - m = &ModuleState{Path: legacyPath} + m = &ModuleState{Path: path} m.init() s.Modules = append(s.Modules, m) s.sort() @@ -207,7 +162,7 @@ func (s *State) addModule(path addrs.ModuleInstance) *ModuleState { // ModuleByPath is used to lookup the module state for the given path. // This should be the preferred lookup mechanism as it allows for future // lookup optimizations. -func (s *State) ModuleByPath(path addrs.ModuleInstance) *ModuleState { +func (s *State) ModuleByPath(path []string) *ModuleState { if s == nil { return nil } @@ -217,7 +172,7 @@ func (s *State) ModuleByPath(path addrs.ModuleInstance) *ModuleState { return s.moduleByPath(path) } -func (s *State) moduleByPath(path addrs.ModuleInstance) *ModuleState { +func (s *State) moduleByPath(path []string) *ModuleState { for _, mod := range s.Modules { if mod == nil { continue @@ -225,14 +180,97 @@ func (s *State) moduleByPath(path addrs.ModuleInstance) *ModuleState { if mod.Path == nil { panic("missing module path") } - modPath := normalizeModulePath(mod.Path) - if modPath.String() == path.String() { + if reflect.DeepEqual(mod.Path, path) { return mod } } return nil } +// ModuleOrphans returns all the module orphans in this state by +// returning their full paths. These paths can be used with ModuleByPath +// to return the actual state. +func (s *State) ModuleOrphans(path []string, c *config.Config) [][]string { + s.Lock() + defer s.Unlock() + + return s.moduleOrphans(path, c) + +} + +func (s *State) moduleOrphans(path []string, c *config.Config) [][]string { + // direct keeps track of what direct children we have both in our config + // and in our state. childrenKeys keeps track of what isn't an orphan. + direct := make(map[string]struct{}) + childrenKeys := make(map[string]struct{}) + if c != nil { + for _, m := range c.Modules { + childrenKeys[m.Name] = struct{}{} + direct[m.Name] = struct{}{} + } + } + + // Go over the direct children and find any that aren't in our keys. + var orphans [][]string + for _, m := range s.children(path) { + key := m.Path[len(m.Path)-1] + + // Record that we found this key as a direct child. We use this + // later to find orphan nested modules. + direct[key] = struct{}{} + + // If we have a direct child still in our config, it is not an orphan + if _, ok := childrenKeys[key]; ok { + continue + } + + orphans = append(orphans, m.Path) + } + + // Find the orphans that are nested... + for _, m := range s.Modules { + if m == nil { + continue + } + + // We only want modules that are at least grandchildren + if len(m.Path) < len(path)+2 { + continue + } + + // If it isn't part of our tree, continue + if !reflect.DeepEqual(path, m.Path[:len(path)]) { + continue + } + + // If we have the direct child, then just skip it. + key := m.Path[len(path)] + if _, ok := direct[key]; ok { + continue + } + + orphanPath := m.Path[:len(path)+1] + + // Don't double-add if we've already added this orphan (which can happen if + // there are multiple nested sub-modules that get orphaned together). + alreadyAdded := false + for _, o := range orphans { + if reflect.DeepEqual(o, orphanPath) { + alreadyAdded = true + break + } + } + if alreadyAdded { + continue + } + + // Add this orphan + orphans = append(orphans, orphanPath) + } + + return orphans +} + // Empty returns true if the state is empty. func (s *State) Empty() bool { if s == nil { @@ -405,7 +443,7 @@ func (s *State) removeModule(path []string, v *ModuleState) { func (s *State) removeResource(path []string, v *ResourceState) { // Get the module this resource lives in. If it doesn't exist, we're done. - mod := s.moduleByPath(normalizeModulePath(path)) + mod := s.moduleByPath(path) if mod == nil { return } @@ -449,7 +487,7 @@ func (s *State) removeInstance(path []string, r *ResourceState, v *InstanceState // RootModule returns the ModuleState for the root module func (s *State) RootModule() *ModuleState { - root := s.ModuleByPath(addrs.RootModuleInstance) + root := s.ModuleByPath(rootModulePath) if root == nil { panic("missing root module") } @@ -484,7 +522,7 @@ func (s *State) equal(other *State) bool { } for _, m := range s.Modules { // This isn't very optimal currently but works. - otherM := other.moduleByPath(normalizeModulePath(m.Path)) + otherM := other.moduleByPath(m.Path) if otherM == nil { return false } @@ -643,8 +681,8 @@ func (s *State) init() { s.Version = StateVersion } - if s.moduleByPath(addrs.RootModuleInstance) == nil { - s.addModule(addrs.RootModuleInstance) + if s.moduleByPath(rootModulePath) == nil { + s.addModule(rootModulePath) } s.ensureHasLineage() @@ -773,9 +811,13 @@ func (s *State) String() string { // BackendState stores the configuration to connect to a remote backend. type BackendState struct { - Type string `json:"type"` // Backend type - ConfigRaw json.RawMessage `json:"config"` // Backend raw config - Hash uint64 `json:"hash"` // Hash of portion of configuration from config files + Type string `json:"type"` // Backend type + Config map[string]interface{} `json:"config"` // Backend raw config + + // Hash is the hash code to uniquely identify the original source + // configuration. We use this to detect when there is a change in + // configuration even when "type" isn't changed. + Hash uint64 `json:"hash"` } // Empty returns true if BackendState has no state. @@ -783,50 +825,25 @@ func (s *BackendState) Empty() bool { return s == nil || s.Type == "" } -// Config decodes the type-specific configuration object using the provided -// schema and returns the result as a cty.Value. -// -// An error is returned if the stored configuration does not conform to the -// given schema. -func (s *BackendState) Config(schema *configschema.Block) (cty.Value, error) { - ty := schema.ImpliedType() +// Rehash returns a unique content hash for this backend's configuration +// as a uint64 value. +// The Hash stored in the backend state needs to match the config itself, but +// we need to compare the backend config after it has been combined with all +// options. +// This function must match the implementation used by config.Backend. +func (s *BackendState) Rehash() uint64 { if s == nil { - return cty.NullVal(ty), nil - } - return ctyjson.Unmarshal(s.ConfigRaw, ty) -} - -// SetConfig replaces (in-place) the type-specific configuration object using -// the provided value and associated schema. -// -// An error is returned if the given value does not conform to the implied -// type of the schema. -func (s *BackendState) SetConfig(val cty.Value, schema *configschema.Block) error { - ty := schema.ImpliedType() - buf, err := ctyjson.Marshal(val, ty) - if err != nil { - return err - } - s.ConfigRaw = buf - return nil -} - -// ForPlan produces an alternative representation of the reciever that is -// suitable for storing in a plan. The current workspace must additionally -// be provided, to be stored alongside the backend configuration. -// -// The backend configuration schema is required in order to properly -// encode the backend-specific configuration settings. -func (s *BackendState) ForPlan(schema *configschema.Block, workspaceName string) (*plans.Backend, error) { - if s == nil { - return nil, nil + return 0 } - configVal, err := s.Config(schema) - if err != nil { - return nil, errwrap.Wrapf("failed to decode backend config: {{err}}", err) + cfg := config.Backend{ + Type: s.Type, + RawConfig: &config.RawConfig{ + Raw: s.Config, + }, } - return plans.NewBackend(s.Type, configVal, schema, workspaceName) + + return cfg.Rehash() } // RemoteState is used to track the information about a remote @@ -1072,64 +1089,58 @@ func (m *ModuleState) IsDescendent(other *ModuleState) bool { // Orphans returns a list of keys of resources that are in the State // but aren't present in the configuration itself. Hence, these keys // represent the state of resources that are orphans. -func (m *ModuleState) Orphans(c *configs.Module) []addrs.ResourceInstance { +func (m *ModuleState) Orphans(c *config.Config) []string { m.Lock() defer m.Unlock() - inConfig := make(map[string]struct{}) - if c != nil { - for _, r := range c.ManagedResources { - inConfig[r.Addr().String()] = struct{}{} - } - for _, r := range c.DataResources { - inConfig[r.Addr().String()] = struct{}{} - } - } - - var result []addrs.ResourceInstance + keys := make(map[string]struct{}) for k := range m.Resources { - // Since we've not yet updated state to use our new address format, - // we need to do some shimming here. - legacyAddr, err := parseResourceAddressInternal(k) - if err != nil { - // Suggests that the user tampered with the state, since we always - // generate valid internal addresses. - log.Printf("ModuleState has invalid resource key %q. Ignoring.", k) - continue - } + keys[k] = struct{}{} + } - addr := legacyAddr.AbsResourceInstanceAddr().Resource - compareKey := addr.Resource.String() // compare by resource address, ignoring instance key - if _, exists := inConfig[compareKey]; !exists { - result = append(result, addr) + if c != nil { + for _, r := range c.Resources { + delete(keys, r.Id()) + + for k := range keys { + if strings.HasPrefix(k, r.Id()+".") { + delete(keys, k) + } + } } } + + result := make([]string, 0, len(keys)) + for k := range keys { + result = append(result, k) + } + return result } // RemovedOutputs returns a list of outputs that are in the State but aren't // present in the configuration itself. -func (s *ModuleState) RemovedOutputs(outputs map[string]*configs.Output) []addrs.OutputValue { - if outputs == nil { - // If we got no output map at all then we'll just treat our set of - // configured outputs as empty, since that suggests that they've all - // been removed by removing their containing module. - outputs = make(map[string]*configs.Output) +func (m *ModuleState) RemovedOutputs(c *config.Config) []string { + m.Lock() + defer m.Unlock() + + keys := make(map[string]struct{}) + for k := range m.Outputs { + keys[k] = struct{}{} } - s.Lock() - defer s.Unlock() - - var ret []addrs.OutputValue - for n := range s.Outputs { - if _, declared := outputs[n]; !declared { - ret = append(ret, addrs.OutputValue{ - Name: n, - }) + if c != nil { + for _, o := range c.Outputs { + delete(keys, o.Name) } } - return ret + result := make([]string, 0, len(keys)) + for k := range keys { + result = append(result, k) + } + + return result } // View returns a view with the given resource prefix. @@ -1532,24 +1543,6 @@ func (s *ResourceState) Untaint() { } } -// ProviderAddr returns the provider address for the receiver, by parsing the -// string representation saved in state. An error can be returned if the -// value in state is corrupt. -func (s *ResourceState) ProviderAddr() (addrs.AbsProviderConfig, error) { - var diags tfdiags.Diagnostics - - str := s.Provider - traversal, travDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(travDiags) - if travDiags.HasErrors() { - return addrs.AbsProviderConfig{}, diags.Err() - } - - addr, addrDiags := addrs.ParseAbsProviderConfig(traversal) - diags = diags.Append(addrDiags) - return addr, diags.Err() -} - func (s *ResourceState) init() { s.Lock() defer s.Unlock() @@ -1658,51 +1651,6 @@ func (s *InstanceState) init() { s.Ephemeral.init() } -// NewInstanceStateShimmedFromValue is a shim method to lower a new-style -// object value representing the attributes of an instance object into the -// legacy InstanceState representation. -// -// This is for shimming to old components only and should not be used in new code. -func NewInstanceStateShimmedFromValue(state cty.Value, schemaVersion int) *InstanceState { - attrs := hcl2shim.FlatmapValueFromHCL2(state) - return &InstanceState{ - ID: attrs["id"], - Attributes: attrs, - Meta: map[string]interface{}{ - "schema_version": schemaVersion, - }, - } -} - -// AttrsAsObjectValue shims from the legacy InstanceState representation to -// a new-style cty object value representation of the state attributes, using -// the given type for guidance. -// -// The given type must be the implied type of the schema of the resource type -// of the object whose state is being converted, or the result is undefined. -// -// This is for shimming from old components only and should not be used in -// new code. -func (s *InstanceState) AttrsAsObjectValue(ty cty.Type) (cty.Value, error) { - if s == nil { - // if the state is nil, we need to construct a complete cty.Value with - // null attributes, rather than a single cty.NullVal(ty) - s = &InstanceState{} - } - - if s.Attributes == nil { - s.Attributes = map[string]string{} - } - - // make sure ID is included in the attributes. The InstanceState.ID value - // takes precedence. - if s.ID != "" { - s.Attributes["id"] = s.ID - } - - return hcl2shim.HCL2ValueFromFlatmap(s.Attributes, ty) -} - // Copy all the Fields from another InstanceState func (s *InstanceState) Set(from *InstanceState) { s.Lock() @@ -1839,19 +1787,13 @@ func (s *InstanceState) MergeDiff(d *InstanceDiff) *InstanceState { } func (s *InstanceState) String() string { - notCreated := "" - - if s == nil { - return notCreated - } - s.Lock() defer s.Unlock() var buf bytes.Buffer - if s.ID == "" { - return notCreated + if s == nil || s.ID == "" { + return "" } buf.WriteString(fmt.Sprintf("ID = %s\n", s.ID)) @@ -2245,6 +2187,19 @@ func (s moduleStateSort) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +// StateCompatible returns an error if the state is not compatible with the +// current version of terraform. +func CheckStateVersion(state *State) error { + if state == nil { + return nil + } + + if state.FromFutureTerraform() { + return fmt.Errorf(stateInvalidTerraformVersionErr, state.TFVersion) + } + return nil +} + const stateValidateErrMultiModule = ` Multiple modules with the same path: %s @@ -2253,3 +2208,11 @@ in your state file that point to the same module. This will cause Terraform to behave in unexpected and error prone ways and is invalid. Please back up and modify your state file manually to resolve this. ` + +const stateInvalidTerraformVersionErr = ` +Terraform doesn't allow running any operations against a state +that was written by a future Terraform version. The state is +reporting it is written by Terraform '%s' + +Please run at least that version of Terraform to continue. +` diff --git a/vendor/github.com/hashicorp/terraform/terraform/state_add.go b/vendor/github.com/hashicorp/terraform/terraform/state_add.go new file mode 100644 index 00000000..11637303 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/state_add.go @@ -0,0 +1,374 @@ +package terraform + +import "fmt" + +// Add adds the item in the state at the given address. +// +// The item can be a ModuleState, ResourceState, or InstanceState. Depending +// on the item type, the address may or may not be valid. For example, a +// module cannot be moved to a resource address, however a resource can be +// moved to a module address (it retains the same name, under that resource). +// +// The item can also be a []*ModuleState, which is the case for nested +// modules. In this case, Add will expect the zero-index to be the top-most +// module to add and will only nest children from there. For semantics, this +// is equivalent to module => module. +// +// The full semantics of Add: +// +// ┌───────────────────┬───────────────────┬───────────────────┐ +// │ Module Address │ Resource Address │ Instance Address │ +// ┌─────────────────┼───────────────────┼───────────────────┼───────────────────┤ +// │ ModuleState │ ✓ │ x │ x │ +// ├─────────────────┼───────────────────┼───────────────────┼───────────────────┤ +// │ ResourceState │ ✓ │ ✓ │ maybe* │ +// ├─────────────────┼───────────────────┼───────────────────┼───────────────────┤ +// │ Instance State │ ✓ │ ✓ │ ✓ │ +// └─────────────────┴───────────────────┴───────────────────┴───────────────────┘ +// +// *maybe - Resources can be added at an instance address only if the resource +// represents a single instance (primary). Example: +// "aws_instance.foo" can be moved to "aws_instance.bar.tainted" +// +func (s *State) Add(fromAddrRaw string, toAddrRaw string, raw interface{}) error { + // Parse the address + + toAddr, err := ParseResourceAddress(toAddrRaw) + if err != nil { + return err + } + + // Parse the from address + fromAddr, err := ParseResourceAddress(fromAddrRaw) + if err != nil { + return err + } + + // Determine the types + from := detectValueAddLoc(raw) + to := detectAddrAddLoc(toAddr) + + // Find the function to do this + fromMap, ok := stateAddFuncs[from] + if !ok { + return fmt.Errorf("invalid source to add to state: %T", raw) + } + f, ok := fromMap[to] + if !ok { + return fmt.Errorf("invalid destination: %s (%d)", toAddr, to) + } + + // Call the migrator + if err := f(s, fromAddr, toAddr, raw); err != nil { + return err + } + + // Prune the state + s.prune() + return nil +} + +func stateAddFunc_Module_Module(s *State, fromAddr, addr *ResourceAddress, raw interface{}) error { + // raw can be either *ModuleState or []*ModuleState. The former means + // we're moving just one module. The latter means we're moving a module + // and children. + root := raw + var rest []*ModuleState + if list, ok := raw.([]*ModuleState); ok { + // We need at least one item + if len(list) == 0 { + return fmt.Errorf("module move with no value to: %s", addr) + } + + // The first item is always the root + root = list[0] + if len(list) > 1 { + rest = list[1:] + } + } + + // Get the actual module state + src := root.(*ModuleState).deepcopy() + + // If the target module exists, it is an error + path := append([]string{"root"}, addr.Path...) + if s.ModuleByPath(path) != nil { + return fmt.Errorf("module target is not empty: %s", addr) + } + + // Create it and copy our outputs and dependencies + mod := s.AddModule(path) + mod.Outputs = src.Outputs + mod.Dependencies = src.Dependencies + + // Go through the resources perform an add for each of those + for k, v := range src.Resources { + resourceKey, err := ParseResourceStateKey(k) + if err != nil { + return err + } + + // Update the resource address for this + addrCopy := *addr + addrCopy.Type = resourceKey.Type + addrCopy.Name = resourceKey.Name + addrCopy.Index = resourceKey.Index + addrCopy.Mode = resourceKey.Mode + + // Perform an add + if err := s.Add(fromAddr.String(), addrCopy.String(), v); err != nil { + return err + } + } + + // Add all the children if we have them + for _, item := range rest { + // If item isn't a descendent of our root, then ignore it + if !src.IsDescendent(item) { + continue + } + + // It is! Strip the leading prefix and attach that to our address + extra := item.Path[len(src.Path):] + addrCopy := addr.Copy() + addrCopy.Path = append(addrCopy.Path, extra...) + + // Add it + s.Add(fromAddr.String(), addrCopy.String(), item) + } + + return nil +} + +func stateAddFunc_Resource_Module( + s *State, from, to *ResourceAddress, raw interface{}) error { + // Build the more specific to addr + addr := *to + addr.Type = from.Type + addr.Name = from.Name + + return s.Add(from.String(), addr.String(), raw) +} + +func stateAddFunc_Resource_Resource(s *State, fromAddr, addr *ResourceAddress, raw interface{}) error { + // raw can be either *ResourceState or []*ResourceState. The former means + // we're moving just one resource. The latter means we're moving a count + // of resources. + if list, ok := raw.([]*ResourceState); ok { + // We need at least one item + if len(list) == 0 { + return fmt.Errorf("resource move with no value to: %s", addr) + } + + // If there is an index, this is an error since we can't assign + // a set of resources to a single index + if addr.Index >= 0 && len(list) > 1 { + return fmt.Errorf( + "multiple resources can't be moved to a single index: "+ + "%s => %s", fromAddr, addr) + } + + // Add each with a specific index + for i, rs := range list { + addrCopy := addr.Copy() + addrCopy.Index = i + + if err := s.Add(fromAddr.String(), addrCopy.String(), rs); err != nil { + return err + } + } + + return nil + } + + src := raw.(*ResourceState).deepcopy() + + // Initialize the resource + resourceRaw, exists := stateAddInitAddr(s, addr) + if exists { + return fmt.Errorf("resource exists and not empty: %s", addr) + } + resource := resourceRaw.(*ResourceState) + resource.Type = src.Type + resource.Dependencies = src.Dependencies + resource.Provider = src.Provider + + // Move the primary + if src.Primary != nil { + addrCopy := *addr + addrCopy.InstanceType = TypePrimary + addrCopy.InstanceTypeSet = true + if err := s.Add(fromAddr.String(), addrCopy.String(), src.Primary); err != nil { + return err + } + } + + // Move all deposed + if len(src.Deposed) > 0 { + resource.Deposed = src.Deposed + } + + return nil +} + +func stateAddFunc_Instance_Instance(s *State, fromAddr, addr *ResourceAddress, raw interface{}) error { + src := raw.(*InstanceState).DeepCopy() + + // Create the instance + instanceRaw, _ := stateAddInitAddr(s, addr) + instance := instanceRaw.(*InstanceState) + + // Set it + instance.Set(src) + + return nil +} + +func stateAddFunc_Instance_Module( + s *State, from, to *ResourceAddress, raw interface{}) error { + addr := *to + addr.Type = from.Type + addr.Name = from.Name + + return s.Add(from.String(), addr.String(), raw) +} + +func stateAddFunc_Instance_Resource( + s *State, from, to *ResourceAddress, raw interface{}) error { + addr := *to + addr.InstanceType = TypePrimary + addr.InstanceTypeSet = true + + return s.Add(from.String(), addr.String(), raw) +} + +// stateAddFunc is the type of function for adding an item to a state +type stateAddFunc func(s *State, from, to *ResourceAddress, item interface{}) error + +// stateAddFuncs has the full matrix mapping of the state adders. +var stateAddFuncs map[stateAddLoc]map[stateAddLoc]stateAddFunc + +func init() { + stateAddFuncs = map[stateAddLoc]map[stateAddLoc]stateAddFunc{ + stateAddModule: { + stateAddModule: stateAddFunc_Module_Module, + }, + stateAddResource: { + stateAddModule: stateAddFunc_Resource_Module, + stateAddResource: stateAddFunc_Resource_Resource, + }, + stateAddInstance: { + stateAddInstance: stateAddFunc_Instance_Instance, + stateAddModule: stateAddFunc_Instance_Module, + stateAddResource: stateAddFunc_Instance_Resource, + }, + } +} + +// stateAddLoc is an enum to represent the location where state is being +// moved from/to. We use this for quick lookups in a function map. +type stateAddLoc uint + +const ( + stateAddInvalid stateAddLoc = iota + stateAddModule + stateAddResource + stateAddInstance +) + +// detectAddrAddLoc detects the state type for the given address. This +// function is specifically not unit tested since we consider the State.Add +// functionality to be comprehensive enough to cover this. +func detectAddrAddLoc(addr *ResourceAddress) stateAddLoc { + if addr.Name == "" { + return stateAddModule + } + + if !addr.InstanceTypeSet { + return stateAddResource + } + + return stateAddInstance +} + +// detectValueAddLoc determines the stateAddLoc value from the raw value +// that is some State structure. +func detectValueAddLoc(raw interface{}) stateAddLoc { + switch raw.(type) { + case *ModuleState: + return stateAddModule + case []*ModuleState: + return stateAddModule + case *ResourceState: + return stateAddResource + case []*ResourceState: + return stateAddResource + case *InstanceState: + return stateAddInstance + default: + return stateAddInvalid + } +} + +// stateAddInitAddr takes a ResourceAddress and creates the non-existing +// resources up to that point, returning the empty (or existing) interface +// at that address. +func stateAddInitAddr(s *State, addr *ResourceAddress) (interface{}, bool) { + addType := detectAddrAddLoc(addr) + + // Get the module + path := append([]string{"root"}, addr.Path...) + exists := true + mod := s.ModuleByPath(path) + if mod == nil { + mod = s.AddModule(path) + exists = false + } + if addType == stateAddModule { + return mod, exists + } + + // Add the resource + resourceKey := (&ResourceStateKey{ + Name: addr.Name, + Type: addr.Type, + Index: addr.Index, + Mode: addr.Mode, + }).String() + exists = true + resource, ok := mod.Resources[resourceKey] + if !ok { + resource = &ResourceState{Type: addr.Type} + resource.init() + mod.Resources[resourceKey] = resource + exists = false + } + if addType == stateAddResource { + return resource, exists + } + + // Get the instance + exists = true + instance := &InstanceState{} + switch addr.InstanceType { + case TypePrimary, TypeTainted: + if v := resource.Primary; v != nil { + instance = resource.Primary + } else { + exists = false + } + case TypeDeposed: + idx := addr.Index + if addr.Index < 0 { + idx = 0 + } + if len(resource.Deposed) > idx { + instance = resource.Deposed[idx] + } else { + resource.Deposed = append(resource.Deposed, instance) + exists = false + } + } + + return instance, exists +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform.go b/vendor/github.com/hashicorp/terraform/terraform/transform.go index fd3f5c7d..0e47f208 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform.go @@ -38,18 +38,13 @@ type graphTransformerMulti struct { } func (t *graphTransformerMulti) Transform(g *Graph) error { - var lastStepStr string for _, t := range t.Transforms { - log.Printf("[TRACE] (graphTransformerMulti) Executing graph transform %T", t) if err := t.Transform(g); err != nil { return err } - if thisStepStr := g.StringWithNodeTypes(); thisStepStr != lastStepStr { - log.Printf("[TRACE] (graphTransformerMulti) Completed graph transform %T with new graph:\n%s------", t, thisStepStr) - lastStepStr = thisStepStr - } else { - log.Printf("[TRACE] (graphTransformerMulti) Completed graph transform %T (no changes)", t) - } + log.Printf( + "[TRACE] Graph after step %T:\n\n%s", + t, g.StringWithNodeTypes()) } return nil diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_config_provider.go b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_config_provider.go index 897a7e79..39cf097a 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_config_provider.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_config_provider.go @@ -1,8 +1,7 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config" ) // GraphNodeAttachProvider is an interface that must be implemented by nodes @@ -12,8 +11,8 @@ type GraphNodeAttachProvider interface { GraphNodeSubPath // ProviderName with no module prefix. Example: "aws". - ProviderAddr() addrs.AbsProviderConfig + ProviderName() string // Sets the configuration - AttachProvider(*configs.Provider) + AttachProvider(*config.ProviderConfig) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_config_resource.go b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_config_resource.go index 03f8564d..f2ee37e5 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_config_resource.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_config_resource.go @@ -1,32 +1,35 @@ package terraform import ( + "fmt" "log" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/dag" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" ) // GraphNodeAttachResourceConfig is an interface that must be implemented by nodes // that want resource configurations attached. type GraphNodeAttachResourceConfig interface { - GraphNodeResource + // ResourceAddr is the address to the resource + ResourceAddr() *ResourceAddress // Sets the configuration - AttachResourceConfig(*configs.Resource) + AttachResourceConfig(*config.Resource) } // AttachResourceConfigTransformer goes through the graph and attaches -// resource configuration structures to nodes that implement -// GraphNodeAttachManagedResourceConfig or GraphNodeAttachDataResourceConfig. +// resource configuration structures to nodes that implement the interfaces +// above. // // The attached configuration structures are directly from the configuration. // If they're going to be modified, a copy should be made. type AttachResourceConfigTransformer struct { - Config *configs.Config // Config is the root node in the config tree + Module *module.Tree // Module is the root module for the config } func (t *AttachResourceConfigTransformer) Transform(g *Graph) error { + log.Printf("[TRACE] AttachResourceConfigTransformer: Beginning...") // Go through and find GraphNodeAttachResource for _, v := range g.Vertices() { @@ -38,35 +41,36 @@ func (t *AttachResourceConfigTransformer) Transform(g *Graph) error { // Determine what we're looking for addr := arn.ResourceAddr() + log.Printf( + "[TRACE] AttachResourceConfigTransformer: Attach resource "+ + "config request: %s", addr) // Get the configuration. - config := t.Config.DescendentForInstance(addr.Module) - if config == nil { - log.Printf("[TRACE] AttachResourceConfigTransformer: %q (%T) has no configuration available", dag.VertexName(v), v) + path := normalizeModulePath(addr.Path) + path = path[1:] + tree := t.Module.Child(path) + if tree == nil { continue } - for _, r := range config.Module.ManagedResources { - rAddr := r.Addr() + // Go through the resource configs to find the matching config + for _, r := range tree.Config().Resources { + // Get a resource address so we can compare + a, err := parseResourceAddressConfig(r) + if err != nil { + panic(fmt.Sprintf( + "Error parsing config address, this is a bug: %#v", r)) + } + a.Path = addr.Path - if rAddr != addr.Resource { - // Not the same resource + // If this is not the same resource, then continue + if !a.Equals(addr) { continue } - log.Printf("[TRACE] AttachResourceConfigTransformer: attaching to %q (%T) config from %s", dag.VertexName(v), v, r.DeclRange) - arn.AttachResourceConfig(r) - } - for _, r := range config.Module.DataResources { - rAddr := r.Addr() - - if rAddr != addr.Resource { - // Not the same resource - continue - } - - log.Printf("[TRACE] AttachResourceConfigTransformer: attaching to %q (%T) config from %#v", dag.VertexName(v), v, r.DeclRange) + log.Printf("[TRACE] Attaching resource config: %#v", r) arn.AttachResourceConfig(r) + break } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_schema.go b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_schema.go deleted file mode 100644 index c7695dd4..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_schema.go +++ /dev/null @@ -1,99 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeAttachResourceSchema is an interface implemented by node types -// that need a resource schema attached. -type GraphNodeAttachResourceSchema interface { - GraphNodeResource - GraphNodeProviderConsumer - - AttachResourceSchema(schema *configschema.Block, version uint64) -} - -// GraphNodeAttachProviderConfigSchema is an interface implemented by node types -// that need a provider configuration schema attached. -type GraphNodeAttachProviderConfigSchema interface { - GraphNodeProvider - - AttachProviderConfigSchema(*configschema.Block) -} - -// GraphNodeAttachProvisionerSchema is an interface implemented by node types -// that need one or more provisioner schemas attached. -type GraphNodeAttachProvisionerSchema interface { - ProvisionedBy() []string - - // SetProvisionerSchema is called during transform for each provisioner - // type returned from ProvisionedBy, providing the configuration schema - // for each provisioner in turn. The implementer should save these for - // later use in evaluating provisioner configuration blocks. - AttachProvisionerSchema(name string, schema *configschema.Block) -} - -// AttachSchemaTransformer finds nodes that implement -// GraphNodeAttachResourceSchema, GraphNodeAttachProviderConfigSchema, or -// GraphNodeAttachProvisionerSchema, looks up the needed schemas for each -// and then passes them to a method implemented by the node. -type AttachSchemaTransformer struct { - Schemas *Schemas -} - -func (t *AttachSchemaTransformer) Transform(g *Graph) error { - if t.Schemas == nil { - // Should never happen with a reasonable caller, but we'll return a - // proper error here anyway so that we'll fail gracefully. - return fmt.Errorf("AttachSchemaTransformer used with nil Schemas") - } - - for _, v := range g.Vertices() { - - if tv, ok := v.(GraphNodeAttachResourceSchema); ok { - addr := tv.ResourceAddr() - mode := addr.Resource.Mode - typeName := addr.Resource.Type - providerAddr, _ := tv.ProvidedBy() - providerType := providerAddr.ProviderConfig.Type - - schema, version := t.Schemas.ResourceTypeConfig(providerType, mode, typeName) - if schema == nil { - log.Printf("[ERROR] AttachSchemaTransformer: No resource schema available for %s", addr) - continue - } - log.Printf("[TRACE] AttachSchemaTransformer: attaching resource schema to %s", dag.VertexName(v)) - tv.AttachResourceSchema(schema, version) - } - - if tv, ok := v.(GraphNodeAttachProviderConfigSchema); ok { - providerAddr := tv.ProviderAddr() - schema := t.Schemas.ProviderConfig(providerAddr.ProviderConfig.Type) - if schema == nil { - log.Printf("[ERROR] AttachSchemaTransformer: No provider config schema available for %s", providerAddr) - continue - } - log.Printf("[TRACE] AttachSchemaTransformer: attaching provider config schema to %s", dag.VertexName(v)) - tv.AttachProviderConfigSchema(schema) - } - - if tv, ok := v.(GraphNodeAttachProvisionerSchema); ok { - names := tv.ProvisionedBy() - for _, name := range names { - schema := t.Schemas.ProvisionerConfig(name) - if schema == nil { - log.Printf("[ERROR] AttachSchemaTransformer: No schema available for provisioner %q on %q", name, dag.VertexName(v)) - continue - } - log.Printf("[TRACE] AttachSchemaTransformer: attaching provisioner %q config schema to %s", name, dag.VertexName(v)) - tv.AttachProvisionerSchema(name, schema) - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_state.go b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_state.go index 3af7b989..564ff08f 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_state.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_state.go @@ -4,64 +4,64 @@ import ( "log" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/states" ) // GraphNodeAttachResourceState is an interface that can be implemented // to request that a ResourceState is attached to the node. -// -// Due to a historical naming inconsistency, the type ResourceState actually -// represents the state for a particular _instance_, while InstanceState -// represents the values for that instance during a particular phase -// (e.g. primary vs. deposed). Consequently, GraphNodeAttachResourceState -// is supported only for nodes that represent resource instances, even though -// the name might suggest it is for containing resources. type GraphNodeAttachResourceState interface { - GraphNodeResourceInstance + // The address to the resource for the state + ResourceAddr() *ResourceAddress // Sets the state - AttachResourceState(*states.Resource) + AttachResourceState(*ResourceState) } // AttachStateTransformer goes through the graph and attaches // state to nodes that implement the interfaces above. type AttachStateTransformer struct { - State *states.State // State is the root state + State *State // State is the root state } func (t *AttachStateTransformer) Transform(g *Graph) error { // If no state, then nothing to do if t.State == nil { - log.Printf("[DEBUG] Not attaching any node states: overall state is nil") + log.Printf("[DEBUG] Not attaching any state: state is nil") return nil } + filter := &StateFilter{State: t.State} for _, v := range g.Vertices() { - // Nodes implement this interface to request state attachment. + // Only care about nodes requesting we're adding state an, ok := v.(GraphNodeAttachResourceState) if !ok { continue } - addr := an.ResourceInstanceAddr() + addr := an.ResourceAddr() - rs := t.State.Resource(addr.ContainingResource()) - if rs == nil { - log.Printf("[DEBUG] Resource state not found for node %q, instance %s", dag.VertexName(v), addr) - continue + // Get the module state + results, err := filter.Filter(addr.String()) + if err != nil { + return err } - is := rs.Instance(addr.Resource.Key) - if is == nil { - // We don't actually need this here, since we'll attach the whole - // resource state, but we still check because it'd be weird - // for the specific instance we're attaching to not to exist. - log.Printf("[DEBUG] Resource instance state not found for node %q, instance %s", dag.VertexName(v), addr) - continue + // Attach the first resource state we get + found := false + for _, result := range results { + if rs, ok := result.Value.(*ResourceState); ok { + log.Printf( + "[DEBUG] Attaching resource state to %q: %#v", + dag.VertexName(v), rs) + an.AttachResourceState(rs) + found = true + break + } } - // make sure to attach a copy of the state, so instances can modify the - // same ResourceState. - an.AttachResourceState(rs.DeepCopy()) + if !found { + log.Printf( + "[DEBUG] Resource state not found for %q: %s", + dag.VertexName(v), addr) + } } return nil diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_config.go b/vendor/github.com/hashicorp/terraform/terraform/transform_config.go index 9d3b6f4b..61bce853 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_config.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_config.go @@ -1,11 +1,13 @@ package terraform import ( + "errors" + "fmt" "log" "sync" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" ) @@ -24,14 +26,14 @@ type ConfigTransformer struct { Concrete ConcreteResourceNodeFunc // Module is the module to add resources from. - Config *configs.Config + Module *module.Tree // Unique will only add resources that aren't already present in the graph. Unique bool // Mode will only add resources that match the given mode ModeFilter bool - Mode addrs.ResourceMode + Mode config.ResourceMode l sync.Mutex uniqueMap map[string]struct{} @@ -42,11 +44,16 @@ func (t *ConfigTransformer) Transform(g *Graph) error { t.l.Lock() defer t.l.Unlock() - // If no configuration is available, we don't do anything - if t.Config == nil { + // If no module is given, we don't do anything + if t.Module == nil { return nil } + // If the module isn't loaded, that is simply an error + if !t.Module.Loaded() { + return errors.New("module must be loaded for ConfigTransformer") + } + // Reset the uniqueness map. If we're tracking uniques, then populate // it with addresses. t.uniqueMap = make(map[string]struct{}) @@ -60,22 +67,22 @@ func (t *ConfigTransformer) Transform(g *Graph) error { } // Start the transformation process - return t.transform(g, t.Config) + return t.transform(g, t.Module) } -func (t *ConfigTransformer) transform(g *Graph, config *configs.Config) error { +func (t *ConfigTransformer) transform(g *Graph, m *module.Tree) error { // If no config, do nothing - if config == nil { + if m == nil { return nil } // Add our resources - if err := t.transformSingle(g, config); err != nil { + if err := t.transformSingle(g, m); err != nil { return err } // Transform all the children. - for _, c := range config.Children { + for _, c := range m.Children() { if err := t.transform(g, c); err != nil { return err } @@ -84,48 +91,43 @@ func (t *ConfigTransformer) transform(g *Graph, config *configs.Config) error { return nil } -func (t *ConfigTransformer) transformSingle(g *Graph, config *configs.Config) error { - path := config.Path - module := config.Module - log.Printf("[TRACE] ConfigTransformer: Starting for path: %v", path) +func (t *ConfigTransformer) transformSingle(g *Graph, m *module.Tree) error { + log.Printf("[TRACE] ConfigTransformer: Starting for path: %v", m.Path()) - // For now we assume that each module call produces only one module - // instance with no key, since we don't yet support "count" and "for_each" - // on modules. - // FIXME: As part of supporting "count" and "for_each" on modules, rework - // this so that we'll "expand" the module call first and then create graph - // nodes for each module instance separately. - instPath := path.UnkeyedInstanceShim() + // Get the configuration for this module + conf := m.Config() - allResources := make([]*configs.Resource, 0, len(module.ManagedResources)+len(module.DataResources)) - for _, r := range module.ManagedResources { - allResources = append(allResources, r) - } - for _, r := range module.DataResources { - allResources = append(allResources, r) - } + // Build the path we're at + path := m.Path() - for _, r := range allResources { - relAddr := r.Addr() - - if t.ModeFilter && relAddr.Mode != t.Mode { - // Skip non-matching modes - continue + // Write all the resources out + for _, r := range conf.Resources { + // Build the resource address + addr, err := parseResourceAddressConfig(r) + if err != nil { + panic(fmt.Sprintf( + "Error parsing config address, this is a bug: %#v", r)) } + addr.Path = path - addr := relAddr.Absolute(instPath) + // If this is already in our uniqueness map, don't add it again if _, ok := t.uniqueMap[addr.String()]; ok { - // We've already seen a resource with this address. This should - // never happen, because we enforce uniqueness in the config loader. continue } + // Remove non-matching modes + if t.ModeFilter && addr.Mode != t.Mode { + continue + } + + // Build the abstract node and the concrete one abstract := &NodeAbstractResource{Addr: addr} var node dag.Vertex = abstract if f := t.Concrete; f != nil { node = f(abstract) } + // Add it to the graph g.Add(node) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_config_flat.go b/vendor/github.com/hashicorp/terraform/terraform/transform_config_flat.go index 866c9175..92f9888d 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_config_flat.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_config_flat.go @@ -1,7 +1,9 @@ package terraform import ( - "github.com/hashicorp/terraform/configs" + "errors" + + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" ) @@ -18,47 +20,54 @@ import ( type FlatConfigTransformer struct { Concrete ConcreteResourceNodeFunc // What to turn resources into - Config *configs.Config + Module *module.Tree } func (t *FlatConfigTransformer) Transform(g *Graph) error { - // We have nothing to do if there is no configuration. - if t.Config == nil { + // If no module, we do nothing + if t.Module == nil { return nil } - return t.transform(g, t.Config) + // If the module is not loaded, that is an error + if !t.Module.Loaded() { + return errors.New("module must be loaded") + } + + return t.transform(g, t.Module) } -func (t *FlatConfigTransformer) transform(g *Graph, config *configs.Config) error { - // If we have no configuration then there's nothing to do. - if config == nil { +func (t *FlatConfigTransformer) transform(g *Graph, m *module.Tree) error { + // If no module, no problem + if m == nil { return nil } // Transform all the children. - for _, c := range config.Children { + for _, c := range m.Children() { if err := t.transform(g, c); err != nil { return err } } - module := config.Module - // For now we assume that each module call produces only one module - // instance with no key, since we don't yet support "count" and "for_each" - // on modules. - // FIXME: As part of supporting "count" and "for_each" on modules, rework - // this so that we'll "expand" the module call first and then create graph - // nodes for each module instance separately. - instPath := config.Path.UnkeyedInstanceShim() + // Get the configuration for this module + config := m.Config() - for _, r := range module.ManagedResources { - addr := r.Addr().Absolute(instPath) + // Write all the resources out + for _, r := range config.Resources { + // Grab the address for this resource + addr, err := parseResourceAddressConfig(r) + if err != nil { + return err + } + addr.Path = m.Path() + + // Build the abstract resource. We have the config already so + // we'll just pre-populate that. abstract := &NodeAbstractResource{ Addr: addr, Config: r, } - // Grab the address for this resource var node dag.Vertex = abstract if f := t.Concrete; f != nil { node = f(abstract) diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_count_boundary.go b/vendor/github.com/hashicorp/terraform/terraform/transform_count_boundary.go index 01601bdd..83415f35 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_count_boundary.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_count_boundary.go @@ -1,21 +1,16 @@ package terraform import ( - "github.com/hashicorp/terraform/configs" "github.com/hashicorp/terraform/dag" ) // CountBoundaryTransformer adds a node that depends on everything else // so that it runs last in order to clean up the state for nodes that // are on the "count boundary": "foo.0" when only one exists becomes "foo" -type CountBoundaryTransformer struct { - Config *configs.Config -} +type CountBoundaryTransformer struct{} func (t *CountBoundaryTransformer) Transform(g *Graph) error { - node := &NodeCountBoundary{ - Config: t.Config, - } + node := &NodeCountBoundary{} g.Add(node) // Depends on everything diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_deposed.go b/vendor/github.com/hashicorp/terraform/terraform/transform_deposed.go new file mode 100644 index 00000000..87a1f9c9 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_deposed.go @@ -0,0 +1,178 @@ +package terraform + +import "fmt" + +// DeposedTransformer is a GraphTransformer that adds deposed resources +// to the graph. +type DeposedTransformer struct { + // State is the global state. We'll automatically find the correct + // ModuleState based on the Graph.Path that is being transformed. + State *State + + // View, if non-empty, is the ModuleState.View used around the state + // to find deposed resources. + View string + + // The provider used by the resourced which were deposed + ResolvedProvider string +} + +func (t *DeposedTransformer) Transform(g *Graph) error { + state := t.State.ModuleByPath(g.Path) + if state == nil { + // If there is no state for our module there can't be any deposed + // resources, since they live in the state. + return nil + } + + // If we have a view, apply it now + if t.View != "" { + state = state.View(t.View) + } + + // Go through all the resources in our state to look for deposed resources + for k, rs := range state.Resources { + // If we have no deposed resources, then move on + if len(rs.Deposed) == 0 { + continue + } + + deposed := rs.Deposed + + for i, _ := range deposed { + g.Add(&graphNodeDeposedResource{ + Index: i, + ResourceName: k, + ResourceType: rs.Type, + ProviderName: rs.Provider, + ResolvedProvider: t.ResolvedProvider, + }) + } + } + + return nil +} + +// graphNodeDeposedResource is the graph vertex representing a deposed resource. +type graphNodeDeposedResource struct { + Index int + ResourceName string + ResourceType string + ProviderName string + ResolvedProvider string +} + +func (n *graphNodeDeposedResource) Name() string { + return fmt.Sprintf("%s (deposed #%d)", n.ResourceName, n.Index) +} + +func (n *graphNodeDeposedResource) ProvidedBy() string { + return resourceProvider(n.ResourceName, n.ProviderName) +} + +func (n *graphNodeDeposedResource) SetProvider(p string) { + n.ResolvedProvider = p +} + +// GraphNodeEvalable impl. +func (n *graphNodeDeposedResource) EvalTree() EvalNode { + var provider ResourceProvider + var state *InstanceState + + seq := &EvalSequence{Nodes: make([]EvalNode, 0, 5)} + + // Build instance info + info := &InstanceInfo{Id: n.Name(), Type: n.ResourceType} + seq.Nodes = append(seq.Nodes, &EvalInstanceInfo{Info: info}) + + // Refresh the resource + seq.Nodes = append(seq.Nodes, &EvalOpFilter{ + Ops: []walkOperation{walkRefresh}, + Node: &EvalSequence{ + Nodes: []EvalNode{ + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, + }, + &EvalReadStateDeposed{ + Name: n.ResourceName, + Output: &state, + Index: n.Index, + }, + &EvalRefresh{ + Info: info, + Provider: &provider, + State: &state, + Output: &state, + }, + &EvalWriteStateDeposed{ + Name: n.ResourceName, + ResourceType: n.ResourceType, + Provider: n.ResolvedProvider, + State: &state, + Index: n.Index, + }, + }, + }, + }) + + // Apply + var diff *InstanceDiff + var err error + seq.Nodes = append(seq.Nodes, &EvalOpFilter{ + Ops: []walkOperation{walkApply, walkDestroy}, + Node: &EvalSequence{ + Nodes: []EvalNode{ + &EvalGetProvider{ + Name: n.ResolvedProvider, + Output: &provider, + }, + &EvalReadStateDeposed{ + Name: n.ResourceName, + Output: &state, + Index: n.Index, + }, + &EvalDiffDestroy{ + Info: info, + State: &state, + Output: &diff, + }, + // Call pre-apply hook + &EvalApplyPre{ + Info: info, + State: &state, + Diff: &diff, + }, + &EvalApply{ + Info: info, + State: &state, + Diff: &diff, + Provider: &provider, + Output: &state, + Error: &err, + }, + // Always write the resource back to the state deposed... if it + // was successfully destroyed it will be pruned. If it was not, it will + // be caught on the next run. + &EvalWriteStateDeposed{ + Name: n.ResourceName, + ResourceType: n.ResourceType, + Provider: n.ResolvedProvider, + State: &state, + Index: n.Index, + }, + &EvalApplyPost{ + Info: info, + State: &state, + Error: &err, + }, + &EvalReturnError{ + Error: &err, + }, + &EvalUpdateStateHook{}, + }, + }, + }) + + return seq +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_cbd.go b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_cbd.go index 2f4d5ede..edfb460b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_cbd.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_cbd.go @@ -4,15 +4,15 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/states" ) // GraphNodeDestroyerCBD must be implemented by nodes that might be -// create-before-destroy destroyers, or might plan a create-before-destroy -// action. +// create-before-destroy destroyers. type GraphNodeDestroyerCBD interface { + GraphNodeDestroyer + // CreateBeforeDestroy returns true if this node represents a node // that is doing a CBD. CreateBeforeDestroy() bool @@ -23,89 +23,6 @@ type GraphNodeDestroyerCBD interface { ModifyCreateBeforeDestroy(bool) error } -// GraphNodeAttachDestroyer is implemented by applyable nodes that have a -// companion destroy node. This allows the creation node to look up the status -// of the destroy node and determine if it needs to depose the existing state, -// or replace it. -// If a node is not marked as create-before-destroy in the configuration, but a -// dependency forces that status, only the destroy node will be aware of that -// status. -type GraphNodeAttachDestroyer interface { - // AttachDestroyNode takes a destroy node and saves a reference to that - // node in the receiver, so it can later check the status of - // CreateBeforeDestroy(). - AttachDestroyNode(n GraphNodeDestroyerCBD) -} - -// ForcedCBDTransformer detects when a particular CBD-able graph node has -// dependencies with another that has create_before_destroy set that require -// it to be forced on, and forces it on. -// -// This must be used in the plan graph builder to ensure that -// create_before_destroy settings are properly propagated before constructing -// the planned changes. This requires that the plannable resource nodes -// implement GraphNodeDestroyerCBD. -type ForcedCBDTransformer struct { -} - -func (t *ForcedCBDTransformer) Transform(g *Graph) error { - for _, v := range g.Vertices() { - dn, ok := v.(GraphNodeDestroyerCBD) - if !ok { - continue - } - - if !dn.CreateBeforeDestroy() { - // If there are no CBD decendent (dependent nodes), then we - // do nothing here. - if !t.hasCBDDescendent(g, v) { - log.Printf("[TRACE] ForcedCBDTransformer: %q (%T) has no CBD descendent, so skipping", dag.VertexName(v), v) - continue - } - - // If this isn't naturally a CBD node, this means that an descendent is - // and we need to auto-upgrade this node to CBD. We do this because - // a CBD node depending on non-CBD will result in cycles. To avoid this, - // we always attempt to upgrade it. - log.Printf("[TRACE] ForcedCBDTransformer: forcing create_before_destroy on for %q (%T)", dag.VertexName(v), v) - if err := dn.ModifyCreateBeforeDestroy(true); err != nil { - return fmt.Errorf( - "%s: must have create before destroy enabled because "+ - "a dependent resource has CBD enabled. However, when "+ - "attempting to automatically do this, an error occurred: %s", - dag.VertexName(v), err) - } - } else { - log.Printf("[TRACE] ForcedCBDTransformer: %q (%T) already has create_before_destroy set", dag.VertexName(v), v) - } - } - return nil -} - -// hasCBDDescendent returns true if any descendent (node that depends on this) -// has CBD set. -func (t *ForcedCBDTransformer) hasCBDDescendent(g *Graph, v dag.Vertex) bool { - s, _ := g.Descendents(v) - if s == nil { - return true - } - - for _, ov := range s.List() { - dn, ok := ov.(GraphNodeDestroyerCBD) - if !ok { - continue - } - - if dn.CreateBeforeDestroy() { - // some descendent is CreateBeforeDestroy, so we need to follow suit - log.Printf("[TRACE] ForcedCBDTransformer: %q has CBD descendent %q", dag.VertexName(v), dag.VertexName(ov)) - return true - } - } - - return false -} - // CBDEdgeTransformer modifies the edges of CBD nodes that went through // the DestroyEdgeTransformer to have the right dependencies. There are // two real tasks here: @@ -118,25 +35,16 @@ func (t *ForcedCBDTransformer) hasCBDDescendent(g *Graph, v dag.Vertex) bool { // update to A. Example: adding a web server updates the load balancer // before deleting the old web server. // -// This transformer requires that a previous transformer has already forced -// create_before_destroy on for nodes that are depended on by explicit CBD -// nodes. This is the logic in ForcedCBDTransformer, though in practice we -// will get here by recording the CBD-ness of each change in the plan during -// the plan walk and then forcing the nodes into the appropriate setting during -// DiffTransformer when building the apply graph. type CBDEdgeTransformer struct { // Module and State are only needed to look up dependencies in // any way possible. Either can be nil if not availabile. - Config *configs.Config - State *states.State - - // If configuration is present then Schemas is required in order to - // obtain schema information from providers and provisioners so we can - // properly resolve implicit dependencies. - Schemas *Schemas + Module *module.Tree + State *State } func (t *CBDEdgeTransformer) Transform(g *Graph) error { + log.Printf("[TRACE] CBDEdgeTransformer: Beginning CBD transformation...") + // Go through and reverse any destroy edges destroyMap := make(map[string][]dag.Vertex) for _, v := range g.Vertices() { @@ -144,13 +52,25 @@ func (t *CBDEdgeTransformer) Transform(g *Graph) error { if !ok { continue } - dern, ok := v.(GraphNodeDestroyer) - if !ok { - continue - } if !dn.CreateBeforeDestroy() { - continue + // If there are no CBD ancestors (dependent nodes), then we + // do nothing here. + if !t.hasCBDAncestor(g, v) { + continue + } + + // If this isn't naturally a CBD node, this means that an ancestor is + // and we need to auto-upgrade this node to CBD. We do this because + // a CBD node depending on non-CBD will result in cycles. To avoid this, + // we always attempt to upgrade it. + if err := dn.ModifyCreateBeforeDestroy(true); err != nil { + return fmt.Errorf( + "%s: must have create before destroy enabled because "+ + "a dependent resource has CBD enabled. However, when "+ + "attempting to automatically do this, an error occurred: %s", + dag.VertexName(v), err) + } } // Find the destroy edge. There should only be one. @@ -166,9 +86,7 @@ func (t *CBDEdgeTransformer) Transform(g *Graph) error { // Found it! Invert. g.RemoveEdge(de) - applyNode := de.Source() - destroyNode := de.Target() - g.Connect(&DestroyEdge{S: destroyNode, T: applyNode}) + g.Connect(&DestroyEdge{S: de.Target(), T: de.Source()}) } // If the address has an index, we strip that. Our depMap creation @@ -176,11 +94,15 @@ func (t *CBDEdgeTransformer) Transform(g *Graph) error { // dependencies. One day when we limit dependencies more exactly // this will have to change. We have a test case covering this // (depNonCBDCountBoth) so it'll be caught. - addr := dern.DestroyAddr() - key := addr.ContainingResource().String() + addr := dn.DestroyAddr() + if addr.Index >= 0 { + addr = addr.Copy() // Copy so that we don't modify any pointers + addr.Index = -1 + } // Add this to the list of nodes that we need to fix up // the edges for (step 2 above in the docs). + key := addr.String() destroyMap[key] = append(destroyMap[key], v) } @@ -229,9 +151,13 @@ func (t *CBDEdgeTransformer) Transform(g *Graph) error { // dependencies. One day when we limit dependencies more exactly // this will have to change. We have a test case covering this // (depNonCBDCount) so it'll be caught. - key := addr.ContainingResource().String() + if addr.Index >= 0 { + addr = addr.Copy() // Copy so that we don't modify any pointers + addr.Index = -1 + } // If there is nothing this resource should depend on, ignore it + key := addr.String() dns, ok := depMap[key] if !ok { continue @@ -248,21 +174,21 @@ func (t *CBDEdgeTransformer) Transform(g *Graph) error { return nil } -func (t *CBDEdgeTransformer) depMap(destroyMap map[string][]dag.Vertex) (map[string][]dag.Vertex, error) { +func (t *CBDEdgeTransformer) depMap( + destroyMap map[string][]dag.Vertex) (map[string][]dag.Vertex, error) { // Build the graph of our config, this ensures that all resources // are present in the graph. - g, diags := (&BasicGraphBuilder{ + g, err := (&BasicGraphBuilder{ Steps: []GraphTransformer{ - &FlatConfigTransformer{Config: t.Config}, - &AttachResourceConfigTransformer{Config: t.Config}, + &FlatConfigTransformer{Module: t.Module}, + &AttachResourceConfigTransformer{Module: t.Module}, &AttachStateTransformer{State: t.State}, - &AttachSchemaTransformer{Schemas: t.Schemas}, &ReferenceTransformer{}, }, Name: "CBDEdgeTransformer", }).Build(nil) - if diags.HasErrors() { - return nil, diags.Err() + if err != nil { + return nil, err } // Using this graph, build the list of destroy nodes that each resource @@ -306,3 +232,26 @@ func (t *CBDEdgeTransformer) depMap(destroyMap map[string][]dag.Vertex) (map[str return depMap, nil } + +// hasCBDAncestor returns true if any ancestor (node that depends on this) +// has CBD set. +func (t *CBDEdgeTransformer) hasCBDAncestor(g *Graph, v dag.Vertex) bool { + s, _ := g.Ancestors(v) + if s == nil { + return true + } + + for _, v := range s.List() { + dn, ok := v.(GraphNodeDestroyerCBD) + if !ok { + continue + } + + if dn.CreateBeforeDestroy() { + // some ancestor is CreateBeforeDestroy, so we need to follow suit + return true + } + } + + return false +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_edge.go b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_edge.go index 7fb415bd..a06ff292 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_edge.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_edge.go @@ -3,10 +3,7 @@ package terraform import ( "log" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/states" - - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" ) @@ -14,16 +11,16 @@ import ( type GraphNodeDestroyer interface { dag.Vertex - // DestroyAddr is the address of the resource that is being + // ResourceAddr is the address of the resource that is being // destroyed by this node. If this returns nil, then this node // is not destroying anything. - DestroyAddr() *addrs.AbsResourceInstance + DestroyAddr() *ResourceAddress } // GraphNodeCreator must be implemented by nodes that create OR update resources. type GraphNodeCreator interface { - // CreateAddr is the address of the resource being created or updated - CreateAddr() *addrs.AbsResourceInstance + // ResourceAddr is the address of the resource being created or updated + CreateAddr() *ResourceAddress } // DestroyEdgeTransformer is a GraphTransformer that creates the proper @@ -43,37 +40,33 @@ type GraphNodeCreator interface { type DestroyEdgeTransformer struct { // These are needed to properly build the graph of dependencies // to determine what a destroy node depends on. Any of these can be nil. - Config *configs.Config - State *states.State - - // If configuration is present then Schemas is required in order to - // obtain schema information from providers and provisioners in order - // to properly resolve implicit dependencies. - Schemas *Schemas + Module *module.Tree + State *State } func (t *DestroyEdgeTransformer) Transform(g *Graph) error { + log.Printf("[TRACE] DestroyEdgeTransformer: Beginning destroy edge transformation...") + // Build a map of what is being destroyed (by address string) to - // the list of destroyers. Usually there will be at most one destroyer - // per node, but we allow multiple if present for completeness. + // the list of destroyers. In general there will only be one destroyer + // but to make it more robust we support multiple. destroyers := make(map[string][]GraphNodeDestroyer) - destroyerAddrs := make(map[string]addrs.AbsResourceInstance) for _, v := range g.Vertices() { dn, ok := v.(GraphNodeDestroyer) if !ok { continue } - addrP := dn.DestroyAddr() - if addrP == nil { + addr := dn.DestroyAddr() + if addr == nil { continue } - addr := *addrP key := addr.String() - log.Printf("[TRACE] DestroyEdgeTransformer: %q (%T) destroys %s", dag.VertexName(dn), v, key) + log.Printf( + "[TRACE] DestroyEdgeTransformer: %s destroying %q", + dag.VertexName(dn), key) destroyers[key] = append(destroyers[key], dn) - destroyerAddrs[key] = addr } // If we aren't destroying anything, there will be no edges to make @@ -107,20 +100,10 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { a := v log.Printf( - "[TRACE] DestroyEdgeTransformer: connecting creator %q with destroyer %q", + "[TRACE] DestroyEdgeTransformer: connecting creator/destroyer: %s, %s", dag.VertexName(a), dag.VertexName(a_d)) g.Connect(&DestroyEdge{S: a, T: a_d}) - - // Attach the destroy node to the creator - // There really shouldn't be more than one destroyer, but even if - // there are, any of them will represent the correct - // CreateBeforeDestroy status. - if n, ok := cn.(GraphNodeAttachDestroyer); ok { - if d, ok := d.(GraphNodeDestroyerCBD); ok { - n.AttachDestroyNode(d) - } - } } } @@ -137,24 +120,20 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { } steps := []GraphTransformer{ // Add the local values - &LocalTransformer{Config: t.Config}, + &LocalTransformer{Module: t.Module}, // Add outputs and metadata - &OutputTransformer{Config: t.Config}, - &AttachResourceConfigTransformer{Config: t.Config}, + &OutputTransformer{Module: t.Module}, + &AttachResourceConfigTransformer{Module: t.Module}, &AttachStateTransformer{State: t.State}, + TransformProviders(nil, providerFn, t.Module), + // Add all the variables. We can depend on resources through // variables due to module parameters, and we need to properly // determine that. - &RootVariableTransformer{Config: t.Config}, - &ModuleVariableTransformer{Config: t.Config}, - - TransformProviders(nil, providerFn, t.Config), - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: t.Schemas}, + &RootVariableTransformer{Module: t.Module}, + &ModuleVariableTransformer{Module: t.Module}, &ReferenceTransformer{}, } @@ -167,36 +146,37 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { // var tempG Graph var tempDestroyed []dag.Vertex - for d := range destroyers { - // d is the string key for the resource being destroyed. We actually - // want the address value, which we stashed earlier. - addr := destroyerAddrs[d] + for d, _ := range destroyers { + // d is what is being destroyed. We parse the resource address + // which it came from it is a panic if this fails. + addr, err := ParseResourceAddress(d) + if err != nil { + panic(err) + } // This part is a little bit weird but is the best way to // find the dependencies we need to: build a graph and use the // attach config and state transformers then ask for references. - abstract := NewNodeAbstractResourceInstance(addr) + abstract := &NodeAbstractResource{Addr: addr} tempG.Add(abstract) tempDestroyed = append(tempDestroyed, abstract) // We also add the destroy version here since the destroy can // depend on things that the creation doesn't (destroy provisioners). - destroy := &NodeDestroyResourceInstance{NodeAbstractResourceInstance: abstract} + destroy := &NodeDestroyResource{NodeAbstractResource: abstract} tempG.Add(destroy) tempDestroyed = append(tempDestroyed, destroy) } // Run the graph transforms so we have the information we need to // build references. - log.Printf("[TRACE] DestroyEdgeTransformer: constructing temporary graph for analysis of references, starting from:\n%s", tempG.StringWithNodeTypes()) for _, s := range steps { - log.Printf("[TRACE] DestroyEdgeTransformer: running %T on temporary graph", s) if err := s.Transform(&tempG); err != nil { - log.Printf("[TRACE] DestroyEdgeTransformer: %T failed: %s", s, err) return err } } - log.Printf("[TRACE] DestroyEdgeTransformer: temporary reference graph:\n%s", tempG.String()) + + log.Printf("[TRACE] DestroyEdgeTransformer: reference graph: %s", tempG.String()) // Go through all the nodes in the graph and determine what they // depend on. @@ -227,13 +207,16 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { // Get the destroy node for this. In the example of our struct, // we are currently at B and we're looking for B_d. - rn, ok := v.(GraphNodeResourceInstance) + rn, ok := v.(GraphNodeResource) if !ok { - log.Printf("[TRACE] DestroyEdgeTransformer: skipping %s, since it's not a resource", dag.VertexName(v)) continue } - addr := rn.ResourceInstanceAddr() + addr := rn.ResourceAddr() + if addr == nil { + continue + } + dns := destroyers[addr.String()] // We have dependencies, check if any are being destroyed @@ -248,12 +231,16 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { // to see if A_d exists. var depDestroyers []dag.Vertex for _, v := range refs { - rn, ok := v.(GraphNodeResourceInstance) + rn, ok := v.(GraphNodeResource) if !ok { continue } - addr := rn.ResourceInstanceAddr() + addr := rn.ResourceAddr() + if addr == nil { + continue + } + key := addr.String() if ds, ok := destroyers[key]; ok { for _, d := range ds { @@ -270,7 +257,6 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { for _, a_d := range dns { for _, b_d := range depDestroyers { if b_d != a_d { - log.Printf("[TRACE] DestroyEdgeTransformer: %q depends on %q", dag.VertexName(b_d), dag.VertexName(a_d)) g.Connect(dag.BasicEdge(b_d, a_d)) } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_diff.go b/vendor/github.com/hashicorp/terraform/terraform/transform_diff.go index 6fb915f8..ad46d3c6 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_diff.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_diff.go @@ -4,189 +4,83 @@ import ( "fmt" "log" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/plans" - "github.com/hashicorp/terraform/states" - "github.com/hashicorp/terraform/tfdiags" ) -// DiffTransformer is a GraphTransformer that adds graph nodes representing -// each of the resource changes described in the given Changes object. +// DiffTransformer is a GraphTransformer that adds the elements of +// the diff to the graph. +// +// This transform is used for example by the ApplyGraphBuilder to ensure +// that only resources that are being modified are represented in the graph. +// +// Module and State is still required for the DiffTransformer for annotations +// since the Diff doesn't contain all the information required to build the +// complete graph (such as create-before-destroy information). The graph +// is built based on the diff first, though, ensuring that only resources +// that are being modified are present in the graph. type DiffTransformer struct { - Concrete ConcreteResourceInstanceNodeFunc - State *states.State - Changes *plans.Changes + Concrete ConcreteResourceNodeFunc + + Diff *Diff + Module *module.Tree + State *State } func (t *DiffTransformer) Transform(g *Graph) error { - if t.Changes == nil || len(t.Changes.Resources) == 0 { - // Nothing to do! + // If the diff is nil or empty (nil is empty) then do nothing + if t.Diff.Empty() { return nil } // Go through all the modules in the diff. - log.Printf("[TRACE] DiffTransformer starting") + log.Printf("[TRACE] DiffTransformer: starting") + var nodes []dag.Vertex + for _, m := range t.Diff.Modules { + log.Printf("[TRACE] DiffTransformer: Module: %s", m) + // TODO: If this is a destroy diff then add a module destroy node - var diags tfdiags.Diagnostics - state := t.State - changes := t.Changes + // Go through all the resources in this module. + for name, inst := range m.Resources { + log.Printf("[TRACE] DiffTransformer: Resource %q: %#v", name, inst) - // DiffTransformer creates resource _instance_ nodes. If there are any - // whole-resource nodes already in the graph, we must ensure that they - // get evaluated before any of the corresponding instances by creating - // dependency edges, so we'll do some prep work here to ensure we'll only - // create connections to nodes that existed before we started here. - resourceNodes := map[string][]GraphNodeResource{} - for _, node := range g.Vertices() { - rn, ok := node.(GraphNodeResource) - if !ok { - continue + // We have changes! This is a create or update operation. + // First grab the address so we have a unique way to + // reference this resource. + addr, err := parseResourceAddressInternal(name) + if err != nil { + panic(fmt.Sprintf( + "Error parsing internal name, this is a bug: %q", name)) + } + + // Very important: add the module path for this resource to + // the address. Remove "root" from it. + addr.Path = m.Path[1:] + + // If we're destroying, add the destroy node + if inst.Destroy || inst.GetDestroyDeposed() { + abstract := &NodeAbstractResource{Addr: addr} + g.Add(&NodeDestroyResource{NodeAbstractResource: abstract}) + } + + // If we have changes, then add the applyable version + if len(inst.Attributes) > 0 { + // Add the resource to the graph + abstract := &NodeAbstractResource{Addr: addr} + var node dag.Vertex = abstract + if f := t.Concrete; f != nil { + node = f(abstract) + } + + nodes = append(nodes, node) + } } - // We ignore any instances that _also_ implement - // GraphNodeResourceInstance, since in the unlikely event that they - // do exist we'd probably end up creating cycles by connecting them. - if _, ok := node.(GraphNodeResourceInstance); ok { - continue - } - - addr := rn.ResourceAddr().String() - resourceNodes[addr] = append(resourceNodes[addr], rn) } - for _, rc := range changes.Resources { - addr := rc.Addr - dk := rc.DeposedKey - - log.Printf("[TRACE] DiffTransformer: found %s change for %s %s", rc.Action, addr, dk) - - // Depending on the action we'll need some different combinations of - // nodes, because destroying uses a special node type separate from - // other actions. - var update, delete, createBeforeDestroy bool - switch rc.Action { - case plans.NoOp: - continue - case plans.Delete: - delete = true - case plans.DeleteThenCreate, plans.CreateThenDelete: - update = true - delete = true - createBeforeDestroy = (rc.Action == plans.CreateThenDelete) - default: - update = true - } - - if dk != states.NotDeposed && update { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid planned change for deposed object", - fmt.Sprintf("The plan contains a non-delete change for %s deposed object %s. The only valid action for a deposed object is to destroy it, so this is a bug in Terraform.", addr, dk), - )) - continue - } - - // If we're going to do a create_before_destroy Replace operation then - // we need to allocate a DeposedKey to use to retain the - // not-yet-destroyed prior object, so that the delete node can destroy - // _that_ rather than the newly-created node, which will be current - // by the time the delete node is visited. - if update && delete && createBeforeDestroy { - // In this case, variable dk will be the _pre-assigned_ DeposedKey - // that must be used if the update graph node deposes the current - // instance, which will then align with the same key we pass - // into the destroy node to ensure we destroy exactly the deposed - // object we expect. - if state != nil { - ris := state.ResourceInstance(addr) - if ris == nil { - // Should never happen, since we don't plan to replace an - // instance that doesn't exist yet. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid planned change", - fmt.Sprintf("The plan contains a replace change for %s, which doesn't exist yet. This is a bug in Terraform.", addr), - )) - continue - } - - // Allocating a deposed key separately from using it can be racy - // in general, but we assume here that nothing except the apply - // node we instantiate below will actually make new deposed objects - // in practice, and so the set of already-used keys will not change - // between now and then. - dk = ris.FindUnusedDeposedKey() - } else { - // If we have no state at all yet then we can use _any_ - // DeposedKey. - dk = states.NewDeposedKey() - } - } - - if update { - // All actions except destroying the node type chosen by t.Concrete - abstract := NewNodeAbstractResourceInstance(addr) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - - if createBeforeDestroy { - // We'll attach our pre-allocated DeposedKey to the node if - // it supports that. NodeApplyableResourceInstance is the - // specific concrete node type we are looking for here really, - // since that's the only node type that might depose objects. - if dn, ok := node.(GraphNodeDeposer); ok { - dn.SetPreallocatedDeposedKey(dk) - } - log.Printf("[TRACE] DiffTransformer: %s will be represented by %s, deposing prior object to %s", addr, dag.VertexName(node), dk) - } else { - log.Printf("[TRACE] DiffTransformer: %s will be represented by %s", addr, dag.VertexName(node)) - } - - g.Add(node) - rsrcAddr := addr.ContainingResource().String() - for _, rsrcNode := range resourceNodes[rsrcAddr] { - g.Connect(dag.BasicEdge(node, rsrcNode)) - } - } - - if delete { - // Destroying always uses a destroy-specific node type, though - // which one depends on whether we're destroying a current object - // or a deposed object. - var node GraphNodeResourceInstance - abstract := NewNodeAbstractResourceInstance(addr) - if dk == states.NotDeposed { - node = &NodeDestroyResourceInstance{ - NodeAbstractResourceInstance: abstract, - DeposedKey: dk, - } - node.(*NodeDestroyResourceInstance).ModifyCreateBeforeDestroy(createBeforeDestroy) - } else { - node = &NodeDestroyDeposedResourceInstanceObject{ - NodeAbstractResourceInstance: abstract, - DeposedKey: dk, - } - } - if dk == states.NotDeposed { - log.Printf("[TRACE] DiffTransformer: %s will be represented for destruction by %s", addr, dag.VertexName(node)) - } else { - log.Printf("[TRACE] DiffTransformer: %s deposed object %s will be represented for destruction by %s", addr, dk, dag.VertexName(node)) - } - g.Add(node) - rsrcAddr := addr.ContainingResource().String() - for _, rsrcNode := range resourceNodes[rsrcAddr] { - // We connect this edge "forwards" (even though destroy dependencies - // are often inverted) because evaluating the resource node - // after the destroy node could cause an unnecessary husk of - // a resource state to be re-added. - g.Connect(dag.BasicEdge(node, rsrcNode)) - } - } - + // Add all the nodes to the graph + for _, n := range nodes { + g.Add(n) } - log.Printf("[TRACE] DiffTransformer complete") - - return diags.Err() + return nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_import_provider.go b/vendor/github.com/hashicorp/terraform/terraform/transform_import_provider.go index c1945f02..3673771c 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_import_provider.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_import_provider.go @@ -2,10 +2,7 @@ package terraform import ( "fmt" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/tfdiags" + "strings" ) // ImportProviderValidateTransformer is a GraphTransformer that goes through @@ -13,8 +10,6 @@ import ( type ImportProviderValidateTransformer struct{} func (t *ImportProviderValidateTransformer) Transform(g *Graph) error { - var diags tfdiags.Diagnostics - for _, v := range g.Vertices() { // We only care about providers pv, ok := v.(GraphNodeProvider) @@ -29,16 +24,15 @@ func (t *ImportProviderValidateTransformer) Transform(g *Graph) error { } for _, ref := range rn.References() { - if _, ok := ref.Subject.(addrs.InputVariable); !ok { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider dependency for import", - Detail: fmt.Sprintf("The configuration for %s depends on %s. Providers used with import must either have literal configuration or refer only to input variables.", pv.ProviderAddr(), ref.Subject.String()), - Subject: ref.SourceRange.ToHCL().Ptr(), - }) + if !strings.HasPrefix(ref, "var.") { + return fmt.Errorf( + "Provider %q depends on non-var %q. Providers for import can currently\n"+ + "only depend on variables or must be hardcoded. You can stop import\n"+ + "from loading configurations by specifying `-config=\"\"`.", + pv.ProviderName(), ref) } } } - return diags.Err() + return nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_import_state.go b/vendor/github.com/hashicorp/terraform/terraform/transform_import_state.go index ab0ecae0..fcbff653 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_import_state.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_import_state.go @@ -2,10 +2,6 @@ package terraform import ( "fmt" - - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/providers" - "github.com/hashicorp/terraform/tfdiags" ) // ImportStateTransformer is a GraphTransformer that adds nodes to the @@ -15,68 +11,64 @@ type ImportStateTransformer struct { } func (t *ImportStateTransformer) Transform(g *Graph) error { + nodes := make([]*graphNodeImportState, 0, len(t.Targets)) for _, target := range t.Targets { - // The ProviderAddr may not be supplied for non-aliased providers. - // This will be populated if the targets come from the cli, but tests - // may not specify implied provider addresses. - providerAddr := target.ProviderAddr - if providerAddr.ProviderConfig.Type == "" { - providerAddr = target.Addr.Resource.Resource.DefaultProviderConfig().Absolute(target.Addr.Module) + addr, err := ParseResourceAddress(target.Addr) + if err != nil { + return fmt.Errorf( + "failed to parse resource address '%s': %s", + target.Addr, err) } - node := &graphNodeImportState{ - Addr: target.Addr, + nodes = append(nodes, &graphNodeImportState{ + Addr: addr, ID: target.ID, - ProviderAddr: providerAddr, - } - g.Add(node) + ProviderName: target.Provider, + }) } + + // Build the graph vertices + for _, n := range nodes { + g.Add(n) + } + return nil } type graphNodeImportState struct { - Addr addrs.AbsResourceInstance // Addr is the resource address to import into - ID string // ID is the ID to import as - ProviderAddr addrs.AbsProviderConfig // Provider address given by the user, or implied by the resource type - ResolvedProvider addrs.AbsProviderConfig // provider node address after resolution + Addr *ResourceAddress // Addr is the resource address to import to + ID string // ID is the ID to import as + ProviderName string // Provider string + ResolvedProvider string // provider node address - states []providers.ImportedResource + states []*InstanceState } -var ( - _ GraphNodeSubPath = (*graphNodeImportState)(nil) - _ GraphNodeEvalable = (*graphNodeImportState)(nil) - _ GraphNodeProviderConsumer = (*graphNodeImportState)(nil) - _ GraphNodeDynamicExpandable = (*graphNodeImportState)(nil) -) - func (n *graphNodeImportState) Name() string { - return fmt.Sprintf("%s (import id %q)", n.Addr, n.ID) + return fmt.Sprintf("%s (import id: %s)", n.Addr, n.ID) } -// GraphNodeProviderConsumer -func (n *graphNodeImportState) ProvidedBy() (addrs.AbsProviderConfig, bool) { - // We assume that n.ProviderAddr has been properly populated here. - // It's the responsibility of the code creating a graphNodeImportState - // to populate this, possibly by calling DefaultProviderConfig() on the - // resource address to infer an implied provider from the resource type - // name. - return n.ProviderAddr, false +func (n *graphNodeImportState) ProvidedBy() string { + return resourceProvider(n.Addr.Type, n.ProviderName) } -// GraphNodeProviderConsumer -func (n *graphNodeImportState) SetProvider(addr addrs.AbsProviderConfig) { - n.ResolvedProvider = addr +func (n *graphNodeImportState) SetProvider(p string) { + n.ResolvedProvider = p } // GraphNodeSubPath -func (n *graphNodeImportState) Path() addrs.ModuleInstance { - return n.Addr.Module +func (n *graphNodeImportState) Path() []string { + return normalizeModulePath(n.Addr.Path) } // GraphNodeEvalable impl. func (n *graphNodeImportState) EvalTree() EvalNode { - var provider providers.Interface + var provider ResourceProvider + info := &InstanceInfo{ + Id: fmt.Sprintf("%s.%s", n.Addr.Type, n.Addr.Name), + ModulePath: n.Path(), + Type: n.Addr.Type, + } // Reset our states n.states = nil @@ -85,13 +77,13 @@ func (n *graphNodeImportState) EvalTree() EvalNode { return &EvalSequence{ Nodes: []EvalNode{ &EvalGetProvider{ - Addr: n.ResolvedProvider, + Name: n.ResolvedProvider, Output: &provider, }, &EvalImportState{ - Addr: n.Addr.Resource, Provider: &provider, - ID: n.ID, + Info: info, + Id: n.ID, Output: &n.states, }, }, @@ -105,8 +97,6 @@ func (n *graphNodeImportState) EvalTree() EvalNode { // resources they don't depend on anything else and refreshes are isolated // so this is nearly a perfect use case for dynamic expand. func (n *graphNodeImportState) DynamicExpand(ctx EvalContext) (*Graph, error) { - var diags tfdiags.Diagnostics - g := &Graph{Path: ctx.Path()} // nameCounter is used to de-dup names in the state. @@ -115,11 +105,11 @@ func (n *graphNodeImportState) DynamicExpand(ctx EvalContext) (*Graph, error) { // Compile the list of addresses that we'll be inserting into the state. // We do this ahead of time so we can verify that we aren't importing // something that already exists. - addrs := make([]addrs.AbsResourceInstance, len(n.states)) + addrs := make([]*ResourceAddress, len(n.states)) for i, state := range n.states { - addr := n.Addr - if t := state.TypeName; t != "" { - addr.Resource.Resource.Type = t + addr := *n.Addr + if t := state.Ephemeral.Type; t != "" { + addr.Type = t } // Determine if we need to suffix the name to de-dup @@ -127,30 +117,35 @@ func (n *graphNodeImportState) DynamicExpand(ctx EvalContext) (*Graph, error) { count, ok := nameCounter[key] if ok { count++ - addr.Resource.Resource.Name += fmt.Sprintf("-%d", count) + addr.Name += fmt.Sprintf("-%d", count) } nameCounter[key] = count // Add it to our list - addrs[i] = addr + addrs[i] = &addr } // Verify that all the addresses are clear - state := ctx.State() + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() + filter := &StateFilter{State: state} for _, addr := range addrs { - existing := state.ResourceInstance(addr) - if existing != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Resource already managed by Terraform", - fmt.Sprintf("Terraform is already managing a remote object for %s. To import to this address you must first remove the existing object from the state.", addr), - )) - continue + result, err := filter.Filter(addr.String()) + if err != nil { + return nil, fmt.Errorf("Error verifying address %s: %s", addr, err) + } + + // Go through the filter results and it is an error if we find + // a matching InstanceState, meaning that we would have a collision. + for _, r := range result { + if _, ok := r.Value.(*InstanceState); ok { + return nil, fmt.Errorf( + "Can't import %s, would collide with an existing resource.\n\n"+ + "Please remove or rename this resource before continuing.", + addr) + } } - } - if diags.HasErrors() { - // Bail out early, then. - return nil, diags.Err() } // For each of the states, we add a node to handle the refresh/add to state. @@ -159,8 +154,10 @@ func (n *graphNodeImportState) DynamicExpand(ctx EvalContext) (*Graph, error) { // is safe. for i, state := range n.states { g.Add(&graphNodeImportStateSub{ - TargetAddr: addrs[i], + Target: addrs[i], + Path_: n.Path(), State: state, + ProviderName: n.ProviderName, ResolvedProvider: n.ResolvedProvider, }) } @@ -172,67 +169,79 @@ func (n *graphNodeImportState) DynamicExpand(ctx EvalContext) (*Graph, error) { } // Done! - return g, diags.Err() + return g, nil } // graphNodeImportStateSub is the sub-node of graphNodeImportState // and is part of the subgraph. This node is responsible for refreshing // and adding a resource to the state once it is imported. type graphNodeImportStateSub struct { - TargetAddr addrs.AbsResourceInstance - State providers.ImportedResource - ResolvedProvider addrs.AbsProviderConfig + Target *ResourceAddress + State *InstanceState + Path_ []string + ProviderName string + ResolvedProvider string } -var ( - _ GraphNodeSubPath = (*graphNodeImportStateSub)(nil) - _ GraphNodeEvalable = (*graphNodeImportStateSub)(nil) -) - func (n *graphNodeImportStateSub) Name() string { - return fmt.Sprintf("import %s result", n.TargetAddr) + return fmt.Sprintf("import %s result: %s", n.Target, n.State.ID) } -func (n *graphNodeImportStateSub) Path() addrs.ModuleInstance { - return n.TargetAddr.Module +func (n *graphNodeImportStateSub) Path() []string { + return n.Path_ } // GraphNodeEvalable impl. func (n *graphNodeImportStateSub) EvalTree() EvalNode { // If the Ephemeral type isn't set, then it is an error - if n.State.TypeName == "" { - err := fmt.Errorf("import of %s didn't set type", n.TargetAddr.String()) + if n.State.Ephemeral.Type == "" { + err := fmt.Errorf( + "import of %s didn't set type for %s", + n.Target.String(), n.State.ID) return &EvalReturnError{Error: &err} } - state := n.State.AsInstanceObject() + // DeepCopy so we're only modifying our local copy + state := n.State.DeepCopy() - var provider providers.Interface - var providerSchema *ProviderSchema + // Build the resource info + info := &InstanceInfo{ + Id: fmt.Sprintf("%s.%s", n.Target.Type, n.Target.Name), + ModulePath: n.Path_, + Type: n.State.Ephemeral.Type, + } + + // Key is the resource key + key := &ResourceStateKey{ + Name: n.Target.Name, + Type: info.Type, + Index: n.Target.Index, + } + + // The eval sequence + var provider ResourceProvider return &EvalSequence{ Nodes: []EvalNode{ &EvalGetProvider{ - Addr: n.ResolvedProvider, + Name: n.ResolvedProvider, Output: &provider, - Schema: &providerSchema, }, &EvalRefresh{ - Addr: n.TargetAddr.Resource, - ProviderAddr: n.ResolvedProvider, - Provider: &provider, - ProviderSchema: &providerSchema, - State: &state, - Output: &state, + Provider: &provider, + State: &state, + Info: info, + Output: &state, }, &EvalImportStateVerify{ - Addr: n.TargetAddr.Resource, + Info: info, + Id: n.State.ID, State: &state, }, &EvalWriteState{ - Addr: n.TargetAddr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, + Name: key.String(), + ResourceType: info.Type, + Provider: n.ResolvedProvider, + State: &state, }, }, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_local.go b/vendor/github.com/hashicorp/terraform/terraform/transform_local.go index 84eb26b2..95ecfc0a 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_local.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_local.go @@ -1,45 +1,37 @@ package terraform import ( - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" ) // LocalTransformer is a GraphTransformer that adds all the local values // from the configuration to the graph. type LocalTransformer struct { - Config *configs.Config + Module *module.Tree } func (t *LocalTransformer) Transform(g *Graph) error { - return t.transformModule(g, t.Config) + return t.transformModule(g, t.Module) } -func (t *LocalTransformer) transformModule(g *Graph, c *configs.Config) error { - if c == nil { +func (t *LocalTransformer) transformModule(g *Graph, m *module.Tree) error { + if m == nil { // Can't have any locals if there's no config return nil } - // Our addressing system distinguishes between modules and module instances, - // but we're not yet ready to make that distinction here (since we don't - // support "count"/"for_each" on modules) and so we just do a naive - // transform of the module path into a module instance path, assuming that - // no keys are in use. This should be removed when "count" and "for_each" - // are implemented for modules. - path := c.Path.UnkeyedInstanceShim() - - for _, local := range c.Module.Locals { - addr := path.LocalValue(local.Name) + for _, local := range m.Config().Locals { node := &NodeLocal{ - Addr: addr, - Config: local, + PathValue: normalizeModulePath(m.Path()), + Config: local, } + g.Add(node) } // Also populate locals for child modules - for _, cc := range c.Children { - if err := t.transformModule(g, cc); err != nil { + for _, c := range m.Children() { + if err := t.transformModule(g, c); err != nil { return err } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_module_variable.go b/vendor/github.com/hashicorp/terraform/terraform/transform_module_variable.go index a994bd4f..467950bd 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_module_variable.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_module_variable.go @@ -1,54 +1,46 @@ package terraform import ( - "fmt" + "log" - "github.com/hashicorp/hcl2/hcl/hclsyntax" - "github.com/hashicorp/terraform/tfdiags" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" + "github.com/hashicorp/terraform/dag" ) // ModuleVariableTransformer is a GraphTransformer that adds all the variables // in the configuration to the graph. // -// Any "variable" block present in any non-root module is included here, even -// if a particular variable is not referenced from anywhere. -// -// The transform will produce errors if a call to a module does not conform -// to the expected set of arguments, but this transformer is not in a good -// position to return errors and so the validate walk should include specific -// steps for validating module blocks, separate from this transform. +// This only adds variables that are referenced by other things in the graph. +// If a module variable is not referenced, it won't be added to the graph. type ModuleVariableTransformer struct { - Config *configs.Config + Module *module.Tree + + DisablePrune bool // True if pruning unreferenced should be disabled } func (t *ModuleVariableTransformer) Transform(g *Graph) error { - return t.transform(g, nil, t.Config) + return t.transform(g, nil, t.Module) } -func (t *ModuleVariableTransformer) transform(g *Graph, parent, c *configs.Config) error { - // We can have no variables if we have no configuration. - if c == nil { +func (t *ModuleVariableTransformer) transform(g *Graph, parent, m *module.Tree) error { + // If no config, no variables + if m == nil { return nil } - // Transform all the children first. - for _, cc := range c.Children { - if err := t.transform(g, c, cc); err != nil { + // Transform all the children. This must be done BEFORE the transform + // above since child module variables can reference parent module variables. + for _, c := range m.Children() { + if err := t.transform(g, m, c); err != nil { return err } } - // If we're processing anything other than the root module then we'll - // add graph nodes for variables defined inside. (Variables for the root - // module are dealt with in RootVariableTransformer). // If we have a parent, we can determine if a module variable is being // used, so we transform this. if parent != nil { - if err := t.transformSingle(g, parent, c); err != nil { + if err := t.transformSingle(g, parent, m); err != nil { return err } } @@ -56,69 +48,71 @@ func (t *ModuleVariableTransformer) transform(g *Graph, parent, c *configs.Confi return nil } -func (t *ModuleVariableTransformer) transformSingle(g *Graph, parent, c *configs.Config) error { - - // Our addressing system distinguishes between modules and module instances, - // but we're not yet ready to make that distinction here (since we don't - // support "count"/"for_each" on modules) and so we just do a naive - // transform of the module path into a module instance path, assuming that - // no keys are in use. This should be removed when "count" and "for_each" - // are implemented for modules. - path := c.Path.UnkeyedInstanceShim() - _, call := path.Call() - - // Find the call in the parent module configuration, so we can get the - // expressions given for each input variable at the call site. - callConfig, exists := parent.Module.ModuleCalls[call.Name] - if !exists { - // This should never happen, since it indicates an improperly-constructed - // configuration tree. - panic(fmt.Errorf("no module call block found for %s", path)) +func (t *ModuleVariableTransformer) transformSingle(g *Graph, parent, m *module.Tree) error { + // If we have no vars, we're done! + vars := m.Config().Variables + if len(vars) == 0 { + log.Printf("[TRACE] Module %#v has no variables, skipping.", m.Path()) + return nil } - // We need to construct a schema for the expected call arguments based on - // the configured variables in our config, which we can then use to - // decode the content of the call block. - schema := &hcl.BodySchema{} - for _, v := range c.Module.Variables { - schema.Attributes = append(schema.Attributes, hcl.AttributeSchema{ - Name: v.Name, - Required: v.Default == cty.NilVal, - }) + // Look for usage of this module + var mod *config.Module + for _, modUse := range parent.Config().Modules { + if modUse.Name == m.Name() { + mod = modUse + break + } + } + if mod == nil { + log.Printf("[INFO] Module %#v not used, not adding variables", m.Path()) + return nil } - content, contentDiags := callConfig.Config.Content(schema) - if contentDiags.HasErrors() { - // Validation code elsewhere should deal with any errors before we - // get in here, but we'll report them out here just in case, to - // avoid crashes. - var diags tfdiags.Diagnostics - diags = diags.Append(contentDiags) - return diags.Err() - } + // Build the reference map so we can determine if we're referencing things. + refMap := NewReferenceMap(g.Vertices()) - for _, v := range c.Module.Variables { - var expr hcl.Expression - if attr := content.Attributes[v.Name]; attr != nil { - expr = attr.Expr - } else { - // No expression provided for this variable, so we'll make a - // synthetic one using the variable's default value. - expr = &hclsyntax.LiteralValueExpr{ - Val: v.Default, - SrcRange: v.DeclRange, // This is not exact, but close enough + // Add all variables here + for _, v := range vars { + // Determine the value of the variable. If it isn't in the + // configuration then it was never set and that's not a problem. + var value *config.RawConfig + if raw, ok := mod.RawConfig.Raw[v.Name]; ok { + var err error + value, err = config.NewRawConfig(map[string]interface{}{ + v.Name: raw, + }) + if err != nil { + // This shouldn't happen because it is already in + // a RawConfig above meaning it worked once before. + panic(err) } } - // For now we treat all module variables as "applyable", even though - // such nodes are valid to use on other walks too. We may specialize - // this in future if we find reasons to employ different behaviors - // in different scenarios. + // Build the node. + // + // NOTE: For now this is just an "applyable" variable. As we build + // new graph builders for the other operations I suspect we'll + // find a way to parameterize this, require new transforms, etc. node := &NodeApplyableModuleVariable{ - Addr: path.InputVariable(v.Name), - Config: v, - Expr: expr, + PathValue: normalizeModulePath(m.Path()), + Config: v, + Value: value, + Module: t.Module, } + + if !t.DisablePrune { + // If the node is not referenced by anything, then we don't need + // to include it since it won't be used. + if matches := refMap.ReferencedBy(node); len(matches) == 0 { + log.Printf( + "[INFO] Not including %q in graph, nothing depends on it", + dag.VertexName(node)) + continue + } + } + + // Add it! g.Add(node) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_count.go b/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_count.go index eec762e5..b256a25b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_count.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_count.go @@ -3,9 +3,7 @@ package terraform import ( "log" - "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/states" ) // OrphanResourceCountTransformer is a GraphTransformer that adds orphans @@ -16,106 +14,95 @@ import ( // This transform assumes that if an element in the state is within the count // bounds given, that it is not an orphan. type OrphanResourceCountTransformer struct { - Concrete ConcreteResourceInstanceNodeFunc + Concrete ConcreteResourceNodeFunc - Count int // Actual count of the resource, or -1 if count is not set at all - Addr addrs.AbsResource // Addr of the resource to look for orphans - State *states.State // Full global state + Count int // Actual count of the resource + Addr *ResourceAddress // Addr of the resource to look for orphans + State *State // Full global state } func (t *OrphanResourceCountTransformer) Transform(g *Graph) error { - rs := t.State.Resource(t.Addr) - if rs == nil { - return nil // Resource doesn't exist in state, so nothing to do! + log.Printf("[TRACE] OrphanResourceCount: Starting...") + + // Grab the module in the state just for this resource address + ms := t.State.ModuleByPath(normalizeModulePath(t.Addr.Path)) + if ms == nil { + // If no state, there can't be orphans + return nil } - haveKeys := make(map[addrs.InstanceKey]struct{}) - for key := range rs.Instances { - haveKeys[key] = struct{}{} + orphanIndex := -1 + if t.Count == 1 { + orphanIndex = 0 } - if t.Count < 0 { - return t.transformNoCount(haveKeys, g) - } - if t.Count == 0 { - return t.transformZeroCount(haveKeys, g) - } - return t.transformCount(haveKeys, g) -} + // Go through the orphans and add them all to the state + for key, _ := range ms.Resources { + // Build the address + addr, err := parseResourceAddressInternal(key) + if err != nil { + return err + } + addr.Path = ms.Path[1:] -func (t *OrphanResourceCountTransformer) transformCount(haveKeys map[addrs.InstanceKey]struct{}, g *Graph) error { - // Due to the logic in Transform, we only get in here if our count is - // at least one. - - _, have0Key := haveKeys[addrs.IntKey(0)] - - for key := range haveKeys { - if key == addrs.NoKey && !have0Key { - // If we have no 0-key then we will accept a no-key instance - // as an alias for it. + // Copy the address for comparison. If we aren't looking at + // the same resource, then just ignore it. + addrCopy := addr.Copy() + addrCopy.Index = -1 + if !addrCopy.Equals(t.Addr) { continue } - i, isInt := key.(addrs.IntKey) - if isInt && int(i) < t.Count { + log.Printf("[TRACE] OrphanResourceCount: Checking: %s", addr) + + idx := addr.Index + + // If we have zero and the index here is 0 or 1, then we + // change the index to a high number so that we treat it as + // an orphan. + if t.Count <= 0 && idx <= 0 { + idx = t.Count + 1 + } + + // If we have a count greater than 0 and we're at the zero index, + // we do a special case check to see if our state also has a + // -1 index value. If so, this is an orphan because our rules are + // that if both a -1 and 0 are in the state, the 0 is destroyed. + if t.Count > 0 && idx == orphanIndex { + // This is a piece of cleverness (beware), but its simple: + // if orphanIndex is 0, then check -1, else check 0. + checkIndex := (orphanIndex + 1) * -1 + + key := &ResourceStateKey{ + Name: addr.Name, + Type: addr.Type, + Mode: addr.Mode, + Index: checkIndex, + } + + if _, ok := ms.Resources[key.String()]; ok { + // We have a -1 index, too. Make an arbitrarily high + // index so that we always mark this as an orphan. + log.Printf( + "[WARN] OrphanResourceCount: %q both -1 and 0 index found, orphaning %d", + addr, orphanIndex) + idx = t.Count + 1 + } + } + + // If the index is within the count bounds, it is not an orphan + if idx < t.Count { continue } - abstract := NewNodeAbstractResourceInstance(t.Addr.Instance(key)) + // Build the abstract node and the concrete one + abstract := &NodeAbstractResource{Addr: addr} var node dag.Vertex = abstract if f := t.Concrete; f != nil { node = f(abstract) } - log.Printf("[TRACE] OrphanResourceCount(non-zero): adding %s as %T", t.Addr, node) - g.Add(node) - } - - return nil -} - -func (t *OrphanResourceCountTransformer) transformZeroCount(haveKeys map[addrs.InstanceKey]struct{}, g *Graph) error { - // This case is easy: we need to orphan any keys we have at all. - - for key := range haveKeys { - abstract := NewNodeAbstractResourceInstance(t.Addr.Instance(key)) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceCount(zero): adding %s as %T", t.Addr, node) - g.Add(node) - } - - return nil -} - -func (t *OrphanResourceCountTransformer) transformNoCount(haveKeys map[addrs.InstanceKey]struct{}, g *Graph) error { - // Negative count indicates that count is not set at all, in which - // case we expect to have a single instance with no key set at all. - // However, we'll also accept an instance with key 0 set as an alias - // for it, in case the user has just deleted the "count" argument and - // so wants to keep the first instance in the set. - - _, haveNoKey := haveKeys[addrs.NoKey] - _, have0Key := haveKeys[addrs.IntKey(0)] - keepKey := addrs.NoKey - if have0Key && !haveNoKey { - // If we don't have a no-key instance then we can use the 0-key instance - // instead. - keepKey = addrs.IntKey(0) - } - - for key := range haveKeys { - if key == keepKey { - continue - } - - abstract := NewNodeAbstractResourceInstance(t.Addr.Instance(key)) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceCount(no-count): adding %s as %T", t.Addr, node) + + // Add it to the graph g.Add(node) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_output.go b/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_output.go index c6754093..aea2bd0e 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_output.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_output.go @@ -3,17 +3,16 @@ package terraform import ( "log" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/states" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" ) // OrphanOutputTransformer finds the outputs that aren't present // in the given config that are in the state and adds them to the graph // for deletion. type OrphanOutputTransformer struct { - Config *configs.Config // Root of config tree - State *states.State // State is the root state + Module *module.Tree // Root module + State *State // State is the root state } func (t *OrphanOutputTransformer) Transform(g *Graph) error { @@ -30,30 +29,24 @@ func (t *OrphanOutputTransformer) Transform(g *Graph) error { return nil } -func (t *OrphanOutputTransformer) transform(g *Graph, ms *states.Module) error { +func (t *OrphanOutputTransformer) transform(g *Graph, ms *ModuleState) error { if ms == nil { return nil } - moduleAddr := ms.Addr + path := normalizeModulePath(ms.Path) // Get the config for this path, which is nil if the entire module has been // removed. - var outputs map[string]*configs.Output - if c := t.Config.DescendentForInstance(moduleAddr); c != nil { - outputs = c.Module.Outputs + var c *config.Config + if m := t.Module.Child(path[1:]); m != nil { + c = m.Config() } - // An output is "orphaned" if it's present in the state but not declared - // in the configuration. - for name := range ms.OutputValues { - if _, exists := outputs[name]; exists { - continue - } + // add all the orphaned outputs to the graph + for _, n := range ms.RemovedOutputs(c) { + g.Add(&NodeOutputOrphan{OutputName: n, PathValue: path}) - g.Add(&NodeOutputOrphan{ - Addr: addrs.OutputValue{Name: name}.Absolute(moduleAddr), - }) } return nil diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_resource.go b/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_resource.go index 50df1781..e42d3c84 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_resource.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_orphan_resource.go @@ -1,43 +1,34 @@ package terraform import ( - "log" - - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/states" ) -// OrphanResourceInstanceTransformer is a GraphTransformer that adds orphaned -// resource instances to the graph. An "orphan" is an instance that is present -// in the state but belongs to a resource that is no longer present in the -// configuration. +// OrphanResourceTransformer is a GraphTransformer that adds resource +// orphans to the graph. A resource orphan is a resource that is +// represented in the state but not in the configuration. // -// This is not the transformer that deals with "count orphans" (instances that -// are no longer covered by a resource's "count" or "for_each" setting); that's -// handled instead by OrphanResourceCountTransformer. -type OrphanResourceInstanceTransformer struct { - Concrete ConcreteResourceInstanceNodeFunc +// This only adds orphans that have no representation at all in the +// configuration. +type OrphanResourceTransformer struct { + Concrete ConcreteResourceNodeFunc // State is the global state. We require the global state to // properly find module orphans at our path. - State *states.State + State *State - // Config is the root node in the configuration tree. We'll look up - // the appropriate note in this tree using the path in each node. - Config *configs.Config + // Module is the root module. We'll look up the proper configuration + // using the graph path. + Module *module.Tree } -func (t *OrphanResourceInstanceTransformer) Transform(g *Graph) error { +func (t *OrphanResourceTransformer) Transform(g *Graph) error { if t.State == nil { // If the entire state is nil, there can't be any orphans return nil } - if t.Config == nil { - // Should never happen: we can't be doing any Terraform operations - // without at least an empty configuration. - panic("OrphanResourceInstanceTransformer used without setting Config") - } // Go through the modules and for each module transform in order // to add the orphan. @@ -50,130 +41,38 @@ func (t *OrphanResourceInstanceTransformer) Transform(g *Graph) error { return nil } -func (t *OrphanResourceInstanceTransformer) transform(g *Graph, ms *states.Module) error { +func (t *OrphanResourceTransformer) transform(g *Graph, ms *ModuleState) error { if ms == nil { return nil } - moduleAddr := ms.Addr - - // Get the configuration for this module. The configuration might be + // Get the configuration for this path. The configuration might be // nil if the module was removed from the configuration. This is okay, // this just means that every resource is an orphan. - var m *configs.Module - if c := t.Config.DescendentForInstance(moduleAddr); c != nil { - m = c.Module + var c *config.Config + if m := t.Module.Child(ms.Path[1:]); m != nil { + c = m.Config() } - // An "orphan" is a resource that is in the state but not the configuration, - // so we'll walk the state resources and try to correlate each of them - // with a configuration block. Each orphan gets a node in the graph whose - // type is decided by t.Concrete. - // - // We don't handle orphans related to changes in the "count" and "for_each" - // pseudo-arguments here. They are handled by OrphanResourceCountTransformer. - for _, rs := range ms.Resources { - if m != nil { - if r := m.ResourceByAddr(rs.Addr); r != nil { - continue - } + // Go through the orphans and add them all to the state + for _, key := range ms.Orphans(c) { + // Build the abstract resource + addr, err := parseResourceAddressInternal(key) + if err != nil { + return err + } + addr.Path = ms.Path[1:] + + // Build the abstract node and the concrete one + abstract := &NodeAbstractResource{Addr: addr} + var node dag.Vertex = abstract + if f := t.Concrete; f != nil { + node = f(abstract) } - for key := range rs.Instances { - addr := rs.Addr.Instance(key).Absolute(moduleAddr) - abstract := NewNodeAbstractResourceInstance(addr) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceInstanceTransformer: adding single-instance orphan node for %s", addr) - g.Add(node) - } + // Add it to the graph + g.Add(node) } return nil } - -// OrphanResourceTransformer is a GraphTransformer that adds orphaned -// resources to the graph. An "orphan" is a resource that is present in -// the state but no longer present in the config. -// -// This is separate to OrphanResourceInstanceTransformer in that it deals with -// whole resources, rather than individual instances of resources. Orphan -// resource nodes are only used during apply to clean up leftover empty -// resource state skeletons, after all of the instances inside have been -// removed. -// -// This transformer will also create edges in the graph to any pre-existing -// node that creates or destroys the entire orphaned resource or any of its -// instances, to ensure that the "orphan-ness" of a resource is always dealt -// with after all other aspects of it. -type OrphanResourceTransformer struct { - Concrete ConcreteResourceNodeFunc - - // State is the global state. - State *states.State - - // Config is the root node in the configuration tree. - Config *configs.Config -} - -func (t *OrphanResourceTransformer) Transform(g *Graph) error { - if t.State == nil { - // If the entire state is nil, there can't be any orphans - return nil - } - if t.Config == nil { - // Should never happen: we can't be doing any Terraform operations - // without at least an empty configuration. - panic("OrphanResourceTransformer used without setting Config") - } - - // We'll first collect up the existing nodes for each resource so we can - // create dependency edges for any new nodes we create. - deps := map[string][]dag.Vertex{} - for _, v := range g.Vertices() { - switch tv := v.(type) { - case GraphNodeResourceInstance: - k := tv.ResourceInstanceAddr().ContainingResource().String() - deps[k] = append(deps[k], v) - case GraphNodeResource: - k := tv.ResourceAddr().String() - deps[k] = append(deps[k], v) - case GraphNodeDestroyer: - k := tv.DestroyAddr().ContainingResource().String() - deps[k] = append(deps[k], v) - } - } - - for _, ms := range t.State.Modules { - moduleAddr := ms.Addr - - mc := t.Config.DescendentForInstance(moduleAddr) // might be nil if whole module has been removed - - for _, rs := range ms.Resources { - if mc != nil { - if r := mc.Module.ResourceByAddr(rs.Addr); r != nil { - // It's in the config, so nothing to do for this one. - continue - } - } - - addr := rs.Addr.Absolute(moduleAddr) - abstract := NewNodeAbstractResource(addr) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceTransformer: adding whole-resource orphan node for %s", addr) - g.Add(node) - for _, dn := range deps[addr.String()] { - log.Printf("[TRACE] OrphanResourceTransformer: node %q depends on %q", dag.VertexName(node), dag.VertexName(dn)) - g.Connect(dag.BasicEdge(node, dn)) - } - } - } - - return nil - -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_output.go b/vendor/github.com/hashicorp/terraform/terraform/transform_output.go index ed93cdb8..faa25e41 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_output.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_output.go @@ -3,7 +3,7 @@ package terraform import ( "log" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" ) @@ -14,42 +14,42 @@ import ( // aren't changing since there is no downside: the state will be available // even if the dependent items aren't changing. type OutputTransformer struct { - Config *configs.Config + Module *module.Tree } func (t *OutputTransformer) Transform(g *Graph) error { - return t.transform(g, t.Config) + return t.transform(g, t.Module) } -func (t *OutputTransformer) transform(g *Graph, c *configs.Config) error { - // If we have no config then there can be no outputs. - if c == nil { +func (t *OutputTransformer) transform(g *Graph, m *module.Tree) error { + // If no config, no outputs + if m == nil { return nil } // Transform all the children. We must do this first because // we can reference module outputs and they must show up in the // reference map. - for _, cc := range c.Children { - if err := t.transform(g, cc); err != nil { + for _, c := range m.Children() { + if err := t.transform(g, c); err != nil { return err } } - // Our addressing system distinguishes between modules and module instances, - // but we're not yet ready to make that distinction here (since we don't - // support "count"/"for_each" on modules) and so we just do a naive - // transform of the module path into a module instance path, assuming that - // no keys are in use. This should be removed when "count" and "for_each" - // are implemented for modules. - path := c.Path.UnkeyedInstanceShim() + // If we have no outputs, we're done! + os := m.Config().Outputs + if len(os) == 0 { + return nil + } - for _, o := range c.Module.Outputs { - addr := path.OutputValue(o.Name) + // Add all outputs here + for _, o := range os { node := &NodeApplyableOutput{ - Addr: addr, - Config: o, + PathValue: normalizeModulePath(m.Path()), + Config: o, } + + // Add it! g.Add(node) } @@ -71,8 +71,8 @@ func (t *DestroyOutputTransformer) Transform(g *Graph) error { // create the destroy node for this output node := &NodeDestroyableOutput{ - Addr: output.Addr, - Config: output.Config, + PathValue: output.PathValue, + Config: output.Config, } log.Printf("[TRACE] creating %s", node.Name()) diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_provider.go b/vendor/github.com/hashicorp/terraform/terraform/transform_provider.go index 6a4fb47c..c4772b40 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_provider.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_provider.go @@ -1,21 +1,22 @@ package terraform import ( + "errors" "fmt" "log" + "strings" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" - "github.com/hashicorp/terraform/tfdiags" ) -func TransformProviders(providers []string, concrete ConcreteProviderNodeFunc, config *configs.Config) GraphTransformer { +func TransformProviders(providers []string, concrete ConcreteProviderNodeFunc, mod *module.Tree) GraphTransformer { return GraphTransformMulti( // Add providers from the config &ProviderConfigTransformer{ - Config: config, + Module: mod, Providers: providers, Concrete: concrete, }, @@ -25,9 +26,7 @@ func TransformProviders(providers []string, concrete ConcreteProviderNodeFunc, c Concrete: concrete, }, // Connect the providers - &ProviderTransformer{ - Config: config, - }, + &ProviderTransformer{}, // Remove unused providers and proxies &PruneProviderTransformer{}, // Connect provider to their parent provider nodes @@ -37,14 +36,10 @@ func TransformProviders(providers []string, concrete ConcreteProviderNodeFunc, c // GraphNodeProvider is an interface that nodes that can be a provider // must implement. -// -// ProviderAddr returns the address of the provider configuration this -// satisfies, which is relative to the path returned by method Path(). -// +// ProviderName returns the name of the provider this satisfies. // Name returns the full name of the provider in the config. type GraphNodeProvider interface { - GraphNodeSubPath - ProviderAddr() addrs.AbsProviderConfig + ProviderName() string Name() string } @@ -52,132 +47,62 @@ type GraphNodeProvider interface { // provider must implement. The CloseProviderName returned is the name of // the provider they satisfy. type GraphNodeCloseProvider interface { - GraphNodeSubPath - CloseProviderAddr() addrs.AbsProviderConfig + CloseProviderName() string } // GraphNodeProviderConsumer is an interface that nodes that require -// a provider must implement. ProvidedBy must return the address of the provider -// to use, which will be resolved to a configuration either in the same module -// or in an ancestor module, with the resulting absolute address passed to -// SetProvider. +// a provider must implement. ProvidedBy must return the name of the provider +// to use. This may be a provider by type, type.alias or a fully resolved +// provider name type GraphNodeProviderConsumer interface { - // ProvidedBy returns the address of the provider configuration the node - // refers to. If the returned "exact" value is true, this address will - // be taken exactly. If "exact" is false, a provider configuration from - // an ancestor module may be selected instead. - ProvidedBy() (addr addrs.AbsProviderConfig, exact bool) + ProvidedBy() string // Set the resolved provider address for this resource. - SetProvider(addrs.AbsProviderConfig) + SetProvider(string) } // ProviderTransformer is a GraphTransformer that maps resources to // providers within the graph. This will error if there are any resources // that don't map to proper resources. -type ProviderTransformer struct { - Config *configs.Config -} +type ProviderTransformer struct{} func (t *ProviderTransformer) Transform(g *Graph) error { - // We need to find a provider configuration address for each resource - // either directly represented by a node or referenced by a node in - // the graph, and then create graph edges from provider to provider user - // so that the providers will get initialized first. - - var diags tfdiags.Diagnostics - - // To start, we'll collect the _requested_ provider addresses for each - // node, which we'll then resolve (handling provider inheritence, etc) in - // the next step. - // Our "requested" map is from graph vertices to string representations of - // provider config addresses (for deduping) to requests. - type ProviderRequest struct { - Addr addrs.AbsProviderConfig - Exact bool // If true, inheritence from parent modules is not attempted - } - requested := map[dag.Vertex]map[string]ProviderRequest{} - needConfigured := map[string]addrs.AbsProviderConfig{} - for _, v := range g.Vertices() { - - // Does the vertex _directly_ use a provider? - if pv, ok := v.(GraphNodeProviderConsumer); ok { - requested[v] = make(map[string]ProviderRequest) - - p, exact := pv.ProvidedBy() - if exact { - log.Printf("[TRACE] ProviderTransformer: %s is provided by %s exactly", dag.VertexName(v), p) - } else { - log.Printf("[TRACE] ProviderTransformer: %s is provided by %s or inherited equivalent", dag.VertexName(v), p) - } - - requested[v][p.String()] = ProviderRequest{ - Addr: p, - Exact: exact, - } - - // Direct references need the provider configured as well as initialized - needConfigured[p.String()] = p - } - } - - // Now we'll go through all the requested addresses we just collected and - // figure out which _actual_ config address each belongs to, after resolving - // for provider inheritance and passing. + // Go through the other nodes and match them to providers they need + var err error m := providerVertexMap(g) - for v, reqs := range requested { - for key, req := range reqs { - p := req.Addr + for _, v := range g.Vertices() { + if pv, ok := v.(GraphNodeProviderConsumer); ok { + p := pv.ProvidedBy() + + key := providerMapKey(p, pv) target := m[key] - _, ok := v.(GraphNodeSubPath) + sp, ok := pv.(GraphNodeSubPath) if !ok && target == nil { - // No target and no path to traverse up from - diags = diags.Append(fmt.Errorf("%s: provider %s couldn't be found", dag.VertexName(v), p)) - continue + // no target, and no path to walk up + err = multierror.Append(err, fmt.Errorf( + "%s: provider %s couldn't be found", + dag.VertexName(v), p)) + break } - if target != nil { - log.Printf("[TRACE] ProviderTransformer: exact match for %s serving %s", p, dag.VertexName(v)) - } - - // if we don't have a provider at this level, walk up the path looking for one, - // unless we were told to be exact. - if target == nil && !req.Exact { - for pp, ok := p.Inherited(); ok; pp, ok = pp.Inherited() { - key := pp.String() - target = m[key] - if target != nil { - log.Printf("[TRACE] ProviderTransformer: %s uses inherited configuration %s", dag.VertexName(v), pp) - break - } - log.Printf("[TRACE] ProviderTransformer: looking for %s to serve %s", pp, dag.VertexName(v)) + // if we don't have a provider at this level, walk up the path looking for one + for i := 1; target == nil; i++ { + path := normalizeModulePath(sp.Path()) + if len(path) < i { + break } - } - // If this provider doesn't need to be configured then we can just - // stub it out with an init-only provider node, which will just - // start up the provider and fetch its schema. - if _, exists := needConfigured[key]; target == nil && !exists { - stubAddr := p.ProviderConfig.Absolute(addrs.RootModuleInstance) - stub := &NodeEvalableProvider{ - &NodeAbstractProvider{ - Addr: stubAddr, - }, + key = ResolveProviderName(p, path[:len(path)-i]) + target = m[key] + if target != nil { + break } - m[stubAddr.String()] = stub - log.Printf("[TRACE] ProviderTransformer: creating init-only node for %s", stubAddr) - target = stub - g.Add(target) } if target == nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider configuration not present", - fmt.Sprintf( - "To work with %s its original provider configuration at %s is required, but it has been removed. This occurs when a provider configuration is removed while objects created by that provider still exist in the state. Re-add the provider configuration to destroy %s, after which you can remove the provider configuration again.", - dag.VertexName(v), p, dag.VertexName(v), - ), + err = multierror.Append(err, fmt.Errorf( + "%s: configuration for %s is not present; a provider configuration block is required for all operations", + dag.VertexName(v), p, )) break } @@ -186,18 +111,16 @@ func (t *ProviderTransformer) Transform(g *Graph) error { if p, ok := target.(*graphNodeProxyProvider); ok { g.Remove(p) target = p.Target() - key = target.(GraphNodeProvider).ProviderAddr().String() + key = target.(GraphNodeProvider).Name() } - log.Printf("[DEBUG] ProviderTransformer: %q (%T) needs %s", dag.VertexName(v), v, dag.VertexName(target)) - if pv, ok := v.(GraphNodeProviderConsumer); ok { - pv.SetProvider(target.ProviderAddr()) - } + log.Printf("[DEBUG] resource %s using provider %s", dag.VertexName(pv), key) + pv.SetProvider(key) g.Connect(dag.BasicEdge(v, target)) } } - return diags.Err() + return err } // CloseProviderTransformer is a GraphTransformer that adds nodes to the @@ -213,16 +136,15 @@ func (t *CloseProviderTransformer) Transform(g *Graph) error { for _, v := range pm { p := v.(GraphNodeProvider) - key := p.ProviderAddr().String() // get the close provider of this type if we alread created it - closer := cpm[key] + closer := cpm[p.Name()] if closer == nil { // create a closer for this provider type - closer = &graphNodeCloseProvider{Addr: p.ProviderAddr()} + closer = &graphNodeCloseProvider{ProviderNameValue: p.Name()} g.Add(closer) - cpm[key] = closer + cpm[p.Name()] = closer } // Close node depends on the provider itself @@ -242,20 +164,10 @@ func (t *CloseProviderTransformer) Transform(g *Graph) error { return err } -// MissingProviderTransformer is a GraphTransformer that adds to the graph -// a node for each default provider configuration that is referenced by another -// node but not already present in the graph. -// -// These "default" nodes are always added to the root module, regardless of -// where they are requested. This is important because our inheritance -// resolution behavior in ProviderTransformer will then treat these as a -// last-ditch fallback after walking up the tree, rather than preferring them -// as it would if they were placed in the same module as the requester. -// -// This transformer may create extra nodes that are not needed in practice, -// due to overriding provider configurations in child modules. -// PruneProviderTransformer can then remove these once ProviderTransformer -// has resolved all of the inheritence, etc. +// MissingProviderTransformer is a GraphTransformer that adds nodes for all +// required providers into the graph. Specifically, it creates provider +// configuration nodes for all the providers that we support. These are pruned +// later during an optimization pass. type MissingProviderTransformer struct { // Providers is the list of providers we support. Providers []string @@ -280,40 +192,34 @@ func (t *MissingProviderTransformer) Transform(g *Graph) error { continue } - // For our work here we actually care only about the provider type and - // we plan to place all default providers in the root module, and so - // it's safe for us to rely on ProvidedBy here rather than waiting for - // the later proper resolution of provider inheritance done by - // ProviderTransformer. - p, _ := pv.ProvidedBy() - if p.ProviderConfig.Alias != "" { - // We do not create default aliased configurations. - log.Println("[TRACE] MissingProviderTransformer: skipping implication of aliased config", p) - continue - } + p := pv.ProvidedBy() + // this may be the resolved provider from the state, so we need to get + // the base provider name. + parts := strings.SplitAfter(p, "provider.") + p = parts[len(parts)-1] - // We're going to create an implicit _default_ configuration for the - // referenced provider type in the _root_ module, ignoring all other - // aspects of the resource's declared provider address. - defaultAddr := addrs.RootModuleInstance.ProviderConfigDefault(p.ProviderConfig.Type) - key := defaultAddr.String() + key := ResolveProviderName(p, nil) provider := m[key] + // we already have it if provider != nil { - // There's already an explicit default configuration for this - // provider type in the root module, so we have nothing to do. continue } - log.Printf("[DEBUG] adding implicit provider configuration %s, implied first by %s", defaultAddr, dag.VertexName(v)) + // we don't implicitly create aliased providers + if strings.Contains(p, ".") { + log.Println("[DEBUG] not adding missing provider alias:", p) + continue + } - // create the missing top-level provider + log.Println("[DEBUG] adding missing provider:", p) + + // create the misisng top-level provider provider = t.Concrete(&NodeAbstractProvider{ - Addr: defaultAddr, - }).(GraphNodeProvider) + NameValue: p, + }).(dag.Vertex) - g.Add(provider) - m[key] = provider + m[key] = g.Add(provider) } return err @@ -331,26 +237,26 @@ func (t *ParentProviderTransformer) Transform(g *Graph) error { for _, v := range g.Vertices() { // Only care about providers pn, ok := v.(GraphNodeProvider) - if !ok { + if !ok || pn.ProviderName() == "" { continue } - // Also require non-empty path, since otherwise we're in the root - // module and so cannot have a parent. - if len(pn.Path()) <= 1 { - continue + // Also require a subpath, if there is no subpath then we + // can't have a parent. + if pn, ok := v.(GraphNodeSubPath); ok { + if len(normalizeModulePath(pn.Path())) <= 1 { + continue + } } // this provider may be disabled, but we can only get it's name from // the ProviderName string - addr := pn.ProviderAddr() - parentAddr, ok := addr.Inherited() - if ok { - parent := pm[parentAddr.String()] - if parent != nil { - g.Connect(dag.BasicEdge(v, parent)) - } + name := ResolveProviderName(strings.SplitN(pn.ProviderName(), " ", 2)[0], nil) + parent := pm[name] + if parent != nil { + g.Connect(dag.BasicEdge(v, parent)) } + } return nil } @@ -364,20 +270,20 @@ type PruneProviderTransformer struct{} func (t *PruneProviderTransformer) Transform(g *Graph) error { for _, v := range g.Vertices() { // We only care about providers - _, ok := v.(GraphNodeProvider) - if !ok { + pn, ok := v.(GraphNodeProvider) + if !ok || pn.ProviderName() == "" { continue } // ProxyProviders will have up edges, but we're now done with them in the graph if _, ok := v.(*graphNodeProxyProvider); ok { - log.Printf("[DEBUG] pruning proxy %s", dag.VertexName(v)) + log.Printf("[DEBUG] pruning proxy provider %s", dag.VertexName(v)) g.Remove(v) } // Remove providers with no dependencies. if g.UpEdges(v).Len() == 0 { - log.Printf("[DEBUG] pruning unused %s", dag.VertexName(v)) + log.Printf("[DEBUG] pruning unused provider %s", dag.VertexName(v)) g.Remove(v) } } @@ -385,24 +291,40 @@ func (t *PruneProviderTransformer) Transform(g *Graph) error { return nil } -func providerVertexMap(g *Graph) map[string]GraphNodeProvider { - m := make(map[string]GraphNodeProvider) +// providerMapKey is a helper that gives us the key to use for the +// maps returned by things such as providerVertexMap. +func providerMapKey(k string, v dag.Vertex) string { + if strings.Contains(k, "provider.") { + // this is already resolved + return k + } + + // we create a dummy provider to + var path []string + if sp, ok := v.(GraphNodeSubPath); ok { + path = normalizeModulePath(sp.Path()) + } + return ResolveProviderName(k, path) +} + +func providerVertexMap(g *Graph) map[string]dag.Vertex { + m := make(map[string]dag.Vertex) for _, v := range g.Vertices() { if pv, ok := v.(GraphNodeProvider); ok { - addr := pv.ProviderAddr() - m[addr.String()] = pv + // TODO: The Name may have meta info, like " (disabled)" + name := strings.SplitN(pv.Name(), " ", 2)[0] + m[name] = v } } return m } -func closeProviderVertexMap(g *Graph) map[string]GraphNodeCloseProvider { - m := make(map[string]GraphNodeCloseProvider) +func closeProviderVertexMap(g *Graph) map[string]dag.Vertex { + m := make(map[string]dag.Vertex) for _, v := range g.Vertices() { if pv, ok := v.(GraphNodeCloseProvider); ok { - addr := pv.CloseProviderAddr() - m[addr.String()] = pv + m[pv.CloseProviderName()] = v } } @@ -410,25 +332,16 @@ func closeProviderVertexMap(g *Graph) map[string]GraphNodeCloseProvider { } type graphNodeCloseProvider struct { - Addr addrs.AbsProviderConfig + ProviderNameValue string } -var ( - _ GraphNodeCloseProvider = (*graphNodeCloseProvider)(nil) -) - func (n *graphNodeCloseProvider) Name() string { - return n.Addr.String() + " (close)" -} - -// GraphNodeSubPath impl. -func (n *graphNodeCloseProvider) Path() addrs.ModuleInstance { - return n.Addr.Module + return n.ProviderNameValue + " (close)" } // GraphNodeEvalable impl. func (n *graphNodeCloseProvider) EvalTree() EvalNode { - return CloseProviderEvalTree(n.Addr) + return CloseProviderEvalTree(n.ProviderNameValue) } // GraphNodeDependable impl. @@ -436,8 +349,8 @@ func (n *graphNodeCloseProvider) DependableName() []string { return []string{n.Name()} } -func (n *graphNodeCloseProvider) CloseProviderAddr() addrs.AbsProviderConfig { - return n.Addr +func (n *graphNodeCloseProvider) CloseProviderName() string { + return n.ProviderNameValue } // GraphNodeDotter impl. @@ -467,24 +380,17 @@ func (n *graphNodeCloseProvider) RemoveIfNotTargeted() bool { // configurations, and are removed after all the resources have been connected // to their providers. type graphNodeProxyProvider struct { - addr addrs.AbsProviderConfig - target GraphNodeProvider + nameValue string + path []string + target GraphNodeProvider } -var ( - _ GraphNodeProvider = (*graphNodeProxyProvider)(nil) -) - -func (n *graphNodeProxyProvider) ProviderAddr() addrs.AbsProviderConfig { - return n.addr -} - -func (n *graphNodeProxyProvider) Path() addrs.ModuleInstance { - return n.addr.Module +func (n *graphNodeProxyProvider) ProviderName() string { + return n.Target().ProviderName() } func (n *graphNodeProxyProvider) Name() string { - return n.addr.String() + " (proxy)" + return ResolveProviderName(n.nameValue, n.path) } // find the concrete provider instance @@ -509,21 +415,26 @@ type ProviderConfigTransformer struct { // record providers that can be overriden with a proxy proxiable map[string]bool - // Config is the root node of the configuration tree to add providers from. - Config *configs.Config + // Module is the module to add resources from. + Module *module.Tree } func (t *ProviderConfigTransformer) Transform(g *Graph) error { - // If no configuration is given, we don't do anything - if t.Config == nil { + // If no module is given, we don't do anything + if t.Module == nil { return nil } + // If the module isn't loaded, that is simply an error + if !t.Module.Loaded() { + return errors.New("module must be loaded for ProviderConfigTransformer") + } + t.providers = make(map[string]GraphNodeProvider) t.proxiable = make(map[string]bool) // Start the transformation process - if err := t.transform(g, t.Config); err != nil { + if err := t.transform(g, t.Module); err != nil { return err } @@ -531,126 +442,95 @@ func (t *ProviderConfigTransformer) Transform(g *Graph) error { return t.attachProviderConfigs(g) } -func (t *ProviderConfigTransformer) transform(g *Graph, c *configs.Config) error { +func (t *ProviderConfigTransformer) transform(g *Graph, m *module.Tree) error { // If no config, do nothing - if c == nil { + if m == nil { return nil } // Add our resources - if err := t.transformSingle(g, c); err != nil { + if err := t.transformSingle(g, m); err != nil { return err } // Transform all the children. - for _, cc := range c.Children { - if err := t.transform(g, cc); err != nil { + for _, c := range m.Children() { + if err := t.transform(g, c); err != nil { return err } } return nil } -func (t *ProviderConfigTransformer) transformSingle(g *Graph, c *configs.Config) error { - // Get the module associated with this configuration tree node - mod := c.Module - staticPath := c.Path +func (t *ProviderConfigTransformer) transformSingle(g *Graph, m *module.Tree) error { + log.Printf("[TRACE] ProviderConfigTransformer: Starting for path: %v", m.Path()) - // We actually need a dynamic module path here, but we've not yet updated - // our graph builders enough to support expansion of module calls with - // "count" and "for_each" set, so for now we'll shim this by converting to - // a dynamic path with no keys. At the time of writing this is the only - // possible kind of dynamic path anyway. - path := make(addrs.ModuleInstance, len(staticPath)) - for i, name := range staticPath { - path[i] = addrs.ModuleInstanceStep{ - Name: name, - } + // Get the configuration for this module + conf := m.Config() + + // Build the path we're at + path := m.Path() + if len(path) > 0 { + path = append([]string{RootModuleName}, path...) } // add all providers from the configuration - for _, p := range mod.ProviderConfigs { - relAddr := p.Addr() - addr := relAddr.Absolute(path) + for _, p := range conf.ProviderConfigs { + name := p.Name + if p.Alias != "" { + name += "." + p.Alias + } - abstract := &NodeAbstractProvider{ - Addr: addr, - } - var v dag.Vertex - if t.Concrete != nil { - v = t.Concrete(abstract) - } else { - v = abstract - } + v := t.Concrete(&NodeAbstractProvider{ + NameValue: name, + PathValue: path, + }) // Add it to the graph g.Add(v) - key := addr.String() - t.providers[key] = v.(GraphNodeProvider) - - // A provider configuration is "proxyable" if its configuration is - // entirely empty. This means it's standing in for a provider - // configuration that must be passed in from the parent module. - // We decide this by evaluating the config with an empty schema; - // if this succeeds, then we know there's nothing in the body. - _, diags := p.Config.Content(&hcl.BodySchema{}) - t.proxiable[key] = !diags.HasErrors() + fullName := ResolveProviderName(name, path) + t.providers[fullName] = v.(GraphNodeProvider) + t.proxiable[fullName] = len(p.RawConfig.RawMap()) == 0 } // Now replace the provider nodes with proxy nodes if a provider was being // passed in, and create implicit proxies if there was no config. Any extra // proxies will be removed in the prune step. - return t.addProxyProviders(g, c) + return t.addProxyProviders(g, m) } -func (t *ProviderConfigTransformer) addProxyProviders(g *Graph, c *configs.Config) error { - path := c.Path +func (t *ProviderConfigTransformer) addProxyProviders(g *Graph, m *module.Tree) error { + path := m.Path() // can't add proxies at the root if len(path) == 0 { return nil } - parentPath, callAddr := path.Call() - parent := c.Parent + parentPath := path[:len(path)-1] + parent := t.Module.Child(parentPath) if parent == nil { return nil } - callName := callAddr.Name - var parentCfg *configs.ModuleCall - for name, mod := range parent.Module.ModuleCalls { - if name == callName { + var parentCfg *config.Module + for _, mod := range parent.Config().Modules { + if mod.Name == m.Name() { parentCfg = mod break } } - // We currently don't support count/for_each for modules and so we must - // shim our path and parentPath into module instances here so that the - // rest of Terraform can behave as if we do. This shimming should be - // removed later as part of implementing count/for_each for modules. - instPath := make(addrs.ModuleInstance, len(path)) - for i, name := range path { - instPath[i] = addrs.ModuleInstanceStep{Name: name} - } - parentInstPath := make(addrs.ModuleInstance, len(parentPath)) - for i, name := range parentPath { - parentInstPath[i] = addrs.ModuleInstanceStep{Name: name} - } - if parentCfg == nil { // this can't really happen during normal execution. - return fmt.Errorf("parent module config not found for %s", c.Path.String()) + return fmt.Errorf("parent module config not found for %s", m.Name()) } // Go through all the providers the parent is passing in, and add proxies to // the parent provider nodes. - for _, pair := range parentCfg.Providers { - fullAddr := pair.InChild.Addr().Absolute(instPath) - fullParentAddr := pair.InParent.Addr().Absolute(parentInstPath) - fullName := fullAddr.String() - fullParentName := fullParentAddr.String() + for name, parentName := range parentCfg.Providers { + fullName := ResolveProviderName(name, path) + fullParentName := ResolveProviderName(parentName, parentPath) parentProvider := t.providers[fullParentName] @@ -659,8 +539,9 @@ func (t *ProviderConfigTransformer) addProxyProviders(g *Graph, c *configs.Confi } proxy := &graphNodeProxyProvider{ - addr: fullAddr, - target: parentProvider, + nameValue: name, + path: path, + target: parentProvider, } concreteProvider := t.providers[fullName] @@ -672,8 +553,8 @@ func (t *ProviderConfigTransformer) addProxyProviders(g *Graph, c *configs.Confi continue } - // aliased configurations can't be implicitly passed in - if fullAddr.ProviderConfig.Alias != "" { + // aliased providers can't be implicitly passed in + if strings.Contains(name, ".") { continue } @@ -694,19 +575,27 @@ func (t *ProviderConfigTransformer) attachProviderConfigs(g *Graph) error { } // Determine what we're looking for - addr := apn.ProviderAddr() + path := normalizeModulePath(apn.Path())[1:] + name := apn.ProviderName() + log.Printf("[TRACE] Attach provider request: %#v %s", path, name) // Get the configuration. - mc := t.Config.DescendentForInstance(addr.Module) - if mc == nil { - log.Printf("[TRACE] ProviderConfigTransformer: no configuration available for %s", addr.String()) + tree := t.Module.Child(path) + if tree == nil { continue } // Go through the provider configs to find the matching config - for _, p := range mc.Module.ProviderConfigs { - if p.Name == addr.ProviderConfig.Type && p.Alias == addr.ProviderConfig.Alias { - log.Printf("[TRACE] ProviderConfigTransformer: attaching to %q provider configuration from %s", dag.VertexName(v), p.DeclRange) + for _, p := range tree.Config().ProviderConfigs { + // Build the name, which is "name.alias" if an alias exists + current := p.Name + if p.Alias != "" { + current += "." + p.Alias + } + + // If the configs match then attach! + if current == name { + log.Printf("[TRACE] Attaching provider config: %#v", p) apn.AttachProvider(p) break } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/transform_provisioner.go index fe4cf0e9..f49d8241 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_provisioner.go @@ -2,9 +2,6 @@ package terraform import ( "fmt" - "log" - - "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/dag" @@ -25,8 +22,8 @@ type GraphNodeCloseProvisioner interface { } // GraphNodeProvisionerConsumer is an interface that nodes that require -// a provisioner must implement. ProvisionedBy must return the names of the -// provisioners to use. +// a provisioner must implement. ProvisionedBy must return the name of the +// provisioner to use. type GraphNodeProvisionerConsumer interface { ProvisionedBy() []string } @@ -51,7 +48,6 @@ func (t *ProvisionerTransformer) Transform(g *Graph) error { continue } - log.Printf("[TRACE] ProvisionerTransformer: %s is provisioned by %s (%q)", dag.VertexName(v), key, dag.VertexName(m[key])) g.Connect(dag.BasicEdge(v, m[key])) } } @@ -87,9 +83,12 @@ func (t *MissingProvisionerTransformer) Transform(g *Graph) error { // If this node has a subpath, then we use that as a prefix // into our map to check for an existing provider. - path := addrs.RootModuleInstance + var path []string if sp, ok := pv.(GraphNodeSubPath); ok { - path = sp.Path() + raw := normalizeModulePath(sp.Path()) + if len(raw) > len(rootModulePath) { + path = raw + } } for _, p := range pv.ProvisionedBy() { @@ -102,7 +101,7 @@ func (t *MissingProvisionerTransformer) Transform(g *Graph) error { } if _, ok := supported[p]; !ok { - // If we don't support the provisioner type, we skip it. + // If we don't support the provisioner type, skip it. // Validation later will catch this as an error. continue } @@ -115,7 +114,6 @@ func (t *MissingProvisionerTransformer) Transform(g *Graph) error { // Add the missing provisioner node to the graph m[key] = g.Add(newV) - log.Printf("[TRACE] MissingProviderTransformer: added implicit provisioner %s, first implied by %s", key, dag.VertexName(v)) } } @@ -158,7 +156,10 @@ func (t *CloseProvisionerTransformer) Transform(g *Graph) error { func provisionerMapKey(k string, v dag.Vertex) string { pathPrefix := "" if sp, ok := v.(GraphNodeSubPath); ok { - pathPrefix = sp.Path().String() + "." + raw := normalizeModulePath(sp.Path()) + if len(raw) > len(rootModulePath) { + pathPrefix = modulePrefixStr(raw) + "." + } } return pathPrefix + k diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_reference.go b/vendor/github.com/hashicorp/terraform/terraform/transform_reference.go index 23bc8cd2..be8c7f96 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_reference.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_reference.go @@ -3,12 +3,8 @@ package terraform import ( "fmt" "log" + "strings" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/configs/configschema" - "github.com/hashicorp/terraform/lang" - - "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/dag" ) @@ -21,46 +17,35 @@ import ( // be referenced and other methods of referencing may still be possible (such // as by path!) type GraphNodeReferenceable interface { - GraphNodeSubPath - - // ReferenceableAddrs returns a list of addresses through which this can be - // referenced. - ReferenceableAddrs() []addrs.Referenceable + // ReferenceableName is the name by which this can be referenced. + // This can be either just the type, or include the field. Example: + // "aws_instance.bar" or "aws_instance.bar.id". + ReferenceableName() []string } // GraphNodeReferencer must be implemented by nodes that reference other // Terraform items and therefore depend on them. type GraphNodeReferencer interface { - GraphNodeSubPath - - // References returns a list of references made by this node, which - // include both a referenced address and source location information for - // the reference. - References() []*addrs.Reference + // References are the list of things that this node references. This + // can include fields or just the type, just like GraphNodeReferenceable + // above. + References() []string } -// GraphNodeReferenceOutside is an interface that can optionally be implemented. -// A node that implements it can specify that its own referenceable addresses -// and/or the addresses it references are in a different module than the -// node itself. +// GraphNodeReferenceGlobal is an interface that can optionally be +// implemented. If ReferenceGlobal returns true, then the References() +// and ReferenceableName() must be _fully qualified_ with "module.foo.bar" +// etc. // -// Any referenceable addresses returned by ReferenceableAddrs are interpreted -// relative to the returned selfPath. +// This allows a node to reference and be referenced by a specific name +// that may cross module boundaries. This can be very dangerous so use +// this wisely. // -// Any references returned by References are interpreted relative to the -// returned referencePath. -// -// It is valid but not required for either of these paths to match what is -// returned by method Path, though if both match the main Path then there -// is no reason to implement this method. -// -// The primary use-case for this is the nodes representing module input -// variables, since their expressions are resolved in terms of their calling -// module, but they are still referenced from their own module. -type GraphNodeReferenceOutside interface { - // ReferenceOutside returns a path in which any references from this node - // are resolved. - ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) +// The primary use case for this is module boundaries (variables coming in). +type GraphNodeReferenceGlobal interface { + // Set to true to signal that references and name are fully + // qualified. See the above docs for more information. + ReferenceGlobal() bool } // ReferenceTransformer is a GraphTransformer that connects all the @@ -173,91 +158,75 @@ func (t *PruneUnusedValuesTransformer) Transform(g *Graph) error { // ReferenceMap is a structure that can be used to efficiently check // for references on a graph. type ReferenceMap struct { - // vertices is a map from internal reference keys (as produced by the - // mapKey method) to one or more vertices that are identified by each key. - // - // A particular reference key might actually identify multiple vertices, - // e.g. in situations where one object is contained inside another. - vertices map[string][]dag.Vertex - - // edges is a map whose keys are a subset of the internal reference keys - // from "vertices", and whose values are the nodes that refer to each - // key. The values in this map are the referrers, while values in - // "verticies" are the referents. The keys in both cases are referents. - edges map[string][]dag.Vertex + // m is the mapping of referenceable name to list of verticies that + // implement that name. This is built on initialization. + references map[string][]dag.Vertex + referencedBy map[string][]dag.Vertex } -// References returns the set of vertices that the given vertex refers to, -// and any referenced addresses that do not have corresponding vertices. -func (m *ReferenceMap) References(v dag.Vertex) ([]dag.Vertex, []addrs.Referenceable) { +// References returns the list of vertices that this vertex +// references along with any missing references. +func (m *ReferenceMap) References(v dag.Vertex) ([]dag.Vertex, []string) { rn, ok := v.(GraphNodeReferencer) if !ok { return nil, nil } - if _, ok := v.(GraphNodeSubPath); !ok { - return nil, nil - } var matches []dag.Vertex - var missing []addrs.Referenceable + var missing []string + prefix := m.prefix(v) - for _, ref := range rn.References() { - subject := ref.Subject - - key := m.referenceMapKey(v, subject) - if _, exists := m.vertices[key]; !exists { - // If what we were looking for was a ResourceInstance then we - // might be in a resource-oriented graph rather than an - // instance-oriented graph, and so we'll see if we have the - // resource itself instead. - switch ri := subject.(type) { - case addrs.ResourceInstance: - subject = ri.ContainingResource() - case addrs.ResourceInstancePhase: - subject = ri.ContainingResource() - } - key = m.referenceMapKey(v, subject) - } - - vertices := m.vertices[key] - for _, rv := range vertices { - // don't include self-references - if rv == v { + for _, ns := range rn.References() { + found := false + for _, n := range strings.Split(ns, "/") { + n = prefix + n + parents, ok := m.references[n] + if !ok { continue } - matches = append(matches, rv) + + // Mark that we found a match + found = true + + for _, p := range parents { + // don't include self-references + if p == v { + continue + } + matches = append(matches, p) + } + + break } - if len(vertices) == 0 { - missing = append(missing, ref.Subject) + + if !found { + missing = append(missing, ns) } } return matches, missing } -// Referrers returns the set of vertices that refer to the given vertex. -func (m *ReferenceMap) Referrers(v dag.Vertex) []dag.Vertex { +// ReferencedBy returns the list of vertices that reference the +// vertex passed in. +func (m *ReferenceMap) ReferencedBy(v dag.Vertex) []dag.Vertex { rn, ok := v.(GraphNodeReferenceable) if !ok { return nil } - sp, ok := v.(GraphNodeSubPath) - if !ok { - return nil - } var matches []dag.Vertex - for _, addr := range rn.ReferenceableAddrs() { - key := m.mapKey(sp.Path(), addr) - referrers, ok := m.edges[key] + prefix := m.prefix(v) + for _, n := range rn.ReferenceableName() { + n = prefix + n + children, ok := m.referencedBy[n] if !ok { continue } - // If the referrer set includes our own given vertex then we skip, - // since we don't want to return self-references. + // Make sure this isn't a self reference, which isn't included selfRef := false - for _, p := range referrers { + for _, p := range children { if p == v { selfRef = true break @@ -267,77 +236,28 @@ func (m *ReferenceMap) Referrers(v dag.Vertex) []dag.Vertex { continue } - matches = append(matches, referrers...) + matches = append(matches, children...) } return matches } -func (m *ReferenceMap) mapKey(path addrs.ModuleInstance, addr addrs.Referenceable) string { - return fmt.Sprintf("%s|%s", path.String(), addr.String()) -} - -// vertexReferenceablePath returns the path in which the given vertex can be -// referenced. This is the path that its results from ReferenceableAddrs -// are considered to be relative to. -// -// Only GraphNodeSubPath implementations can be referenced, so this method will -// panic if the given vertex does not implement that interface. -func (m *ReferenceMap) vertexReferenceablePath(v dag.Vertex) addrs.ModuleInstance { - sp, ok := v.(GraphNodeSubPath) - if !ok { - // Only nodes with paths can participate in a reference map. - panic(fmt.Errorf("vertexMapKey on vertex type %T which doesn't implement GraphNodeSubPath", sp)) +func (m *ReferenceMap) prefix(v dag.Vertex) string { + // If the node is stating it is already fully qualified then + // we don't have to create the prefix! + if gn, ok := v.(GraphNodeReferenceGlobal); ok && gn.ReferenceGlobal() { + return "" } - if outside, ok := v.(GraphNodeReferenceOutside); ok { - // Vertex is referenced from a different module than where it was - // declared. - path, _ := outside.ReferenceOutside() - return path + // Create the prefix based on the path + var prefix string + if pn, ok := v.(GraphNodeSubPath); ok { + if path := normalizeModulePath(pn.Path()); len(path) > 1 { + prefix = modulePrefixStr(path) + "." + } } - // Vertex is referenced from the same module as where it was declared. - return sp.Path() -} - -// vertexReferencePath returns the path in which references _from_ the given -// vertex must be interpreted. -// -// Only GraphNodeSubPath implementations can have references, so this method -// will panic if the given vertex does not implement that interface. -func vertexReferencePath(referrer dag.Vertex) addrs.ModuleInstance { - sp, ok := referrer.(GraphNodeSubPath) - if !ok { - // Only nodes with paths can participate in a reference map. - panic(fmt.Errorf("vertexReferencePath on vertex type %T which doesn't implement GraphNodeSubPath", sp)) - } - - var path addrs.ModuleInstance - if outside, ok := referrer.(GraphNodeReferenceOutside); ok { - // Vertex makes references to objects in a different module than where - // it was declared. - _, path = outside.ReferenceOutside() - return path - } - - // Vertex makes references to objects in the same module as where it - // was declared. - return sp.Path() -} - -// referenceMapKey produces keys for the "edges" map. "referrer" is the vertex -// that the reference is from, and "addr" is the address of the object being -// referenced. -// -// The result is an opaque string that includes both the address of the given -// object and the address of the module instance that object belongs to. -// -// Only GraphNodeSubPath implementations can be referrers, so this method will -// panic if the given vertex does not implement that interface. -func (m *ReferenceMap) referenceMapKey(referrer dag.Vertex, addr addrs.Referenceable) string { - path := vertexReferencePath(referrer) - return m.mapKey(path, addr) + return prefix } // NewReferenceMap is used to create a new reference map for the @@ -346,82 +266,83 @@ func NewReferenceMap(vs []dag.Vertex) *ReferenceMap { var m ReferenceMap // Build the lookup table - vertices := make(map[string][]dag.Vertex) + refMap := make(map[string][]dag.Vertex) for _, v := range vs { - _, ok := v.(GraphNodeSubPath) - if !ok { - // Only nodes with paths can participate in a reference map. - continue - } - // We're only looking for referenceable nodes rn, ok := v.(GraphNodeReferenceable) if !ok { continue } - path := m.vertexReferenceablePath(v) - // Go through and cache them - for _, addr := range rn.ReferenceableAddrs() { - key := m.mapKey(path, addr) - vertices[key] = append(vertices[key], v) + prefix := m.prefix(v) + for _, n := range rn.ReferenceableName() { + n = prefix + n + refMap[n] = append(refMap[n], v) } - // Any node can be referenced by the address of the module it belongs - // to or any of that module's ancestors. - for _, addr := range path.Ancestors()[1:] { - // Can be referenced either as the specific call instance (with - // an instance key) or as the bare module call itself (the "module" - // block in the parent module that created the instance). - callPath, call := addr.Call() - callInstPath, callInst := addr.CallInstance() - callKey := m.mapKey(callPath, call) - callInstKey := m.mapKey(callInstPath, callInst) - vertices[callKey] = append(vertices[callKey], v) - vertices[callInstKey] = append(vertices[callInstKey], v) + // If there is a path, it is always referenceable by that. For + // example, if this is a referenceable thing at path []string{"foo"}, + // then it can be referenced at "module.foo" + if pn, ok := v.(GraphNodeSubPath); ok { + for _, p := range ReferenceModulePath(pn.Path()) { + refMap[p] = append(refMap[p], v) + } } } // Build the lookup table for referenced by - edges := make(map[string][]dag.Vertex) + refByMap := make(map[string][]dag.Vertex) for _, v := range vs { - _, ok := v.(GraphNodeSubPath) - if !ok { - // Only nodes with paths can participate in a reference map. - continue - } - + // We're only looking for referenceable nodes rn, ok := v.(GraphNodeReferencer) if !ok { - // We're only looking for referenceable nodes continue } // Go through and cache them - for _, ref := range rn.References() { - if ref.Subject == nil { - // Should never happen - panic(fmt.Sprintf("%T.References returned reference with nil subject", rn)) - } - key := m.referenceMapKey(v, ref.Subject) - edges[key] = append(edges[key], v) + prefix := m.prefix(v) + for _, n := range rn.References() { + n = prefix + n + refByMap[n] = append(refByMap[n], v) } } - m.vertices = vertices - m.edges = edges + m.references = refMap + m.referencedBy = refByMap return &m } +// Returns the reference name for a module path. The path "foo" would return +// "module.foo". If this is a deeply nested module, it will be every parent +// as well. For example: ["foo", "bar"] would return both "module.foo" and +// "module.foo.module.bar" +func ReferenceModulePath(p []string) []string { + p = normalizeModulePath(p) + if len(p) == 1 { + // Root, no name + return nil + } + + result := make([]string, 0, len(p)-1) + for i := len(p); i > 1; i-- { + result = append(result, modulePrefixStr(p[:i])) + } + + return result +} + // ReferencesFromConfig returns the references that a configuration has // based on the interpolated variables in a configuration. -func ReferencesFromConfig(body hcl.Body, schema *configschema.Block) []*addrs.Reference { - if body == nil { - return nil +func ReferencesFromConfig(c *config.RawConfig) []string { + var result []string + for _, v := range c.Variables { + if r := ReferenceFromInterpolatedVar(v); len(r) > 0 { + result = append(result, r...) + } } - refs, _ := lang.ReferencesInBlock(body, schema) - return refs + + return result } // ReferenceFromInterpolatedVar returns the reference from this variable, @@ -457,31 +378,18 @@ func ReferenceFromInterpolatedVar(v config.InterpolatedVariable) []string { } } -// appendResourceDestroyReferences identifies resource and resource instance -// references in the given slice and appends to it the "destroy-phase" -// equivalents of those references, returning the result. -// -// This can be used in the References implementation for a node which must also -// depend on the destruction of anything it references. -func appendResourceDestroyReferences(refs []*addrs.Reference) []*addrs.Reference { - given := refs - for _, ref := range given { - switch tr := ref.Subject.(type) { - case addrs.Resource: - newRef := *ref // shallow copy - newRef.Subject = tr.Phase(addrs.ResourceInstancePhaseDestroy) - refs = append(refs, &newRef) - case addrs.ResourceInstance: - newRef := *ref // shallow copy - newRef.Subject = tr.Phase(addrs.ResourceInstancePhaseDestroy) - refs = append(refs, &newRef) - } +func modulePrefixStr(p []string) string { + // strip "root" + if len(p) > 0 && p[0] == rootModulePath[0] { + p = p[1:] } - return refs -} -func modulePrefixStr(p addrs.ModuleInstance) string { - return p.String() + parts := make([]string, 0, len(p)*2) + for _, p := range p { + parts = append(parts, "module", p) + } + + return strings.Join(parts, ".") } func modulePrefixList(result []string, prefix string) []string { diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_removed_modules.go b/vendor/github.com/hashicorp/terraform/terraform/transform_removed_modules.go index ee71387e..2e05edba 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_removed_modules.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_removed_modules.go @@ -3,15 +3,14 @@ package terraform import ( "log" - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/states" + "github.com/hashicorp/terraform/config/module" ) -// RemovedModuleTransformer implements GraphTransformer to add nodes indicating +// RemoveModuleTransformer implements GraphTransformer to add nodes indicating // when a module was removed from the configuration. type RemovedModuleTransformer struct { - Config *configs.Config // root node in the config tree - State *states.State + Module *module.Tree // root module + State *State } func (t *RemovedModuleTransformer) Transform(g *Graph) error { @@ -21,13 +20,13 @@ func (t *RemovedModuleTransformer) Transform(g *Graph) error { } for _, m := range t.State.Modules { - cc := t.Config.DescendentForInstance(m.Addr) - if cc != nil { + c := t.Module.Child(m.Path[1:]) + if c != nil { continue } - log.Printf("[DEBUG] %s is no longer in configuration\n", m.Addr) - g.Add(&NodeModuleRemoved{Addr: m.Addr}) + log.Printf("[DEBUG] module %s no longer in config\n", modulePrefixStr(m.Path)) + g.Add(&NodeModuleRemoved{PathValue: m.Path}) } return nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_resource_count.go b/vendor/github.com/hashicorp/terraform/terraform/transform_resource_count.go index 11237909..e528b37b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_resource_count.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_resource_count.go @@ -1,8 +1,8 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs/configschema" + "fmt" + "github.com/hashicorp/terraform/dag" ) @@ -11,44 +11,41 @@ import ( // // This assumes that the count is already interpolated. type ResourceCountTransformer struct { - Concrete ConcreteResourceInstanceNodeFunc - Schema *configschema.Block + Concrete ConcreteResourceNodeFunc - // Count is either the number of indexed instances to create, or -1 to - // indicate that count is not set at all and thus a no-key instance should - // be created. Count int - Addr addrs.AbsResource + Addr *ResourceAddress } func (t *ResourceCountTransformer) Transform(g *Graph) error { + // Don't allow the count to be negative if t.Count < 0 { - // Negative count indicates that count is not set at all. - addr := t.Addr.Instance(addrs.NoKey) - - abstract := NewNodeAbstractResourceInstance(addr) - abstract.Schema = t.Schema - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - - g.Add(node) - return nil + return fmt.Errorf("negative count: %d", t.Count) } // For each count, build and add the node for i := 0; i < t.Count; i++ { - key := addrs.IntKey(i) - addr := t.Addr.Instance(key) + // Set the index. If our count is 1 we special case it so that + // we handle the "resource.0" and "resource" boundary properly. + index := i + if t.Count == 1 { + index = -1 + } - abstract := NewNodeAbstractResourceInstance(addr) - abstract.Schema = t.Schema + // Build the resource address + addr := t.Addr.Copy() + addr.Index = index + + // Build the abstract node and the concrete one + abstract := &NodeAbstractResource{ + Addr: addr, + } var node dag.Vertex = abstract if f := t.Concrete; f != nil { node = f(abstract) } + // Add it to the graph g.Add(node) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_state.go b/vendor/github.com/hashicorp/terraform/terraform/transform_state.go index 0b52347d..471cd746 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_state.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_state.go @@ -1,9 +1,10 @@ package terraform import ( + "fmt" "log" - "github.com/hashicorp/terraform/states" + "github.com/hashicorp/terraform/dag" ) // StateTransformer is a GraphTransformer that adds the elements of @@ -12,62 +13,52 @@ import ( // This transform is used for example by the DestroyPlanGraphBuilder to ensure // that only resources that are in the state are represented in the graph. type StateTransformer struct { - // ConcreteCurrent and ConcreteDeposed are used to specialize the abstract - // resource instance nodes that this transformer will create. - // - // If either of these is nil, the objects of that type will be skipped and - // not added to the graph at all. It doesn't make sense to use this - // transformer without setting at least one of these, since that would - // skip everything and thus be a no-op. - ConcreteCurrent ConcreteResourceInstanceNodeFunc - ConcreteDeposed ConcreteResourceInstanceDeposedNodeFunc + Concrete ConcreteResourceNodeFunc - State *states.State + State *State } func (t *StateTransformer) Transform(g *Graph) error { - if !t.State.HasResources() { - log.Printf("[TRACE] StateTransformer: state is empty, so nothing to do") + // If the state is nil or empty (nil is empty) then do nothing + if t.State.Empty() { return nil } - switch { - case t.ConcreteCurrent != nil && t.ConcreteDeposed != nil: - log.Printf("[TRACE] StateTransformer: creating nodes for both current and deposed instance objects") - case t.ConcreteCurrent != nil: - log.Printf("[TRACE] StateTransformer: creating nodes for current instance objects only") - case t.ConcreteDeposed != nil: - log.Printf("[TRACE] StateTransformer: creating nodes for deposed instance objects only") - default: - log.Printf("[TRACE] StateTransformer: pointless no-op call, creating no nodes at all") + // Go through all the modules in the diff. + log.Printf("[TRACE] StateTransformer: starting") + var nodes []dag.Vertex + for _, ms := range t.State.Modules { + log.Printf("[TRACE] StateTransformer: Module: %v", ms.Path) + + // Go through all the resources in this module. + for name, rs := range ms.Resources { + log.Printf("[TRACE] StateTransformer: Resource %q: %#v", name, rs) + + // Add the resource to the graph + addr, err := parseResourceAddressInternal(name) + if err != nil { + panic(fmt.Sprintf( + "Error parsing internal name, this is a bug: %q", name)) + } + + // Very important: add the module path for this resource to + // the address. Remove "root" from it. + addr.Path = ms.Path[1:] + + // Add the resource to the graph + abstract := &NodeAbstractResource{Addr: addr} + var node dag.Vertex = abstract + if f := t.Concrete; f != nil { + node = f(abstract) + } + + nodes = append(nodes, node) + } } - for _, ms := range t.State.Modules { - moduleAddr := ms.Addr - - for _, rs := range ms.Resources { - resourceAddr := rs.Addr.Absolute(moduleAddr) - - for key, is := range rs.Instances { - addr := resourceAddr.Instance(key) - - if obj := is.Current; obj != nil && t.ConcreteCurrent != nil { - abstract := NewNodeAbstractResourceInstance(addr) - node := t.ConcreteCurrent(abstract) - g.Add(node) - log.Printf("[TRACE] StateTransformer: added %T for %s current object", node, addr) - } - - if t.ConcreteDeposed != nil { - for dk := range is.Deposed { - abstract := NewNodeAbstractResourceInstance(addr) - node := t.ConcreteDeposed(abstract, dk) - g.Add(node) - log.Printf("[TRACE] StateTransformer: added %T for %s deposed object %s", node, addr, dk) - } - } - } - } + // Add all the nodes to the graph + for _, n := range nodes { + g.Add(n) } return nil diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_targets.go b/vendor/github.com/hashicorp/terraform/terraform/transform_targets.go index d25274e6..af6defe3 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_targets.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_targets.go @@ -3,7 +3,6 @@ package terraform import ( "log" - "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/dag" ) @@ -13,7 +12,7 @@ import ( // provided will contain every target provided, and each implementing graph // node must filter this list to targets considered relevant. type GraphNodeTargetable interface { - SetTargets([]addrs.Targetable) + SetTargets([]ResourceAddress) } // GraphNodeTargetDownstream is an interface for graph nodes that need to @@ -36,7 +35,11 @@ type GraphNodeTargetDownstream interface { // their dependencies. type TargetsTransformer struct { // List of targeted resource names specified by the user - Targets []addrs.Targetable + Targets []string + + // List of parsed targets, provided by callers like ResourceCountTransform + // that already have the targets parsed + ParsedTargets []ResourceAddress // If set, the index portions of resource addresses will be ignored // for comparison. This is used when transforming a graph where @@ -50,8 +53,17 @@ type TargetsTransformer struct { } func (t *TargetsTransformer) Transform(g *Graph) error { - if len(t.Targets) > 0 { - targetedNodes, err := t.selectTargetedNodes(g, t.Targets) + if len(t.Targets) > 0 && len(t.ParsedTargets) == 0 { + addrs, err := t.parseTargetAddresses() + if err != nil { + return err + } + + t.ParsedTargets = addrs + } + + if len(t.ParsedTargets) > 0 { + targetedNodes, err := t.selectTargetedNodes(g, t.ParsedTargets) if err != nil { return err } @@ -76,10 +88,24 @@ func (t *TargetsTransformer) Transform(g *Graph) error { return nil } -// Returns a set of targeted nodes. A targeted node is either addressed -// directly, address indirectly via its container, or it's a dependency of a -// targeted node. Destroy mode keeps dependents instead of dependencies. -func (t *TargetsTransformer) selectTargetedNodes(g *Graph, addrs []addrs.Targetable) (*dag.Set, error) { +func (t *TargetsTransformer) parseTargetAddresses() ([]ResourceAddress, error) { + addrs := make([]ResourceAddress, len(t.Targets)) + for i, target := range t.Targets { + ta, err := ParseResourceAddress(target) + if err != nil { + return nil, err + } + addrs[i] = *ta + } + + return addrs, nil +} + +// Returns the list of targeted nodes. A targeted node is either addressed +// directly, or is an Ancestor of a targeted node. Destroy mode keeps +// Descendents instead of Ancestors. +func (t *TargetsTransformer) selectTargetedNodes( + g *Graph, addrs []ResourceAddress) (*dag.Set, error) { targetedNodes := new(dag.Set) vertices := g.Vertices() @@ -128,12 +154,6 @@ func (t *TargetsTransformer) addDependencies(targetedNodes *dag.Set, g *Graph) ( vertices := queue queue = nil // ready to append for next iteration if neccessary for _, v := range vertices { - // providers don't cause transitive dependencies, so don't target - // downstream from them. - if _, ok := v.(GraphNodeProvider); ok { - continue - } - dependers := g.UpEdges(v) if dependers == nil { // indicates that there are no up edges for this node, so @@ -220,34 +240,21 @@ func filterPartialOutputs(v interface{}, targetedNodes *dag.Set, g *Graph) bool return true } -func (t *TargetsTransformer) nodeIsTarget(v dag.Vertex, targets []addrs.Targetable) bool { - var vertexAddr addrs.Targetable - switch r := v.(type) { - case GraphNodeResourceInstance: - vertexAddr = r.ResourceInstanceAddr() - case GraphNodeResource: - vertexAddr = r.ResourceAddr() - default: - // Only resource and resource instance nodes can be targeted. - return false - } - _, ok := v.(GraphNodeResource) +func (t *TargetsTransformer) nodeIsTarget( + v dag.Vertex, addrs []ResourceAddress) bool { + r, ok := v.(GraphNodeResource) if !ok { return false } - for _, targetAddr := range targets { + addr := r.ResourceAddr() + for _, targetAddr := range addrs { if t.IgnoreIndices { - // If we're ignoring indices then we'll convert any resource instance - // addresses into resource addresses. We don't need to convert - // vertexAddr because instance addresses are contained within - // their associated resources, and so .TargetContains will take - // care of this for us. - if instance, isInstance := targetAddr.(addrs.AbsResourceInstance); isInstance { - targetAddr = instance.ContainingResource() - } + // targetAddr is not a pointer, so we can safely mutate it without + // interfering with references elsewhere. + targetAddr.Index = -1 } - if targetAddr.TargetContains(vertexAddr) { + if targetAddr.Contains(addr) { return true } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_variable.go b/vendor/github.com/hashicorp/terraform/terraform/transform_variable.go index 05daa513..b31e2c76 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_variable.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_variable.go @@ -1,8 +1,7 @@ package terraform import ( - "github.com/hashicorp/terraform/addrs" - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/terraform/config/module" ) // RootVariableTransformer is a GraphTransformer that adds all the root @@ -12,27 +11,28 @@ import ( // graph since downstream things that depend on them must be able to // reach them. type RootVariableTransformer struct { - Config *configs.Config + Module *module.Tree } func (t *RootVariableTransformer) Transform(g *Graph) error { - // We can have no variables if we have no config. - if t.Config == nil { + // If no config, no variables + if t.Module == nil { return nil } - // We're only considering root module variables here, since child - // module variables are handled by ModuleVariableTransformer. - vars := t.Config.Module.Variables + // If we have no vars, we're done! + vars := t.Module.Config().Variables + if len(vars) == 0 { + return nil + } // Add all variables here for _, v := range vars { node := &NodeRootVariable{ - Addr: addrs.InputVariable{ - Name: v.Name, - }, Config: v, } + + // Add it! g.Add(node) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/ui_output_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/ui_output_provisioner.go index fff964f4..878a0312 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/ui_output_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/terraform/ui_output_provisioner.go @@ -1,19 +1,15 @@ package terraform -import ( - "github.com/hashicorp/terraform/addrs" -) - // ProvisionerUIOutput is an implementation of UIOutput that calls a hook // for the output so that the hooks can handle it. type ProvisionerUIOutput struct { - InstanceAddr addrs.AbsResourceInstance - ProvisionerType string - Hooks []Hook + Info *InstanceInfo + Type string + Hooks []Hook } func (o *ProvisionerUIOutput) Output(msg string) { for _, h := range o.Hooks { - h.ProvisionOutput(o.InstanceAddr, o.ProvisionerType, msg) + h.ProvisionOutput(o.Info, o.Type, msg) } } diff --git a/vendor/github.com/hashicorp/terraform/terraform/valuesourcetype_string.go b/vendor/github.com/hashicorp/terraform/terraform/valuesourcetype_string.go deleted file mode 100644 index 1380c851..00000000 --- a/vendor/github.com/hashicorp/terraform/terraform/valuesourcetype_string.go +++ /dev/null @@ -1,44 +0,0 @@ -// Code generated by "stringer -type ValueSourceType"; DO NOT EDIT. - -package terraform - -import "strconv" - -const ( - _ValueSourceType_name_0 = "ValueFromUnknown" - _ValueSourceType_name_1 = "ValueFromCLIArg" - _ValueSourceType_name_2 = "ValueFromConfig" - _ValueSourceType_name_3 = "ValueFromEnvVarValueFromAutoFile" - _ValueSourceType_name_4 = "ValueFromInput" - _ValueSourceType_name_5 = "ValueFromNamedFile" - _ValueSourceType_name_6 = "ValueFromPlan" - _ValueSourceType_name_7 = "ValueFromCaller" -) - -var ( - _ValueSourceType_index_3 = [...]uint8{0, 15, 32} -) - -func (i ValueSourceType) String() string { - switch { - case i == 0: - return _ValueSourceType_name_0 - case i == 65: - return _ValueSourceType_name_1 - case i == 67: - return _ValueSourceType_name_2 - case 69 <= i && i <= 70: - i -= 69 - return _ValueSourceType_name_3[_ValueSourceType_index_3[i]:_ValueSourceType_index_3[i+1]] - case i == 73: - return _ValueSourceType_name_4 - case i == 78: - return _ValueSourceType_name_5 - case i == 80: - return _ValueSourceType_name_6 - case i == 83: - return _ValueSourceType_name_7 - default: - return "ValueSourceType(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/variables.go b/vendor/github.com/hashicorp/terraform/terraform/variables.go index 75531b2b..300f2adb 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/variables.go +++ b/vendor/github.com/hashicorp/terraform/terraform/variables.go @@ -2,312 +2,165 @@ package terraform import ( "fmt" + "os" + "strings" - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform/configs" - "github.com/hashicorp/terraform/tfdiags" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" + "github.com/hashicorp/terraform/helper/hilmapstructure" ) -// InputValue represents a value for a variable in the root module, provided -// as part of the definition of an operation. -type InputValue struct { - Value cty.Value - SourceType ValueSourceType - - // SourceRange provides source location information for values whose - // SourceType is either ValueFromConfig or ValueFromFile. It is not - // populated for other source types, and so should not be used. - SourceRange tfdiags.SourceRange -} - -// ValueSourceType describes what broad category of source location provided -// a particular value. -type ValueSourceType rune - -const ( - // ValueFromUnknown is the zero value of ValueSourceType and is not valid. - ValueFromUnknown ValueSourceType = 0 - - // ValueFromConfig indicates that a value came from a .tf or .tf.json file, - // e.g. the default value defined for a variable. - ValueFromConfig ValueSourceType = 'C' - - // ValueFromAutoFile indicates that a value came from a "values file", like - // a .tfvars file, that was implicitly loaded by naming convention. - ValueFromAutoFile ValueSourceType = 'F' - - // ValueFromNamedFile indicates that a value came from a named "values file", - // like a .tfvars file, that was passed explicitly on the command line (e.g. - // -var-file=foo.tfvars). - ValueFromNamedFile ValueSourceType = 'N' - - // ValueFromCLIArg indicates that the value was provided directly in - // a CLI argument. The name of this argument is not recorded and so it must - // be inferred from context. - ValueFromCLIArg ValueSourceType = 'A' - - // ValueFromEnvVar indicates that the value was provided via an environment - // variable. The name of the variable is not recorded and so it must be - // inferred from context. - ValueFromEnvVar ValueSourceType = 'E' - - // ValueFromInput indicates that the value was provided at an interactive - // input prompt. - ValueFromInput ValueSourceType = 'I' - - // ValueFromPlan indicates that the value was retrieved from a stored plan. - ValueFromPlan ValueSourceType = 'P' - - // ValueFromCaller indicates that the value was explicitly overridden by - // a caller to Context.SetVariable after the context was constructed. - ValueFromCaller ValueSourceType = 'S' -) - -func (v *InputValue) GoString() string { - if (v.SourceRange != tfdiags.SourceRange{}) { - return fmt.Sprintf("&terraform.InputValue{Value: %#v, SourceType: %#v, SourceRange: %#v}", v.Value, v.SourceType, v.SourceRange) - } else { - return fmt.Sprintf("&terraform.InputValue{Value: %#v, SourceType: %#v}", v.Value, v.SourceType) - } -} - -func (v ValueSourceType) GoString() string { - return fmt.Sprintf("terraform.%s", v) -} - -//go:generate stringer -type ValueSourceType - -// InputValues is a map of InputValue instances. -type InputValues map[string]*InputValue - -// InputValuesFromCaller turns the given map of naked values into an -// InputValues that attributes each value to "a caller", using the source -// type ValueFromCaller. This is primarily useful for testing purposes. +// Variables returns the fully loaded set of variables to use with +// ContextOpts and NewContext, loading any additional variables from +// the environment or any other sources. // -// This should not be used as a general way to convert map[string]cty.Value -// into InputValues, since in most real cases we want to set a suitable -// other SourceType and possibly SourceRange value. -func InputValuesFromCaller(vals map[string]cty.Value) InputValues { - ret := make(InputValues, len(vals)) - for k, v := range vals { - ret[k] = &InputValue{ - Value: v, - SourceType: ValueFromCaller, - } - } - return ret -} +// The given module tree doesn't need to be loaded. +func Variables( + m *module.Tree, + override map[string]interface{}) (map[string]interface{}, error) { + result := make(map[string]interface{}) -// Override merges the given value maps with the receiver, overriding any -// conflicting keys so that the latest definition wins. -func (vv InputValues) Override(others ...InputValues) InputValues { - // FIXME: This should check to see if any of the values are maps and - // merge them if so, in order to preserve the behavior from prior to - // Terraform 0.12. - ret := make(InputValues) - for k, v := range vv { - ret[k] = v - } - for _, other := range others { - for k, v := range other { - ret[k] = v - } - } - return ret -} + // Variables are loaded in the following sequence. Each additional step + // will override conflicting variable keys from prior steps: + // + // * Take default values from config + // * Take values from TF_VAR_x env vars + // * Take values specified in the "override" param which is usually + // from -var, -var-file, etc. + // -// JustValues returns a map that just includes the values, discarding the -// source information. -func (vv InputValues) JustValues() map[string]cty.Value { - ret := make(map[string]cty.Value, len(vv)) - for k, v := range vv { - ret[k] = v.Value - } - return ret -} - -// DefaultVariableValues returns an InputValues map representing the default -// values specified for variables in the given configuration map. -func DefaultVariableValues(configs map[string]*configs.Variable) InputValues { - ret := make(InputValues) - for k, c := range configs { - if c.Default == cty.NilVal { - continue - } - ret[k] = &InputValue{ - Value: c.Default, - SourceType: ValueFromConfig, - SourceRange: tfdiags.SourceRangeFromHCL(c.DeclRange), - } - } - return ret -} - -// SameValues returns true if the given InputValues has the same values as -// the receiever, disregarding the source types and source ranges. -// -// Values are compared using the cty "RawEquals" method, which means that -// unknown values can be considered equal to one another if they are of the -// same type. -func (vv InputValues) SameValues(other InputValues) bool { - if len(vv) != len(other) { - return false - } - - for k, v := range vv { - ov, exists := other[k] - if !exists { - return false - } - if !v.Value.RawEquals(ov.Value) { - return false - } - } - - return true -} - -// HasValues returns true if the reciever has the same values as in the given -// map, disregarding the source types and source ranges. -// -// Values are compared using the cty "RawEquals" method, which means that -// unknown values can be considered equal to one another if they are of the -// same type. -func (vv InputValues) HasValues(vals map[string]cty.Value) bool { - if len(vv) != len(vals) { - return false - } - - for k, v := range vv { - oVal, exists := vals[k] - if !exists { - return false - } - if !v.Value.RawEquals(oVal) { - return false - } - } - - return true -} - -// Identical returns true if the given InputValues has the same values, -// source types, and source ranges as the receiver. -// -// Values are compared using the cty "RawEquals" method, which means that -// unknown values can be considered equal to one another if they are of the -// same type. -// -// This method is primarily for testing. For most practical purposes, it's -// better to use SameValues or HasValues. -func (vv InputValues) Identical(other InputValues) bool { - if len(vv) != len(other) { - return false - } - - for k, v := range vv { - ov, exists := other[k] - if !exists { - return false - } - if !v.Value.RawEquals(ov.Value) { - return false - } - if v.SourceType != ov.SourceType { - return false - } - if v.SourceRange != ov.SourceRange { - return false - } - } - - return true -} - -// checkInputVariables ensures that variable values supplied at the UI conform -// to their corresponding declarations in configuration. -// -// The set of values is considered valid only if the returned diagnostics -// does not contain errors. A valid set of values may still produce warnings, -// which should be returned to the user. -func checkInputVariables(vcs map[string]*configs.Variable, vs InputValues) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - for name, vc := range vcs { - val, isSet := vs[name] - if !isSet { - // Always an error, since the caller should already have included - // default values from the configuration in the values map. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unassigned variable", - fmt.Sprintf("The input variable %q has not been assigned a value. This is a bug in Terraform; please report it in a GitHub issue.", name), - )) + // First load from the config + for _, v := range m.Config().Variables { + // If the var has no default, ignore + if v.Default == nil { continue } - wantType := vc.Type + // If the type isn't a string, we use it as-is since it is a rich type + if v.Type() != config.VariableTypeString { + result[v.Name] = v.Default + continue + } - // A given value is valid if it can convert to the desired type. - _, err := convert.Convert(val.Value, wantType) - if err != nil { - switch val.SourceType { - case ValueFromConfig, ValueFromAutoFile, ValueFromNamedFile: - // We have source location information for these. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid value for input variable", - Detail: fmt.Sprintf("The given value is not valid for variable %q: %s.", name, err), - Subject: val.SourceRange.ToHCL().Ptr(), - }) - case ValueFromEnvVar: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid value for input variable", - fmt.Sprintf("The environment variable TF_VAR_%s does not contain a valid value for variable %q: %s.", name, name, err), - )) - case ValueFromCLIArg: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid value for input variable", - fmt.Sprintf("The argument -var=\"%s=...\" does not contain a valid value for variable %q: %s.", name, name, err), - )) - case ValueFromInput: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid value for input variable", - fmt.Sprintf("The value entered for variable %q is not valid: %s.", name, err), - )) + // v.Default has already been parsed as HCL but it may be an int type + switch typedDefault := v.Default.(type) { + case string: + if typedDefault == "" { + continue + } + result[v.Name] = typedDefault + case int, int64: + result[v.Name] = fmt.Sprintf("%d", typedDefault) + case float32, float64: + result[v.Name] = fmt.Sprintf("%f", typedDefault) + case bool: + result[v.Name] = fmt.Sprintf("%t", typedDefault) + default: + panic(fmt.Sprintf( + "Unknown default var type: %T\n\n"+ + "THIS IS A BUG. Please report it.", + v.Default)) + } + } + + // Load from env vars + for _, v := range os.Environ() { + if !strings.HasPrefix(v, VarEnvPrefix) { + continue + } + + // Strip off the prefix and get the value after the first "=" + idx := strings.Index(v, "=") + k := v[len(VarEnvPrefix):idx] + v = v[idx+1:] + + // Override the configuration-default values. Note that *not* finding the variable + // in configuration is OK, as we don't want to preclude people from having multiple + // sets of TF_VAR_whatever in their environment even if it is a little weird. + for _, schema := range m.Config().Variables { + if schema.Name != k { + continue + } + + varType := schema.Type() + varVal, err := parseVariableAsHCL(k, v, varType) + if err != nil { + return nil, err + } + + switch varType { + case config.VariableTypeMap: + if err := varSetMap(result, k, varVal); err != nil { + return nil, err + } default: - // The above gets us good coverage for the situations users - // are likely to encounter with their own inputs. The other - // cases are generally implementation bugs, so we'll just - // use a generic error for these. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid value for input variable", - fmt.Sprintf("The value provided for variable %q is not valid: %s.", name, err), - )) + result[k] = varVal } } } - // Check for any variables that are assigned without being configured. - // This is always an implementation error in the caller, because we - // expect undefined variables to be caught during context construction - // where there is better context to report it well. - for name := range vs { - if _, defined := vcs[name]; !defined { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Value assigned to undeclared variable", - fmt.Sprintf("A value was assigned to an undeclared input variable %q.", name), - )) + // Load from overrides + for k, v := range override { + for _, schema := range m.Config().Variables { + if schema.Name != k { + continue + } + + switch schema.Type() { + case config.VariableTypeList: + result[k] = v + case config.VariableTypeMap: + if err := varSetMap(result, k, v); err != nil { + return nil, err + } + case config.VariableTypeString: + // Convert to a string and set. We don't catch any errors + // here because the validation step later should catch + // any type errors. + var strVal string + if err := hilmapstructure.WeakDecode(v, &strVal); err == nil { + result[k] = strVal + } else { + result[k] = v + } + default: + panic(fmt.Sprintf( + "Unhandled var type: %T\n\n"+ + "THIS IS A BUG. Please report it.", + schema.Type())) + } } } - return diags + return result, nil +} + +// varSetMap sets or merges the map in "v" with the key "k" in the +// "current" set of variables. This is just a private function to remove +// duplicate logic in Variables +func varSetMap(current map[string]interface{}, k string, v interface{}) error { + existing, ok := current[k] + if !ok { + current[k] = v + return nil + } + + existingMap, ok := existing.(map[string]interface{}) + if !ok { + panic(fmt.Sprintf("%q is not a map, this is a bug in Terraform.", k)) + } + + switch typedV := v.(type) { + case []map[string]interface{}: + for newKey, newVal := range typedV[0] { + existingMap[newKey] = newVal + } + case map[string]interface{}: + for newKey, newVal := range typedV { + existingMap[newKey] = newVal + } + default: + return fmt.Errorf("variable %q should be type map, got %s", k, hclTypeName(v)) + } + return nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/version_required.go b/vendor/github.com/hashicorp/terraform/terraform/version_required.go index 61423c21..1f430457 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/version_required.go +++ b/vendor/github.com/hashicorp/terraform/terraform/version_required.go @@ -3,60 +3,69 @@ package terraform import ( "fmt" - "github.com/hashicorp/hcl2/hcl" - "github.com/hashicorp/terraform/tfdiags" - - "github.com/hashicorp/terraform/configs" + "github.com/hashicorp/go-version" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" tfversion "github.com/hashicorp/terraform/version" ) -// CheckCoreVersionRequirements visits each of the modules in the given -// configuration tree and verifies that any given Core version constraints -// match with the version of Terraform Core that is being used. +// CheckRequiredVersion verifies that any version requirements specified by +// the configuration are met. // -// The returned diagnostics will contain errors if any constraints do not match. -// The returned diagnostics might also return warnings, which should be -// displayed to the user. -func CheckCoreVersionRequirements(config *configs.Config) tfdiags.Diagnostics { - if config == nil { - return nil - } - - var diags tfdiags.Diagnostics - module := config.Module - - for _, constraint := range module.CoreVersionConstraints { - if !constraint.Required.Check(tfversion.SemVer) { - switch { - case len(config.Path) == 0: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported Terraform Core version", - Detail: fmt.Sprintf( - "This configuration does not support Terraform version %s. To proceed, either choose another supported Terraform version or update this version constraint. Version constraints are normally set for good reason, so updating the constraint may lead to other errors or unexpected behavior.", - tfversion.String(), - ), - Subject: &constraint.DeclRange, - }) - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported Terraform Core version", - Detail: fmt.Sprintf( - "Module %s (from %s) does not support Terraform version %s. To proceed, either choose another supported Terraform version or update this version constraint. Version constraints are normally set for good reason, so updating the constraint may lead to other errors or unexpected behavior.", - config.Path, config.SourceAddr, tfversion.String(), - ), - Subject: &constraint.DeclRange, - }) - } +// This checks the root module as well as any additional version requirements +// from child modules. +// +// This is tested in context_test.go. +func CheckRequiredVersion(m *module.Tree) error { + // Check any children + for _, c := range m.Children() { + if err := CheckRequiredVersion(c); err != nil { + return err } } - for _, c := range config.Children { - childDiags := CheckCoreVersionRequirements(c) - diags = diags.Append(childDiags) + var tf *config.Terraform + if c := m.Config(); c != nil { + tf = c.Terraform } - return diags + // If there is no Terraform config or the required version isn't set, + // we move on. + if tf == nil || tf.RequiredVersion == "" { + return nil + } + + // Path for errors + module := "root" + if path := normalizeModulePath(m.Path()); len(path) > 1 { + module = modulePrefixStr(path) + } + + // Check this version requirement of this module + cs, err := version.NewConstraint(tf.RequiredVersion) + if err != nil { + return fmt.Errorf( + "%s: terraform.required_version %q syntax error: %s", + module, + tf.RequiredVersion, err) + } + + if !cs.Check(tfversion.SemVer) { + return fmt.Errorf( + "The currently running version of Terraform doesn't meet the\n"+ + "version requirements explicitly specified by the configuration.\n"+ + "Please use the required version or update the configuration.\n"+ + "Note that version requirements are usually set for a reason, so\n"+ + "we recommend verifying with whoever set the version requirements\n"+ + "prior to making any manual changes.\n\n"+ + " Module: %s\n"+ + " Required version: %s\n"+ + " Current version: %s", + module, + tf.RequiredVersion, + tfversion.SemVer) + } + + return nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/walkoperation_string.go b/vendor/github.com/hashicorp/terraform/terraform/walkoperation_string.go index a802b528..4cfc528e 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/walkoperation_string.go +++ b/vendor/github.com/hashicorp/terraform/terraform/walkoperation_string.go @@ -4,9 +4,9 @@ package terraform import "strconv" -const _walkOperation_name = "walkInvalidwalkApplywalkPlanwalkPlanDestroywalkRefreshwalkValidatewalkDestroywalkImportwalkEval" +const _walkOperation_name = "walkInvalidwalkInputwalkApplywalkPlanwalkPlanDestroywalkRefreshwalkValidatewalkDestroywalkImport" -var _walkOperation_index = [...]uint8{0, 11, 20, 28, 43, 54, 66, 77, 87, 95} +var _walkOperation_index = [...]uint8{0, 11, 20, 29, 37, 52, 63, 75, 86, 96} func (i walkOperation) String() string { if i >= walkOperation(len(_walkOperation_index)-1) { diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/config_traversals.go b/vendor/github.com/hashicorp/terraform/tfdiags/config_traversals.go deleted file mode 100644 index 8e41f46e..00000000 --- a/vendor/github.com/hashicorp/terraform/tfdiags/config_traversals.go +++ /dev/null @@ -1,68 +0,0 @@ -package tfdiags - -import ( - "bytes" - "fmt" - "strconv" - - "github.com/zclconf/go-cty/cty" -) - -// FormatCtyPath is a helper function to produce a user-friendly string -// representation of a cty.Path. The result uses a syntax similar to the -// HCL expression language in the hope of it being familiar to users. -func FormatCtyPath(path cty.Path) string { - var buf bytes.Buffer - for _, step := range path { - switch ts := step.(type) { - case cty.GetAttrStep: - fmt.Fprintf(&buf, ".%s", ts.Name) - case cty.IndexStep: - buf.WriteByte('[') - key := ts.Key - keyTy := key.Type() - switch { - case key.IsNull(): - buf.WriteString("null") - case !key.IsKnown(): - buf.WriteString("(not yet known)") - case keyTy == cty.Number: - bf := key.AsBigFloat() - buf.WriteString(bf.Text('g', -1)) - case keyTy == cty.String: - buf.WriteString(strconv.Quote(key.AsString())) - default: - buf.WriteString("...") - } - buf.WriteByte(']') - } - } - return buf.String() -} - -// FormatError is a helper function to produce a user-friendly string -// representation of certain special error types that we might want to -// include in diagnostic messages. -// -// This currently has special behavior only for cty.PathError, where a -// non-empty path is rendered in a HCL-like syntax as context. -func FormatError(err error) string { - perr, ok := err.(cty.PathError) - if !ok || len(perr.Path) == 0 { - return err.Error() - } - - return fmt.Sprintf("%s: %s", FormatCtyPath(perr.Path), perr.Error()) -} - -// FormatErrorPrefixed is like FormatError except that it presents any path -// information after the given prefix string, which is assumed to contain -// an HCL syntax representation of the value that errors are relative to. -func FormatErrorPrefixed(err error, prefix string) string { - perr, ok := err.(cty.PathError) - if !ok || len(perr.Path) == 0 { - return fmt.Sprintf("%s: %s", prefix, err.Error()) - } - - return fmt.Sprintf("%s%s: %s", prefix, FormatCtyPath(perr.Path), perr.Error()) -} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/contextual.go b/vendor/github.com/hashicorp/terraform/tfdiags/contextual.go deleted file mode 100644 index 25b21403..00000000 --- a/vendor/github.com/hashicorp/terraform/tfdiags/contextual.go +++ /dev/null @@ -1,372 +0,0 @@ -package tfdiags - -import ( - "github.com/hashicorp/hcl2/hcl" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" -) - -// The "contextual" family of diagnostics are designed to allow separating -// the detection of a problem from placing that problem in context. For -// example, some code that is validating an object extracted from configuration -// may not have access to the configuration that generated it, but can still -// report problems within that object which the caller can then place in -// context by calling IsConfigBody on the returned diagnostics. -// -// When contextual diagnostics are used, the documentation for a method must -// be very explicit about what context is implied for any diagnostics returned, -// to help ensure the expected result. - -// contextualFromConfig is an interface type implemented by diagnostic types -// that can elaborate themselves when given information about the configuration -// body they are embedded in. -// -// Usually this entails extracting source location information in order to -// populate the "Subject" range. -type contextualFromConfigBody interface { - ElaborateFromConfigBody(hcl.Body) Diagnostic -} - -// InConfigBody returns a copy of the receiver with any config-contextual -// diagnostics elaborated in the context of the given body. -func (d Diagnostics) InConfigBody(body hcl.Body) Diagnostics { - if len(d) == 0 { - return nil - } - - ret := make(Diagnostics, len(d)) - for i, srcDiag := range d { - if cd, isCD := srcDiag.(contextualFromConfigBody); isCD { - ret[i] = cd.ElaborateFromConfigBody(body) - } else { - ret[i] = srcDiag - } - } - - return ret -} - -// AttributeValue returns a diagnostic about an attribute value in an implied current -// configuration context. This should be returned only from functions whose -// interface specifies a clear configuration context that this will be -// resolved in. -// -// The given path is relative to the implied configuration context. To describe -// a top-level attribute, it should be a single-element cty.Path with a -// cty.GetAttrStep. It's assumed that the path is returning into a structure -// that would be produced by our conventions in the configschema package; it -// may return unexpected results for structures that can't be represented by -// configschema. -// -// Since mapping attribute paths back onto configuration is an imprecise -// operation (e.g. dynamic block generation may cause the same block to be -// evaluated multiple times) the diagnostic detail should include the attribute -// name and other context required to help the user understand what is being -// referenced in case the identified source range is not unique. -// -// The returned attribute will not have source location information until -// context is applied to the containing diagnostics using diags.InConfigBody. -// After context is applied, the source location is the value assigned to the -// named attribute, or the containing body's "missing item range" if no -// value is present. -func AttributeValue(severity Severity, summary, detail string, attrPath cty.Path) Diagnostic { - return &attributeDiagnostic{ - diagnosticBase: diagnosticBase{ - severity: severity, - summary: summary, - detail: detail, - }, - attrPath: attrPath, - } -} - -// GetAttribute extracts an attribute cty.Path from a diagnostic if it contains -// one. Normally this is not accessed directly, and instead the config body is -// added to the Diagnostic to create a more complete message for the user. In -// some cases however, we may want to know just the name of the attribute that -// generated the Diagnostic message. -// This returns a nil cty.Path if it does not exist in the Diagnostic. -func GetAttribute(d Diagnostic) cty.Path { - if d, ok := d.(*attributeDiagnostic); ok { - return d.attrPath - } - return nil -} - -type attributeDiagnostic struct { - diagnosticBase - attrPath cty.Path - subject *SourceRange // populated only after ElaborateFromConfigBody -} - -// ElaborateFromConfigBody finds the most accurate possible source location -// for a diagnostic's attribute path within the given body. -// -// Backing out from a path back to a source location is not always entirely -// possible because we lose some information in the decoding process, so -// if an exact position cannot be found then the returned diagnostic will -// refer to a position somewhere within the containing body, which is assumed -// to be better than no location at all. -// -// If possible it is generally better to report an error at a layer where -// source location information is still available, for more accuracy. This -// is not always possible due to system architecture, so this serves as a -// "best effort" fallback behavior for such situations. -func (d *attributeDiagnostic) ElaborateFromConfigBody(body hcl.Body) Diagnostic { - if len(d.attrPath) < 1 { - // Should never happen, but we'll allow it rather than crashing. - return d - } - - if d.subject != nil { - // Don't modify an already-elaborated diagnostic. - return d - } - - ret := *d - - // This function will often end up re-decoding values that were already - // decoded by an earlier step. This is non-ideal but is architecturally - // more convenient than arranging for source location information to be - // propagated to every place in Terraform, and this happens only in the - // presence of errors where performance isn't a concern. - - traverse := d.attrPath[:] - final := d.attrPath[len(d.attrPath)-1] - - // Index should never be the first step - // as indexing of top blocks (such as resources & data sources) - // is handled elsewhere - if _, isIdxStep := traverse[0].(cty.IndexStep); isIdxStep { - subject := SourceRangeFromHCL(body.MissingItemRange()) - ret.subject = &subject - return &ret - } - - // Process index separately - idxStep, hasIdx := final.(cty.IndexStep) - if hasIdx { - final = d.attrPath[len(d.attrPath)-2] - traverse = d.attrPath[:len(d.attrPath)-1] - } - - // If we have more than one step after removing index - // then we'll first try to traverse to a child body - // corresponding to the requested path. - if len(traverse) > 1 { - body = traversePathSteps(traverse, body) - } - - // Default is to indicate a missing item in the deepest body we reached - // while traversing. - subject := SourceRangeFromHCL(body.MissingItemRange()) - ret.subject = &subject - - // Once we get here, "final" should be a GetAttr step that maps to an - // attribute in our current body. - finalStep, isAttr := final.(cty.GetAttrStep) - if !isAttr { - return &ret - } - - content, _, contentDiags := body.PartialContent(&hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: finalStep.Name, - Required: true, - }, - }, - }) - if contentDiags.HasErrors() { - return &ret - } - - if attr, ok := content.Attributes[finalStep.Name]; ok { - hclRange := attr.Expr.Range() - if hasIdx { - // Try to be more precise by finding index range - hclRange = hclRangeFromIndexStepAndAttribute(idxStep, attr) - } - subject = SourceRangeFromHCL(hclRange) - ret.subject = &subject - } - - return &ret -} - -func traversePathSteps(traverse []cty.PathStep, body hcl.Body) hcl.Body { - for i := 0; i < len(traverse); i++ { - step := traverse[i] - - switch tStep := step.(type) { - case cty.GetAttrStep: - - var next cty.PathStep - if i < (len(traverse) - 1) { - next = traverse[i+1] - } - - // Will be indexing into our result here? - var indexType cty.Type - var indexVal cty.Value - if nextIndex, ok := next.(cty.IndexStep); ok { - indexVal = nextIndex.Key - indexType = indexVal.Type() - i++ // skip over the index on subsequent iterations - } - - var blockLabelNames []string - if indexType == cty.String { - // Map traversal means we expect one label for the key. - blockLabelNames = []string{"key"} - } - - // For intermediate steps we expect to be referring to a child - // block, so we'll attempt decoding under that assumption. - content, _, contentDiags := body.PartialContent(&hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: tStep.Name, - LabelNames: blockLabelNames, - }, - }, - }) - if contentDiags.HasErrors() { - return body - } - filtered := make([]*hcl.Block, 0, len(content.Blocks)) - for _, block := range content.Blocks { - if block.Type == tStep.Name { - filtered = append(filtered, block) - } - } - if len(filtered) == 0 { - // Step doesn't refer to a block - continue - } - - switch indexType { - case cty.NilType: // no index at all - if len(filtered) != 1 { - return body - } - body = filtered[0].Body - case cty.Number: - var idx int - err := gocty.FromCtyValue(indexVal, &idx) - if err != nil || idx >= len(filtered) { - return body - } - body = filtered[idx].Body - case cty.String: - key := indexVal.AsString() - var block *hcl.Block - for _, candidate := range filtered { - if candidate.Labels[0] == key { - block = candidate - break - } - } - if block == nil { - // No block with this key, so we'll just indicate a - // missing item in the containing block. - return body - } - body = block.Body - default: - // Should never happen, because only string and numeric indices - // are supported by cty collections. - return body - } - - default: - // For any other kind of step, we'll just return our current body - // as the subject and accept that this is a little inaccurate. - return body - } - } - return body -} - -func hclRangeFromIndexStepAndAttribute(idxStep cty.IndexStep, attr *hcl.Attribute) hcl.Range { - switch idxStep.Key.Type() { - case cty.Number: - var idx int - err := gocty.FromCtyValue(idxStep.Key, &idx) - items, diags := hcl.ExprList(attr.Expr) - if diags.HasErrors() { - return attr.Expr.Range() - } - if err != nil || idx >= len(items) { - return attr.NameRange - } - return items[idx].Range() - case cty.String: - pairs, diags := hcl.ExprMap(attr.Expr) - if diags.HasErrors() { - return attr.Expr.Range() - } - stepKey := idxStep.Key.AsString() - for _, kvPair := range pairs { - key, err := kvPair.Key.Value(nil) - if err != nil { - return attr.Expr.Range() - } - if key.AsString() == stepKey { - startRng := kvPair.Value.StartRange() - return startRng - } - } - return attr.NameRange - } - return attr.Expr.Range() -} - -func (d *attributeDiagnostic) Source() Source { - return Source{ - Subject: d.subject, - } -} - -// WholeContainingBody returns a diagnostic about the body that is an implied -// current configuration context. This should be returned only from -// functions whose interface specifies a clear configuration context that this -// will be resolved in. -// -// The returned attribute will not have source location information until -// context is applied to the containing diagnostics using diags.InConfigBody. -// After context is applied, the source location is currently the missing item -// range of the body. In future, this may change to some other suitable -// part of the containing body. -func WholeContainingBody(severity Severity, summary, detail string) Diagnostic { - return &wholeBodyDiagnostic{ - diagnosticBase: diagnosticBase{ - severity: severity, - summary: summary, - detail: detail, - }, - } -} - -type wholeBodyDiagnostic struct { - diagnosticBase - subject *SourceRange // populated only after ElaborateFromConfigBody -} - -func (d *wholeBodyDiagnostic) ElaborateFromConfigBody(body hcl.Body) Diagnostic { - if d.subject != nil { - // Don't modify an already-elaborated diagnostic. - return d - } - - ret := *d - rng := SourceRangeFromHCL(body.MissingItemRange()) - ret.subject = &rng - return &ret -} - -func (d *wholeBodyDiagnostic) Source() Source { - return Source{ - Subject: d.subject, - } -} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/diagnostic.go b/vendor/github.com/hashicorp/terraform/tfdiags/diagnostic.go index c91ba9a5..2c23f76a 100644 --- a/vendor/github.com/hashicorp/terraform/tfdiags/diagnostic.go +++ b/vendor/github.com/hashicorp/terraform/tfdiags/diagnostic.go @@ -1,18 +1,9 @@ package tfdiags -import ( - "github.com/hashicorp/hcl2/hcl" -) - type Diagnostic interface { Severity() Severity Description() Description Source() Source - - // FromExpr returns the expression-related context for the diagnostic, if - // available. Returns nil if the diagnostic is not related to an - // expression evaluation. - FromExpr() *FromExpr } type Severity rune @@ -33,8 +24,3 @@ type Source struct { Subject *SourceRange Context *SourceRange } - -type FromExpr struct { - Expression hcl.Expression - EvalContext *hcl.EvalContext -} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/diagnostic_base.go b/vendor/github.com/hashicorp/terraform/tfdiags/diagnostic_base.go deleted file mode 100644 index 50bf9d8e..00000000 --- a/vendor/github.com/hashicorp/terraform/tfdiags/diagnostic_base.go +++ /dev/null @@ -1,31 +0,0 @@ -package tfdiags - -// diagnosticBase can be embedded in other diagnostic structs to get -// default implementations of Severity and Description. This type also -// has default implementations of Source and FromExpr that return no source -// location or expression-related information, so embedders should generally -// override those method to return more useful results where possible. -type diagnosticBase struct { - severity Severity - summary string - detail string -} - -func (d diagnosticBase) Severity() Severity { - return d.severity -} - -func (d diagnosticBase) Description() Description { - return Description{ - Summary: d.summary, - Detail: d.detail, - } -} - -func (d diagnosticBase) Source() Source { - return Source{} -} - -func (d diagnosticBase) FromExpr() *FromExpr { - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/diagnostics.go b/vendor/github.com/hashicorp/terraform/tfdiags/diagnostics.go index 465b230f..667ba809 100644 --- a/vendor/github.com/hashicorp/terraform/tfdiags/diagnostics.go +++ b/vendor/github.com/hashicorp/terraform/tfdiags/diagnostics.go @@ -3,9 +3,6 @@ package tfdiags import ( "bytes" "fmt" - "path/filepath" - "sort" - "strings" "github.com/hashicorp/errwrap" multierror "github.com/hashicorp/go-multierror" @@ -57,8 +54,6 @@ func (diags Diagnostics) Append(new ...interface{}) Diagnostics { diags = append(diags, ti...) // flatten case diagnosticsAsError: diags = diags.Append(ti.Diagnostics) // unwrap - case NonFatalError: - diags = diags.Append(ti.Diagnostics) // unwrap case hcl.Diagnostics: for _, hclDiag := range ti { diags = append(diags, hclDiagnostic{hclDiag}) @@ -141,54 +136,6 @@ func (diags Diagnostics) Err() error { return diagnosticsAsError{diags} } -// ErrWithWarnings is similar to Err except that it will also return a non-nil -// error if the receiver contains only warnings. -// -// In the warnings-only situation, the result is guaranteed to be of dynamic -// type NonFatalError, allowing diagnostics-aware callers to type-assert -// and unwrap it, treating it as non-fatal. -// -// This should be used only in contexts where the caller is able to recognize -// and handle NonFatalError. For normal callers that expect a lack of errors -// to be signaled by nil, use just Diagnostics.Err. -func (diags Diagnostics) ErrWithWarnings() error { - if len(diags) == 0 { - return nil - } - if diags.HasErrors() { - return diags.Err() - } - return NonFatalError{diags} -} - -// NonFatalErr is similar to Err except that it always returns either nil -// (if there are no diagnostics at all) or NonFatalError. -// -// This allows diagnostics to be returned over an error return channel while -// being explicit that the diagnostics should not halt processing. -// -// This should be used only in contexts where the caller is able to recognize -// and handle NonFatalError. For normal callers that expect a lack of errors -// to be signaled by nil, use just Diagnostics.Err. -func (diags Diagnostics) NonFatalErr() error { - if len(diags) == 0 { - return nil - } - return NonFatalError{diags} -} - -// Sort applies an ordering to the diagnostics in the receiver in-place. -// -// The ordering is: warnings before errors, sourceless before sourced, -// short source paths before long source paths, and then ordering by -// position within each file. -// -// Diagnostics that do not differ by any of these sortable characteristics -// will remain in the same relative order after this method returns. -func (diags Diagnostics) Sort() { - sort.Stable(sortDiagnostics(diags)) -} - type diagnosticsAsError struct { Diagnostics } @@ -232,99 +179,3 @@ func (dae diagnosticsAsError) WrappedErrors() []error { } return errs } - -// NonFatalError is a special error type, returned by -// Diagnostics.ErrWithWarnings and Diagnostics.NonFatalErr, -// that indicates that the wrapped diagnostics should be treated as non-fatal. -// Callers can conditionally type-assert an error to this type in order to -// detect the non-fatal scenario and handle it in a different way. -type NonFatalError struct { - Diagnostics -} - -func (woe NonFatalError) Error() string { - diags := woe.Diagnostics - switch { - case len(diags) == 0: - // should never happen, since we don't create this wrapper if - // there are no diagnostics in the list. - return "no errors or warnings" - case len(diags) == 1: - desc := diags[0].Description() - if desc.Detail == "" { - return desc.Summary - } - return fmt.Sprintf("%s: %s", desc.Summary, desc.Detail) - default: - var ret bytes.Buffer - if diags.HasErrors() { - fmt.Fprintf(&ret, "%d problems:\n", len(diags)) - } else { - fmt.Fprintf(&ret, "%d warnings:\n", len(diags)) - } - for _, diag := range woe.Diagnostics { - desc := diag.Description() - if desc.Detail == "" { - fmt.Fprintf(&ret, "\n- %s", desc.Summary) - } else { - fmt.Fprintf(&ret, "\n- %s: %s", desc.Summary, desc.Detail) - } - } - return ret.String() - } -} - -// sortDiagnostics is an implementation of sort.Interface -type sortDiagnostics []Diagnostic - -var _ sort.Interface = sortDiagnostics(nil) - -func (sd sortDiagnostics) Len() int { - return len(sd) -} - -func (sd sortDiagnostics) Less(i, j int) bool { - iD, jD := sd[i], sd[j] - iSev, jSev := iD.Severity(), jD.Severity() - iSrc, jSrc := iD.Source(), jD.Source() - - switch { - - case iSev != jSev: - return iSev == Warning - - case (iSrc.Subject == nil) != (jSrc.Subject == nil): - return iSrc.Subject == nil - - case iSrc.Subject != nil && *iSrc.Subject != *jSrc.Subject: - iSubj := iSrc.Subject - jSubj := jSrc.Subject - switch { - case iSubj.Filename != jSubj.Filename: - // Path with fewer segments goes first if they are different lengths - sep := string(filepath.Separator) - iCount := strings.Count(iSubj.Filename, sep) - jCount := strings.Count(jSubj.Filename, sep) - if iCount != jCount { - return iCount < jCount - } - return iSubj.Filename < jSubj.Filename - case iSubj.Start.Byte != jSubj.Start.Byte: - return iSubj.Start.Byte < jSubj.Start.Byte - case iSubj.End.Byte != jSubj.End.Byte: - return iSubj.End.Byte < jSubj.End.Byte - } - fallthrough - - default: - // The remaining properties do not have a defined ordering, so - // we'll leave it unspecified. Since we use sort.Stable in - // the caller of this, the ordering of remaining items will - // be preserved. - return false - } -} - -func (sd sortDiagnostics) Swap(i, j int) { - sd[i], sd[j] = sd[j], sd[i] -} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/error.go b/vendor/github.com/hashicorp/terraform/tfdiags/error.go index 13f7a714..35edc304 100644 --- a/vendor/github.com/hashicorp/terraform/tfdiags/error.go +++ b/vendor/github.com/hashicorp/terraform/tfdiags/error.go @@ -13,7 +13,7 @@ func (e nativeError) Severity() Severity { func (e nativeError) Description() Description { return Description{ - Summary: FormatError(e.err), + Summary: e.err.Error(), } } @@ -21,8 +21,3 @@ func (e nativeError) Source() Source { // No source information available for a native error return Source{} } - -func (e nativeError) FromExpr() *FromExpr { - // Native errors are not expression-related - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/hcl.go b/vendor/github.com/hashicorp/terraform/tfdiags/hcl.go index f9aec41c..24851f4d 100644 --- a/vendor/github.com/hashicorp/terraform/tfdiags/hcl.go +++ b/vendor/github.com/hashicorp/terraform/tfdiags/hcl.go @@ -40,16 +40,6 @@ func (d hclDiagnostic) Source() Source { return ret } -func (d hclDiagnostic) FromExpr() *FromExpr { - if d.diag.Expression == nil || d.diag.EvalContext == nil { - return nil - } - return &FromExpr{ - Expression: d.diag.Expression, - EvalContext: d.diag.EvalContext, - } -} - // SourceRangeFromHCL constructs a SourceRange from the corresponding range // type within the HCL package. func SourceRangeFromHCL(hclRange hcl.Range) SourceRange { diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/rpc_friendly.go b/vendor/github.com/hashicorp/terraform/tfdiags/rpc_friendly.go index 485063b0..6cc95cc2 100644 --- a/vendor/github.com/hashicorp/terraform/tfdiags/rpc_friendly.go +++ b/vendor/github.com/hashicorp/terraform/tfdiags/rpc_friendly.go @@ -48,12 +48,6 @@ func (d *rpcFriendlyDiag) Source() Source { } } -func (d rpcFriendlyDiag) FromExpr() *FromExpr { - // RPC-friendly diagnostics cannot preserve expression information because - // expressions themselves are not RPC-friendly. - return nil -} - func init() { gob.Register((*rpcFriendlyDiag)(nil)) } diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/simple_warning.go b/vendor/github.com/hashicorp/terraform/tfdiags/simple_warning.go index b0f1ecd4..fb3ac989 100644 --- a/vendor/github.com/hashicorp/terraform/tfdiags/simple_warning.go +++ b/vendor/github.com/hashicorp/terraform/tfdiags/simple_warning.go @@ -20,11 +20,6 @@ func (e simpleWarning) Description() Description { } func (e simpleWarning) Source() Source { - // No source information available for a simple warning + // No source information available for a native error return Source{} } - -func (e simpleWarning) FromExpr() *FromExpr { - // Simple warnings are not expression-related - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/sourceless.go b/vendor/github.com/hashicorp/terraform/tfdiags/sourceless.go deleted file mode 100644 index eaa27373..00000000 --- a/vendor/github.com/hashicorp/terraform/tfdiags/sourceless.go +++ /dev/null @@ -1,13 +0,0 @@ -package tfdiags - -// Sourceless creates and returns a diagnostic with no source location -// information. This is generally used for operational-type errors that are -// caused by or relate to the environment where Terraform is running rather -// than to the provided configuration. -func Sourceless(severity Severity, summary, detail string) Diagnostic { - return diagnosticBase{ - severity: severity, - summary: summary, - detail: detail, - } -} diff --git a/vendor/github.com/hashicorp/terraform/version/version.go b/vendor/github.com/hashicorp/terraform/version/version.go index e6cc1650..2b1db162 100644 --- a/vendor/github.com/hashicorp/terraform/version/version.go +++ b/vendor/github.com/hashicorp/terraform/version/version.go @@ -11,7 +11,7 @@ import ( ) // The main version number that is being run at the moment. -var Version = "0.12.0" +const Version = "0.11.9" // A pre-release marker for the version. If this is "" (empty string) // then it means that it is a final release. Otherwise, this is a pre-release @@ -21,11 +21,7 @@ var Prerelease = "dev" // SemVer is an instance of version.Version. This has the secondary // benefit of verifying during tests and init time that our version is a // proper semantic version, which should always be the case. -var SemVer *version.Version - -func init() { - SemVer = version.Must(version.NewVersion(Version)) -} +var SemVer = version.Must(version.NewVersion(Version)) // Header is the header name used to send the current terraform version // in http requests. diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 404e10ca..e17a5474 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -29,15 +29,6 @@ const ( backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) ) -const ( - genericRead = 0x80000000 - genericWrite = 0x40000000 -) - -const ( - consoleTextmodeBuffer = 0x1 -) - type wchar uint16 type short int16 type dword uint32 @@ -78,17 +69,14 @@ var ( procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") - procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) // Writer provide colorable Writer to the console type Writer struct { - out io.Writer - handle syscall.Handle - althandle syscall.Handle - oldattr word - oldpos coord - rest bytes.Buffer + out io.Writer + handle syscall.Handle + oldattr word + oldpos coord } // NewColorable return new instance of Writer which handle escape sequence from File. @@ -419,18 +407,7 @@ func (w *Writer) Write(data []byte) (n int, err error) { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - handle := w.handle - - var er *bytes.Reader - if w.rest.Len() > 0 { - var rest bytes.Buffer - w.rest.WriteTo(&rest) - w.rest.Reset() - rest.Write(data) - er = bytes.NewReader(rest.Bytes()) - } else { - er = bytes.NewReader(data) - } + er := bytes.NewReader(data) var bw [1]byte loop: for { @@ -448,55 +425,29 @@ loop: break loop } - switch c2 { - case '>': - continue - case ']': - w.rest.WriteByte(c1) - w.rest.WriteByte(c2) - er.WriteTo(&w.rest) - if bytes.IndexByte(w.rest.Bytes(), 0x07) == -1 { + if c2 == ']' { + if err := doTitleSequence(er); err != nil { break loop } - er = bytes.NewReader(w.rest.Bytes()[2:]) - err := doTitleSequence(er) - if err != nil { - break loop - } - w.rest.Reset() - continue - // https://github.com/mattn/go-colorable/issues/27 - case '7': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - w.oldpos = csbi.cursorPosition - continue - case '8': - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) - continue - case 0x5b: - // execute part after switch - default: continue } - - w.rest.WriteByte(c1) - w.rest.WriteByte(c2) - er.WriteTo(&w.rest) + if c2 != 0x5b { + continue + } var buf bytes.Buffer var m byte - for i, c := range w.rest.Bytes()[2:] { + for { + c, err := er.ReadByte() + if err != nil { + break loop + } if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { m = c - er = bytes.NewReader(w.rest.Bytes()[2+i+1:]) - w.rest.Reset() break } buf.Write([]byte(string(c))) } - if m == 0 { - break loop - } switch m { case 'A': @@ -504,64 +455,61 @@ loop: if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'B': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'C': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'D': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x -= short(n) - if csbi.cursorPosition.x < 0 { - csbi.cursorPosition.x = 0 - } - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'E': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'F': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'G': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = short(n - 1) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'H', 'f': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) if buf.Len() > 0 { token := strings.Split(buf.String(), ";") switch len(token) { @@ -586,7 +534,7 @@ loop: } else { csbi.cursorPosition.y = 0 } - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'J': n := 0 if buf.Len() > 0 { @@ -597,20 +545,20 @@ loop: } var count, written dword var cursor coord - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) switch n { case 0: cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) + count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) case 1: cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.window.top-csbi.cursorPosition.y)*dword(csbi.size.x) + count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.window.top-csbi.cursorPosition.y)*csbi.size.x) case 2: cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) + count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) } - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'K': n := 0 if buf.Len() > 0 { @@ -619,28 +567,28 @@ loop: continue } } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) var cursor coord var count, written dword switch n { case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - count = dword(csbi.size.x - csbi.cursorPosition.x) + cursor = coord{x: csbi.cursorPosition.x + 1, y: csbi.cursorPosition.y} + count = dword(csbi.size.x - csbi.cursorPosition.x - 1) case 1: - cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} + cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} count = dword(csbi.size.x - csbi.cursorPosition.x) case 2: - cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} + cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} count = dword(csbi.size.x) } - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'm': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) attr := csbi.attributes cs := buf.String() if cs == "" { - procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(w.oldattr)) + procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) continue } token := strings.Split(cs, ";") @@ -679,21 +627,6 @@ loop: attr |= n256foreAttr[n256] i += 2 } - } else if len(token) == 5 && token[i+1] == "2" { - var r, g, b int - r, _ = strconv.Atoi(token[i+2]) - g, _ = strconv.Atoi(token[i+3]) - b, _ = strconv.Atoi(token[i+4]) - i += 4 - if r > 127 { - attr |= foregroundRed - } - if g > 127 { - attr |= foregroundGreen - } - if b > 127 { - attr |= foregroundBlue - } } else { attr = attr & (w.oldattr & backgroundMask) } @@ -721,21 +654,6 @@ loop: attr |= n256backAttr[n256] i += 2 } - } else if len(token) == 5 && token[i+1] == "2" { - var r, g, b int - r, _ = strconv.Atoi(token[i+2]) - g, _ = strconv.Atoi(token[i+3]) - b, _ = strconv.Atoi(token[i+4]) - i += 4 - if r > 127 { - attr |= backgroundRed - } - if g > 127 { - attr |= backgroundGreen - } - if b > 127 { - attr |= backgroundBlue - } } else { attr = attr & (w.oldattr & foregroundMask) } @@ -767,52 +685,38 @@ loop: attr |= backgroundBlue } } - procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(attr)) + procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) } } case 'h': var ci consoleCursorInfo cs := buf.String() if cs == "5>" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) } else if cs == "?25" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?1049" { - if w.althandle == 0 { - h, _, _ := procCreateConsoleScreenBuffer.Call(uintptr(genericRead|genericWrite), 0, 0, uintptr(consoleTextmodeBuffer), 0, 0) - w.althandle = syscall.Handle(h) - if w.althandle != 0 { - handle = w.althandle - } - } + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) } case 'l': var ci consoleCursorInfo cs := buf.String() if cs == "5>" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) } else if cs == "?25" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?1049" { - if w.althandle != 0 { - syscall.CloseHandle(w.althandle) - w.althandle = 0 - handle = w.handle - } + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) } case 's': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) w.oldpos = csbi.cursorPosition case 'u': - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) } } diff --git a/vendor/github.com/mattn/go-colorable/go.mod b/vendor/github.com/mattn/go-colorable/go.mod deleted file mode 100644 index 9d9f4248..00000000 --- a/vendor/github.com/mattn/go-colorable/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/mattn/go-colorable - -require github.com/mattn/go-isatty v0.0.5 diff --git a/vendor/github.com/mattn/go-colorable/go.sum b/vendor/github.com/mattn/go-colorable/go.sum deleted file mode 100644 index 2c12960e..00000000 --- a/vendor/github.com/mattn/go-colorable/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/mattn/go-isatty/go.mod b/vendor/github.com/mattn/go-isatty/go.mod deleted file mode 100644 index f310320c..00000000 --- a/vendor/github.com/mattn/go-isatty/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/mattn/go-isatty - -require golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 diff --git a/vendor/github.com/mattn/go-isatty/go.sum b/vendor/github.com/mattn/go-isatty/go.sum deleted file mode 100644 index 426c8973..00000000 --- a/vendor/github.com/mattn/go-isatty/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/mattn/go-isatty/isatty_appengine.go b/vendor/github.com/mattn/go-isatty/isatty_appengine.go new file mode 100644 index 00000000..9584a988 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_appengine.go @@ -0,0 +1,15 @@ +// +build appengine + +package isatty + +// IsTerminal returns true if the file descriptor is terminal which +// is always false on on appengine classic which is a sandboxed PaaS. +func IsTerminal(fd uintptr) bool { + return false +} + +// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go index 07e93039..42f2514d 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ b/vendor/github.com/mattn/go-isatty/isatty_bsd.go @@ -16,9 +16,3 @@ func IsTerminal(fd uintptr) bool { _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } - -// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_linux.go b/vendor/github.com/mattn/go-isatty/isatty_linux.go index e004038e..7384cf99 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_linux.go +++ b/vendor/github.com/mattn/go-isatty/isatty_linux.go @@ -1,18 +1,18 @@ // +build linux -// +build !appengine +// +build !appengine,!ppc64,!ppc64le package isatty -import "golang.org/x/sys/unix" +import ( + "syscall" + "unsafe" +) + +const ioctlReadTermios = syscall.TCGETS // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { - _, err := unix.IoctlGetTermios(int(fd), unix.TCGETS) - return err == nil -} - -// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 } diff --git a/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go b/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go new file mode 100644 index 00000000..44e5d213 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go @@ -0,0 +1,19 @@ +// +build linux +// +build ppc64 ppc64le + +package isatty + +import ( + "unsafe" + + syscall "golang.org/x/sys/unix" +) + +const ioctlReadTermios = syscall.TCGETS + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go index f02849c5..9d8b4a59 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_others.go +++ b/vendor/github.com/mattn/go-isatty/isatty_others.go @@ -1,14 +1,9 @@ -// +build appengine js +// +build !windows +// +build !appengine package isatty -// IsTerminal returns true if the file descriptor is terminal which -// is always false on js and appengine classic which is a sandboxed PaaS. -func IsTerminal(fd uintptr) bool { - return false -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 // terminal. This is also always false on this environment. func IsCygwinTerminal(fd uintptr) bool { return false diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go index bdd5c79a..1f0c6bf5 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_solaris.go +++ b/vendor/github.com/mattn/go-isatty/isatty_solaris.go @@ -14,9 +14,3 @@ func IsTerminal(fd uintptr) bool { err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) return err == nil } - -// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mitchellh/colorstring/.travis.yml b/vendor/github.com/mitchellh/colorstring/.travis.yml deleted file mode 100644 index 74e286ae..00000000 --- a/vendor/github.com/mitchellh/colorstring/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go - -go: - - 1.0 - - 1.1 - - 1.2 - - 1.3 - - tip - -script: - - go test - -matrix: - allow_failures: - - go: tip diff --git a/vendor/github.com/mitchellh/colorstring/LICENSE b/vendor/github.com/mitchellh/colorstring/LICENSE deleted file mode 100644 index 22985159..00000000 --- a/vendor/github.com/mitchellh/colorstring/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/colorstring/README.md b/vendor/github.com/mitchellh/colorstring/README.md deleted file mode 100644 index 0654d454..00000000 --- a/vendor/github.com/mitchellh/colorstring/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# colorstring [![Build Status](https://travis-ci.org/mitchellh/colorstring.svg)](https://travis-ci.org/mitchellh/colorstring) - -colorstring is a [Go](http://www.golang.org) library for outputting colored -strings to a console using a simple inline syntax in your string to specify -the color to print as. - -For example, the string `[blue]hello [red]world` would output the text -"hello world" in two colors. The API of colorstring allows for easily disabling -colors, adding aliases, etc. - -## Installation - -Standard `go get`: - -``` -$ go get github.com/mitchellh/colorstring -``` - -## Usage & Example - -For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/colorstring). - -Usage is easy enough: - -```go -colorstring.Println("[blue]Hello [red]World!") -``` - -Additionally, the `Colorize` struct can be used to set options such as -custom colors, color disabling, etc. diff --git a/vendor/github.com/mitchellh/colorstring/colorstring.go b/vendor/github.com/mitchellh/colorstring/colorstring.go deleted file mode 100644 index 3de5b241..00000000 --- a/vendor/github.com/mitchellh/colorstring/colorstring.go +++ /dev/null @@ -1,244 +0,0 @@ -// colorstring provides functions for colorizing strings for terminal -// output. -package colorstring - -import ( - "bytes" - "fmt" - "io" - "regexp" - "strings" -) - -// Color colorizes your strings using the default settings. -// -// Strings given to Color should use the syntax `[color]` to specify the -// color for text following. For example: `[blue]Hello` will return "Hello" -// in blue. See DefaultColors for all the supported colors and attributes. -// -// If an unrecognized color is given, it is ignored and assumed to be part -// of the string. For example: `[hi]world` will result in "[hi]world". -// -// A color reset is appended to the end of every string. This will reset -// the color of following strings when you output this text to the same -// terminal session. -// -// If you want to customize any of this behavior, use the Colorize struct. -func Color(v string) string { - return def.Color(v) -} - -// ColorPrefix returns the color sequence that prefixes the given text. -// -// This is useful when wrapping text if you want to inherit the color -// of the wrapped text. For example, "[green]foo" will return "[green]". -// If there is no color sequence, then this will return "". -func ColorPrefix(v string) string { - return def.ColorPrefix(v) -} - -// Colorize colorizes your strings, giving you the ability to customize -// some of the colorization process. -// -// The options in Colorize can be set to customize colorization. If you're -// only interested in the defaults, just use the top Color function directly, -// which creates a default Colorize. -type Colorize struct { - // Colors maps a color string to the code for that color. The code - // is a string so that you can use more complex colors to set foreground, - // background, attributes, etc. For example, "boldblue" might be - // "1;34" - Colors map[string]string - - // If true, color attributes will be ignored. This is useful if you're - // outputting to a location that doesn't support colors and you just - // want the strings returned. - Disable bool - - // Reset, if true, will reset the color after each colorization by - // adding a reset code at the end. - Reset bool -} - -// Color colorizes a string according to the settings setup in the struct. -// -// For more details on the syntax, see the top-level Color function. -func (c *Colorize) Color(v string) string { - matches := parseRe.FindAllStringIndex(v, -1) - if len(matches) == 0 { - return v - } - - result := new(bytes.Buffer) - colored := false - m := []int{0, 0} - for _, nm := range matches { - // Write the text in between this match and the last - result.WriteString(v[m[1]:nm[0]]) - m = nm - - var replace string - if code, ok := c.Colors[v[m[0]+1:m[1]-1]]; ok { - colored = true - - if !c.Disable { - replace = fmt.Sprintf("\033[%sm", code) - } - } else { - replace = v[m[0]:m[1]] - } - - result.WriteString(replace) - } - result.WriteString(v[m[1]:]) - - if colored && c.Reset && !c.Disable { - // Write the clear byte at the end - result.WriteString("\033[0m") - } - - return result.String() -} - -// ColorPrefix returns the first color sequence that exists in this string. -// -// For example: "[green]foo" would return "[green]". If no color sequence -// exists, then "" is returned. This is especially useful when wrapping -// colored texts to inherit the color of the wrapped text. -func (c *Colorize) ColorPrefix(v string) string { - return prefixRe.FindString(strings.TrimSpace(v)) -} - -// DefaultColors are the default colors used when colorizing. -// -// If the color is surrounded in underscores, such as "_blue_", then that -// color will be used for the background color. -var DefaultColors map[string]string - -func init() { - DefaultColors = map[string]string{ - // Default foreground/background colors - "default": "39", - "_default_": "49", - - // Foreground colors - "black": "30", - "red": "31", - "green": "32", - "yellow": "33", - "blue": "34", - "magenta": "35", - "cyan": "36", - "light_gray": "37", - "dark_gray": "90", - "light_red": "91", - "light_green": "92", - "light_yellow": "93", - "light_blue": "94", - "light_magenta": "95", - "light_cyan": "96", - "white": "97", - - // Background colors - "_black_": "40", - "_red_": "41", - "_green_": "42", - "_yellow_": "43", - "_blue_": "44", - "_magenta_": "45", - "_cyan_": "46", - "_light_gray_": "47", - "_dark_gray_": "100", - "_light_red_": "101", - "_light_green_": "102", - "_light_yellow_": "103", - "_light_blue_": "104", - "_light_magenta_": "105", - "_light_cyan_": "106", - "_white_": "107", - - // Attributes - "bold": "1", - "dim": "2", - "underline": "4", - "blink_slow": "5", - "blink_fast": "6", - "invert": "7", - "hidden": "8", - - // Reset to reset everything to their defaults - "reset": "0", - "reset_bold": "21", - } - - def = Colorize{ - Colors: DefaultColors, - Reset: true, - } -} - -var def Colorize -var parseReRaw = `\[[a-z0-9_-]+\]` -var parseRe = regexp.MustCompile(`(?i)` + parseReRaw) -var prefixRe = regexp.MustCompile(`^(?i)(` + parseReRaw + `)+`) - -// Print is a convenience wrapper for fmt.Print with support for color codes. -// -// Print formats using the default formats for its operands and writes to -// standard output with support for color codes. Spaces are added between -// operands when neither is a string. It returns the number of bytes written -// and any write error encountered. -func Print(a string) (n int, err error) { - return fmt.Print(Color(a)) -} - -// Println is a convenience wrapper for fmt.Println with support for color -// codes. -// -// Println formats using the default formats for its operands and writes to -// standard output with support for color codes. Spaces are always added -// between operands and a newline is appended. It returns the number of bytes -// written and any write error encountered. -func Println(a string) (n int, err error) { - return fmt.Println(Color(a)) -} - -// Printf is a convenience wrapper for fmt.Printf with support for color codes. -// -// Printf formats according to a format specifier and writes to standard output -// with support for color codes. It returns the number of bytes written and any -// write error encountered. -func Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(Color(format), a...) -} - -// Fprint is a convenience wrapper for fmt.Fprint with support for color codes. -// -// Fprint formats using the default formats for its operands and writes to w -// with support for color codes. Spaces are added between operands when neither -// is a string. It returns the number of bytes written and any write error -// encountered. -func Fprint(w io.Writer, a string) (n int, err error) { - return fmt.Fprint(w, Color(a)) -} - -// Fprintln is a convenience wrapper for fmt.Fprintln with support for color -// codes. -// -// Fprintln formats using the default formats for its operands and writes to w -// with support for color codes. Spaces are always added between operands and a -// newline is appended. It returns the number of bytes written and any write -// error encountered. -func Fprintln(w io.Writer, a string) (n int, err error) { - return fmt.Fprintln(w, Color(a)) -} - -// Fprintf is a convenience wrapper for fmt.Fprintf with support for color -// codes. -// -// Fprintf formats according to a format specifier and writes to w with support -// for color codes. It returns the number of bytes written and any write error -// encountered. -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, Color(format), a...) -} diff --git a/vendor/github.com/mitchellh/colorstring/go.mod b/vendor/github.com/mitchellh/colorstring/go.mod deleted file mode 100644 index 446ff8d3..00000000 --- a/vendor/github.com/mitchellh/colorstring/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/colorstring diff --git a/vendor/github.com/mitchellh/go-wordwrap/go.mod b/vendor/github.com/mitchellh/go-wordwrap/go.mod deleted file mode 100644 index 2ae411b2..00000000 --- a/vendor/github.com/mitchellh/go-wordwrap/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/go-wordwrap diff --git a/vendor/github.com/posener/complete/.gitignore b/vendor/github.com/posener/complete/.gitignore index 293955f9..13637208 100644 --- a/vendor/github.com/posener/complete/.gitignore +++ b/vendor/github.com/posener/complete/.gitignore @@ -1,4 +1,2 @@ .idea coverage.txt -gocomplete/gocomplete -example/self/self diff --git a/vendor/github.com/posener/complete/.travis.yml b/vendor/github.com/posener/complete/.travis.yml index 2fae9454..c2798f8f 100644 --- a/vendor/github.com/posener/complete/.travis.yml +++ b/vendor/github.com/posener/complete/.travis.yml @@ -1,16 +1,17 @@ language: go sudo: false go: - - 1.11 - - 1.10.x - 1.9 - 1.8 before_install: - go get -u -t ./... + - go get -u gopkg.in/alecthomas/gometalinter.v1 + - gometalinter.v1 --install script: - - GO111MODULE=on ./test.sh + - gometalinter.v1 --config metalinter.json ./... + - ./test.sh after_success: - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/posener/complete/args.go b/vendor/github.com/posener/complete/args.go index 17ab2c6d..1ba4d691 100644 --- a/vendor/github.com/posener/complete/args.go +++ b/vendor/github.com/posener/complete/args.go @@ -57,20 +57,11 @@ func newArgs(line string) Args { } } -// splitFields returns a list of fields from the given command line. -// If the last character is space, it appends an empty field in the end -// indicating that the field before it was completed. -// If the last field is of the form "a=b", it splits it to two fields: "a", "b", -// So it can be completed. func splitFields(line string) []string { parts := strings.Fields(line) - - // Add empty field if the last field was completed. if len(line) > 0 && unicode.IsSpace(rune(line[len(line)-1])) { parts = append(parts, "") } - - // Treat the last field if it is of the form "a=b" parts = splitLastEqual(parts) return parts } diff --git a/vendor/github.com/posener/complete/cmd/cmd.go b/vendor/github.com/posener/complete/cmd/cmd.go index b99fe529..7137dee1 100644 --- a/vendor/github.com/posener/complete/cmd/cmd.go +++ b/vendor/github.com/posener/complete/cmd/cmd.go @@ -103,7 +103,7 @@ func (f *CLI) AddFlags(flags *flag.FlagSet) { fmt.Sprintf("Uninstall completion for %s command", f.Name)) } if flags.Lookup("y") == nil { - flags.BoolVar(&f.yes, "y", false, "Don't prompt user for typing 'yes' when installing completion") + flags.BoolVar(&f.yes, "y", false, "Don't prompt user for typing 'yes'") } } diff --git a/vendor/github.com/posener/complete/cmd/install/fish.go b/vendor/github.com/posener/complete/cmd/install/fish.go index 6467196b..f04e7c3a 100644 --- a/vendor/github.com/posener/complete/cmd/install/fish.go +++ b/vendor/github.com/posener/complete/cmd/install/fish.go @@ -16,10 +16,7 @@ type fish struct { func (f fish) Install(cmd, bin string) error { completionFile := filepath.Join(f.configDir, "completions", fmt.Sprintf("%s.fish", cmd)) - completeCmd, err := f.cmd(cmd, bin) - if err != nil { - return err - } + completeCmd := f.cmd(cmd, bin) if _, err := os.Stat(completionFile); err == nil { return fmt.Errorf("already installed at %s", completionFile) } @@ -36,10 +33,10 @@ func (f fish) Uninstall(cmd, bin string) error { return os.Remove(completionFile) } -func (f fish) cmd(cmd, bin string) (string, error) { +func (f fish) cmd(cmd, bin string) string { var buf bytes.Buffer params := struct{ Cmd, Bin string }{cmd, bin} - tmpl := template.Must(template.New("cmd").Parse(` + template.Must(template.New("cmd").Parse(` function __complete_{{.Cmd}} set -lx COMP_LINE (string join ' ' (commandline -o)) test (commandline -ct) = "" @@ -47,10 +44,7 @@ function __complete_{{.Cmd}} {{.Bin}} end complete -c {{.Cmd}} -a "(__complete_{{.Cmd}})" -`)) - err := tmpl.Execute(&buf, params) - if err != nil { - return "", err - } - return buf.String(), nil +`)).Execute(&buf, params) + + return string(buf.Bytes()) } diff --git a/vendor/github.com/posener/complete/cmd/install/install.go b/vendor/github.com/posener/complete/cmd/install/install.go index dfa1963b..4a706242 100644 --- a/vendor/github.com/posener/complete/cmd/install/install.go +++ b/vendor/github.com/posener/complete/cmd/install/install.go @@ -51,7 +51,7 @@ func Uninstall(cmd string) error { for _, i := range is { errI := i.Uninstall(cmd, bin) if errI != nil { - err = multierror.Append(err, errI) + multierror.Append(err, errI) } } diff --git a/vendor/github.com/posener/complete/cmd/install/utils.go b/vendor/github.com/posener/complete/cmd/install/utils.go index d34ac8ca..bb709bc6 100644 --- a/vendor/github.com/posener/complete/cmd/install/utils.go +++ b/vendor/github.com/posener/complete/cmd/install/utils.go @@ -115,10 +115,7 @@ func removeContentToTempFile(name, content string) (string, error) { if str == content { continue } - _, err = wf.WriteString(str + "\n") - if err != nil { - return "", err - } + wf.WriteString(str + "\n") prefix = prefix[:0] } return wf.Name(), nil diff --git a/vendor/github.com/posener/complete/complete.go b/vendor/github.com/posener/complete/complete.go index 725c4deb..185d1e8b 100644 --- a/vendor/github.com/posener/complete/complete.go +++ b/vendor/github.com/posener/complete/complete.go @@ -10,16 +10,14 @@ import ( "fmt" "io" "os" - "strconv" "github.com/posener/complete/cmd" "github.com/posener/complete/match" ) const ( - envLine = "COMP_LINE" - envPoint = "COMP_POINT" - envDebug = "COMP_DEBUG" + envComplete = "COMP_LINE" + envDebug = "COMP_DEBUG" ) // Complete structs define completion for a command with CLI options @@ -57,18 +55,13 @@ func (c *Complete) Run() bool { // For installation: it assumes that flags were added and parsed before // it was called. func (c *Complete) Complete() bool { - line, point, ok := getEnv() + line, ok := getLine() if !ok { // make sure flags parsed, // in case they were not added in the main program return c.CLI.Run() } - - if point >= 0 && point < len(line) { - line = line[:point] - } - - Log("Completing phrase: %s", line) + Log("Completing line: %s", line) a := newArgs(line) Log("Completing last field: %s", a.Last) options := c.Command.Predict(a) @@ -86,19 +79,12 @@ func (c *Complete) Complete() bool { return true } -func getEnv() (line string, point int, ok bool) { - line = os.Getenv(envLine) +func getLine() (string, bool) { + line := os.Getenv(envComplete) if line == "" { - return + return "", false } - point, err := strconv.Atoi(os.Getenv(envPoint)) - if err != nil { - // If failed parsing point for some reason, set it to point - // on the end of the line. - Log("Failed parsing point %s: %v", os.Getenv(envPoint), err) - point = len(line) - } - return line, point, true + return line, true } func (c *Complete) output(options []string) { diff --git a/vendor/github.com/posener/complete/go.mod b/vendor/github.com/posener/complete/go.mod deleted file mode 100644 index fef0c440..00000000 --- a/vendor/github.com/posener/complete/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/posener/complete - -require github.com/hashicorp/go-multierror v1.0.0 diff --git a/vendor/github.com/posener/complete/go.sum b/vendor/github.com/posener/complete/go.sum deleted file mode 100644 index d2f13301..00000000 --- a/vendor/github.com/posener/complete/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= diff --git a/vendor/github.com/posener/complete/log.go b/vendor/github.com/posener/complete/log.go index c3029556..797a80ce 100644 --- a/vendor/github.com/posener/complete/log.go +++ b/vendor/github.com/posener/complete/log.go @@ -1,6 +1,7 @@ package complete import ( + "io" "io/ioutil" "log" "os" @@ -14,7 +15,7 @@ import ( var Log = getLogger() func getLogger() func(format string, args ...interface{}) { - var logfile = ioutil.Discard + var logfile io.Writer = ioutil.Discard if os.Getenv(envDebug) != "" { logfile = os.Stderr } diff --git a/vendor/github.com/posener/complete/metalinter.json b/vendor/github.com/posener/complete/metalinter.json new file mode 100644 index 00000000..799c1d03 --- /dev/null +++ b/vendor/github.com/posener/complete/metalinter.json @@ -0,0 +1,21 @@ +{ + "Vendor": true, + "DisableAll": true, + "Enable": [ + "gofmt", + "goimports", + "interfacer", + "goconst", + "misspell", + "unconvert", + "gosimple", + "golint", + "structcheck", + "deadcode", + "vet" + ], + "Exclude": [ + "initTests is unused" + ], + "Deadline": "2m" +} diff --git a/vendor/github.com/posener/complete/readme.md b/vendor/github.com/posener/complete/readme.md index 6d757ef8..2a999ba7 100644 --- a/vendor/github.com/posener/complete/readme.md +++ b/vendor/github.com/posener/complete/readme.md @@ -4,7 +4,6 @@ A tool for bash writing bash completion in go, and bash completion for the go co [![Build Status](https://travis-ci.org/posener/complete.svg?branch=master)](https://travis-ci.org/posener/complete) [![codecov](https://codecov.io/gh/posener/complete/branch/master/graph/badge.svg)](https://codecov.io/gh/posener/complete) -[![golangci](https://golangci.com/badges/github.com/posener/complete.svg)](https://golangci.com/r/github.com/posener/complete) [![GoDoc](https://godoc.org/github.com/posener/complete?status.svg)](http://godoc.org/github.com/posener/complete) [![Go Report Card](https://goreportcard.com/badge/github.com/posener/complete)](https://goreportcard.com/report/github.com/posener/complete) diff --git a/vendor/github.com/spf13/afero/.travis.yml b/vendor/github.com/spf13/afero/.travis.yml deleted file mode 100644 index 0637db72..00000000 --- a/vendor/github.com/spf13/afero/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -sudo: false -language: go - -go: - - 1.9 - - "1.10" - - tip - -os: - - linux - - osx - -matrix: - allow_failures: - - go: tip - fast_finish: true - -script: - - go build - - go test -race -v ./... - diff --git a/vendor/github.com/spf13/afero/LICENSE.txt b/vendor/github.com/spf13/afero/LICENSE.txt deleted file mode 100644 index 298f0e26..00000000 --- a/vendor/github.com/spf13/afero/LICENSE.txt +++ /dev/null @@ -1,174 +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. diff --git a/vendor/github.com/spf13/afero/README.md b/vendor/github.com/spf13/afero/README.md deleted file mode 100644 index 0c9b04b5..00000000 --- a/vendor/github.com/spf13/afero/README.md +++ /dev/null @@ -1,452 +0,0 @@ -![afero logo-sm](https://cloud.githubusercontent.com/assets/173412/11490338/d50e16dc-97a5-11e5-8b12-019a300d0fcb.png) - -A FileSystem Abstraction System for Go - -[![Build Status](https://travis-ci.org/spf13/afero.svg)](https://travis-ci.org/spf13/afero) [![Build status](https://ci.appveyor.com/api/projects/status/github/spf13/afero?branch=master&svg=true)](https://ci.appveyor.com/project/spf13/afero) [![GoDoc](https://godoc.org/github.com/spf13/afero?status.svg)](https://godoc.org/github.com/spf13/afero) [![Join the chat at https://gitter.im/spf13/afero](https://badges.gitter.im/Dev%20Chat.svg)](https://gitter.im/spf13/afero?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -# Overview - -Afero is an filesystem framework providing a simple, uniform and universal API -interacting with any filesystem, as an abstraction layer providing interfaces, -types and methods. Afero has an exceptionally clean interface and simple design -without needless constructors or initialization methods. - -Afero is also a library providing a base set of interoperable backend -filesystems that make it easy to work with afero while retaining all the power -and benefit of the os and ioutil packages. - -Afero provides significant improvements over using the os package alone, most -notably the ability to create mock and testing filesystems without relying on the disk. - -It is suitable for use in a any situation where you would consider using the OS -package as it provides an additional abstraction that makes it easy to use a -memory backed file system during testing. It also adds support for the http -filesystem for full interoperability. - - -## Afero Features - -* A single consistent API for accessing a variety of filesystems -* Interoperation between a variety of file system types -* A set of interfaces to encourage and enforce interoperability between backends -* An atomic cross platform memory backed file system -* Support for compositional (union) file systems by combining multiple file systems acting as one -* Specialized backends which modify existing filesystems (Read Only, Regexp filtered) -* A set of utility functions ported from io, ioutil & hugo to be afero aware - - -# Using Afero - -Afero is easy to use and easier to adopt. - -A few different ways you could use Afero: - -* Use the interfaces alone to define you own file system. -* Wrap for the OS packages. -* Define different filesystems for different parts of your application. -* Use Afero for mock filesystems while testing - -## Step 1: Install Afero - -First use go get to install the latest version of the library. - - $ go get github.com/spf13/afero - -Next include Afero in your application. -```go -import "github.com/spf13/afero" -``` - -## Step 2: Declare a backend - -First define a package variable and set it to a pointer to a filesystem. -```go -var AppFs = afero.NewMemMapFs() - -or - -var AppFs = afero.NewOsFs() -``` -It is important to note that if you repeat the composite literal you -will be using a completely new and isolated filesystem. In the case of -OsFs it will still use the same underlying filesystem but will reduce -the ability to drop in other filesystems as desired. - -## Step 3: Use it like you would the OS package - -Throughout your application use any function and method like you normally -would. - -So if my application before had: -```go -os.Open('/tmp/foo') -``` -We would replace it with: -```go -AppFs.Open('/tmp/foo') -``` - -`AppFs` being the variable we defined above. - - -## List of all available functions - -File System Methods Available: -```go -Chmod(name string, mode os.FileMode) : error -Chtimes(name string, atime time.Time, mtime time.Time) : error -Create(name string) : File, error -Mkdir(name string, perm os.FileMode) : error -MkdirAll(path string, perm os.FileMode) : error -Name() : string -Open(name string) : File, error -OpenFile(name string, flag int, perm os.FileMode) : File, error -Remove(name string) : error -RemoveAll(path string) : error -Rename(oldname, newname string) : error -Stat(name string) : os.FileInfo, error -``` -File Interfaces and Methods Available: -```go -io.Closer -io.Reader -io.ReaderAt -io.Seeker -io.Writer -io.WriterAt - -Name() : string -Readdir(count int) : []os.FileInfo, error -Readdirnames(n int) : []string, error -Stat() : os.FileInfo, error -Sync() : error -Truncate(size int64) : error -WriteString(s string) : ret int, err error -``` -In some applications it may make sense to define a new package that -simply exports the file system variable for easy access from anywhere. - -## Using Afero's utility functions - -Afero provides a set of functions to make it easier to use the underlying file systems. -These functions have been primarily ported from io & ioutil with some developed for Hugo. - -The afero utilities support all afero compatible backends. - -The list of utilities includes: - -```go -DirExists(path string) (bool, error) -Exists(path string) (bool, error) -FileContainsBytes(filename string, subslice []byte) (bool, error) -GetTempDir(subPath string) string -IsDir(path string) (bool, error) -IsEmpty(path string) (bool, error) -ReadDir(dirname string) ([]os.FileInfo, error) -ReadFile(filename string) ([]byte, error) -SafeWriteReader(path string, r io.Reader) (err error) -TempDir(dir, prefix string) (name string, err error) -TempFile(dir, prefix string) (f File, err error) -Walk(root string, walkFn filepath.WalkFunc) error -WriteFile(filename string, data []byte, perm os.FileMode) error -WriteReader(path string, r io.Reader) (err error) -``` -For a complete list see [Afero's GoDoc](https://godoc.org/github.com/spf13/afero) - -They are available under two different approaches to use. You can either call -them directly where the first parameter of each function will be the file -system, or you can declare a new `Afero`, a custom type used to bind these -functions as methods to a given filesystem. - -### Calling utilities directly - -```go -fs := new(afero.MemMapFs) -f, err := afero.TempFile(fs,"", "ioutil-test") - -``` - -### Calling via Afero - -```go -fs := afero.NewMemMapFs() -afs := &afero.Afero{Fs: fs} -f, err := afs.TempFile("", "ioutil-test") -``` - -## Using Afero for Testing - -There is a large benefit to using a mock filesystem for testing. It has a -completely blank state every time it is initialized and can be easily -reproducible regardless of OS. You could create files to your heart’s content -and the file access would be fast while also saving you from all the annoying -issues with deleting temporary files, Windows file locking, etc. The MemMapFs -backend is perfect for testing. - -* Much faster than performing I/O operations on disk -* Avoid security issues and permissions -* Far more control. 'rm -rf /' with confidence -* Test setup is far more easier to do -* No test cleanup needed - -One way to accomplish this is to define a variable as mentioned above. -In your application this will be set to afero.NewOsFs() during testing you -can set it to afero.NewMemMapFs(). - -It wouldn't be uncommon to have each test initialize a blank slate memory -backend. To do this I would define my `appFS = afero.NewOsFs()` somewhere -appropriate in my application code. This approach ensures that Tests are order -independent, with no test relying on the state left by an earlier test. - -Then in my tests I would initialize a new MemMapFs for each test: -```go -func TestExist(t *testing.T) { - appFS := afero.NewMemMapFs() - // create test files and directories - appFS.MkdirAll("src/a", 0755) - afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644) - afero.WriteFile(appFS, "src/c", []byte("file c"), 0644) - name := "src/c" - _, err := appFS.Stat(name) - if os.IsNotExist(err) { - t.Errorf("file \"%s\" does not exist.\n", name) - } -} -``` - -# Available Backends - -## Operating System Native - -### OsFs - -The first is simply a wrapper around the native OS calls. This makes it -very easy to use as all of the calls are the same as the existing OS -calls. It also makes it trivial to have your code use the OS during -operation and a mock filesystem during testing or as needed. - -```go -appfs := afero.NewOsFs() -appfs.MkdirAll("src/a", 0755)) -``` - -## Memory Backed Storage - -### MemMapFs - -Afero also provides a fully atomic memory backed filesystem perfect for use in -mocking and to speed up unnecessary disk io when persistence isn’t -necessary. It is fully concurrent and will work within go routines -safely. - -```go -mm := afero.NewMemMapFs() -mm.MkdirAll("src/a", 0755)) -``` - -#### InMemoryFile - -As part of MemMapFs, Afero also provides an atomic, fully concurrent memory -backed file implementation. This can be used in other memory backed file -systems with ease. Plans are to add a radix tree memory stored file -system using InMemoryFile. - -## Network Interfaces - -### SftpFs - -Afero has experimental support for secure file transfer protocol (sftp). Which can -be used to perform file operations over a encrypted channel. - -## Filtering Backends - -### BasePathFs - -The BasePathFs restricts all operations to a given path within an Fs. -The given file name to the operations on this Fs will be prepended with -the base path before calling the source Fs. - -```go -bp := afero.NewBasePathFs(afero.NewOsFs(), "/base/path") -``` - -### ReadOnlyFs - -A thin wrapper around the source Fs providing a read only view. - -```go -fs := afero.NewReadOnlyFs(afero.NewOsFs()) -_, err := fs.Create("/file.txt") -// err = syscall.EPERM -``` - -# RegexpFs - -A filtered view on file names, any file NOT matching -the passed regexp will be treated as non-existing. -Files not matching the regexp provided will not be created. -Directories are not filtered. - -```go -fs := afero.NewRegexpFs(afero.NewMemMapFs(), regexp.MustCompile(`\.txt$`)) -_, err := fs.Create("/file.html") -// err = syscall.ENOENT -``` - -### HttpFs - -Afero provides an http compatible backend which can wrap any of the existing -backends. - -The Http package requires a slightly specific version of Open which -returns an http.File type. - -Afero provides an httpFs file system which satisfies this requirement. -Any Afero FileSystem can be used as an httpFs. - -```go -httpFs := afero.NewHttpFs() -fileserver := http.FileServer(httpFs.Dir())) -http.Handle("/", fileserver) -``` - -## Composite Backends - -Afero provides the ability have two filesystems (or more) act as a single -file system. - -### CacheOnReadFs - -The CacheOnReadFs will lazily make copies of any accessed files from the base -layer into the overlay. Subsequent reads will be pulled from the overlay -directly permitting the request is within the cache duration of when it was -created in the overlay. - -If the base filesystem is writeable, any changes to files will be -done first to the base, then to the overlay layer. Write calls to open file -handles like `Write()` or `Truncate()` to the overlay first. - -To writing files to the overlay only, you can use the overlay Fs directly (not -via the union Fs). - -Cache files in the layer for the given time.Duration, a cache duration of 0 -means "forever" meaning the file will not be re-requested from the base ever. - -A read-only base will make the overlay also read-only but still copy files -from the base to the overlay when they're not present (or outdated) in the -caching layer. - -```go -base := afero.NewOsFs() -layer := afero.NewMemMapFs() -ufs := afero.NewCacheOnReadFs(base, layer, 100 * time.Second) -``` - -### CopyOnWriteFs() - -The CopyOnWriteFs is a read only base file system with a potentially -writeable layer on top. - -Read operations will first look in the overlay and if not found there, will -serve the file from the base. - -Changes to the file system will only be made in the overlay. - -Any attempt to modify a file found only in the base will copy the file to the -overlay layer before modification (including opening a file with a writable -handle). - -Removing and Renaming files present only in the base layer is not currently -permitted. If a file is present in the base layer and the overlay, only the -overlay will be removed/renamed. - -```go - base := afero.NewOsFs() - roBase := afero.NewReadOnlyFs(base) - ufs := afero.NewCopyOnWriteFs(roBase, afero.NewMemMapFs()) - - fh, _ = ufs.Create("/home/test/file2.txt") - fh.WriteString("This is a test") - fh.Close() -``` - -In this example all write operations will only occur in memory (MemMapFs) -leaving the base filesystem (OsFs) untouched. - - -## Desired/possible backends - -The following is a short list of possible backends we hope someone will -implement: - -* SSH -* ZIP -* TAR -* S3 - -# About the project - -## What's in the name - -Afero comes from the latin roots Ad-Facere. - -**"Ad"** is a prefix meaning "to". - -**"Facere"** is a form of the root "faciō" making "make or do". - -The literal meaning of afero is "to make" or "to do" which seems very fitting -for a library that allows one to make files and directories and do things with them. - -The English word that shares the same roots as Afero is "affair". Affair shares -the same concept but as a noun it means "something that is made or done" or "an -object of a particular type". - -It's also nice that unlike some of my other libraries (hugo, cobra, viper) it -Googles very well. - -## Release Notes - -* **0.10.0** 2015.12.10 - * Full compatibility with Windows - * Introduction of afero utilities - * Test suite rewritten to work cross platform - * Normalize paths for MemMapFs - * Adding Sync to the file interface - * **Breaking Change** Walk and ReadDir have changed parameter order - * Moving types used by MemMapFs to a subpackage - * General bugfixes and improvements -* **0.9.0** 2015.11.05 - * New Walk function similar to filepath.Walk - * MemMapFs.OpenFile handles O_CREATE, O_APPEND, O_TRUNC - * MemMapFs.Remove now really deletes the file - * InMemoryFile.Readdir and Readdirnames work correctly - * InMemoryFile functions lock it for concurrent access - * Test suite improvements -* **0.8.0** 2014.10.28 - * First public version - * Interfaces feel ready for people to build using - * Interfaces satisfy all known uses - * MemMapFs passes the majority of the OS test suite - * OsFs passes the majority of the OS test suite - -## Contributing - -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Add some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request - -## Contributors - -Names in no particular order: - -* [spf13](https://github.com/spf13) -* [jaqx0r](https://github.com/jaqx0r) -* [mbertschler](https://github.com/mbertschler) -* [xor-gate](https://github.com/xor-gate) - -## License - -Afero is released under the Apache 2.0 license. See -[LICENSE.txt](https://github.com/spf13/afero/blob/master/LICENSE.txt) diff --git a/vendor/github.com/spf13/afero/afero.go b/vendor/github.com/spf13/afero/afero.go deleted file mode 100644 index f5b5e127..00000000 --- a/vendor/github.com/spf13/afero/afero.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright © 2014 Steve Francia . -// Copyright 2013 tsuru authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package afero provides types and methods for interacting with the filesystem, -// as an abstraction layer. - -// Afero also provides a few implementations that are mostly interoperable. One that -// uses the operating system filesystem, one that uses memory to store files -// (cross platform) and an interface that should be implemented if you want to -// provide your own filesystem. - -package afero - -import ( - "errors" - "io" - "os" - "time" -) - -type Afero struct { - Fs -} - -// File represents a file in the filesystem. -type File interface { - io.Closer - io.Reader - io.ReaderAt - io.Seeker - io.Writer - io.WriterAt - - Name() string - Readdir(count int) ([]os.FileInfo, error) - Readdirnames(n int) ([]string, error) - Stat() (os.FileInfo, error) - Sync() error - Truncate(size int64) error - WriteString(s string) (ret int, err error) -} - -// Fs is the filesystem interface. -// -// Any simulated or real filesystem should implement this interface. -type Fs interface { - // Create creates a file in the filesystem, returning the file and an - // error, if any happens. - Create(name string) (File, error) - - // Mkdir creates a directory in the filesystem, return an error if any - // happens. - Mkdir(name string, perm os.FileMode) error - - // MkdirAll creates a directory path and all parents that does not exist - // yet. - MkdirAll(path string, perm os.FileMode) error - - // Open opens a file, returning it or an error, if any happens. - Open(name string) (File, error) - - // OpenFile opens a file using the given flags and the given mode. - OpenFile(name string, flag int, perm os.FileMode) (File, error) - - // Remove removes a file identified by name, returning an error, if any - // happens. - Remove(name string) error - - // RemoveAll removes a directory path and any children it contains. It - // does not fail if the path does not exist (return nil). - RemoveAll(path string) error - - // Rename renames a file. - Rename(oldname, newname string) error - - // Stat returns a FileInfo describing the named file, or an error, if any - // happens. - Stat(name string) (os.FileInfo, error) - - // The name of this FileSystem - Name() string - - //Chmod changes the mode of the named file to mode. - Chmod(name string, mode os.FileMode) error - - //Chtimes changes the access and modification times of the named file - Chtimes(name string, atime time.Time, mtime time.Time) error -} - -var ( - ErrFileClosed = errors.New("File is closed") - ErrOutOfRange = errors.New("Out of range") - ErrTooLarge = errors.New("Too large") - ErrFileNotFound = os.ErrNotExist - ErrFileExists = os.ErrExist - ErrDestinationExists = os.ErrExist -) diff --git a/vendor/github.com/spf13/afero/appveyor.yml b/vendor/github.com/spf13/afero/appveyor.yml deleted file mode 100644 index a633ad50..00000000 --- a/vendor/github.com/spf13/afero/appveyor.yml +++ /dev/null @@ -1,15 +0,0 @@ -version: '{build}' -clone_folder: C:\gopath\src\github.com\spf13\afero -environment: - GOPATH: C:\gopath -build_script: -- cmd: >- - go version - - go env - - go get -v github.com/spf13/afero/... - - go build github.com/spf13/afero -test_script: -- cmd: go test -race -v github.com/spf13/afero/... diff --git a/vendor/github.com/spf13/afero/basepath.go b/vendor/github.com/spf13/afero/basepath.go deleted file mode 100644 index 616ff8ff..00000000 --- a/vendor/github.com/spf13/afero/basepath.go +++ /dev/null @@ -1,180 +0,0 @@ -package afero - -import ( - "os" - "path/filepath" - "runtime" - "strings" - "time" -) - -var _ Lstater = (*BasePathFs)(nil) - -// The BasePathFs restricts all operations to a given path within an Fs. -// The given file name to the operations on this Fs will be prepended with -// the base path before calling the base Fs. -// Any file name (after filepath.Clean()) outside this base path will be -// treated as non existing file. -// -// Note that it does not clean the error messages on return, so you may -// reveal the real path on errors. -type BasePathFs struct { - source Fs - path string -} - -type BasePathFile struct { - File - path string -} - -func (f *BasePathFile) Name() string { - sourcename := f.File.Name() - return strings.TrimPrefix(sourcename, filepath.Clean(f.path)) -} - -func NewBasePathFs(source Fs, path string) Fs { - return &BasePathFs{source: source, path: path} -} - -// on a file outside the base path it returns the given file name and an error, -// else the given file with the base path prepended -func (b *BasePathFs) RealPath(name string) (path string, err error) { - if err := validateBasePathName(name); err != nil { - return name, err - } - - bpath := filepath.Clean(b.path) - path = filepath.Clean(filepath.Join(bpath, name)) - if !strings.HasPrefix(path, bpath) { - return name, os.ErrNotExist - } - - return path, nil -} - -func validateBasePathName(name string) error { - if runtime.GOOS != "windows" { - // Not much to do here; - // the virtual file paths all look absolute on *nix. - return nil - } - - // On Windows a common mistake would be to provide an absolute OS path - // We could strip out the base part, but that would not be very portable. - if filepath.IsAbs(name) { - return os.ErrNotExist - } - - return nil -} - -func (b *BasePathFs) Chtimes(name string, atime, mtime time.Time) (err error) { - if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "chtimes", Path: name, Err: err} - } - return b.source.Chtimes(name, atime, mtime) -} - -func (b *BasePathFs) Chmod(name string, mode os.FileMode) (err error) { - if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "chmod", Path: name, Err: err} - } - return b.source.Chmod(name, mode) -} - -func (b *BasePathFs) Name() string { - return "BasePathFs" -} - -func (b *BasePathFs) Stat(name string) (fi os.FileInfo, err error) { - if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{Op: "stat", Path: name, Err: err} - } - return b.source.Stat(name) -} - -func (b *BasePathFs) Rename(oldname, newname string) (err error) { - if oldname, err = b.RealPath(oldname); err != nil { - return &os.PathError{Op: "rename", Path: oldname, Err: err} - } - if newname, err = b.RealPath(newname); err != nil { - return &os.PathError{Op: "rename", Path: newname, Err: err} - } - return b.source.Rename(oldname, newname) -} - -func (b *BasePathFs) RemoveAll(name string) (err error) { - if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "remove_all", Path: name, Err: err} - } - return b.source.RemoveAll(name) -} - -func (b *BasePathFs) Remove(name string) (err error) { - if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "remove", Path: name, Err: err} - } - return b.source.Remove(name) -} - -func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File, err error) { - if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{Op: "openfile", Path: name, Err: err} - } - sourcef, err := b.source.OpenFile(name, flag, mode) - if err != nil { - return nil, err - } - return &BasePathFile{sourcef, b.path}, nil -} - -func (b *BasePathFs) Open(name string) (f File, err error) { - if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{Op: "open", Path: name, Err: err} - } - sourcef, err := b.source.Open(name) - if err != nil { - return nil, err - } - return &BasePathFile{File: sourcef, path: b.path}, nil -} - -func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) { - if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - return b.source.Mkdir(name, mode) -} - -func (b *BasePathFs) MkdirAll(name string, mode os.FileMode) (err error) { - if name, err = b.RealPath(name); err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - return b.source.MkdirAll(name, mode) -} - -func (b *BasePathFs) Create(name string) (f File, err error) { - if name, err = b.RealPath(name); err != nil { - return nil, &os.PathError{Op: "create", Path: name, Err: err} - } - sourcef, err := b.source.Create(name) - if err != nil { - return nil, err - } - return &BasePathFile{File: sourcef, path: b.path}, nil -} - -func (b *BasePathFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { - name, err := b.RealPath(name) - if err != nil { - return nil, false, &os.PathError{Op: "lstat", Path: name, Err: err} - } - if lstater, ok := b.source.(Lstater); ok { - return lstater.LstatIfPossible(name) - } - fi, err := b.source.Stat(name) - return fi, false, err -} - -// vim: ts=4 sw=4 noexpandtab nolist syn=go diff --git a/vendor/github.com/spf13/afero/cacheOnReadFs.go b/vendor/github.com/spf13/afero/cacheOnReadFs.go deleted file mode 100644 index 29a26c67..00000000 --- a/vendor/github.com/spf13/afero/cacheOnReadFs.go +++ /dev/null @@ -1,290 +0,0 @@ -package afero - -import ( - "os" - "syscall" - "time" -) - -// If the cache duration is 0, cache time will be unlimited, i.e. once -// a file is in the layer, the base will never be read again for this file. -// -// For cache times greater than 0, the modification time of a file is -// checked. Note that a lot of file system implementations only allow a -// resolution of a second for timestamps... or as the godoc for os.Chtimes() -// states: "The underlying filesystem may truncate or round the values to a -// less precise time unit." -// -// This caching union will forward all write calls also to the base file -// system first. To prevent writing to the base Fs, wrap it in a read-only -// filter - Note: this will also make the overlay read-only, for writing files -// in the overlay, use the overlay Fs directly, not via the union Fs. -type CacheOnReadFs struct { - base Fs - layer Fs - cacheTime time.Duration -} - -func NewCacheOnReadFs(base Fs, layer Fs, cacheTime time.Duration) Fs { - return &CacheOnReadFs{base: base, layer: layer, cacheTime: cacheTime} -} - -type cacheState int - -const ( - // not present in the overlay, unknown if it exists in the base: - cacheMiss cacheState = iota - // present in the overlay and in base, base file is newer: - cacheStale - // present in the overlay - with cache time == 0 it may exist in the base, - // with cacheTime > 0 it exists in the base and is same age or newer in the - // overlay - cacheHit - // happens if someone writes directly to the overlay without - // going through this union - cacheLocal -) - -func (u *CacheOnReadFs) cacheStatus(name string) (state cacheState, fi os.FileInfo, err error) { - var lfi, bfi os.FileInfo - lfi, err = u.layer.Stat(name) - if err == nil { - if u.cacheTime == 0 { - return cacheHit, lfi, nil - } - if lfi.ModTime().Add(u.cacheTime).Before(time.Now()) { - bfi, err = u.base.Stat(name) - if err != nil { - return cacheLocal, lfi, nil - } - if bfi.ModTime().After(lfi.ModTime()) { - return cacheStale, bfi, nil - } - } - return cacheHit, lfi, nil - } - - if err == syscall.ENOENT || os.IsNotExist(err) { - return cacheMiss, nil, nil - } - - return cacheMiss, nil, err -} - -func (u *CacheOnReadFs) copyToLayer(name string) error { - return copyToLayer(u.base, u.layer, name) -} - -func (u *CacheOnReadFs) Chtimes(name string, atime, mtime time.Time) error { - st, _, err := u.cacheStatus(name) - if err != nil { - return err - } - switch st { - case cacheLocal: - case cacheHit: - err = u.base.Chtimes(name, atime, mtime) - case cacheStale, cacheMiss: - if err := u.copyToLayer(name); err != nil { - return err - } - err = u.base.Chtimes(name, atime, mtime) - } - if err != nil { - return err - } - return u.layer.Chtimes(name, atime, mtime) -} - -func (u *CacheOnReadFs) Chmod(name string, mode os.FileMode) error { - st, _, err := u.cacheStatus(name) - if err != nil { - return err - } - switch st { - case cacheLocal: - case cacheHit: - err = u.base.Chmod(name, mode) - case cacheStale, cacheMiss: - if err := u.copyToLayer(name); err != nil { - return err - } - err = u.base.Chmod(name, mode) - } - if err != nil { - return err - } - return u.layer.Chmod(name, mode) -} - -func (u *CacheOnReadFs) Stat(name string) (os.FileInfo, error) { - st, fi, err := u.cacheStatus(name) - if err != nil { - return nil, err - } - switch st { - case cacheMiss: - return u.base.Stat(name) - default: // cacheStale has base, cacheHit and cacheLocal the layer os.FileInfo - return fi, nil - } -} - -func (u *CacheOnReadFs) Rename(oldname, newname string) error { - st, _, err := u.cacheStatus(oldname) - if err != nil { - return err - } - switch st { - case cacheLocal: - case cacheHit: - err = u.base.Rename(oldname, newname) - case cacheStale, cacheMiss: - if err := u.copyToLayer(oldname); err != nil { - return err - } - err = u.base.Rename(oldname, newname) - } - if err != nil { - return err - } - return u.layer.Rename(oldname, newname) -} - -func (u *CacheOnReadFs) Remove(name string) error { - st, _, err := u.cacheStatus(name) - if err != nil { - return err - } - switch st { - case cacheLocal: - case cacheHit, cacheStale, cacheMiss: - err = u.base.Remove(name) - } - if err != nil { - return err - } - return u.layer.Remove(name) -} - -func (u *CacheOnReadFs) RemoveAll(name string) error { - st, _, err := u.cacheStatus(name) - if err != nil { - return err - } - switch st { - case cacheLocal: - case cacheHit, cacheStale, cacheMiss: - err = u.base.RemoveAll(name) - } - if err != nil { - return err - } - return u.layer.RemoveAll(name) -} - -func (u *CacheOnReadFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - st, _, err := u.cacheStatus(name) - if err != nil { - return nil, err - } - switch st { - case cacheLocal, cacheHit: - default: - if err := u.copyToLayer(name); err != nil { - return nil, err - } - } - if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 { - bfi, err := u.base.OpenFile(name, flag, perm) - if err != nil { - return nil, err - } - lfi, err := u.layer.OpenFile(name, flag, perm) - if err != nil { - bfi.Close() // oops, what if O_TRUNC was set and file opening in the layer failed...? - return nil, err - } - return &UnionFile{Base: bfi, Layer: lfi}, nil - } - return u.layer.OpenFile(name, flag, perm) -} - -func (u *CacheOnReadFs) Open(name string) (File, error) { - st, fi, err := u.cacheStatus(name) - if err != nil { - return nil, err - } - - switch st { - case cacheLocal: - return u.layer.Open(name) - - case cacheMiss: - bfi, err := u.base.Stat(name) - if err != nil { - return nil, err - } - if bfi.IsDir() { - return u.base.Open(name) - } - if err := u.copyToLayer(name); err != nil { - return nil, err - } - return u.layer.Open(name) - - case cacheStale: - if !fi.IsDir() { - if err := u.copyToLayer(name); err != nil { - return nil, err - } - return u.layer.Open(name) - } - case cacheHit: - if !fi.IsDir() { - return u.layer.Open(name) - } - } - // the dirs from cacheHit, cacheStale fall down here: - bfile, _ := u.base.Open(name) - lfile, err := u.layer.Open(name) - if err != nil && bfile == nil { - return nil, err - } - return &UnionFile{Base: bfile, Layer: lfile}, nil -} - -func (u *CacheOnReadFs) Mkdir(name string, perm os.FileMode) error { - err := u.base.Mkdir(name, perm) - if err != nil { - return err - } - return u.layer.MkdirAll(name, perm) // yes, MkdirAll... we cannot assume it exists in the cache -} - -func (u *CacheOnReadFs) Name() string { - return "CacheOnReadFs" -} - -func (u *CacheOnReadFs) MkdirAll(name string, perm os.FileMode) error { - err := u.base.MkdirAll(name, perm) - if err != nil { - return err - } - return u.layer.MkdirAll(name, perm) -} - -func (u *CacheOnReadFs) Create(name string) (File, error) { - bfh, err := u.base.Create(name) - if err != nil { - return nil, err - } - lfh, err := u.layer.Create(name) - if err != nil { - // oops, see comment about OS_TRUNC above, should we remove? then we have to - // remember if the file did not exist before - bfh.Close() - return nil, err - } - return &UnionFile{Base: bfh, Layer: lfh}, nil -} diff --git a/vendor/github.com/spf13/afero/const_bsds.go b/vendor/github.com/spf13/afero/const_bsds.go deleted file mode 100644 index 5728243d..00000000 --- a/vendor/github.com/spf13/afero/const_bsds.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright © 2016 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build darwin openbsd freebsd netbsd dragonfly - -package afero - -import ( - "syscall" -) - -const BADFD = syscall.EBADF diff --git a/vendor/github.com/spf13/afero/const_win_unix.go b/vendor/github.com/spf13/afero/const_win_unix.go deleted file mode 100644 index 968fc278..00000000 --- a/vendor/github.com/spf13/afero/const_win_unix.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright © 2016 Steve Francia . -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// +build !darwin -// +build !openbsd -// +build !freebsd -// +build !dragonfly -// +build !netbsd - -package afero - -import ( - "syscall" -) - -const BADFD = syscall.EBADFD diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs.go b/vendor/github.com/spf13/afero/copyOnWriteFs.go deleted file mode 100644 index e8108a85..00000000 --- a/vendor/github.com/spf13/afero/copyOnWriteFs.go +++ /dev/null @@ -1,293 +0,0 @@ -package afero - -import ( - "fmt" - "os" - "path/filepath" - "syscall" - "time" -) - -var _ Lstater = (*CopyOnWriteFs)(nil) - -// The CopyOnWriteFs is a union filesystem: a read only base file system with -// a possibly writeable layer on top. Changes to the file system will only -// be made in the overlay: Changing an existing file in the base layer which -// is not present in the overlay will copy the file to the overlay ("changing" -// includes also calls to e.g. Chtimes() and Chmod()). -// -// Reading directories is currently only supported via Open(), not OpenFile(). -type CopyOnWriteFs struct { - base Fs - layer Fs -} - -func NewCopyOnWriteFs(base Fs, layer Fs) Fs { - return &CopyOnWriteFs{base: base, layer: layer} -} - -// Returns true if the file is not in the overlay -func (u *CopyOnWriteFs) isBaseFile(name string) (bool, error) { - if _, err := u.layer.Stat(name); err == nil { - return false, nil - } - _, err := u.base.Stat(name) - if err != nil { - if oerr, ok := err.(*os.PathError); ok { - if oerr.Err == os.ErrNotExist || oerr.Err == syscall.ENOENT || oerr.Err == syscall.ENOTDIR { - return false, nil - } - } - if err == syscall.ENOENT { - return false, nil - } - } - return true, err -} - -func (u *CopyOnWriteFs) copyToLayer(name string) error { - return copyToLayer(u.base, u.layer, name) -} - -func (u *CopyOnWriteFs) Chtimes(name string, atime, mtime time.Time) error { - b, err := u.isBaseFile(name) - if err != nil { - return err - } - if b { - if err := u.copyToLayer(name); err != nil { - return err - } - } - return u.layer.Chtimes(name, atime, mtime) -} - -func (u *CopyOnWriteFs) Chmod(name string, mode os.FileMode) error { - b, err := u.isBaseFile(name) - if err != nil { - return err - } - if b { - if err := u.copyToLayer(name); err != nil { - return err - } - } - return u.layer.Chmod(name, mode) -} - -func (u *CopyOnWriteFs) Stat(name string) (os.FileInfo, error) { - fi, err := u.layer.Stat(name) - if err != nil { - isNotExist := u.isNotExist(err) - if isNotExist { - return u.base.Stat(name) - } - return nil, err - } - return fi, nil -} - -func (u *CopyOnWriteFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { - llayer, ok1 := u.layer.(Lstater) - lbase, ok2 := u.base.(Lstater) - - if ok1 { - fi, b, err := llayer.LstatIfPossible(name) - if err == nil { - return fi, b, nil - } - - if !u.isNotExist(err) { - return nil, b, err - } - } - - if ok2 { - fi, b, err := lbase.LstatIfPossible(name) - if err == nil { - return fi, b, nil - } - if !u.isNotExist(err) { - return nil, b, err - } - } - - fi, err := u.Stat(name) - - return fi, false, err -} - -func (u *CopyOnWriteFs) isNotExist(err error) bool { - if e, ok := err.(*os.PathError); ok { - err = e.Err - } - if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR { - return true - } - return false -} - -// Renaming files present only in the base layer is not permitted -func (u *CopyOnWriteFs) Rename(oldname, newname string) error { - b, err := u.isBaseFile(oldname) - if err != nil { - return err - } - if b { - return syscall.EPERM - } - return u.layer.Rename(oldname, newname) -} - -// Removing files present only in the base layer is not permitted. If -// a file is present in the base layer and the overlay, only the overlay -// will be removed. -func (u *CopyOnWriteFs) Remove(name string) error { - err := u.layer.Remove(name) - switch err { - case syscall.ENOENT: - _, err = u.base.Stat(name) - if err == nil { - return syscall.EPERM - } - return syscall.ENOENT - default: - return err - } -} - -func (u *CopyOnWriteFs) RemoveAll(name string) error { - err := u.layer.RemoveAll(name) - switch err { - case syscall.ENOENT: - _, err = u.base.Stat(name) - if err == nil { - return syscall.EPERM - } - return syscall.ENOENT - default: - return err - } -} - -func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - b, err := u.isBaseFile(name) - if err != nil { - return nil, err - } - - if flag&(os.O_WRONLY|os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 { - if b { - if err = u.copyToLayer(name); err != nil { - return nil, err - } - return u.layer.OpenFile(name, flag, perm) - } - - dir := filepath.Dir(name) - isaDir, err := IsDir(u.base, dir) - if err != nil && !os.IsNotExist(err) { - return nil, err - } - if isaDir { - if err = u.layer.MkdirAll(dir, 0777); err != nil { - return nil, err - } - return u.layer.OpenFile(name, flag, perm) - } - - isaDir, err = IsDir(u.layer, dir) - if err != nil { - return nil, err - } - if isaDir { - return u.layer.OpenFile(name, flag, perm) - } - - return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOTDIR} // ...or os.ErrNotExist? - } - if b { - return u.base.OpenFile(name, flag, perm) - } - return u.layer.OpenFile(name, flag, perm) -} - -// This function handles the 9 different possibilities caused -// by the union which are the intersection of the following... -// layer: doesn't exist, exists as a file, and exists as a directory -// base: doesn't exist, exists as a file, and exists as a directory -func (u *CopyOnWriteFs) Open(name string) (File, error) { - // Since the overlay overrides the base we check that first - b, err := u.isBaseFile(name) - if err != nil { - return nil, err - } - - // If overlay doesn't exist, return the base (base state irrelevant) - if b { - return u.base.Open(name) - } - - // If overlay is a file, return it (base state irrelevant) - dir, err := IsDir(u.layer, name) - if err != nil { - return nil, err - } - if !dir { - return u.layer.Open(name) - } - - // Overlay is a directory, base state now matters. - // Base state has 3 states to check but 2 outcomes: - // A. It's a file or non-readable in the base (return just the overlay) - // B. It's an accessible directory in the base (return a UnionFile) - - // If base is file or nonreadable, return overlay - dir, err = IsDir(u.base, name) - if !dir || err != nil { - return u.layer.Open(name) - } - - // Both base & layer are directories - // Return union file (if opens are without error) - bfile, bErr := u.base.Open(name) - lfile, lErr := u.layer.Open(name) - - // If either have errors at this point something is very wrong. Return nil and the errors - if bErr != nil || lErr != nil { - return nil, fmt.Errorf("BaseErr: %v\nOverlayErr: %v", bErr, lErr) - } - - return &UnionFile{Base: bfile, Layer: lfile}, nil -} - -func (u *CopyOnWriteFs) Mkdir(name string, perm os.FileMode) error { - dir, err := IsDir(u.base, name) - if err != nil { - return u.layer.MkdirAll(name, perm) - } - if dir { - return ErrFileExists - } - return u.layer.MkdirAll(name, perm) -} - -func (u *CopyOnWriteFs) Name() string { - return "CopyOnWriteFs" -} - -func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error { - dir, err := IsDir(u.base, name) - if err != nil { - return u.layer.MkdirAll(name, perm) - } - if dir { - // This is in line with how os.MkdirAll behaves. - return nil - } - return u.layer.MkdirAll(name, perm) -} - -func (u *CopyOnWriteFs) Create(name string) (File, error) { - return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666) -} diff --git a/vendor/github.com/spf13/afero/go.mod b/vendor/github.com/spf13/afero/go.mod deleted file mode 100644 index 08685509..00000000 --- a/vendor/github.com/spf13/afero/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/spf13/afero - -require golang.org/x/text v0.3.0 diff --git a/vendor/github.com/spf13/afero/go.sum b/vendor/github.com/spf13/afero/go.sum deleted file mode 100644 index 6bad37b2..00000000 --- a/vendor/github.com/spf13/afero/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= diff --git a/vendor/github.com/spf13/afero/httpFs.go b/vendor/github.com/spf13/afero/httpFs.go deleted file mode 100644 index c4219368..00000000 --- a/vendor/github.com/spf13/afero/httpFs.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright © 2014 Steve Francia . -// -// 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 afero - -import ( - "errors" - "net/http" - "os" - "path" - "path/filepath" - "strings" - "time" -) - -type httpDir struct { - basePath string - fs HttpFs -} - -func (d httpDir) Open(name string) (http.File, error) { - if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 || - strings.Contains(name, "\x00") { - return nil, errors.New("http: invalid character in file path") - } - dir := string(d.basePath) - if dir == "" { - dir = "." - } - - f, err := d.fs.Open(filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))) - if err != nil { - return nil, err - } - return f, nil -} - -type HttpFs struct { - source Fs -} - -func NewHttpFs(source Fs) *HttpFs { - return &HttpFs{source: source} -} - -func (h HttpFs) Dir(s string) *httpDir { - return &httpDir{basePath: s, fs: h} -} - -func (h HttpFs) Name() string { return "h HttpFs" } - -func (h HttpFs) Create(name string) (File, error) { - return h.source.Create(name) -} - -func (h HttpFs) Chmod(name string, mode os.FileMode) error { - return h.source.Chmod(name, mode) -} - -func (h HttpFs) Chtimes(name string, atime time.Time, mtime time.Time) error { - return h.source.Chtimes(name, atime, mtime) -} - -func (h HttpFs) Mkdir(name string, perm os.FileMode) error { - return h.source.Mkdir(name, perm) -} - -func (h HttpFs) MkdirAll(path string, perm os.FileMode) error { - return h.source.MkdirAll(path, perm) -} - -func (h HttpFs) Open(name string) (http.File, error) { - f, err := h.source.Open(name) - if err == nil { - if httpfile, ok := f.(http.File); ok { - return httpfile, nil - } - } - return nil, err -} - -func (h HttpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - return h.source.OpenFile(name, flag, perm) -} - -func (h HttpFs) Remove(name string) error { - return h.source.Remove(name) -} - -func (h HttpFs) RemoveAll(path string) error { - return h.source.RemoveAll(path) -} - -func (h HttpFs) Rename(oldname, newname string) error { - return h.source.Rename(oldname, newname) -} - -func (h HttpFs) Stat(name string) (os.FileInfo, error) { - return h.source.Stat(name) -} diff --git a/vendor/github.com/spf13/afero/ioutil.go b/vendor/github.com/spf13/afero/ioutil.go deleted file mode 100644 index 5c3a3d8f..00000000 --- a/vendor/github.com/spf13/afero/ioutil.go +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright ©2015 The Go Authors -// Copyright ©2015 Steve Francia -// -// 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 afero - -import ( - "bytes" - "io" - "os" - "path/filepath" - "sort" - "strconv" - "sync" - "time" -) - -// byName implements sort.Interface. -type byName []os.FileInfo - -func (f byName) Len() int { return len(f) } -func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() } -func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] } - -// ReadDir reads the directory named by dirname and returns -// a list of sorted directory entries. -func (a Afero) ReadDir(dirname string) ([]os.FileInfo, error) { - return ReadDir(a.Fs, dirname) -} - -func ReadDir(fs Fs, dirname string) ([]os.FileInfo, error) { - f, err := fs.Open(dirname) - if err != nil { - return nil, err - } - list, err := f.Readdir(-1) - f.Close() - if err != nil { - return nil, err - } - sort.Sort(byName(list)) - return list, nil -} - -// ReadFile reads the file named by filename and returns the contents. -// A successful call returns err == nil, not err == EOF. Because ReadFile -// reads the whole file, it does not treat an EOF from Read as an error -// to be reported. -func (a Afero) ReadFile(filename string) ([]byte, error) { - return ReadFile(a.Fs, filename) -} - -func ReadFile(fs Fs, filename string) ([]byte, error) { - f, err := fs.Open(filename) - if err != nil { - return nil, err - } - defer f.Close() - // It's a good but not certain bet that FileInfo will tell us exactly how much to - // read, so let's try it but be prepared for the answer to be wrong. - var n int64 - - if fi, err := f.Stat(); err == nil { - // Don't preallocate a huge buffer, just in case. - if size := fi.Size(); size < 1e9 { - n = size - } - } - // As initial capacity for readAll, use n + a little extra in case Size is zero, - // and to avoid another allocation after Read has filled the buffer. The readAll - // call will read into its allocated internal buffer cheaply. If the size was - // wrong, we'll either waste some space off the end or reallocate as needed, but - // in the overwhelmingly common case we'll get it just right. - return readAll(f, n+bytes.MinRead) -} - -// readAll reads from r until an error or EOF and returns the data it read -// from the internal buffer allocated with a specified capacity. -func readAll(r io.Reader, capacity int64) (b []byte, err error) { - buf := bytes.NewBuffer(make([]byte, 0, capacity)) - // If the buffer overflows, we will get bytes.ErrTooLarge. - // Return that as an error. Any other panic remains. - defer func() { - e := recover() - if e == nil { - return - } - if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge { - err = panicErr - } else { - panic(e) - } - }() - _, err = buf.ReadFrom(r) - return buf.Bytes(), err -} - -// ReadAll reads from r until an error or EOF and returns the data it read. -// A successful call returns err == nil, not err == EOF. Because ReadAll is -// defined to read from src until EOF, it does not treat an EOF from Read -// as an error to be reported. -func ReadAll(r io.Reader) ([]byte, error) { - return readAll(r, bytes.MinRead) -} - -// WriteFile writes data to a file named by filename. -// If the file does not exist, WriteFile creates it with permissions perm; -// otherwise WriteFile truncates it before writing. -func (a Afero) WriteFile(filename string, data []byte, perm os.FileMode) error { - return WriteFile(a.Fs, filename, data, perm) -} - -func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error { - f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) - if err != nil { - return err - } - n, err := f.Write(data) - if err == nil && n < len(data) { - err = io.ErrShortWrite - } - if err1 := f.Close(); err == nil { - err = err1 - } - return err -} - -// Random number state. -// We generate random temporary file names so that there's a good -// chance the file doesn't exist yet - keeps the number of tries in -// TempFile to a minimum. -var rand uint32 -var randmu sync.Mutex - -func reseed() uint32 { - return uint32(time.Now().UnixNano() + int64(os.Getpid())) -} - -func nextSuffix() string { - randmu.Lock() - r := rand - if r == 0 { - r = reseed() - } - r = r*1664525 + 1013904223 // constants from Numerical Recipes - rand = r - randmu.Unlock() - return strconv.Itoa(int(1e9 + r%1e9))[1:] -} - -// TempFile creates a new temporary file in the directory dir -// with a name beginning with prefix, opens the file for reading -// and writing, and returns the resulting *File. -// If dir is the empty string, TempFile uses the default directory -// for temporary files (see os.TempDir). -// Multiple programs calling TempFile simultaneously -// will not choose the same file. The caller can use f.Name() -// to find the pathname of the file. It is the caller's responsibility -// to remove the file when no longer needed. -func (a Afero) TempFile(dir, prefix string) (f File, err error) { - return TempFile(a.Fs, dir, prefix) -} - -func TempFile(fs Fs, dir, prefix string) (f File, err error) { - if dir == "" { - dir = os.TempDir() - } - - nconflict := 0 - for i := 0; i < 10000; i++ { - name := filepath.Join(dir, prefix+nextSuffix()) - f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if os.IsExist(err) { - if nconflict++; nconflict > 10 { - randmu.Lock() - rand = reseed() - randmu.Unlock() - } - continue - } - break - } - return -} - -// TempDir creates a new temporary directory in the directory dir -// with a name beginning with prefix and returns the path of the -// new directory. If dir is the empty string, TempDir uses the -// default directory for temporary files (see os.TempDir). -// Multiple programs calling TempDir simultaneously -// will not choose the same directory. It is the caller's responsibility -// to remove the directory when no longer needed. -func (a Afero) TempDir(dir, prefix string) (name string, err error) { - return TempDir(a.Fs, dir, prefix) -} -func TempDir(fs Fs, dir, prefix string) (name string, err error) { - if dir == "" { - dir = os.TempDir() - } - - nconflict := 0 - for i := 0; i < 10000; i++ { - try := filepath.Join(dir, prefix+nextSuffix()) - err = fs.Mkdir(try, 0700) - if os.IsExist(err) { - if nconflict++; nconflict > 10 { - randmu.Lock() - rand = reseed() - randmu.Unlock() - } - continue - } - if err == nil { - name = try - } - break - } - return -} diff --git a/vendor/github.com/spf13/afero/lstater.go b/vendor/github.com/spf13/afero/lstater.go deleted file mode 100644 index 89c1bfc0..00000000 --- a/vendor/github.com/spf13/afero/lstater.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2018 Steve Francia . -// -// 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 afero - -import ( - "os" -) - -// Lstater is an optional interface in Afero. It is only implemented by the -// filesystems saying so. -// It will call Lstat if the filesystem iself is, or it delegates to, the os filesystem. -// Else it will call Stat. -// In addtion to the FileInfo, it will return a boolean telling whether Lstat was called or not. -type Lstater interface { - LstatIfPossible(name string) (os.FileInfo, bool, error) -} diff --git a/vendor/github.com/spf13/afero/match.go b/vendor/github.com/spf13/afero/match.go deleted file mode 100644 index c18a87fb..00000000 --- a/vendor/github.com/spf13/afero/match.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright © 2014 Steve Francia . -// Copyright 2009 The Go Authors. All rights reserved. - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package afero - -import ( - "path/filepath" - "sort" - "strings" -) - -// Glob returns the names of all files matching pattern or nil -// if there is no matching file. The syntax of patterns is the same -// as in Match. The pattern may describe hierarchical names such as -// /usr/*/bin/ed (assuming the Separator is '/'). -// -// Glob ignores file system errors such as I/O errors reading directories. -// The only possible returned error is ErrBadPattern, when pattern -// is malformed. -// -// This was adapted from (http://golang.org/pkg/path/filepath) and uses several -// built-ins from that package. -func Glob(fs Fs, pattern string) (matches []string, err error) { - if !hasMeta(pattern) { - // Lstat not supported by a ll filesystems. - if _, err = lstatIfPossible(fs, pattern); err != nil { - return nil, nil - } - return []string{pattern}, nil - } - - dir, file := filepath.Split(pattern) - switch dir { - case "": - dir = "." - case string(filepath.Separator): - // nothing - default: - dir = dir[0 : len(dir)-1] // chop off trailing separator - } - - if !hasMeta(dir) { - return glob(fs, dir, file, nil) - } - - var m []string - m, err = Glob(fs, dir) - if err != nil { - return - } - for _, d := range m { - matches, err = glob(fs, d, file, matches) - if err != nil { - return - } - } - return -} - -// glob searches for files matching pattern in the directory dir -// and appends them to matches. If the directory cannot be -// opened, it returns the existing matches. New matches are -// added in lexicographical order. -func glob(fs Fs, dir, pattern string, matches []string) (m []string, e error) { - m = matches - fi, err := fs.Stat(dir) - if err != nil { - return - } - if !fi.IsDir() { - return - } - d, err := fs.Open(dir) - if err != nil { - return - } - defer d.Close() - - names, _ := d.Readdirnames(-1) - sort.Strings(names) - - for _, n := range names { - matched, err := filepath.Match(pattern, n) - if err != nil { - return m, err - } - if matched { - m = append(m, filepath.Join(dir, n)) - } - } - return -} - -// hasMeta reports whether path contains any of the magic characters -// recognized by Match. -func hasMeta(path string) bool { - // TODO(niemeyer): Should other magic characters be added here? - return strings.IndexAny(path, "*?[") >= 0 -} diff --git a/vendor/github.com/spf13/afero/mem/dir.go b/vendor/github.com/spf13/afero/mem/dir.go deleted file mode 100644 index e104013f..00000000 --- a/vendor/github.com/spf13/afero/mem/dir.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright © 2014 Steve Francia . -// -// 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 mem - -type Dir interface { - Len() int - Names() []string - Files() []*FileData - Add(*FileData) - Remove(*FileData) -} - -func RemoveFromMemDir(dir *FileData, f *FileData) { - dir.memDir.Remove(f) -} - -func AddToMemDir(dir *FileData, f *FileData) { - dir.memDir.Add(f) -} - -func InitializeDir(d *FileData) { - if d.memDir == nil { - d.dir = true - d.memDir = &DirMap{} - } -} diff --git a/vendor/github.com/spf13/afero/mem/dirmap.go b/vendor/github.com/spf13/afero/mem/dirmap.go deleted file mode 100644 index 03a57ee5..00000000 --- a/vendor/github.com/spf13/afero/mem/dirmap.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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 mem - -import "sort" - -type DirMap map[string]*FileData - -func (m DirMap) Len() int { return len(m) } -func (m DirMap) Add(f *FileData) { m[f.name] = f } -func (m DirMap) Remove(f *FileData) { delete(m, f.name) } -func (m DirMap) Files() (files []*FileData) { - for _, f := range m { - files = append(files, f) - } - sort.Sort(filesSorter(files)) - return files -} - -// implement sort.Interface for []*FileData -type filesSorter []*FileData - -func (s filesSorter) Len() int { return len(s) } -func (s filesSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s filesSorter) Less(i, j int) bool { return s[i].name < s[j].name } - -func (m DirMap) Names() (names []string) { - for x := range m { - names = append(names, x) - } - return names -} diff --git a/vendor/github.com/spf13/afero/mem/file.go b/vendor/github.com/spf13/afero/mem/file.go deleted file mode 100644 index 7af2fb56..00000000 --- a/vendor/github.com/spf13/afero/mem/file.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright © 2015 Steve Francia . -// Copyright 2013 tsuru authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mem - -import ( - "bytes" - "errors" - "io" - "os" - "path/filepath" - "sync" - "sync/atomic" -) - -import "time" - -const FilePathSeparator = string(filepath.Separator) - -type File struct { - // atomic requires 64-bit alignment for struct field access - at int64 - readDirCount int64 - closed bool - readOnly bool - fileData *FileData -} - -func NewFileHandle(data *FileData) *File { - return &File{fileData: data} -} - -func NewReadOnlyFileHandle(data *FileData) *File { - return &File{fileData: data, readOnly: true} -} - -func (f File) Data() *FileData { - return f.fileData -} - -type FileData struct { - sync.Mutex - name string - data []byte - memDir Dir - dir bool - mode os.FileMode - modtime time.Time -} - -func (d *FileData) Name() string { - d.Lock() - defer d.Unlock() - return d.name -} - -func CreateFile(name string) *FileData { - return &FileData{name: name, mode: os.ModeTemporary, modtime: time.Now()} -} - -func CreateDir(name string) *FileData { - return &FileData{name: name, memDir: &DirMap{}, dir: true} -} - -func ChangeFileName(f *FileData, newname string) { - f.Lock() - f.name = newname - f.Unlock() -} - -func SetMode(f *FileData, mode os.FileMode) { - f.Lock() - f.mode = mode - f.Unlock() -} - -func SetModTime(f *FileData, mtime time.Time) { - f.Lock() - setModTime(f, mtime) - f.Unlock() -} - -func setModTime(f *FileData, mtime time.Time) { - f.modtime = mtime -} - -func GetFileInfo(f *FileData) *FileInfo { - return &FileInfo{f} -} - -func (f *File) Open() error { - atomic.StoreInt64(&f.at, 0) - atomic.StoreInt64(&f.readDirCount, 0) - f.fileData.Lock() - f.closed = false - f.fileData.Unlock() - return nil -} - -func (f *File) Close() error { - f.fileData.Lock() - f.closed = true - if !f.readOnly { - setModTime(f.fileData, time.Now()) - } - f.fileData.Unlock() - return nil -} - -func (f *File) Name() string { - return f.fileData.Name() -} - -func (f *File) Stat() (os.FileInfo, error) { - return &FileInfo{f.fileData}, nil -} - -func (f *File) Sync() error { - return nil -} - -func (f *File) Readdir(count int) (res []os.FileInfo, err error) { - if !f.fileData.dir { - return nil, &os.PathError{Op: "readdir", Path: f.fileData.name, Err: errors.New("not a dir")} - } - var outLength int64 - - f.fileData.Lock() - files := f.fileData.memDir.Files()[f.readDirCount:] - if count > 0 { - if len(files) < count { - outLength = int64(len(files)) - } else { - outLength = int64(count) - } - if len(files) == 0 { - err = io.EOF - } - } else { - outLength = int64(len(files)) - } - f.readDirCount += outLength - f.fileData.Unlock() - - res = make([]os.FileInfo, outLength) - for i := range res { - res[i] = &FileInfo{files[i]} - } - - return res, err -} - -func (f *File) Readdirnames(n int) (names []string, err error) { - fi, err := f.Readdir(n) - names = make([]string, len(fi)) - for i, f := range fi { - _, names[i] = filepath.Split(f.Name()) - } - return names, err -} - -func (f *File) Read(b []byte) (n int, err error) { - f.fileData.Lock() - defer f.fileData.Unlock() - if f.closed == true { - return 0, ErrFileClosed - } - if len(b) > 0 && int(f.at) == len(f.fileData.data) { - return 0, io.EOF - } - if int(f.at) > len(f.fileData.data) { - return 0, io.ErrUnexpectedEOF - } - if len(f.fileData.data)-int(f.at) >= len(b) { - n = len(b) - } else { - n = len(f.fileData.data) - int(f.at) - } - copy(b, f.fileData.data[f.at:f.at+int64(n)]) - atomic.AddInt64(&f.at, int64(n)) - return -} - -func (f *File) ReadAt(b []byte, off int64) (n int, err error) { - atomic.StoreInt64(&f.at, off) - return f.Read(b) -} - -func (f *File) Truncate(size int64) error { - if f.closed == true { - return ErrFileClosed - } - if f.readOnly { - return &os.PathError{Op: "truncate", Path: f.fileData.name, Err: errors.New("file handle is read only")} - } - if size < 0 { - return ErrOutOfRange - } - if size > int64(len(f.fileData.data)) { - diff := size - int64(len(f.fileData.data)) - f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...) - } else { - f.fileData.data = f.fileData.data[0:size] - } - setModTime(f.fileData, time.Now()) - return nil -} - -func (f *File) Seek(offset int64, whence int) (int64, error) { - if f.closed == true { - return 0, ErrFileClosed - } - switch whence { - case 0: - atomic.StoreInt64(&f.at, offset) - case 1: - atomic.AddInt64(&f.at, int64(offset)) - case 2: - atomic.StoreInt64(&f.at, int64(len(f.fileData.data))+offset) - } - return f.at, nil -} - -func (f *File) Write(b []byte) (n int, err error) { - if f.readOnly { - return 0, &os.PathError{Op: "write", Path: f.fileData.name, Err: errors.New("file handle is read only")} - } - n = len(b) - cur := atomic.LoadInt64(&f.at) - f.fileData.Lock() - defer f.fileData.Unlock() - diff := cur - int64(len(f.fileData.data)) - var tail []byte - if n+int(cur) < len(f.fileData.data) { - tail = f.fileData.data[n+int(cur):] - } - if diff > 0 { - f.fileData.data = append(bytes.Repeat([]byte{00}, int(diff)), b...) - f.fileData.data = append(f.fileData.data, tail...) - } else { - f.fileData.data = append(f.fileData.data[:cur], b...) - f.fileData.data = append(f.fileData.data, tail...) - } - setModTime(f.fileData, time.Now()) - - atomic.StoreInt64(&f.at, int64(len(f.fileData.data))) - return -} - -func (f *File) WriteAt(b []byte, off int64) (n int, err error) { - atomic.StoreInt64(&f.at, off) - return f.Write(b) -} - -func (f *File) WriteString(s string) (ret int, err error) { - return f.Write([]byte(s)) -} - -func (f *File) Info() *FileInfo { - return &FileInfo{f.fileData} -} - -type FileInfo struct { - *FileData -} - -// Implements os.FileInfo -func (s *FileInfo) Name() string { - s.Lock() - _, name := filepath.Split(s.name) - s.Unlock() - return name -} -func (s *FileInfo) Mode() os.FileMode { - s.Lock() - defer s.Unlock() - return s.mode -} -func (s *FileInfo) ModTime() time.Time { - s.Lock() - defer s.Unlock() - return s.modtime -} -func (s *FileInfo) IsDir() bool { - s.Lock() - defer s.Unlock() - return s.dir -} -func (s *FileInfo) Sys() interface{} { return nil } -func (s *FileInfo) Size() int64 { - if s.IsDir() { - return int64(42) - } - s.Lock() - defer s.Unlock() - return int64(len(s.data)) -} - -var ( - ErrFileClosed = errors.New("File is closed") - ErrOutOfRange = errors.New("Out of range") - ErrTooLarge = errors.New("Too large") - ErrFileNotFound = os.ErrNotExist - ErrFileExists = os.ErrExist - ErrDestinationExists = os.ErrExist -) diff --git a/vendor/github.com/spf13/afero/memmap.go b/vendor/github.com/spf13/afero/memmap.go deleted file mode 100644 index 09498e70..00000000 --- a/vendor/github.com/spf13/afero/memmap.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright © 2014 Steve Francia . -// -// 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 afero - -import ( - "fmt" - "log" - "os" - "path/filepath" - "strings" - "sync" - "time" - - "github.com/spf13/afero/mem" -) - -type MemMapFs struct { - mu sync.RWMutex - data map[string]*mem.FileData - init sync.Once -} - -func NewMemMapFs() Fs { - return &MemMapFs{} -} - -func (m *MemMapFs) getData() map[string]*mem.FileData { - m.init.Do(func() { - m.data = make(map[string]*mem.FileData) - // Root should always exist, right? - // TODO: what about windows? - m.data[FilePathSeparator] = mem.CreateDir(FilePathSeparator) - }) - return m.data -} - -func (*MemMapFs) Name() string { return "MemMapFS" } - -func (m *MemMapFs) Create(name string) (File, error) { - name = normalizePath(name) - m.mu.Lock() - file := mem.CreateFile(name) - m.getData()[name] = file - m.registerWithParent(file) - m.mu.Unlock() - return mem.NewFileHandle(file), nil -} - -func (m *MemMapFs) unRegisterWithParent(fileName string) error { - f, err := m.lockfreeOpen(fileName) - if err != nil { - return err - } - parent := m.findParent(f) - if parent == nil { - log.Panic("parent of ", f.Name(), " is nil") - } - - parent.Lock() - mem.RemoveFromMemDir(parent, f) - parent.Unlock() - return nil -} - -func (m *MemMapFs) findParent(f *mem.FileData) *mem.FileData { - pdir, _ := filepath.Split(f.Name()) - pdir = filepath.Clean(pdir) - pfile, err := m.lockfreeOpen(pdir) - if err != nil { - return nil - } - return pfile -} - -func (m *MemMapFs) registerWithParent(f *mem.FileData) { - if f == nil { - return - } - parent := m.findParent(f) - if parent == nil { - pdir := filepath.Dir(filepath.Clean(f.Name())) - err := m.lockfreeMkdir(pdir, 0777) - if err != nil { - //log.Println("Mkdir error:", err) - return - } - parent, err = m.lockfreeOpen(pdir) - if err != nil { - //log.Println("Open after Mkdir error:", err) - return - } - } - - parent.Lock() - mem.InitializeDir(parent) - mem.AddToMemDir(parent, f) - parent.Unlock() -} - -func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error { - name = normalizePath(name) - x, ok := m.getData()[name] - if ok { - // Only return ErrFileExists if it's a file, not a directory. - i := mem.FileInfo{FileData: x} - if !i.IsDir() { - return ErrFileExists - } - } else { - item := mem.CreateDir(name) - m.getData()[name] = item - m.registerWithParent(item) - } - return nil -} - -func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error { - name = normalizePath(name) - - m.mu.RLock() - _, ok := m.getData()[name] - m.mu.RUnlock() - if ok { - return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists} - } - - m.mu.Lock() - item := mem.CreateDir(name) - m.getData()[name] = item - m.registerWithParent(item) - m.mu.Unlock() - - m.Chmod(name, perm|os.ModeDir) - - return nil -} - -func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error { - err := m.Mkdir(path, perm) - if err != nil { - if err.(*os.PathError).Err == ErrFileExists { - return nil - } - return err - } - return nil -} - -// Handle some relative paths -func normalizePath(path string) string { - path = filepath.Clean(path) - - switch path { - case ".": - return FilePathSeparator - case "..": - return FilePathSeparator - default: - return path - } -} - -func (m *MemMapFs) Open(name string) (File, error) { - f, err := m.open(name) - if f != nil { - return mem.NewReadOnlyFileHandle(f), err - } - return nil, err -} - -func (m *MemMapFs) openWrite(name string) (File, error) { - f, err := m.open(name) - if f != nil { - return mem.NewFileHandle(f), err - } - return nil, err -} - -func (m *MemMapFs) open(name string) (*mem.FileData, error) { - name = normalizePath(name) - - m.mu.RLock() - f, ok := m.getData()[name] - m.mu.RUnlock() - if !ok { - return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileNotFound} - } - return f, nil -} - -func (m *MemMapFs) lockfreeOpen(name string) (*mem.FileData, error) { - name = normalizePath(name) - f, ok := m.getData()[name] - if ok { - return f, nil - } else { - return nil, ErrFileNotFound - } -} - -func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - chmod := false - file, err := m.openWrite(name) - if os.IsNotExist(err) && (flag&os.O_CREATE > 0) { - file, err = m.Create(name) - chmod = true - } - if err != nil { - return nil, err - } - if flag == os.O_RDONLY { - file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data()) - } - if flag&os.O_APPEND > 0 { - _, err = file.Seek(0, os.SEEK_END) - if err != nil { - file.Close() - return nil, err - } - } - if flag&os.O_TRUNC > 0 && flag&(os.O_RDWR|os.O_WRONLY) > 0 { - err = file.Truncate(0) - if err != nil { - file.Close() - return nil, err - } - } - if chmod { - m.Chmod(name, perm) - } - return file, nil -} - -func (m *MemMapFs) Remove(name string) error { - name = normalizePath(name) - - m.mu.Lock() - defer m.mu.Unlock() - - if _, ok := m.getData()[name]; ok { - err := m.unRegisterWithParent(name) - if err != nil { - return &os.PathError{Op: "remove", Path: name, Err: err} - } - delete(m.getData(), name) - } else { - return &os.PathError{Op: "remove", Path: name, Err: os.ErrNotExist} - } - return nil -} - -func (m *MemMapFs) RemoveAll(path string) error { - path = normalizePath(path) - m.mu.Lock() - m.unRegisterWithParent(path) - m.mu.Unlock() - - m.mu.RLock() - defer m.mu.RUnlock() - - for p, _ := range m.getData() { - if strings.HasPrefix(p, path) { - m.mu.RUnlock() - m.mu.Lock() - delete(m.getData(), p) - m.mu.Unlock() - m.mu.RLock() - } - } - return nil -} - -func (m *MemMapFs) Rename(oldname, newname string) error { - oldname = normalizePath(oldname) - newname = normalizePath(newname) - - if oldname == newname { - return nil - } - - m.mu.RLock() - defer m.mu.RUnlock() - if _, ok := m.getData()[oldname]; ok { - m.mu.RUnlock() - m.mu.Lock() - m.unRegisterWithParent(oldname) - fileData := m.getData()[oldname] - delete(m.getData(), oldname) - mem.ChangeFileName(fileData, newname) - m.getData()[newname] = fileData - m.registerWithParent(fileData) - m.mu.Unlock() - m.mu.RLock() - } else { - return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound} - } - return nil -} - -func (m *MemMapFs) Stat(name string) (os.FileInfo, error) { - f, err := m.Open(name) - if err != nil { - return nil, err - } - fi := mem.GetFileInfo(f.(*mem.File).Data()) - return fi, nil -} - -func (m *MemMapFs) Chmod(name string, mode os.FileMode) error { - name = normalizePath(name) - - m.mu.RLock() - f, ok := m.getData()[name] - m.mu.RUnlock() - if !ok { - return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound} - } - - m.mu.Lock() - mem.SetMode(f, mode) - m.mu.Unlock() - - return nil -} - -func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error { - name = normalizePath(name) - - m.mu.RLock() - f, ok := m.getData()[name] - m.mu.RUnlock() - if !ok { - return &os.PathError{Op: "chtimes", Path: name, Err: ErrFileNotFound} - } - - m.mu.Lock() - mem.SetModTime(f, mtime) - m.mu.Unlock() - - return nil -} - -func (m *MemMapFs) List() { - for _, x := range m.data { - y := mem.FileInfo{FileData: x} - fmt.Println(x.Name(), y.Size()) - } -} - -// func debugMemMapList(fs Fs) { -// if x, ok := fs.(*MemMapFs); ok { -// x.List() -// } -// } diff --git a/vendor/github.com/spf13/afero/os.go b/vendor/github.com/spf13/afero/os.go deleted file mode 100644 index 13cc1b84..00000000 --- a/vendor/github.com/spf13/afero/os.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright © 2014 Steve Francia . -// Copyright 2013 tsuru authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package afero - -import ( - "os" - "time" -) - -var _ Lstater = (*OsFs)(nil) - -// OsFs is a Fs implementation that uses functions provided by the os package. -// -// For details in any method, check the documentation of the os package -// (http://golang.org/pkg/os/). -type OsFs struct{} - -func NewOsFs() Fs { - return &OsFs{} -} - -func (OsFs) Name() string { return "OsFs" } - -func (OsFs) Create(name string) (File, error) { - f, e := os.Create(name) - if f == nil { - // while this looks strange, we need to return a bare nil (of type nil) not - // a nil value of type *os.File or nil won't be nil - return nil, e - } - return f, e -} - -func (OsFs) Mkdir(name string, perm os.FileMode) error { - return os.Mkdir(name, perm) -} - -func (OsFs) MkdirAll(path string, perm os.FileMode) error { - return os.MkdirAll(path, perm) -} - -func (OsFs) Open(name string) (File, error) { - f, e := os.Open(name) - if f == nil { - // while this looks strange, we need to return a bare nil (of type nil) not - // a nil value of type *os.File or nil won't be nil - return nil, e - } - return f, e -} - -func (OsFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - f, e := os.OpenFile(name, flag, perm) - if f == nil { - // while this looks strange, we need to return a bare nil (of type nil) not - // a nil value of type *os.File or nil won't be nil - return nil, e - } - return f, e -} - -func (OsFs) Remove(name string) error { - return os.Remove(name) -} - -func (OsFs) RemoveAll(path string) error { - return os.RemoveAll(path) -} - -func (OsFs) Rename(oldname, newname string) error { - return os.Rename(oldname, newname) -} - -func (OsFs) Stat(name string) (os.FileInfo, error) { - return os.Stat(name) -} - -func (OsFs) Chmod(name string, mode os.FileMode) error { - return os.Chmod(name, mode) -} - -func (OsFs) Chtimes(name string, atime time.Time, mtime time.Time) error { - return os.Chtimes(name, atime, mtime) -} - -func (OsFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { - fi, err := os.Lstat(name) - return fi, true, err -} diff --git a/vendor/github.com/spf13/afero/path.go b/vendor/github.com/spf13/afero/path.go deleted file mode 100644 index 18f60a0f..00000000 --- a/vendor/github.com/spf13/afero/path.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright ©2015 The Go Authors -// Copyright ©2015 Steve Francia -// -// 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 afero - -import ( - "os" - "path/filepath" - "sort" -) - -// readDirNames reads the directory named by dirname and returns -// a sorted list of directory entries. -// adapted from https://golang.org/src/path/filepath/path.go -func readDirNames(fs Fs, dirname string) ([]string, error) { - f, err := fs.Open(dirname) - if err != nil { - return nil, err - } - names, err := f.Readdirnames(-1) - f.Close() - if err != nil { - return nil, err - } - sort.Strings(names) - return names, nil -} - -// walk recursively descends path, calling walkFn -// adapted from https://golang.org/src/path/filepath/path.go -func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error { - err := walkFn(path, info, nil) - if err != nil { - if info.IsDir() && err == filepath.SkipDir { - return nil - } - return err - } - - if !info.IsDir() { - return nil - } - - names, err := readDirNames(fs, path) - if err != nil { - return walkFn(path, info, err) - } - - for _, name := range names { - filename := filepath.Join(path, name) - fileInfo, err := lstatIfPossible(fs, filename) - if err != nil { - if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir { - return err - } - } else { - err = walk(fs, filename, fileInfo, walkFn) - if err != nil { - if !fileInfo.IsDir() || err != filepath.SkipDir { - return err - } - } - } - } - return nil -} - -// if the filesystem supports it, use Lstat, else use fs.Stat -func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) { - if lfs, ok := fs.(Lstater); ok { - fi, _, err := lfs.LstatIfPossible(path) - return fi, err - } - return fs.Stat(path) -} - -// Walk walks the file tree rooted at root, calling walkFn for each file or -// directory in the tree, including root. All errors that arise visiting files -// and directories are filtered by walkFn. The files are walked in lexical -// order, which makes the output deterministic but means that for very -// large directories Walk can be inefficient. -// Walk does not follow symbolic links. - -func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error { - return Walk(a.Fs, root, walkFn) -} - -func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error { - info, err := lstatIfPossible(fs, root) - if err != nil { - return walkFn(root, nil, err) - } - return walk(fs, root, info, walkFn) -} diff --git a/vendor/github.com/spf13/afero/readonlyfs.go b/vendor/github.com/spf13/afero/readonlyfs.go deleted file mode 100644 index c6376ec3..00000000 --- a/vendor/github.com/spf13/afero/readonlyfs.go +++ /dev/null @@ -1,80 +0,0 @@ -package afero - -import ( - "os" - "syscall" - "time" -) - -var _ Lstater = (*ReadOnlyFs)(nil) - -type ReadOnlyFs struct { - source Fs -} - -func NewReadOnlyFs(source Fs) Fs { - return &ReadOnlyFs{source: source} -} - -func (r *ReadOnlyFs) ReadDir(name string) ([]os.FileInfo, error) { - return ReadDir(r.source, name) -} - -func (r *ReadOnlyFs) Chtimes(n string, a, m time.Time) error { - return syscall.EPERM -} - -func (r *ReadOnlyFs) Chmod(n string, m os.FileMode) error { - return syscall.EPERM -} - -func (r *ReadOnlyFs) Name() string { - return "ReadOnlyFilter" -} - -func (r *ReadOnlyFs) Stat(name string) (os.FileInfo, error) { - return r.source.Stat(name) -} - -func (r *ReadOnlyFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { - if lsf, ok := r.source.(Lstater); ok { - return lsf.LstatIfPossible(name) - } - fi, err := r.Stat(name) - return fi, false, err -} - -func (r *ReadOnlyFs) Rename(o, n string) error { - return syscall.EPERM -} - -func (r *ReadOnlyFs) RemoveAll(p string) error { - return syscall.EPERM -} - -func (r *ReadOnlyFs) Remove(n string) error { - return syscall.EPERM -} - -func (r *ReadOnlyFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 { - return nil, syscall.EPERM - } - return r.source.OpenFile(name, flag, perm) -} - -func (r *ReadOnlyFs) Open(n string) (File, error) { - return r.source.Open(n) -} - -func (r *ReadOnlyFs) Mkdir(n string, p os.FileMode) error { - return syscall.EPERM -} - -func (r *ReadOnlyFs) MkdirAll(n string, p os.FileMode) error { - return syscall.EPERM -} - -func (r *ReadOnlyFs) Create(n string) (File, error) { - return nil, syscall.EPERM -} diff --git a/vendor/github.com/spf13/afero/regexpfs.go b/vendor/github.com/spf13/afero/regexpfs.go deleted file mode 100644 index 9d92dbc0..00000000 --- a/vendor/github.com/spf13/afero/regexpfs.go +++ /dev/null @@ -1,214 +0,0 @@ -package afero - -import ( - "os" - "regexp" - "syscall" - "time" -) - -// The RegexpFs filters files (not directories) by regular expression. Only -// files matching the given regexp will be allowed, all others get a ENOENT error ( -// "No such file or directory"). -// -type RegexpFs struct { - re *regexp.Regexp - source Fs -} - -func NewRegexpFs(source Fs, re *regexp.Regexp) Fs { - return &RegexpFs{source: source, re: re} -} - -type RegexpFile struct { - f File - re *regexp.Regexp -} - -func (r *RegexpFs) matchesName(name string) error { - if r.re == nil { - return nil - } - if r.re.MatchString(name) { - return nil - } - return syscall.ENOENT -} - -func (r *RegexpFs) dirOrMatches(name string) error { - dir, err := IsDir(r.source, name) - if err != nil { - return err - } - if dir { - return nil - } - return r.matchesName(name) -} - -func (r *RegexpFs) Chtimes(name string, a, m time.Time) error { - if err := r.dirOrMatches(name); err != nil { - return err - } - return r.source.Chtimes(name, a, m) -} - -func (r *RegexpFs) Chmod(name string, mode os.FileMode) error { - if err := r.dirOrMatches(name); err != nil { - return err - } - return r.source.Chmod(name, mode) -} - -func (r *RegexpFs) Name() string { - return "RegexpFs" -} - -func (r *RegexpFs) Stat(name string) (os.FileInfo, error) { - if err := r.dirOrMatches(name); err != nil { - return nil, err - } - return r.source.Stat(name) -} - -func (r *RegexpFs) Rename(oldname, newname string) error { - dir, err := IsDir(r.source, oldname) - if err != nil { - return err - } - if dir { - return nil - } - if err := r.matchesName(oldname); err != nil { - return err - } - if err := r.matchesName(newname); err != nil { - return err - } - return r.source.Rename(oldname, newname) -} - -func (r *RegexpFs) RemoveAll(p string) error { - dir, err := IsDir(r.source, p) - if err != nil { - return err - } - if !dir { - if err := r.matchesName(p); err != nil { - return err - } - } - return r.source.RemoveAll(p) -} - -func (r *RegexpFs) Remove(name string) error { - if err := r.dirOrMatches(name); err != nil { - return err - } - return r.source.Remove(name) -} - -func (r *RegexpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) { - if err := r.dirOrMatches(name); err != nil { - return nil, err - } - return r.source.OpenFile(name, flag, perm) -} - -func (r *RegexpFs) Open(name string) (File, error) { - dir, err := IsDir(r.source, name) - if err != nil { - return nil, err - } - if !dir { - if err := r.matchesName(name); err != nil { - return nil, err - } - } - f, err := r.source.Open(name) - return &RegexpFile{f: f, re: r.re}, nil -} - -func (r *RegexpFs) Mkdir(n string, p os.FileMode) error { - return r.source.Mkdir(n, p) -} - -func (r *RegexpFs) MkdirAll(n string, p os.FileMode) error { - return r.source.MkdirAll(n, p) -} - -func (r *RegexpFs) Create(name string) (File, error) { - if err := r.matchesName(name); err != nil { - return nil, err - } - return r.source.Create(name) -} - -func (f *RegexpFile) Close() error { - return f.f.Close() -} - -func (f *RegexpFile) Read(s []byte) (int, error) { - return f.f.Read(s) -} - -func (f *RegexpFile) ReadAt(s []byte, o int64) (int, error) { - return f.f.ReadAt(s, o) -} - -func (f *RegexpFile) Seek(o int64, w int) (int64, error) { - return f.f.Seek(o, w) -} - -func (f *RegexpFile) Write(s []byte) (int, error) { - return f.f.Write(s) -} - -func (f *RegexpFile) WriteAt(s []byte, o int64) (int, error) { - return f.f.WriteAt(s, o) -} - -func (f *RegexpFile) Name() string { - return f.f.Name() -} - -func (f *RegexpFile) Readdir(c int) (fi []os.FileInfo, err error) { - var rfi []os.FileInfo - rfi, err = f.f.Readdir(c) - if err != nil { - return nil, err - } - for _, i := range rfi { - if i.IsDir() || f.re.MatchString(i.Name()) { - fi = append(fi, i) - } - } - return fi, nil -} - -func (f *RegexpFile) Readdirnames(c int) (n []string, err error) { - fi, err := f.Readdir(c) - if err != nil { - return nil, err - } - for _, s := range fi { - n = append(n, s.Name()) - } - return n, nil -} - -func (f *RegexpFile) Stat() (os.FileInfo, error) { - return f.f.Stat() -} - -func (f *RegexpFile) Sync() error { - return f.f.Sync() -} - -func (f *RegexpFile) Truncate(s int64) error { - return f.f.Truncate(s) -} - -func (f *RegexpFile) WriteString(s string) (int, error) { - return f.f.WriteString(s) -} diff --git a/vendor/github.com/spf13/afero/unionFile.go b/vendor/github.com/spf13/afero/unionFile.go deleted file mode 100644 index abcf12d3..00000000 --- a/vendor/github.com/spf13/afero/unionFile.go +++ /dev/null @@ -1,316 +0,0 @@ -package afero - -import ( - "io" - "os" - "path/filepath" - "syscall" -) - -// The UnionFile implements the afero.File interface and will be returned -// when reading a directory present at least in the overlay or opening a file -// for writing. -// -// The calls to -// Readdir() and Readdirnames() merge the file os.FileInfo / names from the -// base and the overlay - for files present in both layers, only those -// from the overlay will be used. -// -// When opening files for writing (Create() / OpenFile() with the right flags) -// the operations will be done in both layers, starting with the overlay. A -// successful read in the overlay will move the cursor position in the base layer -// by the number of bytes read. -type UnionFile struct { - Base File - Layer File - Merger DirsMerger - off int - files []os.FileInfo -} - -func (f *UnionFile) Close() error { - // first close base, so we have a newer timestamp in the overlay. If we'd close - // the overlay first, we'd get a cacheStale the next time we access this file - // -> cache would be useless ;-) - if f.Base != nil { - f.Base.Close() - } - if f.Layer != nil { - return f.Layer.Close() - } - return BADFD -} - -func (f *UnionFile) Read(s []byte) (int, error) { - if f.Layer != nil { - n, err := f.Layer.Read(s) - if (err == nil || err == io.EOF) && f.Base != nil { - // advance the file position also in the base file, the next - // call may be a write at this position (or a seek with SEEK_CUR) - if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil { - // only overwrite err in case the seek fails: we need to - // report an eventual io.EOF to the caller - err = seekErr - } - } - return n, err - } - if f.Base != nil { - return f.Base.Read(s) - } - return 0, BADFD -} - -func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) { - if f.Layer != nil { - n, err := f.Layer.ReadAt(s, o) - if (err == nil || err == io.EOF) && f.Base != nil { - _, err = f.Base.Seek(o+int64(n), os.SEEK_SET) - } - return n, err - } - if f.Base != nil { - return f.Base.ReadAt(s, o) - } - return 0, BADFD -} - -func (f *UnionFile) Seek(o int64, w int) (pos int64, err error) { - if f.Layer != nil { - pos, err = f.Layer.Seek(o, w) - if (err == nil || err == io.EOF) && f.Base != nil { - _, err = f.Base.Seek(o, w) - } - return pos, err - } - if f.Base != nil { - return f.Base.Seek(o, w) - } - return 0, BADFD -} - -func (f *UnionFile) Write(s []byte) (n int, err error) { - if f.Layer != nil { - n, err = f.Layer.Write(s) - if err == nil && f.Base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark? - _, err = f.Base.Write(s) - } - return n, err - } - if f.Base != nil { - return f.Base.Write(s) - } - return 0, BADFD -} - -func (f *UnionFile) WriteAt(s []byte, o int64) (n int, err error) { - if f.Layer != nil { - n, err = f.Layer.WriteAt(s, o) - if err == nil && f.Base != nil { - _, err = f.Base.WriteAt(s, o) - } - return n, err - } - if f.Base != nil { - return f.Base.WriteAt(s, o) - } - return 0, BADFD -} - -func (f *UnionFile) Name() string { - if f.Layer != nil { - return f.Layer.Name() - } - return f.Base.Name() -} - -// DirsMerger is how UnionFile weaves two directories together. -// It takes the FileInfo slices from the layer and the base and returns a -// single view. -type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) - -var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) { - var files = make(map[string]os.FileInfo) - - for _, fi := range lofi { - files[fi.Name()] = fi - } - - for _, fi := range bofi { - if _, exists := files[fi.Name()]; !exists { - files[fi.Name()] = fi - } - } - - rfi := make([]os.FileInfo, len(files)) - - i := 0 - for _, fi := range files { - rfi[i] = fi - i++ - } - - return rfi, nil - -} - -// Readdir will weave the two directories together and -// return a single view of the overlayed directories -// At the end of the directory view, the error is io.EOF. -func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) { - var merge DirsMerger = f.Merger - if merge == nil { - merge = defaultUnionMergeDirsFn - } - - if f.off == 0 { - var lfi []os.FileInfo - if f.Layer != nil { - lfi, err = f.Layer.Readdir(-1) - if err != nil { - return nil, err - } - } - - var bfi []os.FileInfo - if f.Base != nil { - bfi, err = f.Base.Readdir(-1) - if err != nil { - return nil, err - } - - } - merged, err := merge(lfi, bfi) - if err != nil { - return nil, err - } - f.files = append(f.files, merged...) - } - - if f.off >= len(f.files) { - return nil, io.EOF - } - - if c == -1 { - return f.files[f.off:], nil - } - - if c > len(f.files) { - c = len(f.files) - } - - defer func() { f.off += c }() - return f.files[f.off:c], nil -} - -func (f *UnionFile) Readdirnames(c int) ([]string, error) { - rfi, err := f.Readdir(c) - if err != nil { - return nil, err - } - var names []string - for _, fi := range rfi { - names = append(names, fi.Name()) - } - return names, nil -} - -func (f *UnionFile) Stat() (os.FileInfo, error) { - if f.Layer != nil { - return f.Layer.Stat() - } - if f.Base != nil { - return f.Base.Stat() - } - return nil, BADFD -} - -func (f *UnionFile) Sync() (err error) { - if f.Layer != nil { - err = f.Layer.Sync() - if err == nil && f.Base != nil { - err = f.Base.Sync() - } - return err - } - if f.Base != nil { - return f.Base.Sync() - } - return BADFD -} - -func (f *UnionFile) Truncate(s int64) (err error) { - if f.Layer != nil { - err = f.Layer.Truncate(s) - if err == nil && f.Base != nil { - err = f.Base.Truncate(s) - } - return err - } - if f.Base != nil { - return f.Base.Truncate(s) - } - return BADFD -} - -func (f *UnionFile) WriteString(s string) (n int, err error) { - if f.Layer != nil { - n, err = f.Layer.WriteString(s) - if err == nil && f.Base != nil { - _, err = f.Base.WriteString(s) - } - return n, err - } - if f.Base != nil { - return f.Base.WriteString(s) - } - return 0, BADFD -} - -func copyToLayer(base Fs, layer Fs, name string) error { - bfh, err := base.Open(name) - if err != nil { - return err - } - defer bfh.Close() - - // First make sure the directory exists - exists, err := Exists(layer, filepath.Dir(name)) - if err != nil { - return err - } - if !exists { - err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME? - if err != nil { - return err - } - } - - // Create the file on the overlay - lfh, err := layer.Create(name) - if err != nil { - return err - } - n, err := io.Copy(lfh, bfh) - if err != nil { - // If anything fails, clean up the file - layer.Remove(name) - lfh.Close() - return err - } - - bfi, err := bfh.Stat() - if err != nil || bfi.Size() != n { - layer.Remove(name) - lfh.Close() - return syscall.EIO - } - - err = lfh.Close() - if err != nil { - layer.Remove(name) - lfh.Close() - return err - } - return layer.Chtimes(name, bfi.ModTime(), bfi.ModTime()) -} diff --git a/vendor/github.com/spf13/afero/util.go b/vendor/github.com/spf13/afero/util.go deleted file mode 100644 index 4f253f48..00000000 --- a/vendor/github.com/spf13/afero/util.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright ©2015 Steve Francia -// Portions Copyright ©2015 The Hugo Authors -// Portions Copyright 2016-present Bjørn Erik Pedersen -// -// 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 afero - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "unicode" - - "golang.org/x/text/transform" - "golang.org/x/text/unicode/norm" -) - -// Filepath separator defined by os.Separator. -const FilePathSeparator = string(filepath.Separator) - -// Takes a reader and a path and writes the content -func (a Afero) WriteReader(path string, r io.Reader) (err error) { - return WriteReader(a.Fs, path, r) -} - -func WriteReader(fs Fs, path string, r io.Reader) (err error) { - dir, _ := filepath.Split(path) - ospath := filepath.FromSlash(dir) - - if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r - if err != nil { - if err != os.ErrExist { - return err - } - } - } - - file, err := fs.Create(path) - if err != nil { - return - } - defer file.Close() - - _, err = io.Copy(file, r) - return -} - -// Same as WriteReader but checks to see if file/directory already exists. -func (a Afero) SafeWriteReader(path string, r io.Reader) (err error) { - return SafeWriteReader(a.Fs, path, r) -} - -func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) { - dir, _ := filepath.Split(path) - ospath := filepath.FromSlash(dir) - - if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r - if err != nil { - return - } - } - - exists, err := Exists(fs, path) - if err != nil { - return - } - if exists { - return fmt.Errorf("%v already exists", path) - } - - file, err := fs.Create(path) - if err != nil { - return - } - defer file.Close() - - _, err = io.Copy(file, r) - return -} - -func (a Afero) GetTempDir(subPath string) string { - return GetTempDir(a.Fs, subPath) -} - -// GetTempDir returns the default temp directory with trailing slash -// if subPath is not empty then it will be created recursively with mode 777 rwx rwx rwx -func GetTempDir(fs Fs, subPath string) string { - addSlash := func(p string) string { - if FilePathSeparator != p[len(p)-1:] { - p = p + FilePathSeparator - } - return p - } - dir := addSlash(os.TempDir()) - - if subPath != "" { - // preserve windows backslash :-( - if FilePathSeparator == "\\" { - subPath = strings.Replace(subPath, "\\", "____", -1) - } - dir = dir + UnicodeSanitize((subPath)) - if FilePathSeparator == "\\" { - dir = strings.Replace(dir, "____", "\\", -1) - } - - if exists, _ := Exists(fs, dir); exists { - return addSlash(dir) - } - - err := fs.MkdirAll(dir, 0777) - if err != nil { - panic(err) - } - dir = addSlash(dir) - } - return dir -} - -// Rewrite string to remove non-standard path characters -func UnicodeSanitize(s string) string { - source := []rune(s) - target := make([]rune, 0, len(source)) - - for _, r := range source { - if unicode.IsLetter(r) || - unicode.IsDigit(r) || - unicode.IsMark(r) || - r == '.' || - r == '/' || - r == '\\' || - r == '_' || - r == '-' || - r == '%' || - r == ' ' || - r == '#' { - target = append(target, r) - } - } - - return string(target) -} - -// Transform characters with accents into plain forms. -func NeuterAccents(s string) string { - t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC) - result, _, _ := transform.String(t, string(s)) - - return result -} - -func isMn(r rune) bool { - return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks -} - -func (a Afero) FileContainsBytes(filename string, subslice []byte) (bool, error) { - return FileContainsBytes(a.Fs, filename, subslice) -} - -// Check if a file contains a specified byte slice. -func FileContainsBytes(fs Fs, filename string, subslice []byte) (bool, error) { - f, err := fs.Open(filename) - if err != nil { - return false, err - } - defer f.Close() - - return readerContainsAny(f, subslice), nil -} - -func (a Afero) FileContainsAnyBytes(filename string, subslices [][]byte) (bool, error) { - return FileContainsAnyBytes(a.Fs, filename, subslices) -} - -// Check if a file contains any of the specified byte slices. -func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, error) { - f, err := fs.Open(filename) - if err != nil { - return false, err - } - defer f.Close() - - return readerContainsAny(f, subslices...), nil -} - -// readerContains reports whether any of the subslices is within r. -func readerContainsAny(r io.Reader, subslices ...[]byte) bool { - - if r == nil || len(subslices) == 0 { - return false - } - - largestSlice := 0 - - for _, sl := range subslices { - if len(sl) > largestSlice { - largestSlice = len(sl) - } - } - - if largestSlice == 0 { - return false - } - - bufflen := largestSlice * 4 - halflen := bufflen / 2 - buff := make([]byte, bufflen) - var err error - var n, i int - - for { - i++ - if i == 1 { - n, err = io.ReadAtLeast(r, buff[:halflen], halflen) - } else { - if i != 2 { - // shift left to catch overlapping matches - copy(buff[:], buff[halflen:]) - } - n, err = io.ReadAtLeast(r, buff[halflen:], halflen) - } - - if n > 0 { - for _, sl := range subslices { - if bytes.Contains(buff, sl) { - return true - } - } - } - - if err != nil { - break - } - } - return false -} - -func (a Afero) DirExists(path string) (bool, error) { - return DirExists(a.Fs, path) -} - -// DirExists checks if a path exists and is a directory. -func DirExists(fs Fs, path string) (bool, error) { - fi, err := fs.Stat(path) - if err == nil && fi.IsDir() { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} - -func (a Afero) IsDir(path string) (bool, error) { - return IsDir(a.Fs, path) -} - -// IsDir checks if a given path is a directory. -func IsDir(fs Fs, path string) (bool, error) { - fi, err := fs.Stat(path) - if err != nil { - return false, err - } - return fi.IsDir(), nil -} - -func (a Afero) IsEmpty(path string) (bool, error) { - return IsEmpty(a.Fs, path) -} - -// IsEmpty checks if a given file or directory is empty. -func IsEmpty(fs Fs, path string) (bool, error) { - if b, _ := Exists(fs, path); !b { - return false, fmt.Errorf("%q path does not exist", path) - } - fi, err := fs.Stat(path) - if err != nil { - return false, err - } - if fi.IsDir() { - f, err := fs.Open(path) - if err != nil { - return false, err - } - defer f.Close() - list, err := f.Readdir(-1) - return len(list) == 0, nil - } - return fi.Size() == 0, nil -} - -func (a Afero) Exists(path string) (bool, error) { - return Exists(a.Fs, path) -} - -// Check if a file or directory exists. -func Exists(fs Fs, path string) (bool, error) { - _, err := fs.Stat(path) - if err == nil { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} - -func FullBaseFsPath(basePathFs *BasePathFs, relativePath string) string { - combinedPath := filepath.Join(basePathFs.path, relativePath) - if parent, ok := basePathFs.source.(*BasePathFs); ok { - return FullBaseFsPath(parent, combinedPath) - } - - return combinedPath -} diff --git a/vendor/github.com/vmihailenco/msgpack/.travis.yml b/vendor/github.com/vmihailenco/msgpack/.travis.yml deleted file mode 100644 index 0c2f74ed..00000000 --- a/vendor/github.com/vmihailenco/msgpack/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -sudo: false -language: go - -go: - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - - tip - -matrix: - allow_failures: - - go: tip - -install: - - go get gopkg.in/check.v1 diff --git a/vendor/github.com/vmihailenco/msgpack/CHANGELOG.md b/vendor/github.com/vmihailenco/msgpack/CHANGELOG.md deleted file mode 100644 index 9a4f38a9..00000000 --- a/vendor/github.com/vmihailenco/msgpack/CHANGELOG.md +++ /dev/null @@ -1,24 +0,0 @@ -## 3.4 - -- Encode, Decode, Marshal, and Unmarshal are changed to accept single argument. EncodeMulti and DecodeMulti are added as replacement. -- Added EncodeInt8/16/32/64 and EncodeUint8/16/32/64. -- Encoder changed to preserve type of numbers instead of chosing most compact encoding. The old behavior can be achieved with Encoder.UseCompactEncoding. - -## v3.3 - -- `msgpack:",inline"` tag is restored to force inlining structs. - -## v3.2 - -- Decoding extension types returns pointer to the value instead of the value. Fixes #153 - -## v3 - -- gopkg.in is not supported any more. Update import path to github.com/vmihailenco/msgpack. -- Msgpack maps are decoded into map[string]interface{} by default. -- EncodeSliceLen is removed in favor of EncodeArrayLen. DecodeSliceLen is removed in favor of DecodeArrayLen. -- Embedded structs are automatically inlined where possible. -- Time is encoded using extension as described in https://github.com/msgpack/msgpack/pull/209. Old format is supported as well. -- EncodeInt8/16/32/64 is replaced with EncodeInt. EncodeUint8/16/32/64 is replaced with EncodeUint. There should be no performance differences. -- DecodeInterface can now return int8/16/32 and uint8/16/32. -- PeekCode returns codes.Code instead of byte. diff --git a/vendor/github.com/vmihailenco/msgpack/LICENSE b/vendor/github.com/vmihailenco/msgpack/LICENSE deleted file mode 100644 index b749d070..00000000 --- a/vendor/github.com/vmihailenco/msgpack/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2013 The github.com/vmihailenco/msgpack 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. - -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/vmihailenco/msgpack/Makefile b/vendor/github.com/vmihailenco/msgpack/Makefile deleted file mode 100644 index b62ae6a4..00000000 --- a/vendor/github.com/vmihailenco/msgpack/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -all: - go test ./... - env GOOS=linux GOARCH=386 go test ./... - go test ./... -short -race - go vet diff --git a/vendor/github.com/vmihailenco/msgpack/README.md b/vendor/github.com/vmihailenco/msgpack/README.md deleted file mode 100644 index 0c75ae16..00000000 --- a/vendor/github.com/vmihailenco/msgpack/README.md +++ /dev/null @@ -1,69 +0,0 @@ -# MessagePack encoding for Golang - -[![Build Status](https://travis-ci.org/vmihailenco/msgpack.svg?branch=v2)](https://travis-ci.org/vmihailenco/msgpack) -[![GoDoc](https://godoc.org/github.com/vmihailenco/msgpack?status.svg)](https://godoc.org/github.com/vmihailenco/msgpack) - -Supports: -- Primitives, arrays, maps, structs, time.Time and interface{}. -- Appengine *datastore.Key and datastore.Cursor. -- [CustomEncoder](https://godoc.org/github.com/vmihailenco/msgpack#example-CustomEncoder)/CustomDecoder interfaces for custom encoding. -- [Extensions](https://godoc.org/github.com/vmihailenco/msgpack#example-RegisterExt) to encode type information. -- Renaming fields via `msgpack:"my_field_name"`. -- Omitting individual empty fields via `msgpack:",omitempty"` tag or all [empty fields in a struct](https://godoc.org/github.com/vmihailenco/msgpack#example-Marshal--OmitEmpty). -- [Map keys sorting](https://godoc.org/github.com/vmihailenco/msgpack#Encoder.SortMapKeys). -- Encoding/decoding all [structs as arrays](https://godoc.org/github.com/vmihailenco/msgpack#Encoder.StructAsArray) or [individual structs](https://godoc.org/github.com/vmihailenco/msgpack#example-Marshal--AsArray). -- [Encoder.UseJSONTag](https://godoc.org/github.com/vmihailenco/msgpack#Encoder.UseJSONTag) with [Decoder.UseJSONTag](https://godoc.org/github.com/vmihailenco/msgpack#Decoder.UseJSONTag) can turn msgpack into drop-in replacement for JSON. -- Simple but very fast and efficient [queries](https://godoc.org/github.com/vmihailenco/msgpack#example-Decoder-Query). - -API docs: https://godoc.org/github.com/vmihailenco/msgpack. -Examples: https://godoc.org/github.com/vmihailenco/msgpack#pkg-examples. - -## Installation - -Install: - -```shell -go get -u github.com/vmihailenco/msgpack -``` - -## Quickstart - -```go -func ExampleMarshal() { - type Item struct { - Foo string - } - - b, err := msgpack.Marshal(&Item{Foo: "bar"}) - if err != nil { - panic(err) - } - - var item Item - err = msgpack.Unmarshal(b, &item) - if err != nil { - panic(err) - } - fmt.Println(item.Foo) - // Output: bar -} -``` - -## Benchmark - -``` -BenchmarkStructVmihailencoMsgpack-4 200000 12814 ns/op 2128 B/op 26 allocs/op -BenchmarkStructUgorjiGoMsgpack-4 100000 17678 ns/op 3616 B/op 70 allocs/op -BenchmarkStructUgorjiGoCodec-4 100000 19053 ns/op 7346 B/op 23 allocs/op -BenchmarkStructJSON-4 20000 69438 ns/op 7864 B/op 26 allocs/op -BenchmarkStructGOB-4 10000 104331 ns/op 14664 B/op 278 allocs/op -``` - -## Howto - -Please go through [examples](https://godoc.org/github.com/vmihailenco/msgpack#pkg-examples) to get an idea how to use this package. - -## See also - -- [Golang PostgreSQL ORM](https://github.com/go-pg/pg) -- [Golang message task queue](https://github.com/go-msgqueue/msgqueue) diff --git a/vendor/github.com/vmihailenco/msgpack/appengine.go b/vendor/github.com/vmihailenco/msgpack/appengine.go deleted file mode 100644 index e8e91e53..00000000 --- a/vendor/github.com/vmihailenco/msgpack/appengine.go +++ /dev/null @@ -1,64 +0,0 @@ -// +build appengine - -package msgpack - -import ( - "reflect" - - ds "google.golang.org/appengine/datastore" -) - -func init() { - Register((*ds.Key)(nil), encodeDatastoreKeyValue, decodeDatastoreKeyValue) - Register((*ds.Cursor)(nil), encodeDatastoreCursorValue, decodeDatastoreCursorValue) -} - -func EncodeDatastoreKey(e *Encoder, key *ds.Key) error { - if key == nil { - return e.EncodeNil() - } - return e.EncodeString(key.Encode()) -} - -func encodeDatastoreKeyValue(e *Encoder, v reflect.Value) error { - key := v.Interface().(*ds.Key) - return EncodeDatastoreKey(e, key) -} - -func DecodeDatastoreKey(d *Decoder) (*ds.Key, error) { - v, err := d.DecodeString() - if err != nil { - return nil, err - } - if v == "" { - return nil, nil - } - return ds.DecodeKey(v) -} - -func decodeDatastoreKeyValue(d *Decoder, v reflect.Value) error { - key, err := DecodeDatastoreKey(d) - if err != nil { - return err - } - v.Set(reflect.ValueOf(key)) - return nil -} - -func encodeDatastoreCursorValue(e *Encoder, v reflect.Value) error { - cursor := v.Interface().(ds.Cursor) - return e.Encode(cursor.String()) -} - -func decodeDatastoreCursorValue(d *Decoder, v reflect.Value) error { - s, err := d.DecodeString() - if err != nil { - return err - } - cursor, err := ds.DecodeCursor(s) - if err != nil { - return err - } - v.Set(reflect.ValueOf(cursor)) - return nil -} diff --git a/vendor/github.com/vmihailenco/msgpack/codes/codes.go b/vendor/github.com/vmihailenco/msgpack/codes/codes.go deleted file mode 100644 index 906af376..00000000 --- a/vendor/github.com/vmihailenco/msgpack/codes/codes.go +++ /dev/null @@ -1,86 +0,0 @@ -package codes - -type Code byte - -var ( - PosFixedNumHigh Code = 0x7f - NegFixedNumLow Code = 0xe0 - - Nil Code = 0xc0 - - False Code = 0xc2 - True Code = 0xc3 - - Float Code = 0xca - Double Code = 0xcb - - Uint8 Code = 0xcc - Uint16 Code = 0xcd - Uint32 Code = 0xce - Uint64 Code = 0xcf - - Int8 Code = 0xd0 - Int16 Code = 0xd1 - Int32 Code = 0xd2 - Int64 Code = 0xd3 - - FixedStrLow Code = 0xa0 - FixedStrHigh Code = 0xbf - FixedStrMask Code = 0x1f - Str8 Code = 0xd9 - Str16 Code = 0xda - Str32 Code = 0xdb - - Bin8 Code = 0xc4 - Bin16 Code = 0xc5 - Bin32 Code = 0xc6 - - FixedArrayLow Code = 0x90 - FixedArrayHigh Code = 0x9f - FixedArrayMask Code = 0xf - Array16 Code = 0xdc - Array32 Code = 0xdd - - FixedMapLow Code = 0x80 - FixedMapHigh Code = 0x8f - FixedMapMask Code = 0xf - Map16 Code = 0xde - Map32 Code = 0xdf - - FixExt1 Code = 0xd4 - FixExt2 Code = 0xd5 - FixExt4 Code = 0xd6 - FixExt8 Code = 0xd7 - FixExt16 Code = 0xd8 - Ext8 Code = 0xc7 - Ext16 Code = 0xc8 - Ext32 Code = 0xc9 -) - -func IsFixedNum(c Code) bool { - return c <= PosFixedNumHigh || c >= NegFixedNumLow -} - -func IsFixedMap(c Code) bool { - return c >= FixedMapLow && c <= FixedMapHigh -} - -func IsFixedArray(c Code) bool { - return c >= FixedArrayLow && c <= FixedArrayHigh -} - -func IsFixedString(c Code) bool { - return c >= FixedStrLow && c <= FixedStrHigh -} - -func IsString(c Code) bool { - return IsFixedString(c) || c == Str8 || c == Str16 || c == Str32 -} - -func IsFixedExt(c Code) bool { - return c >= FixExt1 && c <= FixExt16 -} - -func IsExt(c Code) bool { - return IsFixedExt(c) || c == Ext8 || c == Ext16 || c == Ext32 -} diff --git a/vendor/github.com/vmihailenco/msgpack/decode.go b/vendor/github.com/vmihailenco/msgpack/decode.go deleted file mode 100644 index 74141004..00000000 --- a/vendor/github.com/vmihailenco/msgpack/decode.go +++ /dev/null @@ -1,546 +0,0 @@ -package msgpack - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io" - "reflect" - "time" - - "github.com/vmihailenco/msgpack/codes" -) - -const bytesAllocLimit = 1024 * 1024 // 1mb - -type bufReader interface { - io.Reader - io.ByteScanner -} - -func newBufReader(r io.Reader) bufReader { - if br, ok := r.(bufReader); ok { - return br - } - return bufio.NewReader(r) -} - -func makeBuffer() []byte { - return make([]byte, 0, 64) -} - -// Unmarshal decodes the MessagePack-encoded data and stores the result -// in the value pointed to by v. -func Unmarshal(data []byte, v interface{}) error { - return NewDecoder(bytes.NewReader(data)).Decode(v) -} - -type Decoder struct { - r io.Reader - s io.ByteScanner - buf []byte - - extLen int - rec []byte // accumulates read data if not nil - - useLoose bool - useJSONTag bool - - decodeMapFunc func(*Decoder) (interface{}, error) -} - -// NewDecoder returns a new decoder that reads from r. -// -// The decoder introduces its own buffering and may read data from r -// beyond the MessagePack values requested. Buffering can be disabled -// by passing a reader that implements io.ByteScanner interface. -func NewDecoder(r io.Reader) *Decoder { - d := &Decoder{ - buf: makeBuffer(), - } - d.resetReader(r) - return d -} - -func (d *Decoder) SetDecodeMapFunc(fn func(*Decoder) (interface{}, error)) { - d.decodeMapFunc = fn -} - -// UseDecodeInterfaceLoose causes decoder to use DecodeInterfaceLoose -// to decode msgpack value into Go interface{}. -func (d *Decoder) UseDecodeInterfaceLoose(flag bool) { - d.useLoose = flag -} - -// UseJSONTag causes the Decoder to use json struct tag as fallback option -// if there is no msgpack tag. -func (d *Decoder) UseJSONTag(v bool) *Decoder { - d.useJSONTag = v - return d -} - -func (d *Decoder) Reset(r io.Reader) error { - d.resetReader(r) - return nil -} - -func (d *Decoder) resetReader(r io.Reader) { - reader := newBufReader(r) - d.r = reader - d.s = reader -} - -func (d *Decoder) Decode(v interface{}) error { - var err error - switch v := v.(type) { - case *string: - if v != nil { - *v, err = d.DecodeString() - return err - } - case *[]byte: - if v != nil { - return d.decodeBytesPtr(v) - } - case *int: - if v != nil { - *v, err = d.DecodeInt() - return err - } - case *int8: - if v != nil { - *v, err = d.DecodeInt8() - return err - } - case *int16: - if v != nil { - *v, err = d.DecodeInt16() - return err - } - case *int32: - if v != nil { - *v, err = d.DecodeInt32() - return err - } - case *int64: - if v != nil { - *v, err = d.DecodeInt64() - return err - } - case *uint: - if v != nil { - *v, err = d.DecodeUint() - return err - } - case *uint8: - if v != nil { - *v, err = d.DecodeUint8() - return err - } - case *uint16: - if v != nil { - *v, err = d.DecodeUint16() - return err - } - case *uint32: - if v != nil { - *v, err = d.DecodeUint32() - return err - } - case *uint64: - if v != nil { - *v, err = d.DecodeUint64() - return err - } - case *bool: - if v != nil { - *v, err = d.DecodeBool() - return err - } - case *float32: - if v != nil { - *v, err = d.DecodeFloat32() - return err - } - case *float64: - if v != nil { - *v, err = d.DecodeFloat64() - return err - } - case *[]string: - return d.decodeStringSlicePtr(v) - case *map[string]string: - return d.decodeMapStringStringPtr(v) - case *map[string]interface{}: - return d.decodeMapStringInterfacePtr(v) - case *time.Duration: - if v != nil { - vv, err := d.DecodeInt64() - *v = time.Duration(vv) - return err - } - case *time.Time: - if v != nil { - *v, err = d.DecodeTime() - return err - } - } - - vv := reflect.ValueOf(v) - if !vv.IsValid() { - return errors.New("msgpack: Decode(nil)") - } - if vv.Kind() != reflect.Ptr { - return fmt.Errorf("msgpack: Decode(nonsettable %T)", v) - } - vv = vv.Elem() - if !vv.IsValid() { - return fmt.Errorf("msgpack: Decode(nonsettable %T)", v) - } - return d.DecodeValue(vv) -} - -func (d *Decoder) DecodeMulti(v ...interface{}) error { - for _, vv := range v { - if err := d.Decode(vv); err != nil { - return err - } - } - return nil -} - -func (d *Decoder) decodeInterfaceCond() (interface{}, error) { - if d.useLoose { - return d.DecodeInterfaceLoose() - } - return d.DecodeInterface() -} - -func (d *Decoder) DecodeValue(v reflect.Value) error { - decode := getDecoder(v.Type()) - return decode(d, v) -} - -func (d *Decoder) DecodeNil() error { - c, err := d.readCode() - if err != nil { - return err - } - if c != codes.Nil { - return fmt.Errorf("msgpack: invalid code=%x decoding nil", c) - } - return nil -} - -func (d *Decoder) decodeNilValue(v reflect.Value) error { - err := d.DecodeNil() - if v.IsNil() { - return err - } - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - v.Set(reflect.Zero(v.Type())) - return err -} - -func (d *Decoder) DecodeBool() (bool, error) { - c, err := d.readCode() - if err != nil { - return false, err - } - return d.bool(c) -} - -func (d *Decoder) bool(c codes.Code) (bool, error) { - if c == codes.False { - return false, nil - } - if c == codes.True { - return true, nil - } - return false, fmt.Errorf("msgpack: invalid code=%x decoding bool", c) -} - -// DecodeInterface decodes value into interface. It returns following types: -// - nil, -// - bool, -// - int8, int16, int32, int64, -// - uint8, uint16, uint32, uint64, -// - float32 and float64, -// - string, -// - []byte, -// - slices of any of the above, -// - maps of any of the above. -// -// DecodeInterface should be used only when you don't know the type of value -// you are decoding. For example, if you are decoding number it is better to use -// DecodeInt64 for negative numbers and DecodeUint64 for positive numbers. -func (d *Decoder) DecodeInterface() (interface{}, error) { - c, err := d.readCode() - if err != nil { - return nil, err - } - - if codes.IsFixedNum(c) { - return int8(c), nil - } - if codes.IsFixedMap(c) { - err = d.s.UnreadByte() - if err != nil { - return nil, err - } - return d.DecodeMap() - } - if codes.IsFixedArray(c) { - return d.decodeSlice(c) - } - if codes.IsFixedString(c) { - return d.string(c) - } - - switch c { - case codes.Nil: - return nil, nil - case codes.False, codes.True: - return d.bool(c) - case codes.Float: - return d.float32(c) - case codes.Double: - return d.float64(c) - case codes.Uint8: - return d.uint8() - case codes.Uint16: - return d.uint16() - case codes.Uint32: - return d.uint32() - case codes.Uint64: - return d.uint64() - case codes.Int8: - return d.int8() - case codes.Int16: - return d.int16() - case codes.Int32: - return d.int32() - case codes.Int64: - return d.int64() - case codes.Bin8, codes.Bin16, codes.Bin32: - return d.bytes(c, nil) - case codes.Str8, codes.Str16, codes.Str32: - return d.string(c) - case codes.Array16, codes.Array32: - return d.decodeSlice(c) - case codes.Map16, codes.Map32: - err = d.s.UnreadByte() - if err != nil { - return nil, err - } - return d.DecodeMap() - case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16, - codes.Ext8, codes.Ext16, codes.Ext32: - return d.extInterface(c) - } - - return 0, fmt.Errorf("msgpack: unknown code %x decoding interface{}", c) -} - -// DecodeInterfaceLoose is like DecodeInterface except that: -// - int8, int16, and int32 are converted to int64, -// - uint8, uint16, and uint32 are converted to uint64, -// - float32 is converted to float64. -func (d *Decoder) DecodeInterfaceLoose() (interface{}, error) { - c, err := d.readCode() - if err != nil { - return nil, err - } - - if codes.IsFixedNum(c) { - return int64(c), nil - } - if codes.IsFixedMap(c) { - err = d.s.UnreadByte() - if err != nil { - return nil, err - } - return d.DecodeMap() - } - if codes.IsFixedArray(c) { - return d.decodeSlice(c) - } - if codes.IsFixedString(c) { - return d.string(c) - } - - switch c { - case codes.Nil: - return nil, nil - case codes.False, codes.True: - return d.bool(c) - case codes.Float, codes.Double: - return d.float64(c) - case codes.Uint8, codes.Uint16, codes.Uint32, codes.Uint64: - return d.uint(c) - case codes.Int8, codes.Int16, codes.Int32, codes.Int64: - return d.int(c) - case codes.Bin8, codes.Bin16, codes.Bin32: - return d.bytes(c, nil) - case codes.Str8, codes.Str16, codes.Str32: - return d.string(c) - case codes.Array16, codes.Array32: - return d.decodeSlice(c) - case codes.Map16, codes.Map32: - err = d.s.UnreadByte() - if err != nil { - return nil, err - } - return d.DecodeMap() - case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16, - codes.Ext8, codes.Ext16, codes.Ext32: - return d.extInterface(c) - } - - return 0, fmt.Errorf("msgpack: unknown code %x decoding interface{}", c) -} - -// Skip skips next value. -func (d *Decoder) Skip() error { - c, err := d.readCode() - if err != nil { - return err - } - - if codes.IsFixedNum(c) { - return nil - } else if codes.IsFixedMap(c) { - return d.skipMap(c) - } else if codes.IsFixedArray(c) { - return d.skipSlice(c) - } else if codes.IsFixedString(c) { - return d.skipBytes(c) - } - - switch c { - case codes.Nil, codes.False, codes.True: - return nil - case codes.Uint8, codes.Int8: - return d.skipN(1) - case codes.Uint16, codes.Int16: - return d.skipN(2) - case codes.Uint32, codes.Int32, codes.Float: - return d.skipN(4) - case codes.Uint64, codes.Int64, codes.Double: - return d.skipN(8) - case codes.Bin8, codes.Bin16, codes.Bin32: - return d.skipBytes(c) - case codes.Str8, codes.Str16, codes.Str32: - return d.skipBytes(c) - case codes.Array16, codes.Array32: - return d.skipSlice(c) - case codes.Map16, codes.Map32: - return d.skipMap(c) - case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16, - codes.Ext8, codes.Ext16, codes.Ext32: - return d.skipExt(c) - } - - return fmt.Errorf("msgpack: unknown code %x", c) -} - -// PeekCode returns the next MessagePack code without advancing the reader. -// Subpackage msgpack/codes contains list of available codes. -func (d *Decoder) PeekCode() (codes.Code, error) { - c, err := d.s.ReadByte() - if err != nil { - return 0, err - } - return codes.Code(c), d.s.UnreadByte() -} - -func (d *Decoder) hasNilCode() bool { - code, err := d.PeekCode() - return err == nil && code == codes.Nil -} - -func (d *Decoder) readCode() (codes.Code, error) { - d.extLen = 0 - c, err := d.s.ReadByte() - if err != nil { - return 0, err - } - if d.rec != nil { - d.rec = append(d.rec, c) - } - return codes.Code(c), nil -} - -func (d *Decoder) readFull(b []byte) error { - _, err := io.ReadFull(d.r, b) - if err != nil { - return err - } - if d.rec != nil { - d.rec = append(d.rec, b...) - } - return nil -} - -func (d *Decoder) readN(n int) ([]byte, error) { - buf, err := readN(d.r, d.buf, n) - if err != nil { - return nil, err - } - d.buf = buf - if d.rec != nil { - d.rec = append(d.rec, buf...) - } - return buf, nil -} - -func readN(r io.Reader, b []byte, n int) ([]byte, error) { - if b == nil { - if n == 0 { - return make([]byte, 0), nil - } - if n <= bytesAllocLimit { - b = make([]byte, n) - } else { - b = make([]byte, bytesAllocLimit) - } - } - - if n <= cap(b) { - b = b[:n] - _, err := io.ReadFull(r, b) - return b, err - } - b = b[:cap(b)] - - var pos int - for { - alloc := n - len(b) - if alloc > bytesAllocLimit { - alloc = bytesAllocLimit - } - b = append(b, make([]byte, alloc)...) - - _, err := io.ReadFull(r, b[pos:]) - if err != nil { - return nil, err - } - - if len(b) == n { - break - } - pos = len(b) - } - - return b, nil -} - -func min(a, b int) int { - if a <= b { - return a - } - return b -} diff --git a/vendor/github.com/vmihailenco/msgpack/decode_map.go b/vendor/github.com/vmihailenco/msgpack/decode_map.go deleted file mode 100644 index b542a754..00000000 --- a/vendor/github.com/vmihailenco/msgpack/decode_map.go +++ /dev/null @@ -1,338 +0,0 @@ -package msgpack - -import ( - "errors" - "fmt" - "reflect" - - "github.com/vmihailenco/msgpack/codes" -) - -const mapElemsAllocLimit = 1e4 - -var mapStringStringPtrType = reflect.TypeOf((*map[string]string)(nil)) -var mapStringStringType = mapStringStringPtrType.Elem() - -var mapStringInterfacePtrType = reflect.TypeOf((*map[string]interface{})(nil)) -var mapStringInterfaceType = mapStringInterfacePtrType.Elem() - -var errInvalidCode = errors.New("invalid code") - -func decodeMapValue(d *Decoder, v reflect.Value) error { - size, err := d.DecodeMapLen() - if err != nil { - return err - } - - typ := v.Type() - if size == -1 { - v.Set(reflect.Zero(typ)) - return nil - } - - if v.IsNil() { - v.Set(reflect.MakeMap(typ)) - } - if size == 0 { - return nil - } - - return decodeMapValueSize(d, v, size) -} - -func decodeMapValueSize(d *Decoder, v reflect.Value, size int) error { - typ := v.Type() - keyType := typ.Key() - valueType := typ.Elem() - - for i := 0; i < size; i++ { - mk := reflect.New(keyType).Elem() - if err := d.DecodeValue(mk); err != nil { - return err - } - - mv := reflect.New(valueType).Elem() - if err := d.DecodeValue(mv); err != nil { - return err - } - - v.SetMapIndex(mk, mv) - } - - return nil -} - -// DecodeMapLen decodes map length. Length is -1 when map is nil. -func (d *Decoder) DecodeMapLen() (int, error) { - c, err := d.readCode() - if err != nil { - return 0, err - } - - if codes.IsExt(c) { - if err = d.skipExtHeader(c); err != nil { - return 0, err - } - - c, err = d.readCode() - if err != nil { - return 0, err - } - } - return d.mapLen(c) -} - -func (d *Decoder) mapLen(c codes.Code) (int, error) { - size, err := d._mapLen(c) - err = expandInvalidCodeMapLenError(c, err) - return size, err -} - -func (d *Decoder) _mapLen(c codes.Code) (int, error) { - if c == codes.Nil { - return -1, nil - } - if c >= codes.FixedMapLow && c <= codes.FixedMapHigh { - return int(c & codes.FixedMapMask), nil - } - if c == codes.Map16 { - size, err := d.uint16() - return int(size), err - } - if c == codes.Map32 { - size, err := d.uint32() - return int(size), err - } - return 0, errInvalidCode -} - -func expandInvalidCodeMapLenError(c codes.Code, err error) error { - if err == errInvalidCode { - return fmt.Errorf("msgpack: invalid code=%x decoding map length", c) - } - return err -} - -func decodeMapStringStringValue(d *Decoder, v reflect.Value) error { - mptr := v.Addr().Convert(mapStringStringPtrType).Interface().(*map[string]string) - return d.decodeMapStringStringPtr(mptr) -} - -func (d *Decoder) decodeMapStringStringPtr(ptr *map[string]string) error { - size, err := d.DecodeMapLen() - if err != nil { - return err - } - if size == -1 { - *ptr = nil - return nil - } - - m := *ptr - if m == nil { - *ptr = make(map[string]string, min(size, mapElemsAllocLimit)) - m = *ptr - } - - for i := 0; i < size; i++ { - mk, err := d.DecodeString() - if err != nil { - return err - } - mv, err := d.DecodeString() - if err != nil { - return err - } - m[mk] = mv - } - - return nil -} - -func decodeMapStringInterfaceValue(d *Decoder, v reflect.Value) error { - ptr := v.Addr().Convert(mapStringInterfacePtrType).Interface().(*map[string]interface{}) - return d.decodeMapStringInterfacePtr(ptr) -} - -func (d *Decoder) decodeMapStringInterfacePtr(ptr *map[string]interface{}) error { - n, err := d.DecodeMapLen() - if err != nil { - return err - } - if n == -1 { - *ptr = nil - return nil - } - - m := *ptr - if m == nil { - *ptr = make(map[string]interface{}, min(n, mapElemsAllocLimit)) - m = *ptr - } - - for i := 0; i < n; i++ { - mk, err := d.DecodeString() - if err != nil { - return err - } - mv, err := d.decodeInterfaceCond() - if err != nil { - return err - } - m[mk] = mv - } - - return nil -} - -func (d *Decoder) DecodeMap() (interface{}, error) { - if d.decodeMapFunc != nil { - return d.decodeMapFunc(d) - } - - size, err := d.DecodeMapLen() - if err != nil { - return nil, err - } - if size == -1 { - return nil, nil - } - if size == 0 { - return make(map[string]interface{}), nil - } - - code, err := d.PeekCode() - if err != nil { - return nil, err - } - - if codes.IsString(code) { - return d.decodeMapStringInterfaceSize(size) - } - - key, err := d.decodeInterfaceCond() - if err != nil { - return nil, err - } - - value, err := d.decodeInterfaceCond() - if err != nil { - return nil, err - } - - keyType := reflect.TypeOf(key) - valueType := reflect.TypeOf(value) - mapType := reflect.MapOf(keyType, valueType) - mapValue := reflect.MakeMap(mapType) - - mapValue.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value)) - size-- - - err = decodeMapValueSize(d, mapValue, size) - if err != nil { - return nil, err - } - - return mapValue.Interface(), nil -} - -func (d *Decoder) decodeMapStringInterfaceSize(size int) (map[string]interface{}, error) { - m := make(map[string]interface{}, min(size, mapElemsAllocLimit)) - for i := 0; i < size; i++ { - mk, err := d.DecodeString() - if err != nil { - return nil, err - } - mv, err := d.decodeInterfaceCond() - if err != nil { - return nil, err - } - m[mk] = mv - } - return m, nil -} - -func (d *Decoder) skipMap(c codes.Code) error { - n, err := d.mapLen(c) - if err != nil { - return err - } - for i := 0; i < n; i++ { - if err := d.Skip(); err != nil { - return err - } - if err := d.Skip(); err != nil { - return err - } - } - return nil -} - -func decodeStructValue(d *Decoder, v reflect.Value) error { - c, err := d.readCode() - if err != nil { - return err - } - - var isArray bool - - n, err := d._mapLen(c) - if err != nil { - var err2 error - n, err2 = d.arrayLen(c) - if err2 != nil { - return expandInvalidCodeMapLenError(c, err) - } - isArray = true - } - if n == -1 { - if err = mustSet(v); err != nil { - return err - } - v.Set(reflect.Zero(v.Type())) - return nil - } - - var fields *fields - if d.useJSONTag { - fields = jsonStructs.Fields(v.Type()) - } else { - fields = structs.Fields(v.Type()) - } - - if isArray { - for i, f := range fields.List { - if i >= n { - break - } - if err := f.DecodeValue(d, v); err != nil { - return err - } - } - // Skip extra values. - for i := len(fields.List); i < n; i++ { - if err := d.Skip(); err != nil { - return err - } - } - return nil - } - - for i := 0; i < n; i++ { - name, err := d.DecodeString() - if err != nil { - return err - } - if f := fields.Table[name]; f != nil { - if err := f.DecodeValue(d, v); err != nil { - return err - } - } else { - if err := d.Skip(); err != nil { - return err - } - } - } - - return nil -} diff --git a/vendor/github.com/vmihailenco/msgpack/decode_number.go b/vendor/github.com/vmihailenco/msgpack/decode_number.go deleted file mode 100644 index 15019cc9..00000000 --- a/vendor/github.com/vmihailenco/msgpack/decode_number.go +++ /dev/null @@ -1,307 +0,0 @@ -package msgpack - -import ( - "fmt" - "math" - "reflect" - - "github.com/vmihailenco/msgpack/codes" -) - -func (d *Decoder) skipN(n int) error { - _, err := d.readN(n) - return err -} - -func (d *Decoder) uint8() (uint8, error) { - c, err := d.readCode() - if err != nil { - return 0, err - } - return uint8(c), nil -} - -func (d *Decoder) int8() (int8, error) { - n, err := d.uint8() - return int8(n), err -} - -func (d *Decoder) uint16() (uint16, error) { - b, err := d.readN(2) - if err != nil { - return 0, err - } - return (uint16(b[0]) << 8) | uint16(b[1]), nil -} - -func (d *Decoder) int16() (int16, error) { - n, err := d.uint16() - return int16(n), err -} - -func (d *Decoder) uint32() (uint32, error) { - b, err := d.readN(4) - if err != nil { - return 0, err - } - n := (uint32(b[0]) << 24) | - (uint32(b[1]) << 16) | - (uint32(b[2]) << 8) | - uint32(b[3]) - return n, nil -} - -func (d *Decoder) int32() (int32, error) { - n, err := d.uint32() - return int32(n), err -} - -func (d *Decoder) uint64() (uint64, error) { - b, err := d.readN(8) - if err != nil { - return 0, err - } - n := (uint64(b[0]) << 56) | - (uint64(b[1]) << 48) | - (uint64(b[2]) << 40) | - (uint64(b[3]) << 32) | - (uint64(b[4]) << 24) | - (uint64(b[5]) << 16) | - (uint64(b[6]) << 8) | - uint64(b[7]) - return n, nil -} - -func (d *Decoder) int64() (int64, error) { - n, err := d.uint64() - return int64(n), err -} - -// DecodeUint64 decodes msgpack int8/16/32/64 and uint8/16/32/64 -// into Go uint64. -func (d *Decoder) DecodeUint64() (uint64, error) { - c, err := d.readCode() - if err != nil { - return 0, err - } - return d.uint(c) -} - -func (d *Decoder) uint(c codes.Code) (uint64, error) { - if c == codes.Nil { - return 0, nil - } - if codes.IsFixedNum(c) { - return uint64(int8(c)), nil - } - switch c { - case codes.Uint8: - n, err := d.uint8() - return uint64(n), err - case codes.Int8: - n, err := d.int8() - return uint64(n), err - case codes.Uint16: - n, err := d.uint16() - return uint64(n), err - case codes.Int16: - n, err := d.int16() - return uint64(n), err - case codes.Uint32: - n, err := d.uint32() - return uint64(n), err - case codes.Int32: - n, err := d.int32() - return uint64(n), err - case codes.Uint64, codes.Int64: - return d.uint64() - } - return 0, fmt.Errorf("msgpack: invalid code=%x decoding uint64", c) -} - -// DecodeInt64 decodes msgpack int8/16/32/64 and uint8/16/32/64 -// into Go int64. -func (d *Decoder) DecodeInt64() (int64, error) { - c, err := d.readCode() - if err != nil { - return 0, err - } - return d.int(c) -} - -func (d *Decoder) int(c codes.Code) (int64, error) { - if c == codes.Nil { - return 0, nil - } - if codes.IsFixedNum(c) { - return int64(int8(c)), nil - } - switch c { - case codes.Uint8: - n, err := d.uint8() - return int64(n), err - case codes.Int8: - n, err := d.uint8() - return int64(int8(n)), err - case codes.Uint16: - n, err := d.uint16() - return int64(n), err - case codes.Int16: - n, err := d.uint16() - return int64(int16(n)), err - case codes.Uint32: - n, err := d.uint32() - return int64(n), err - case codes.Int32: - n, err := d.uint32() - return int64(int32(n)), err - case codes.Uint64, codes.Int64: - n, err := d.uint64() - return int64(n), err - } - return 0, fmt.Errorf("msgpack: invalid code=%x decoding int64", c) -} - -func (d *Decoder) DecodeFloat32() (float32, error) { - c, err := d.readCode() - if err != nil { - return 0, err - } - return d.float32(c) -} - -func (d *Decoder) float32(c codes.Code) (float32, error) { - if c == codes.Float { - n, err := d.uint32() - if err != nil { - return 0, err - } - return math.Float32frombits(n), nil - } - - n, err := d.int(c) - if err != nil { - return 0, fmt.Errorf("msgpack: invalid code=%x decoding float32", c) - } - return float32(n), nil -} - -// DecodeFloat64 decodes msgpack float32/64 into Go float64. -func (d *Decoder) DecodeFloat64() (float64, error) { - c, err := d.readCode() - if err != nil { - return 0, err - } - return d.float64(c) -} - -func (d *Decoder) float64(c codes.Code) (float64, error) { - switch c { - case codes.Float: - n, err := d.float32(c) - if err != nil { - return 0, err - } - return float64(n), nil - case codes.Double: - n, err := d.uint64() - if err != nil { - return 0, err - } - return math.Float64frombits(n), nil - } - - n, err := d.int(c) - if err != nil { - return 0, fmt.Errorf("msgpack: invalid code=%x decoding float32", c) - } - return float64(n), nil -} - -func (d *Decoder) DecodeUint() (uint, error) { - n, err := d.DecodeUint64() - return uint(n), err -} - -func (d *Decoder) DecodeUint8() (uint8, error) { - n, err := d.DecodeUint64() - return uint8(n), err -} - -func (d *Decoder) DecodeUint16() (uint16, error) { - n, err := d.DecodeUint64() - return uint16(n), err -} - -func (d *Decoder) DecodeUint32() (uint32, error) { - n, err := d.DecodeUint64() - return uint32(n), err -} - -func (d *Decoder) DecodeInt() (int, error) { - n, err := d.DecodeInt64() - return int(n), err -} - -func (d *Decoder) DecodeInt8() (int8, error) { - n, err := d.DecodeInt64() - return int8(n), err -} - -func (d *Decoder) DecodeInt16() (int16, error) { - n, err := d.DecodeInt64() - return int16(n), err -} - -func (d *Decoder) DecodeInt32() (int32, error) { - n, err := d.DecodeInt64() - return int32(n), err -} - -func decodeFloat32Value(d *Decoder, v reflect.Value) error { - f, err := d.DecodeFloat32() - if err != nil { - return err - } - if err = mustSet(v); err != nil { - return err - } - v.SetFloat(float64(f)) - return nil -} - -func decodeFloat64Value(d *Decoder, v reflect.Value) error { - f, err := d.DecodeFloat64() - if err != nil { - return err - } - if err = mustSet(v); err != nil { - return err - } - v.SetFloat(f) - return nil -} - -func decodeInt64Value(d *Decoder, v reflect.Value) error { - n, err := d.DecodeInt64() - if err != nil { - return err - } - if err = mustSet(v); err != nil { - return err - } - v.SetInt(n) - return nil -} - -func decodeUint64Value(d *Decoder, v reflect.Value) error { - n, err := d.DecodeUint64() - if err != nil { - return err - } - if err = mustSet(v); err != nil { - return err - } - v.SetUint(n) - return nil -} diff --git a/vendor/github.com/vmihailenco/msgpack/decode_query.go b/vendor/github.com/vmihailenco/msgpack/decode_query.go deleted file mode 100644 index d680be80..00000000 --- a/vendor/github.com/vmihailenco/msgpack/decode_query.go +++ /dev/null @@ -1,158 +0,0 @@ -package msgpack - -import ( - "fmt" - "strconv" - "strings" - - "github.com/vmihailenco/msgpack/codes" -) - -type queryResult struct { - query string - key string - hasAsterisk bool - - values []interface{} -} - -func (q *queryResult) nextKey() { - ind := strings.IndexByte(q.query, '.') - if ind == -1 { - q.key = q.query - q.query = "" - return - } - q.key = q.query[:ind] - q.query = q.query[ind+1:] -} - -// Query extracts data specified by the query from the msgpack stream skipping -// any other data. Query consists of map keys and array indexes separated with dot, -// e.g. key1.0.key2. -func (d *Decoder) Query(query string) ([]interface{}, error) { - res := queryResult{ - query: query, - } - if err := d.query(&res); err != nil { - return nil, err - } - return res.values, nil -} - -func (d *Decoder) query(q *queryResult) error { - q.nextKey() - if q.key == "" { - v, err := d.decodeInterfaceCond() - if err != nil { - return err - } - q.values = append(q.values, v) - return nil - } - - code, err := d.PeekCode() - if err != nil { - return err - } - - switch { - case code == codes.Map16 || code == codes.Map32 || codes.IsFixedMap(code): - err = d.queryMapKey(q) - case code == codes.Array16 || code == codes.Array32 || codes.IsFixedArray(code): - err = d.queryArrayIndex(q) - default: - err = fmt.Errorf("msgpack: unsupported code=%x decoding key=%q", code, q.key) - } - return err -} - -func (d *Decoder) queryMapKey(q *queryResult) error { - n, err := d.DecodeMapLen() - if err != nil { - return err - } - if n == -1 { - return nil - } - - for i := 0; i < n; i++ { - k, err := d.bytesNoCopy() - if err != nil { - return err - } - - if string(k) == q.key { - if err := d.query(q); err != nil { - return err - } - if q.hasAsterisk { - return d.skipNext((n - i - 1) * 2) - } - return nil - } - - if err := d.Skip(); err != nil { - return err - } - } - - return nil -} - -func (d *Decoder) queryArrayIndex(q *queryResult) error { - n, err := d.DecodeArrayLen() - if err != nil { - return err - } - if n == -1 { - return nil - } - - if q.key == "*" { - q.hasAsterisk = true - - query := q.query - for i := 0; i < n; i++ { - q.query = query - if err := d.query(q); err != nil { - return err - } - } - - q.hasAsterisk = false - return nil - } - - ind, err := strconv.Atoi(q.key) - if err != nil { - return err - } - - for i := 0; i < n; i++ { - if i == ind { - if err := d.query(q); err != nil { - return err - } - if q.hasAsterisk { - return d.skipNext(n - i - 1) - } - return nil - } - - if err := d.Skip(); err != nil { - return err - } - } - - return nil -} - -func (d *Decoder) skipNext(n int) error { - for i := 0; i < n; i++ { - if err := d.Skip(); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/vmihailenco/msgpack/decode_slice.go b/vendor/github.com/vmihailenco/msgpack/decode_slice.go deleted file mode 100644 index 778d80b9..00000000 --- a/vendor/github.com/vmihailenco/msgpack/decode_slice.go +++ /dev/null @@ -1,193 +0,0 @@ -package msgpack - -import ( - "fmt" - "reflect" - - "github.com/vmihailenco/msgpack/codes" -) - -const sliceElemsAllocLimit = 1e4 - -var sliceStringPtrType = reflect.TypeOf((*[]string)(nil)) - -// DecodeArrayLen decodes array length. Length is -1 when array is nil. -func (d *Decoder) DecodeArrayLen() (int, error) { - c, err := d.readCode() - if err != nil { - return 0, err - } - return d.arrayLen(c) -} - -func (d *Decoder) arrayLen(c codes.Code) (int, error) { - if c == codes.Nil { - return -1, nil - } else if c >= codes.FixedArrayLow && c <= codes.FixedArrayHigh { - return int(c & codes.FixedArrayMask), nil - } - switch c { - case codes.Array16: - n, err := d.uint16() - return int(n), err - case codes.Array32: - n, err := d.uint32() - return int(n), err - } - return 0, fmt.Errorf("msgpack: invalid code=%x decoding array length", c) -} - -func decodeStringSliceValue(d *Decoder, v reflect.Value) error { - ptr := v.Addr().Convert(sliceStringPtrType).Interface().(*[]string) - return d.decodeStringSlicePtr(ptr) -} - -func (d *Decoder) decodeStringSlicePtr(ptr *[]string) error { - n, err := d.DecodeArrayLen() - if err != nil { - return err - } - if n == -1 { - return nil - } - - ss := setStringsCap(*ptr, n) - for i := 0; i < n; i++ { - s, err := d.DecodeString() - if err != nil { - return err - } - ss = append(ss, s) - } - *ptr = ss - - return nil -} - -func setStringsCap(s []string, n int) []string { - if n > sliceElemsAllocLimit { - n = sliceElemsAllocLimit - } - - if s == nil { - return make([]string, 0, n) - } - - if cap(s) >= n { - return s[:0] - } - - s = s[:cap(s)] - s = append(s, make([]string, n-len(s))...) - return s[:0] -} - -func decodeSliceValue(d *Decoder, v reflect.Value) error { - n, err := d.DecodeArrayLen() - if err != nil { - return err - } - - if n == -1 { - v.Set(reflect.Zero(v.Type())) - return nil - } - if n == 0 && v.IsNil() { - v.Set(reflect.MakeSlice(v.Type(), 0, 0)) - return nil - } - - if v.Cap() >= n { - v.Set(v.Slice(0, n)) - } else if v.Len() < v.Cap() { - v.Set(v.Slice(0, v.Cap())) - } - - for i := 0; i < n; i++ { - if i >= v.Len() { - v.Set(growSliceValue(v, n)) - } - sv := v.Index(i) - if err := d.DecodeValue(sv); err != nil { - return err - } - } - - return nil -} - -func growSliceValue(v reflect.Value, n int) reflect.Value { - diff := n - v.Len() - if diff > sliceElemsAllocLimit { - diff = sliceElemsAllocLimit - } - v = reflect.AppendSlice(v, reflect.MakeSlice(v.Type(), diff, diff)) - return v -} - -func decodeArrayValue(d *Decoder, v reflect.Value) error { - n, err := d.DecodeArrayLen() - if err != nil { - return err - } - - if n == -1 { - return nil - } - - if n > v.Len() { - return fmt.Errorf("%s len is %d, but msgpack has %d elements", v.Type(), v.Len(), n) - } - for i := 0; i < n; i++ { - sv := v.Index(i) - if err := d.DecodeValue(sv); err != nil { - return err - } - } - - return nil -} - -func (d *Decoder) DecodeSlice() ([]interface{}, error) { - c, err := d.readCode() - if err != nil { - return nil, err - } - return d.decodeSlice(c) -} - -func (d *Decoder) decodeSlice(c codes.Code) ([]interface{}, error) { - n, err := d.arrayLen(c) - if err != nil { - return nil, err - } - if n == -1 { - return nil, nil - } - - s := make([]interface{}, 0, min(n, sliceElemsAllocLimit)) - for i := 0; i < n; i++ { - v, err := d.decodeInterfaceCond() - if err != nil { - return nil, err - } - s = append(s, v) - } - - return s, nil -} - -func (d *Decoder) skipSlice(c codes.Code) error { - n, err := d.arrayLen(c) - if err != nil { - return err - } - - for i := 0; i < n; i++ { - if err := d.Skip(); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/vmihailenco/msgpack/decode_string.go b/vendor/github.com/vmihailenco/msgpack/decode_string.go deleted file mode 100644 index 5402022e..00000000 --- a/vendor/github.com/vmihailenco/msgpack/decode_string.go +++ /dev/null @@ -1,175 +0,0 @@ -package msgpack - -import ( - "fmt" - "reflect" - - "github.com/vmihailenco/msgpack/codes" -) - -func (d *Decoder) bytesLen(c codes.Code) (int, error) { - if c == codes.Nil { - return -1, nil - } else if codes.IsFixedString(c) { - return int(c & codes.FixedStrMask), nil - } - switch c { - case codes.Str8, codes.Bin8: - n, err := d.uint8() - return int(n), err - case codes.Str16, codes.Bin16: - n, err := d.uint16() - return int(n), err - case codes.Str32, codes.Bin32: - n, err := d.uint32() - return int(n), err - } - return 0, fmt.Errorf("msgpack: invalid code=%x decoding bytes length", c) -} - -func (d *Decoder) DecodeString() (string, error) { - c, err := d.readCode() - if err != nil { - return "", err - } - return d.string(c) -} - -func (d *Decoder) string(c codes.Code) (string, error) { - n, err := d.bytesLen(c) - if err != nil { - return "", err - } - if n == -1 { - return "", nil - } - b, err := d.readN(n) - return string(b), err -} - -func decodeStringValue(d *Decoder, v reflect.Value) error { - s, err := d.DecodeString() - if err != nil { - return err - } - if err = mustSet(v); err != nil { - return err - } - v.SetString(s) - return nil -} - -func (d *Decoder) DecodeBytesLen() (int, error) { - c, err := d.readCode() - if err != nil { - return 0, err - } - return d.bytesLen(c) -} - -func (d *Decoder) DecodeBytes() ([]byte, error) { - c, err := d.readCode() - if err != nil { - return nil, err - } - return d.bytes(c, nil) -} - -func (d *Decoder) bytes(c codes.Code, b []byte) ([]byte, error) { - n, err := d.bytesLen(c) - if err != nil { - return nil, err - } - if n == -1 { - return nil, nil - } - return readN(d.r, b, n) -} - -func (d *Decoder) bytesNoCopy() ([]byte, error) { - c, err := d.readCode() - if err != nil { - return nil, err - } - n, err := d.bytesLen(c) - if err != nil { - return nil, err - } - if n == -1 { - return nil, nil - } - return d.readN(n) -} - -func (d *Decoder) decodeBytesPtr(ptr *[]byte) error { - c, err := d.readCode() - if err != nil { - return err - } - return d.bytesPtr(c, ptr) -} - -func (d *Decoder) bytesPtr(c codes.Code, ptr *[]byte) error { - n, err := d.bytesLen(c) - if err != nil { - return err - } - if n == -1 { - *ptr = nil - return nil - } - - *ptr, err = readN(d.r, *ptr, n) - return err -} - -func (d *Decoder) skipBytes(c codes.Code) error { - n, err := d.bytesLen(c) - if err != nil { - return err - } - if n == -1 { - return nil - } - return d.skipN(n) -} - -func decodeBytesValue(d *Decoder, v reflect.Value) error { - c, err := d.readCode() - if err != nil { - return err - } - - b, err := d.bytes(c, v.Bytes()) - if err != nil { - return err - } - - if err = mustSet(v); err != nil { - return err - } - v.SetBytes(b) - - return nil -} - -func decodeByteArrayValue(d *Decoder, v reflect.Value) error { - c, err := d.readCode() - if err != nil { - return err - } - - n, err := d.bytesLen(c) - if err != nil { - return err - } - if n == -1 { - return nil - } - if n > v.Len() { - return fmt.Errorf("%s len is %d, but msgpack has %d elements", v.Type(), v.Len(), n) - } - - b := v.Slice(0, n).Bytes() - return d.readFull(b) -} diff --git a/vendor/github.com/vmihailenco/msgpack/decode_value.go b/vendor/github.com/vmihailenco/msgpack/decode_value.go deleted file mode 100644 index 7b858b5f..00000000 --- a/vendor/github.com/vmihailenco/msgpack/decode_value.go +++ /dev/null @@ -1,234 +0,0 @@ -package msgpack - -import ( - "errors" - "fmt" - "reflect" -) - -var interfaceType = reflect.TypeOf((*interface{})(nil)).Elem() -var stringType = reflect.TypeOf((*string)(nil)).Elem() - -var valueDecoders []decoderFunc - -func init() { - valueDecoders = []decoderFunc{ - reflect.Bool: decodeBoolValue, - reflect.Int: decodeInt64Value, - reflect.Int8: decodeInt64Value, - reflect.Int16: decodeInt64Value, - reflect.Int32: decodeInt64Value, - reflect.Int64: decodeInt64Value, - reflect.Uint: decodeUint64Value, - reflect.Uint8: decodeUint64Value, - reflect.Uint16: decodeUint64Value, - reflect.Uint32: decodeUint64Value, - reflect.Uint64: decodeUint64Value, - reflect.Float32: decodeFloat32Value, - reflect.Float64: decodeFloat64Value, - reflect.Complex64: decodeUnsupportedValue, - reflect.Complex128: decodeUnsupportedValue, - reflect.Array: decodeArrayValue, - reflect.Chan: decodeUnsupportedValue, - reflect.Func: decodeUnsupportedValue, - reflect.Interface: decodeInterfaceValue, - reflect.Map: decodeMapValue, - reflect.Ptr: decodeUnsupportedValue, - reflect.Slice: decodeSliceValue, - reflect.String: decodeStringValue, - reflect.Struct: decodeStructValue, - reflect.UnsafePointer: decodeUnsupportedValue, - } -} - -func mustSet(v reflect.Value) error { - if !v.CanSet() { - return fmt.Errorf("msgpack: Decode(nonsettable %s)", v.Type()) - } - return nil -} - -func getDecoder(typ reflect.Type) decoderFunc { - kind := typ.Kind() - - decoder, ok := typDecMap[typ] - if ok { - return decoder - } - - if typ.Implements(customDecoderType) { - return decodeCustomValue - } - if typ.Implements(unmarshalerType) { - return unmarshalValue - } - - // Addressable struct field value. - if kind != reflect.Ptr { - ptr := reflect.PtrTo(typ) - if ptr.Implements(customDecoderType) { - return decodeCustomValueAddr - } - if ptr.Implements(unmarshalerType) { - return unmarshalValueAddr - } - } - - switch kind { - case reflect.Ptr: - return ptrDecoderFunc(typ) - case reflect.Slice: - elem := typ.Elem() - switch elem.Kind() { - case reflect.Uint8: - return decodeBytesValue - } - switch elem { - case stringType: - return decodeStringSliceValue - } - case reflect.Array: - if typ.Elem().Kind() == reflect.Uint8 { - return decodeByteArrayValue - } - case reflect.Map: - if typ.Key() == stringType { - switch typ.Elem() { - case stringType: - return decodeMapStringStringValue - case interfaceType: - return decodeMapStringInterfaceValue - } - } - } - return valueDecoders[kind] -} - -func ptrDecoderFunc(typ reflect.Type) decoderFunc { - decoder := getDecoder(typ.Elem()) - return func(d *Decoder, v reflect.Value) error { - if d.hasNilCode() { - if err := mustSet(v); err != nil { - return err - } - if !v.IsNil() { - v.Set(reflect.Zero(v.Type())) - } - return d.DecodeNil() - } - if v.IsNil() { - if err := mustSet(v); err != nil { - return err - } - v.Set(reflect.New(v.Type().Elem())) - } - return decoder(d, v.Elem()) - } -} - -func decodeCustomValueAddr(d *Decoder, v reflect.Value) error { - if !v.CanAddr() { - return fmt.Errorf("msgpack: Decode(nonaddressable %T)", v.Interface()) - } - return decodeCustomValue(d, v.Addr()) -} - -func decodeCustomValue(d *Decoder, v reflect.Value) error { - if d.hasNilCode() { - return d.decodeNilValue(v) - } - - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - - decoder := v.Interface().(CustomDecoder) - return decoder.DecodeMsgpack(d) -} - -func unmarshalValueAddr(d *Decoder, v reflect.Value) error { - if !v.CanAddr() { - return fmt.Errorf("msgpack: Decode(nonaddressable %T)", v.Interface()) - } - return unmarshalValue(d, v.Addr()) -} - -func unmarshalValue(d *Decoder, v reflect.Value) error { - if d.hasNilCode() { - return d.decodeNilValue(v) - } - - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - - if d.extLen != 0 { - b, err := d.readN(d.extLen) - if err != nil { - return err - } - d.rec = b - } else { - d.rec = makeBuffer() - if err := d.Skip(); err != nil { - return err - } - } - - unmarshaler := v.Interface().(Unmarshaler) - err := unmarshaler.UnmarshalMsgpack(d.rec) - d.rec = nil - return err -} - -func decodeBoolValue(d *Decoder, v reflect.Value) error { - flag, err := d.DecodeBool() - if err != nil { - return err - } - if err = mustSet(v); err != nil { - return err - } - v.SetBool(flag) - return nil -} - -func decodeInterfaceValue(d *Decoder, v reflect.Value) error { - if v.IsNil() { - return d.interfaceValue(v) - } - - elem := v.Elem() - if !elem.CanAddr() { - if d.hasNilCode() { - v.Set(reflect.Zero(v.Type())) - return d.DecodeNil() - } - } - - return d.DecodeValue(elem) -} - -func (d *Decoder) interfaceValue(v reflect.Value) error { - vv, err := d.decodeInterfaceCond() - if err != nil { - return err - } - - if vv != nil { - if v.Type() == errorType { - if vv, ok := vv.(string); ok { - v.Set(reflect.ValueOf(errors.New(vv))) - return nil - } - } - - v.Set(reflect.ValueOf(vv)) - } - - return nil -} - -func decodeUnsupportedValue(d *Decoder, v reflect.Value) error { - return fmt.Errorf("msgpack: Decode(unsupported %s)", v.Type()) -} diff --git a/vendor/github.com/vmihailenco/msgpack/encode.go b/vendor/github.com/vmihailenco/msgpack/encode.go deleted file mode 100644 index c2bb23cd..00000000 --- a/vendor/github.com/vmihailenco/msgpack/encode.go +++ /dev/null @@ -1,170 +0,0 @@ -package msgpack - -import ( - "bytes" - "io" - "reflect" - "time" - - "github.com/vmihailenco/msgpack/codes" -) - -type writer interface { - io.Writer - WriteByte(byte) error - WriteString(string) (int, error) -} - -type byteWriter struct { - io.Writer - - buf []byte - bootstrap [64]byte -} - -func newByteWriter(w io.Writer) *byteWriter { - bw := &byteWriter{ - Writer: w, - } - bw.buf = bw.bootstrap[:] - return bw -} - -func (w *byteWriter) WriteByte(c byte) error { - w.buf = w.buf[:1] - w.buf[0] = c - _, err := w.Write(w.buf) - return err -} - -func (w *byteWriter) WriteString(s string) (int, error) { - w.buf = append(w.buf[:0], s...) - return w.Write(w.buf) -} - -// Marshal returns the MessagePack encoding of v. -func Marshal(v interface{}) ([]byte, error) { - var buf bytes.Buffer - err := NewEncoder(&buf).Encode(v) - return buf.Bytes(), err -} - -type Encoder struct { - w writer - buf []byte - - sortMapKeys bool - structAsArray bool - useJSONTag bool - useCompact bool -} - -// NewEncoder returns a new encoder that writes to w. -func NewEncoder(w io.Writer) *Encoder { - bw, ok := w.(writer) - if !ok { - bw = newByteWriter(w) - } - return &Encoder{ - w: bw, - buf: make([]byte, 9), - } -} - -// SortMapKeys causes the Encoder to encode map keys in increasing order. -// Supported map types are: -// - map[string]string -// - map[string]interface{} -func (e *Encoder) SortMapKeys(flag bool) *Encoder { - e.sortMapKeys = flag - return e -} - -// StructAsArray causes the Encoder to encode Go structs as MessagePack arrays. -func (e *Encoder) StructAsArray(flag bool) *Encoder { - e.structAsArray = flag - return e -} - -// UseJSONTag causes the Encoder to use json struct tag as fallback option -// if there is no msgpack tag. -func (e *Encoder) UseJSONTag(flag bool) *Encoder { - e.useJSONTag = flag - return e -} - -// UseCompactEncoding causes the Encoder to chose the most compact encoding. -// For example, it allows to encode Go int64 as msgpack int8 saving 7 bytes. -func (e *Encoder) UseCompactEncoding(flag bool) *Encoder { - e.useCompact = flag - return e -} - -func (e *Encoder) Encode(v interface{}) error { - switch v := v.(type) { - case nil: - return e.EncodeNil() - case string: - return e.EncodeString(v) - case []byte: - return e.EncodeBytes(v) - case int: - return e.encodeInt64Cond(int64(v)) - case int64: - return e.encodeInt64Cond(v) - case uint: - return e.encodeUint64Cond(uint64(v)) - case uint64: - return e.encodeUint64Cond(v) - case bool: - return e.EncodeBool(v) - case float32: - return e.EncodeFloat32(v) - case float64: - return e.EncodeFloat64(v) - case time.Duration: - return e.encodeInt64Cond(int64(v)) - case time.Time: - return e.EncodeTime(v) - } - return e.EncodeValue(reflect.ValueOf(v)) -} - -func (e *Encoder) EncodeMulti(v ...interface{}) error { - for _, vv := range v { - if err := e.Encode(vv); err != nil { - return err - } - } - return nil -} - -func (e *Encoder) EncodeValue(v reflect.Value) error { - fn := getEncoder(v.Type()) - return fn(e, v) -} - -func (e *Encoder) EncodeNil() error { - return e.writeCode(codes.Nil) -} - -func (e *Encoder) EncodeBool(value bool) error { - if value { - return e.writeCode(codes.True) - } - return e.writeCode(codes.False) -} - -func (e *Encoder) writeCode(c codes.Code) error { - return e.w.WriteByte(byte(c)) -} - -func (e *Encoder) write(b []byte) error { - _, err := e.w.Write(b) - return err -} - -func (e *Encoder) writeString(s string) error { - _, err := e.w.WriteString(s) - return err -} diff --git a/vendor/github.com/vmihailenco/msgpack/encode_map.go b/vendor/github.com/vmihailenco/msgpack/encode_map.go deleted file mode 100644 index a87c4075..00000000 --- a/vendor/github.com/vmihailenco/msgpack/encode_map.go +++ /dev/null @@ -1,172 +0,0 @@ -package msgpack - -import ( - "reflect" - "sort" - - "github.com/vmihailenco/msgpack/codes" -) - -func encodeMapValue(e *Encoder, v reflect.Value) error { - if v.IsNil() { - return e.EncodeNil() - } - - if err := e.EncodeMapLen(v.Len()); err != nil { - return err - } - - for _, key := range v.MapKeys() { - if err := e.EncodeValue(key); err != nil { - return err - } - if err := e.EncodeValue(v.MapIndex(key)); err != nil { - return err - } - } - - return nil -} - -func encodeMapStringStringValue(e *Encoder, v reflect.Value) error { - if v.IsNil() { - return e.EncodeNil() - } - - if err := e.EncodeMapLen(v.Len()); err != nil { - return err - } - - m := v.Convert(mapStringStringType).Interface().(map[string]string) - if e.sortMapKeys { - return e.encodeSortedMapStringString(m) - } - - for mk, mv := range m { - if err := e.EncodeString(mk); err != nil { - return err - } - if err := e.EncodeString(mv); err != nil { - return err - } - } - - return nil -} - -func encodeMapStringInterfaceValue(e *Encoder, v reflect.Value) error { - if v.IsNil() { - return e.EncodeNil() - } - - if err := e.EncodeMapLen(v.Len()); err != nil { - return err - } - - m := v.Convert(mapStringInterfaceType).Interface().(map[string]interface{}) - if e.sortMapKeys { - return e.encodeSortedMapStringInterface(m) - } - - for mk, mv := range m { - if err := e.EncodeString(mk); err != nil { - return err - } - if err := e.Encode(mv); err != nil { - return err - } - } - - return nil -} - -func (e *Encoder) encodeSortedMapStringString(m map[string]string) error { - keys := make([]string, 0, len(m)) - for k, _ := range m { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - err := e.EncodeString(k) - if err != nil { - return err - } - if err = e.EncodeString(m[k]); err != nil { - return err - } - } - - return nil -} - -func (e *Encoder) encodeSortedMapStringInterface(m map[string]interface{}) error { - keys := make([]string, 0, len(m)) - for k, _ := range m { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - err := e.EncodeString(k) - if err != nil { - return err - } - if err = e.Encode(m[k]); err != nil { - return err - } - } - - return nil -} - -func (e *Encoder) EncodeMapLen(l int) error { - if l < 16 { - return e.writeCode(codes.FixedMapLow | codes.Code(l)) - } - if l < 65536 { - return e.write2(codes.Map16, uint16(l)) - } - return e.write4(codes.Map32, uint32(l)) -} - -func encodeStructValue(e *Encoder, strct reflect.Value) error { - var structFields *fields - if e.useJSONTag { - structFields = jsonStructs.Fields(strct.Type()) - } else { - structFields = structs.Fields(strct.Type()) - } - - if e.structAsArray || structFields.AsArray { - return encodeStructValueAsArray(e, strct, structFields.List) - } - fields := structFields.OmitEmpty(strct) - - if err := e.EncodeMapLen(len(fields)); err != nil { - return err - } - - for _, f := range fields { - if err := e.EncodeString(f.name); err != nil { - return err - } - if err := f.EncodeValue(e, strct); err != nil { - return err - } - } - - return nil -} - -func encodeStructValueAsArray(e *Encoder, strct reflect.Value, fields []*field) error { - if err := e.EncodeArrayLen(len(fields)); err != nil { - return err - } - for _, f := range fields { - if err := f.EncodeValue(e, strct); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/vmihailenco/msgpack/encode_number.go b/vendor/github.com/vmihailenco/msgpack/encode_number.go deleted file mode 100644 index dd7db6fd..00000000 --- a/vendor/github.com/vmihailenco/msgpack/encode_number.go +++ /dev/null @@ -1,230 +0,0 @@ -package msgpack - -import ( - "math" - "reflect" - - "github.com/vmihailenco/msgpack/codes" -) - -// EncodeUint8 encodes an uint8 in 2 bytes preserving type of the number. -func (e *Encoder) EncodeUint8(n uint8) error { - return e.write1(codes.Uint8, n) -} - -func (e *Encoder) encodeUint8Cond(n uint8) error { - if e.useCompact { - return e.EncodeUint(uint64(n)) - } - return e.EncodeUint8(n) -} - -// EncodeUint16 encodes an uint16 in 3 bytes preserving type of the number. -func (e *Encoder) EncodeUint16(n uint16) error { - return e.write2(codes.Uint16, n) -} - -func (e *Encoder) encodeUint16Cond(n uint16) error { - if e.useCompact { - return e.EncodeUint(uint64(n)) - } - return e.EncodeUint16(n) -} - -// EncodeUint32 encodes an uint16 in 5 bytes preserving type of the number. -func (e *Encoder) EncodeUint32(n uint32) error { - return e.write4(codes.Uint32, n) -} - -func (e *Encoder) encodeUint32Cond(n uint32) error { - if e.useCompact { - return e.EncodeUint(uint64(n)) - } - return e.EncodeUint32(n) -} - -// EncodeUint64 encodes an uint16 in 9 bytes preserving type of the number. -func (e *Encoder) EncodeUint64(n uint64) error { - return e.write8(codes.Uint64, n) -} - -func (e *Encoder) encodeUint64Cond(n uint64) error { - if e.useCompact { - return e.EncodeUint(n) - } - return e.EncodeUint64(n) -} - -// EncodeInt8 encodes an int8 in 2 bytes preserving type of the number. -func (e *Encoder) EncodeInt8(n int8) error { - return e.write1(codes.Int8, uint8(n)) -} - -func (e *Encoder) encodeInt8Cond(n int8) error { - if e.useCompact { - return e.EncodeInt(int64(n)) - } - return e.EncodeInt8(n) -} - -// EncodeInt16 encodes an int16 in 3 bytes preserving type of the number. -func (e *Encoder) EncodeInt16(n int16) error { - return e.write2(codes.Int16, uint16(n)) -} - -func (e *Encoder) encodeInt16Cond(n int16) error { - if e.useCompact { - return e.EncodeInt(int64(n)) - } - return e.EncodeInt16(n) -} - -// EncodeInt32 encodes an int32 in 5 bytes preserving type of the number. -func (e *Encoder) EncodeInt32(n int32) error { - return e.write4(codes.Int32, uint32(n)) -} - -func (e *Encoder) encodeInt32Cond(n int32) error { - if e.useCompact { - return e.EncodeInt(int64(n)) - } - return e.EncodeInt32(n) -} - -// EncodeInt64 encodes an int64 in 9 bytes preserving type of the number. -func (e *Encoder) EncodeInt64(n int64) error { - return e.write8(codes.Int64, uint64(n)) -} - -func (e *Encoder) encodeInt64Cond(n int64) error { - if e.useCompact { - return e.EncodeInt(n) - } - return e.EncodeInt64(n) -} - -// EncodeUnsignedNumber encodes an uint64 in 1, 2, 3, 5, or 9 bytes. -// Type of the number is lost during encoding. -func (e *Encoder) EncodeUint(n uint64) error { - if n <= math.MaxInt8 { - return e.w.WriteByte(byte(n)) - } - if n <= math.MaxUint8 { - return e.EncodeUint8(uint8(n)) - } - if n <= math.MaxUint16 { - return e.EncodeUint16(uint16(n)) - } - if n <= math.MaxUint32 { - return e.EncodeUint32(uint32(n)) - } - return e.EncodeUint64(uint64(n)) -} - -// EncodeNumber encodes an int64 in 1, 2, 3, 5, or 9 bytes. -// Type of number is lost during encoding. -func (e *Encoder) EncodeInt(n int64) error { - if n >= 0 { - return e.EncodeUint(uint64(n)) - } - if n >= int64(int8(codes.NegFixedNumLow)) { - return e.w.WriteByte(byte(n)) - } - if n >= math.MinInt8 { - return e.EncodeInt8(int8(n)) - } - if n >= math.MinInt16 { - return e.EncodeInt16(int16(n)) - } - if n >= math.MinInt32 { - return e.EncodeInt32(int32(n)) - } - return e.EncodeInt64(int64(n)) -} - -func (e *Encoder) EncodeFloat32(n float32) error { - return e.write4(codes.Float, math.Float32bits(n)) -} - -func (e *Encoder) EncodeFloat64(n float64) error { - return e.write8(codes.Double, math.Float64bits(n)) -} - -func (e *Encoder) write1(code codes.Code, n uint8) error { - e.buf = e.buf[:2] - e.buf[0] = byte(code) - e.buf[1] = byte(n) - return e.write(e.buf) -} - -func (e *Encoder) write2(code codes.Code, n uint16) error { - e.buf = e.buf[:3] - e.buf[0] = byte(code) - e.buf[1] = byte(n >> 8) - e.buf[2] = byte(n) - return e.write(e.buf) -} - -func (e *Encoder) write4(code codes.Code, n uint32) error { - e.buf = e.buf[:5] - e.buf[0] = byte(code) - e.buf[1] = byte(n >> 24) - e.buf[2] = byte(n >> 16) - e.buf[3] = byte(n >> 8) - e.buf[4] = byte(n) - return e.write(e.buf) -} - -func (e *Encoder) write8(code codes.Code, n uint64) error { - e.buf = e.buf[:9] - e.buf[0] = byte(code) - e.buf[1] = byte(n >> 56) - e.buf[2] = byte(n >> 48) - e.buf[3] = byte(n >> 40) - e.buf[4] = byte(n >> 32) - e.buf[5] = byte(n >> 24) - e.buf[6] = byte(n >> 16) - e.buf[7] = byte(n >> 8) - e.buf[8] = byte(n) - return e.write(e.buf) -} - -func encodeUint8CondValue(e *Encoder, v reflect.Value) error { - return e.encodeUint8Cond(uint8(v.Uint())) -} - -func encodeUint16CondValue(e *Encoder, v reflect.Value) error { - return e.encodeUint16Cond(uint16(v.Uint())) -} - -func encodeUint32CondValue(e *Encoder, v reflect.Value) error { - return e.encodeUint32Cond(uint32(v.Uint())) -} - -func encodeUint64CondValue(e *Encoder, v reflect.Value) error { - return e.encodeUint64Cond(v.Uint()) -} - -func encodeInt8CondValue(e *Encoder, v reflect.Value) error { - return e.encodeInt8Cond(int8(v.Int())) -} - -func encodeInt16CondValue(e *Encoder, v reflect.Value) error { - return e.encodeInt16Cond(int16(v.Int())) -} - -func encodeInt32CondValue(e *Encoder, v reflect.Value) error { - return e.encodeInt32Cond(int32(v.Int())) -} - -func encodeInt64CondValue(e *Encoder, v reflect.Value) error { - return e.encodeInt64Cond(v.Int()) -} - -func encodeFloat32Value(e *Encoder, v reflect.Value) error { - return e.EncodeFloat32(float32(v.Float())) -} - -func encodeFloat64Value(e *Encoder, v reflect.Value) error { - return e.EncodeFloat64(v.Float()) -} diff --git a/vendor/github.com/vmihailenco/msgpack/encode_slice.go b/vendor/github.com/vmihailenco/msgpack/encode_slice.go deleted file mode 100644 index 5ddbd631..00000000 --- a/vendor/github.com/vmihailenco/msgpack/encode_slice.go +++ /dev/null @@ -1,124 +0,0 @@ -package msgpack - -import ( - "reflect" - - "github.com/vmihailenco/msgpack/codes" -) - -func encodeStringValue(e *Encoder, v reflect.Value) error { - return e.EncodeString(v.String()) -} - -func encodeByteSliceValue(e *Encoder, v reflect.Value) error { - return e.EncodeBytes(v.Bytes()) -} - -func encodeByteArrayValue(e *Encoder, v reflect.Value) error { - if err := e.EncodeBytesLen(v.Len()); err != nil { - return err - } - - if v.CanAddr() { - b := v.Slice(0, v.Len()).Bytes() - return e.write(b) - } - - e.buf = grow(e.buf, v.Len()) - reflect.Copy(reflect.ValueOf(e.buf), v) - return e.write(e.buf) -} - -func grow(b []byte, n int) []byte { - if cap(b) >= n { - return b[:n] - } - b = b[:cap(b)] - b = append(b, make([]byte, n-len(b))...) - return b -} - -func (e *Encoder) EncodeBytesLen(l int) error { - if l < 256 { - return e.write1(codes.Bin8, uint8(l)) - } - if l < 65536 { - return e.write2(codes.Bin16, uint16(l)) - } - return e.write4(codes.Bin32, uint32(l)) -} - -func (e *Encoder) encodeStrLen(l int) error { - if l < 32 { - return e.writeCode(codes.FixedStrLow | codes.Code(l)) - } - if l < 256 { - return e.write1(codes.Str8, uint8(l)) - } - if l < 65536 { - return e.write2(codes.Str16, uint16(l)) - } - return e.write4(codes.Str32, uint32(l)) -} - -func (e *Encoder) EncodeString(v string) error { - if err := e.encodeStrLen(len(v)); err != nil { - return err - } - return e.writeString(v) -} - -func (e *Encoder) EncodeBytes(v []byte) error { - if v == nil { - return e.EncodeNil() - } - if err := e.EncodeBytesLen(len(v)); err != nil { - return err - } - return e.write(v) -} - -func (e *Encoder) EncodeArrayLen(l int) error { - if l < 16 { - return e.writeCode(codes.FixedArrayLow | codes.Code(l)) - } - if l < 65536 { - return e.write2(codes.Array16, uint16(l)) - } - return e.write4(codes.Array32, uint32(l)) -} - -func (e *Encoder) encodeStringSlice(s []string) error { - if s == nil { - return e.EncodeNil() - } - if err := e.EncodeArrayLen(len(s)); err != nil { - return err - } - for _, v := range s { - if err := e.EncodeString(v); err != nil { - return err - } - } - return nil -} - -func encodeSliceValue(e *Encoder, v reflect.Value) error { - if v.IsNil() { - return e.EncodeNil() - } - return encodeArrayValue(e, v) -} - -func encodeArrayValue(e *Encoder, v reflect.Value) error { - l := v.Len() - if err := e.EncodeArrayLen(l); err != nil { - return err - } - for i := 0; i < l; i++ { - if err := e.EncodeValue(v.Index(i)); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/vmihailenco/msgpack/encode_value.go b/vendor/github.com/vmihailenco/msgpack/encode_value.go deleted file mode 100644 index b46ab02a..00000000 --- a/vendor/github.com/vmihailenco/msgpack/encode_value.go +++ /dev/null @@ -1,167 +0,0 @@ -package msgpack - -import ( - "fmt" - "reflect" -) - -var valueEncoders []encoderFunc - -func init() { - valueEncoders = []encoderFunc{ - reflect.Bool: encodeBoolValue, - reflect.Int: encodeInt64CondValue, - reflect.Int8: encodeInt8CondValue, - reflect.Int16: encodeInt16CondValue, - reflect.Int32: encodeInt32CondValue, - reflect.Int64: encodeInt64CondValue, - reflect.Uint: encodeUint64CondValue, - reflect.Uint8: encodeUint8CondValue, - reflect.Uint16: encodeUint16CondValue, - reflect.Uint32: encodeUint32CondValue, - reflect.Uint64: encodeUint64CondValue, - reflect.Float32: encodeFloat32Value, - reflect.Float64: encodeFloat64Value, - reflect.Complex64: encodeUnsupportedValue, - reflect.Complex128: encodeUnsupportedValue, - reflect.Array: encodeArrayValue, - reflect.Chan: encodeUnsupportedValue, - reflect.Func: encodeUnsupportedValue, - reflect.Interface: encodeInterfaceValue, - reflect.Map: encodeMapValue, - reflect.Ptr: encodeUnsupportedValue, - reflect.Slice: encodeSliceValue, - reflect.String: encodeStringValue, - reflect.Struct: encodeStructValue, - reflect.UnsafePointer: encodeUnsupportedValue, - } -} - -func getEncoder(typ reflect.Type) encoderFunc { - if encoder, ok := typEncMap[typ]; ok { - return encoder - } - - if typ.Implements(customEncoderType) { - return encodeCustomValue - } - if typ.Implements(marshalerType) { - return marshalValue - } - - kind := typ.Kind() - - // Addressable struct field value. - if kind != reflect.Ptr { - ptr := reflect.PtrTo(typ) - if ptr.Implements(customEncoderType) { - return encodeCustomValuePtr - } - if ptr.Implements(marshalerType) { - return marshalValuePtr - } - } - - if typ == errorType { - return encodeErrorValue - } - - switch kind { - case reflect.Ptr: - return ptrEncoderFunc(typ) - case reflect.Slice: - if typ.Elem().Kind() == reflect.Uint8 { - return encodeByteSliceValue - } - case reflect.Array: - if typ.Elem().Kind() == reflect.Uint8 { - return encodeByteArrayValue - } - case reflect.Map: - if typ.Key() == stringType { - switch typ.Elem() { - case stringType: - return encodeMapStringStringValue - case interfaceType: - return encodeMapStringInterfaceValue - } - } - } - return valueEncoders[kind] -} - -func ptrEncoderFunc(typ reflect.Type) encoderFunc { - encoder := getEncoder(typ.Elem()) - return func(e *Encoder, v reflect.Value) error { - if v.IsNil() { - return e.EncodeNil() - } - return encoder(e, v.Elem()) - } -} - -func encodeCustomValuePtr(e *Encoder, v reflect.Value) error { - if !v.CanAddr() { - return fmt.Errorf("msgpack: Encode(non-addressable %T)", v.Interface()) - } - encoder := v.Addr().Interface().(CustomEncoder) - return encoder.EncodeMsgpack(e) -} - -func encodeCustomValue(e *Encoder, v reflect.Value) error { - switch v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - if v.IsNil() { - return e.EncodeNil() - } - } - - encoder := v.Interface().(CustomEncoder) - return encoder.EncodeMsgpack(e) -} - -func marshalValuePtr(e *Encoder, v reflect.Value) error { - if !v.CanAddr() { - return fmt.Errorf("msgpack: Encode(non-addressable %T)", v.Interface()) - } - return marshalValue(e, v.Addr()) -} - -func marshalValue(e *Encoder, v reflect.Value) error { - switch v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - if v.IsNil() { - return e.EncodeNil() - } - } - - marshaler := v.Interface().(Marshaler) - b, err := marshaler.MarshalMsgpack() - if err != nil { - return err - } - _, err = e.w.Write(b) - return err -} - -func encodeBoolValue(e *Encoder, v reflect.Value) error { - return e.EncodeBool(v.Bool()) -} - -func encodeInterfaceValue(e *Encoder, v reflect.Value) error { - if v.IsNil() { - return e.EncodeNil() - } - return e.EncodeValue(v.Elem()) -} - -func encodeErrorValue(e *Encoder, v reflect.Value) error { - if v.IsNil() { - return e.EncodeNil() - } - return e.EncodeString(v.Interface().(error).Error()) -} - -func encodeUnsupportedValue(e *Encoder, v reflect.Value) error { - return fmt.Errorf("msgpack: Encode(unsupported %s)", v.Type()) -} diff --git a/vendor/github.com/vmihailenco/msgpack/ext.go b/vendor/github.com/vmihailenco/msgpack/ext.go deleted file mode 100644 index 7970be85..00000000 --- a/vendor/github.com/vmihailenco/msgpack/ext.go +++ /dev/null @@ -1,238 +0,0 @@ -package msgpack - -import ( - "bytes" - "fmt" - "reflect" - "sync" - - "github.com/vmihailenco/msgpack/codes" -) - -var extTypes = make(map[int8]reflect.Type) - -var bufferPool = &sync.Pool{ - New: func() interface{} { - return new(bytes.Buffer) - }, -} - -// RegisterExt records a type, identified by a value for that type, -// under the provided id. That id will identify the concrete type of a value -// sent or received as an interface variable. Only types that will be -// transferred as implementations of interface values need to be registered. -// Expecting to be used only during initialization, it panics if the mapping -// between types and ids is not a bijection. -func RegisterExt(id int8, value interface{}) { - typ := reflect.TypeOf(value) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - } - ptr := reflect.PtrTo(typ) - - if _, ok := extTypes[id]; ok { - panic(fmt.Errorf("msgpack: ext with id=%d is already registered", id)) - } - - registerExt(id, ptr, getEncoder(ptr), getDecoder(ptr)) - registerExt(id, typ, getEncoder(typ), getDecoder(typ)) -} - -func registerExt(id int8, typ reflect.Type, enc encoderFunc, dec decoderFunc) { - if dec != nil { - extTypes[id] = typ - } - if enc != nil { - typEncMap[typ] = makeExtEncoder(id, enc) - } - if dec != nil { - typDecMap[typ] = makeExtDecoder(id, dec) - } -} - -func (e *Encoder) EncodeExtHeader(typeId int8, length int) error { - if err := e.encodeExtLen(length); err != nil { - return err - } - if err := e.w.WriteByte(byte(typeId)); err != nil { - return err - } - return nil -} - -func makeExtEncoder(typeId int8, enc encoderFunc) encoderFunc { - return func(e *Encoder, v reflect.Value) error { - buf := bufferPool.Get().(*bytes.Buffer) - defer bufferPool.Put(buf) - buf.Reset() - - oldw := e.w - e.w = buf - err := enc(e, v) - e.w = oldw - - if err != nil { - return err - } - - err = e.EncodeExtHeader(typeId, buf.Len()) - if err != nil { - return err - } - return e.write(buf.Bytes()) - } -} - -func makeExtDecoder(typeId int8, dec decoderFunc) decoderFunc { - return func(d *Decoder, v reflect.Value) error { - c, err := d.PeekCode() - if err != nil { - return err - } - - if !codes.IsExt(c) { - return dec(d, v) - } - - id, extLen, err := d.DecodeExtHeader() - if err != nil { - return err - } - - if id != typeId { - return fmt.Errorf("msgpack: got ext type=%d, wanted %d", int8(c), typeId) - } - - d.extLen = extLen - return dec(d, v) - } -} - -func (e *Encoder) encodeExtLen(l int) error { - switch l { - case 1: - return e.writeCode(codes.FixExt1) - case 2: - return e.writeCode(codes.FixExt2) - case 4: - return e.writeCode(codes.FixExt4) - case 8: - return e.writeCode(codes.FixExt8) - case 16: - return e.writeCode(codes.FixExt16) - } - if l < 256 { - return e.write1(codes.Ext8, uint8(l)) - } - if l < 65536 { - return e.write2(codes.Ext16, uint16(l)) - } - return e.write4(codes.Ext32, uint32(l)) -} - -func (d *Decoder) parseExtLen(c codes.Code) (int, error) { - switch c { - case codes.FixExt1: - return 1, nil - case codes.FixExt2: - return 2, nil - case codes.FixExt4: - return 4, nil - case codes.FixExt8: - return 8, nil - case codes.FixExt16: - return 16, nil - case codes.Ext8: - n, err := d.uint8() - return int(n), err - case codes.Ext16: - n, err := d.uint16() - return int(n), err - case codes.Ext32: - n, err := d.uint32() - return int(n), err - default: - return 0, fmt.Errorf("msgpack: invalid code=%x decoding ext length", c) - } -} - -func (d *Decoder) decodeExtHeader(c codes.Code) (int8, int, error) { - length, err := d.parseExtLen(c) - if err != nil { - return 0, 0, err - } - - typeId, err := d.readCode() - if err != nil { - return 0, 0, err - } - - return int8(typeId), length, nil -} - -func (d *Decoder) DecodeExtHeader() (typeId int8, length int, err error) { - c, err := d.readCode() - if err != nil { - return - } - return d.decodeExtHeader(c) -} - -func (d *Decoder) extInterface(c codes.Code) (interface{}, error) { - extId, extLen, err := d.decodeExtHeader(c) - if err != nil { - return nil, err - } - - typ, ok := extTypes[extId] - if !ok { - return nil, fmt.Errorf("msgpack: unregistered ext id=%d", extId) - } - - v := reflect.New(typ) - - d.extLen = extLen - err = d.DecodeValue(v.Elem()) - d.extLen = 0 - if err != nil { - return nil, err - } - - return v.Interface(), nil -} - -func (d *Decoder) skipExt(c codes.Code) error { - n, err := d.parseExtLen(c) - if err != nil { - return err - } - return d.skipN(n + 1) -} - -func (d *Decoder) skipExtHeader(c codes.Code) error { - // Read ext type. - _, err := d.readCode() - if err != nil { - return err - } - // Read ext body len. - for i := 0; i < extHeaderLen(c); i++ { - _, err := d.readCode() - if err != nil { - return err - } - } - return nil -} - -func extHeaderLen(c codes.Code) int { - switch c { - case codes.Ext8: - return 1 - case codes.Ext16: - return 2 - case codes.Ext32: - return 4 - } - return 0 -} diff --git a/vendor/github.com/vmihailenco/msgpack/msgpack.go b/vendor/github.com/vmihailenco/msgpack/msgpack.go deleted file mode 100644 index 220b43c4..00000000 --- a/vendor/github.com/vmihailenco/msgpack/msgpack.go +++ /dev/null @@ -1,17 +0,0 @@ -package msgpack - -type Marshaler interface { - MarshalMsgpack() ([]byte, error) -} - -type Unmarshaler interface { - UnmarshalMsgpack([]byte) error -} - -type CustomEncoder interface { - EncodeMsgpack(*Encoder) error -} - -type CustomDecoder interface { - DecodeMsgpack(*Decoder) error -} diff --git a/vendor/github.com/vmihailenco/msgpack/tag.go b/vendor/github.com/vmihailenco/msgpack/tag.go deleted file mode 100644 index 48e6f942..00000000 --- a/vendor/github.com/vmihailenco/msgpack/tag.go +++ /dev/null @@ -1,42 +0,0 @@ -package msgpack - -import ( - "strings" -) - -type tagOptions string - -func (o tagOptions) Get(name string) (string, bool) { - s := string(o) - for len(s) > 0 { - var next string - idx := strings.IndexByte(s, ',') - if idx >= 0 { - s, next = s[:idx], s[idx+1:] - } - if strings.HasPrefix(s, name) { - return s[len(name):], true - } - s = next - } - return "", false -} - -func (o tagOptions) Contains(name string) bool { - _, ok := o.Get(name) - return ok -} - -func parseTag(tag string) (string, tagOptions) { - if idx := strings.IndexByte(tag, ','); idx != -1 { - name := tag[:idx] - if strings.IndexByte(name, ':') == -1 { - return name, tagOptions(tag[idx+1:]) - } - } - - if strings.IndexByte(tag, ':') == -1 { - return tag, "" - } - return "", tagOptions(tag) -} diff --git a/vendor/github.com/vmihailenco/msgpack/time.go b/vendor/github.com/vmihailenco/msgpack/time.go deleted file mode 100644 index f7409690..00000000 --- a/vendor/github.com/vmihailenco/msgpack/time.go +++ /dev/null @@ -1,145 +0,0 @@ -package msgpack - -import ( - "encoding/binary" - "fmt" - "reflect" - "time" - - "github.com/vmihailenco/msgpack/codes" -) - -var timeExtId int8 = -1 - -func init() { - timeType := reflect.TypeOf((*time.Time)(nil)).Elem() - registerExt(timeExtId, timeType, encodeTimeValue, decodeTimeValue) -} - -func (e *Encoder) EncodeTime(tm time.Time) error { - b := e.encodeTime(tm) - if err := e.encodeExtLen(len(b)); err != nil { - return err - } - if err := e.w.WriteByte(byte(timeExtId)); err != nil { - return err - } - return e.write(b) -} - -func (e *Encoder) encodeTime(tm time.Time) []byte { - secs := uint64(tm.Unix()) - if secs>>34 == 0 { - data := uint64(tm.Nanosecond())<<34 | secs - if data&0xffffffff00000000 == 0 { - b := make([]byte, 4) - binary.BigEndian.PutUint32(b, uint32(data)) - return b - } else { - b := make([]byte, 8) - binary.BigEndian.PutUint64(b, data) - return b - } - } - - b := make([]byte, 12) - binary.BigEndian.PutUint32(b, uint32(tm.Nanosecond())) - binary.BigEndian.PutUint64(b[4:], uint64(secs)) - return b -} - -func (d *Decoder) DecodeTime() (time.Time, error) { - tm, err := d.decodeTime() - if err != nil { - return tm, err - } - - if tm.IsZero() { - // Assume that zero time does not have timezone information. - return tm.UTC(), nil - } - return tm, nil -} - -func (d *Decoder) decodeTime() (time.Time, error) { - extLen := d.extLen - d.extLen = 0 - if extLen == 0 { - c, err := d.readCode() - if err != nil { - return time.Time{}, err - } - - // Legacy format. - if c == codes.FixedArrayLow|2 { - sec, err := d.DecodeInt64() - if err != nil { - return time.Time{}, err - } - - nsec, err := d.DecodeInt64() - if err != nil { - return time.Time{}, err - } - - return time.Unix(sec, nsec), nil - } - - if codes.IsString(c) { - s, err := d.string(c) - if err != nil { - return time.Time{}, err - } - return time.Parse(time.RFC3339Nano, s) - } - - extLen, err = d.parseExtLen(c) - if err != nil { - return time.Time{}, err - } - - // Skip ext id. - _, err = d.s.ReadByte() - if err != nil { - return time.Time{}, nil - } - } - - b, err := d.readN(extLen) - if err != nil { - return time.Time{}, err - } - - switch len(b) { - case 4: - sec := binary.BigEndian.Uint32(b) - return time.Unix(int64(sec), 0), nil - case 8: - sec := binary.BigEndian.Uint64(b) - nsec := int64(sec >> 34) - sec &= 0x00000003ffffffff - return time.Unix(int64(sec), nsec), nil - case 12: - nsec := binary.BigEndian.Uint32(b) - sec := binary.BigEndian.Uint64(b[4:]) - return time.Unix(int64(sec), int64(nsec)), nil - default: - err = fmt.Errorf("msgpack: invalid ext len=%d decoding time", extLen) - return time.Time{}, err - } -} - -func encodeTimeValue(e *Encoder, v reflect.Value) error { - tm := v.Interface().(time.Time) - b := e.encodeTime(tm) - return e.write(b) -} - -func decodeTimeValue(d *Decoder, v reflect.Value) error { - tm, err := d.DecodeTime() - if err != nil { - return err - } - v.Set(reflect.ValueOf(tm)) - return nil -} diff --git a/vendor/github.com/vmihailenco/msgpack/types.go b/vendor/github.com/vmihailenco/msgpack/types.go deleted file mode 100644 index 6a1bf7f9..00000000 --- a/vendor/github.com/vmihailenco/msgpack/types.go +++ /dev/null @@ -1,310 +0,0 @@ -package msgpack - -import ( - "reflect" - "sync" -) - -var errorType = reflect.TypeOf((*error)(nil)).Elem() - -var customEncoderType = reflect.TypeOf((*CustomEncoder)(nil)).Elem() -var customDecoderType = reflect.TypeOf((*CustomDecoder)(nil)).Elem() - -var marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() -var unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() - -type encoderFunc func(*Encoder, reflect.Value) error -type decoderFunc func(*Decoder, reflect.Value) error - -var typEncMap = make(map[reflect.Type]encoderFunc) -var typDecMap = make(map[reflect.Type]decoderFunc) - -// Register registers encoder and decoder functions for a value. -// This is low level API and in most cases you should prefer implementing -// Marshaler/CustomEncoder and Unmarshaler/CustomDecoder interfaces. -func Register(value interface{}, enc encoderFunc, dec decoderFunc) { - typ := reflect.TypeOf(value) - if enc != nil { - typEncMap[typ] = enc - } - if dec != nil { - typDecMap[typ] = dec - } -} - -//------------------------------------------------------------------------------ - -var structs = newStructCache(false) -var jsonStructs = newStructCache(true) - -type structCache struct { - mu sync.RWMutex - m map[reflect.Type]*fields - - useJSONTag bool -} - -func newStructCache(useJSONTag bool) *structCache { - return &structCache{ - m: make(map[reflect.Type]*fields), - - useJSONTag: useJSONTag, - } -} - -func (m *structCache) Fields(typ reflect.Type) *fields { - m.mu.RLock() - fs, ok := m.m[typ] - m.mu.RUnlock() - if ok { - return fs - } - - m.mu.Lock() - fs, ok = m.m[typ] - if !ok { - fs = getFields(typ, m.useJSONTag) - m.m[typ] = fs - } - m.mu.Unlock() - - return fs -} - -//------------------------------------------------------------------------------ - -type field struct { - name string - index []int - omitEmpty bool - encoder encoderFunc - decoder decoderFunc -} - -func (f *field) value(v reflect.Value) reflect.Value { - return fieldByIndex(v, f.index) -} - -func (f *field) Omit(strct reflect.Value) bool { - return f.omitEmpty && isEmptyValue(f.value(strct)) -} - -func (f *field) EncodeValue(e *Encoder, strct reflect.Value) error { - return f.encoder(e, f.value(strct)) -} - -func (f *field) DecodeValue(d *Decoder, strct reflect.Value) error { - return f.decoder(d, f.value(strct)) -} - -//------------------------------------------------------------------------------ - -type fields struct { - Table map[string]*field - List []*field - AsArray bool - - hasOmitEmpty bool -} - -func newFields(numField int) *fields { - return &fields{ - Table: make(map[string]*field, numField), - List: make([]*field, 0, numField), - } -} - -func (fs *fields) Add(field *field) { - fs.Table[field.name] = field - fs.List = append(fs.List, field) - if field.omitEmpty { - fs.hasOmitEmpty = true - } -} - -func (fs *fields) OmitEmpty(strct reflect.Value) []*field { - if !fs.hasOmitEmpty { - return fs.List - } - - fields := make([]*field, 0, len(fs.List)) - for _, f := range fs.List { - if !f.Omit(strct) { - fields = append(fields, f) - } - } - return fields -} - -func getFields(typ reflect.Type, useJSONTag bool) *fields { - numField := typ.NumField() - fs := newFields(numField) - - var omitEmpty bool - for i := 0; i < numField; i++ { - f := typ.Field(i) - - tag := f.Tag.Get("msgpack") - if useJSONTag && tag == "" { - tag = f.Tag.Get("json") - } - - name, opt := parseTag(tag) - if name == "-" { - continue - } - - if f.Name == "_msgpack" { - if opt.Contains("asArray") { - fs.AsArray = true - } - if opt.Contains("omitempty") { - omitEmpty = true - } - } - - if f.PkgPath != "" && !f.Anonymous { - continue - } - - field := &field{ - name: name, - index: f.Index, - omitEmpty: omitEmpty || opt.Contains("omitempty"), - encoder: getEncoder(f.Type), - decoder: getDecoder(f.Type), - } - - if field.name == "" { - field.name = f.Name - } - - if f.Anonymous && !opt.Contains("noinline") { - inline := opt.Contains("inline") - if inline { - inlineFields(fs, f.Type, field, useJSONTag) - } else { - inline = autoinlineFields(fs, f.Type, field, useJSONTag) - } - if inline { - fs.Table[field.name] = field - continue - } - } - - fs.Add(field) - } - return fs -} - -var encodeStructValuePtr uintptr -var decodeStructValuePtr uintptr - -func init() { - encodeStructValuePtr = reflect.ValueOf(encodeStructValue).Pointer() - decodeStructValuePtr = reflect.ValueOf(decodeStructValue).Pointer() -} - -func inlineFields(fs *fields, typ reflect.Type, f *field, useJSONTag bool) { - inlinedFields := getFields(typ, useJSONTag).List - for _, field := range inlinedFields { - if _, ok := fs.Table[field.name]; ok { - // Don't inline shadowed fields. - continue - } - field.index = append(f.index, field.index...) - fs.Add(field) - } -} - -func autoinlineFields(fs *fields, typ reflect.Type, f *field, useJSONTag bool) bool { - var encoder encoderFunc - var decoder decoderFunc - - if typ.Kind() == reflect.Struct { - encoder = f.encoder - decoder = f.decoder - } else { - for typ.Kind() == reflect.Ptr { - typ = typ.Elem() - encoder = getEncoder(typ) - decoder = getDecoder(typ) - } - if typ.Kind() != reflect.Struct { - return false - } - } - - if reflect.ValueOf(encoder).Pointer() != encodeStructValuePtr { - return false - } - if reflect.ValueOf(decoder).Pointer() != decodeStructValuePtr { - return false - } - - inlinedFields := getFields(typ, useJSONTag).List - for _, field := range inlinedFields { - if _, ok := fs.Table[field.name]; ok { - // Don't auto inline if there are shadowed fields. - return false - } - } - - for _, field := range inlinedFields { - field.index = append(f.index, field.index...) - fs.Add(field) - } - return true -} - -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - return false -} - -func fieldByIndex(v reflect.Value, index []int) reflect.Value { - if len(index) == 1 { - return v.Field(index[0]) - } - for i, x := range index { - if i > 0 { - var ok bool - v, ok = indirectNew(v) - if !ok { - return v - } - } - v = v.Field(x) - } - return v -} - -func indirectNew(v reflect.Value) (reflect.Value, bool) { - if v.Kind() == reflect.Ptr { - if v.IsNil() { - if !v.CanSet() { - return v, false - } - elemType := v.Type().Elem() - if elemType.Kind() != reflect.Struct { - return v, false - } - v.Set(reflect.New(elemType)) - } - v = v.Elem() - } - return v, true -} diff --git a/vendor/github.com/zclconf/go-cty/cty/convert/conversion_primitive.go b/vendor/github.com/zclconf/go-cty/cty/convert/conversion_primitive.go index e0dbf491..e563ee34 100644 --- a/vendor/github.com/zclconf/go-cty/cty/convert/conversion_primitive.go +++ b/vendor/github.com/zclconf/go-cty/cty/convert/conversion_primitive.go @@ -1,6 +1,8 @@ package convert import ( + "math/big" + "github.com/zclconf/go-cty/cty" ) @@ -28,11 +30,11 @@ var primitiveConversionsSafe = map[cty.Type]map[cty.Type]conversion{ var primitiveConversionsUnsafe = map[cty.Type]map[cty.Type]conversion{ cty.String: { cty.Number: func(val cty.Value, path cty.Path) (cty.Value, error) { - v, err := cty.ParseNumberVal(val.AsString()) + f, _, err := big.ParseFloat(val.AsString(), 10, 512, big.ToNearestEven) if err != nil { return cty.NilVal, path.NewErrorf("a number is required") } - return v, nil + return cty.NumberVal(f), nil }, cty.Bool: func(val cty.Value, path cty.Path) (cty.Value, error) { switch val.AsString() { diff --git a/vendor/github.com/zclconf/go-cty/cty/json/unmarshal.go b/vendor/github.com/zclconf/go-cty/cty/json/unmarshal.go index 38106455..155f0b8a 100644 --- a/vendor/github.com/zclconf/go-cty/cty/json/unmarshal.go +++ b/vendor/github.com/zclconf/go-cty/cty/json/unmarshal.go @@ -72,7 +72,7 @@ func unmarshalPrimitive(tok json.Token, t cty.Type, path cty.Path) (cty.Value, e } switch v := tok.(type) { case string: - val, err := cty.ParseNumberVal(v) + val, err := convert.Convert(cty.StringVal(v), t) if err != nil { return cty.NilVal, path.NewError(err) } diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/doc.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/doc.go deleted file mode 100644 index 1eb99f28..00000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/doc.go +++ /dev/null @@ -1,14 +0,0 @@ -// Package msgpack provides functions for serializing cty values in the -// msgpack encoding, and decoding them again. -// -// If the same type information is provided both at encoding and decoding time -// then values can be round-tripped without loss, except for capsule types -// which are not currently supported. -// -// If any unknown values are passed to Marshal then they will be represented -// using a msgpack extension with type code zero, which is understood by -// the Unmarshal function within this package but will not be understood by -// a generic (non-cty-aware) msgpack decoder. Ensure that no unknown values -// are used if interoperability with other msgpack implementations is -// required. -package msgpack diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/dynamic.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/dynamic.go deleted file mode 100644 index 1b631d0a..00000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/dynamic.go +++ /dev/null @@ -1,31 +0,0 @@ -package msgpack - -import ( - "bytes" - - "github.com/vmihailenco/msgpack" - "github.com/zclconf/go-cty/cty" -) - -type dynamicVal struct { - Value cty.Value - Path cty.Path -} - -func (dv *dynamicVal) MarshalMsgpack() ([]byte, error) { - // Rather than defining a msgpack-specific serialization of types, - // instead we use the existing JSON serialization. - typeJSON, err := dv.Value.Type().MarshalJSON() - if err != nil { - return nil, dv.Path.NewErrorf("failed to serialize type: %s", err) - } - var buf bytes.Buffer - enc := msgpack.NewEncoder(&buf) - enc.EncodeArrayLen(2) - enc.EncodeBytes(typeJSON) - err = marshal(dv.Value, dv.Value.Type(), dv.Path, enc) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/infinity.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/infinity.go deleted file mode 100644 index 6db0815e..00000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/infinity.go +++ /dev/null @@ -1,8 +0,0 @@ -package msgpack - -import ( - "math" -) - -var negativeInfinity = math.Inf(-1) -var positiveInfinity = math.Inf(1) diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/marshal.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/marshal.go deleted file mode 100644 index 87b096ca..00000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/marshal.go +++ /dev/null @@ -1,207 +0,0 @@ -package msgpack - -import ( - "bytes" - "math/big" - "sort" - - "github.com/vmihailenco/msgpack" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// Marshal produces a msgpack serialization of the given value that -// can be decoded into the given type later using Unmarshal. -// -// The given value must conform to the given type, or an error will -// be returned. -func Marshal(val cty.Value, ty cty.Type) ([]byte, error) { - errs := val.Type().TestConformance(ty) - if errs != nil { - // Attempt a conversion - var err error - val, err = convert.Convert(val, ty) - if err != nil { - return nil, err - } - } - - // From this point onward, val can be assumed to be conforming to t. - - var path cty.Path - var buf bytes.Buffer - enc := msgpack.NewEncoder(&buf) - - err := marshal(val, ty, path, enc) - if err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -func marshal(val cty.Value, ty cty.Type, path cty.Path, enc *msgpack.Encoder) error { - // If we're going to decode as DynamicPseudoType then we need to save - // dynamic type information to recover the real type. - if ty == cty.DynamicPseudoType && val.Type() != cty.DynamicPseudoType { - return marshalDynamic(val, path, enc) - } - - if !val.IsKnown() { - err := enc.Encode(unknownVal) - if err != nil { - return path.NewError(err) - } - return nil - } - if val.IsNull() { - err := enc.EncodeNil() - if err != nil { - return path.NewError(err) - } - return nil - } - - // The caller should've guaranteed that the given val is conformant with - // the given type ty, so we'll proceed under that assumption here. - switch { - case ty.IsPrimitiveType(): - switch ty { - case cty.String: - err := enc.EncodeString(val.AsString()) - if err != nil { - return path.NewError(err) - } - return nil - case cty.Number: - var err error - switch { - case val.RawEquals(cty.PositiveInfinity): - err = enc.EncodeFloat64(positiveInfinity) - case val.RawEquals(cty.NegativeInfinity): - err = enc.EncodeFloat64(negativeInfinity) - default: - bf := val.AsBigFloat() - if iv, acc := bf.Int64(); acc == big.Exact { - err = enc.EncodeInt(iv) - } else if fv, acc := bf.Float64(); acc == big.Exact { - err = enc.EncodeFloat64(fv) - } else { - err = enc.EncodeString(bf.Text('f', -1)) - } - } - if err != nil { - return path.NewError(err) - } - return nil - case cty.Bool: - err := enc.EncodeBool(val.True()) - if err != nil { - return path.NewError(err) - } - return nil - default: - panic("unsupported primitive type") - } - case ty.IsListType(), ty.IsSetType(): - enc.EncodeArrayLen(val.LengthInt()) - ety := ty.ElementType() - it := val.ElementIterator() - path := append(path, nil) // local override of 'path' with extra element - for it.Next() { - ek, ev := it.Element() - path[len(path)-1] = cty.IndexStep{ - Key: ek, - } - err := marshal(ev, ety, path, enc) - if err != nil { - return err - } - } - return nil - case ty.IsMapType(): - enc.EncodeMapLen(val.LengthInt()) - ety := ty.ElementType() - it := val.ElementIterator() - path := append(path, nil) // local override of 'path' with extra element - for it.Next() { - ek, ev := it.Element() - path[len(path)-1] = cty.IndexStep{ - Key: ek, - } - var err error - err = marshal(ek, ek.Type(), path, enc) - if err != nil { - return err - } - err = marshal(ev, ety, path, enc) - if err != nil { - return err - } - } - return nil - case ty.IsTupleType(): - etys := ty.TupleElementTypes() - it := val.ElementIterator() - path := append(path, nil) // local override of 'path' with extra element - i := 0 - enc.EncodeArrayLen(len(etys)) - for it.Next() { - ety := etys[i] - ek, ev := it.Element() - path[len(path)-1] = cty.IndexStep{ - Key: ek, - } - err := marshal(ev, ety, path, enc) - if err != nil { - return err - } - i++ - } - return nil - case ty.IsObjectType(): - atys := ty.AttributeTypes() - path := append(path, nil) // local override of 'path' with extra element - - names := make([]string, 0, len(atys)) - for k := range atys { - names = append(names, k) - } - sort.Strings(names) - - enc.EncodeMapLen(len(names)) - - for _, k := range names { - aty := atys[k] - av := val.GetAttr(k) - path[len(path)-1] = cty.GetAttrStep{ - Name: k, - } - var err error - err = marshal(cty.StringVal(k), cty.String, path, enc) - if err != nil { - return err - } - err = marshal(av, aty, path, enc) - if err != nil { - return err - } - } - return nil - case ty.IsCapsuleType(): - return path.NewErrorf("capsule types not supported for msgpack encoding") - default: - // should never happen - return path.NewErrorf("cannot msgpack-serialize %s", ty.FriendlyName()) - } -} - -// marshalDynamic adds an extra wrapping object containing dynamic type -// information for the given value. -func marshalDynamic(val cty.Value, path cty.Path, enc *msgpack.Encoder) error { - dv := dynamicVal{ - Value: val, - Path: path, - } - return enc.Encode(&dv) -} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/type_implied.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/type_implied.go deleted file mode 100644 index 6f6022e4..00000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/type_implied.go +++ /dev/null @@ -1,167 +0,0 @@ -package msgpack - -import ( - "bytes" - "fmt" - "io" - - "github.com/vmihailenco/msgpack" - msgpackcodes "github.com/vmihailenco/msgpack/codes" - "github.com/zclconf/go-cty/cty" -) - -// ImpliedType returns the cty Type implied by the structure of the given -// msgpack-compliant buffer. This function implements the default type mapping -// behavior used when decoding arbitrary msgpack without explicit cty Type -// information. -// -// The rules are as follows: -// -// msgpack strings, numbers and bools map to their equivalent primitive type in -// cty. -// -// msgpack maps become cty object types, with the attributes defined by the -// map keys and the types of their values. -// -// msgpack arrays become cty tuple types, with the elements defined by the -// types of the array members. -// -// Any nulls are typed as DynamicPseudoType, so callers of this function -// must be prepared to deal with this. Callers that do not wish to deal with -// dynamic typing should not use this function and should instead describe -// their required types explicitly with a cty.Type instance when decoding. -// -// Any unknown values are similarly typed as DynamicPseudoType, because these -// do not carry type information on the wire. -// -// Any parse errors will be returned as an error, and the type will be the -// invalid value cty.NilType. -func ImpliedType(buf []byte) (cty.Type, error) { - r := bytes.NewReader(buf) - dec := msgpack.NewDecoder(r) - - ty, err := impliedType(dec) - if err != nil { - return cty.NilType, err - } - - // We must now be at the end of the buffer - err = dec.Skip() - if err != io.EOF { - return ty, fmt.Errorf("extra bytes after msgpack value") - } - - return ty, nil -} - -func impliedType(dec *msgpack.Decoder) (cty.Type, error) { - // If this function returns with a nil error then it must have already - // consumed the next value from the decoder, since when called recursively - // the caller will be expecting to find a following value here. - - code, err := dec.PeekCode() - if err != nil { - return cty.NilType, err - } - - switch { - - case code == msgpackcodes.Nil || msgpackcodes.IsExt(code): - err := dec.Skip() - return cty.DynamicPseudoType, err - - case code == msgpackcodes.True || code == msgpackcodes.False: - _, err := dec.DecodeBool() - return cty.Bool, err - - case msgpackcodes.IsFixedNum(code): - _, err := dec.DecodeInt64() - return cty.Number, err - - case code == msgpackcodes.Int8 || code == msgpackcodes.Int16 || code == msgpackcodes.Int32 || code == msgpackcodes.Int64: - _, err := dec.DecodeInt64() - return cty.Number, err - - case code == msgpackcodes.Uint8 || code == msgpackcodes.Uint16 || code == msgpackcodes.Uint32 || code == msgpackcodes.Uint64: - _, err := dec.DecodeUint64() - return cty.Number, err - - case code == msgpackcodes.Float || code == msgpackcodes.Double: - _, err := dec.DecodeFloat64() - return cty.Number, err - - case msgpackcodes.IsString(code): - _, err := dec.DecodeString() - return cty.String, err - - case msgpackcodes.IsFixedMap(code) || code == msgpackcodes.Map16 || code == msgpackcodes.Map32: - return impliedObjectType(dec) - - case msgpackcodes.IsFixedArray(code) || code == msgpackcodes.Array16 || code == msgpackcodes.Array32: - return impliedTupleType(dec) - - default: - return cty.NilType, fmt.Errorf("unsupported msgpack code %#v", code) - } -} - -func impliedObjectType(dec *msgpack.Decoder) (cty.Type, error) { - // If we get in here then we've already peeked the next code and know - // it's some sort of map. - l, err := dec.DecodeMapLen() - if err != nil { - return cty.DynamicPseudoType, nil - } - - var atys map[string]cty.Type - - for i := 0; i < l; i++ { - // Read the map key first. We require maps to be strings, but msgpack - // doesn't so we're prepared to error here if not. - k, err := dec.DecodeString() - if err != nil { - return cty.DynamicPseudoType, err - } - - aty, err := impliedType(dec) - if err != nil { - return cty.DynamicPseudoType, err - } - - if atys == nil { - atys = make(map[string]cty.Type) - } - atys[k] = aty - } - - if len(atys) == 0 { - return cty.EmptyObject, nil - } - - return cty.Object(atys), nil -} - -func impliedTupleType(dec *msgpack.Decoder) (cty.Type, error) { - // If we get in here then we've already peeked the next code and know - // it's some sort of array. - l, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicPseudoType, nil - } - - if l == 0 { - return cty.EmptyTuple, nil - } - - etys := make([]cty.Type, l) - - for i := 0; i < l; i++ { - ety, err := impliedType(dec) - if err != nil { - return cty.DynamicPseudoType, err - } - etys[i] = ety - } - - return cty.Tuple(etys), nil -} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/unknown.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/unknown.go deleted file mode 100644 index 6507bc4b..00000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/unknown.go +++ /dev/null @@ -1,16 +0,0 @@ -package msgpack - -type unknownType struct{} - -var unknownVal = unknownType{} - -// unknownValBytes is the raw bytes of the msgpack fixext1 value we -// write to represent an unknown value. It's an extension value of -// type zero whose value is irrelevant. Since it's irrelevant, we -// set it to a single byte whose value is also zero, since that's -// the most compact possible representation. -var unknownValBytes = []byte{0xd4, 0, 0} - -func (uv unknownType) MarshalMsgpack() ([]byte, error) { - return unknownValBytes, nil -} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/unmarshal.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/unmarshal.go deleted file mode 100644 index 51bb76a8..00000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/unmarshal.go +++ /dev/null @@ -1,334 +0,0 @@ -package msgpack - -import ( - "bytes" - - "github.com/vmihailenco/msgpack" - msgpackCodes "github.com/vmihailenco/msgpack/codes" - "github.com/zclconf/go-cty/cty" -) - -// Unmarshal interprets the given bytes as a msgpack-encoded cty Value of -// the given type, returning the result. -// -// If an error is returned, the error is written with a hypothetical -// end-user that wrote the msgpack file as its audience, using cty type -// system concepts rather than Go type system concepts. -func Unmarshal(b []byte, ty cty.Type) (cty.Value, error) { - r := bytes.NewReader(b) - dec := msgpack.NewDecoder(r) - - var path cty.Path - return unmarshal(dec, ty, path) -} - -func unmarshal(dec *msgpack.Decoder, ty cty.Type, path cty.Path) (cty.Value, error) { - peek, err := dec.PeekCode() - if err != nil { - return cty.DynamicVal, path.NewError(err) - } - if msgpackCodes.IsExt(peek) { - // We just assume _all_ extensions are unknown values, - // since we don't have any other extensions. - dec.Skip() // skip what we've peeked - return cty.UnknownVal(ty), nil - } - if ty == cty.DynamicPseudoType { - return unmarshalDynamic(dec, path) - } - if peek == msgpackCodes.Nil { - dec.Skip() // skip what we've peeked - return cty.NullVal(ty), nil - } - - switch { - case ty.IsPrimitiveType(): - val, err := unmarshalPrimitive(dec, ty, path) - if err != nil { - return cty.NilVal, err - } - return val, nil - case ty.IsListType(): - return unmarshalList(dec, ty.ElementType(), path) - case ty.IsSetType(): - return unmarshalSet(dec, ty.ElementType(), path) - case ty.IsMapType(): - return unmarshalMap(dec, ty.ElementType(), path) - case ty.IsTupleType(): - return unmarshalTuple(dec, ty.TupleElementTypes(), path) - case ty.IsObjectType(): - return unmarshalObject(dec, ty.AttributeTypes(), path) - default: - return cty.NilVal, path.NewErrorf("unsupported type %s", ty.FriendlyName()) - } -} - -func unmarshalPrimitive(dec *msgpack.Decoder, ty cty.Type, path cty.Path) (cty.Value, error) { - switch ty { - case cty.Bool: - rv, err := dec.DecodeBool() - if err != nil { - return cty.DynamicVal, path.NewErrorf("bool is required") - } - return cty.BoolVal(rv), nil - case cty.Number: - // Marshal will try int and float first, if the value can be - // losslessly represented in these encodings, and then fall - // back on a string if the number is too large or too precise. - peek, err := dec.PeekCode() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - - if msgpackCodes.IsFixedNum(peek) { - rv, err := dec.DecodeInt64() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return cty.NumberIntVal(rv), nil - } - - switch peek { - case msgpackCodes.Int8, msgpackCodes.Int16, msgpackCodes.Int32, msgpackCodes.Int64: - rv, err := dec.DecodeInt64() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return cty.NumberIntVal(rv), nil - case msgpackCodes.Uint8, msgpackCodes.Uint16, msgpackCodes.Uint32, msgpackCodes.Uint64: - rv, err := dec.DecodeUint64() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return cty.NumberUIntVal(rv), nil - case msgpackCodes.Float, msgpackCodes.Double: - rv, err := dec.DecodeFloat64() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return cty.NumberFloatVal(rv), nil - default: - rv, err := dec.DecodeString() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - v, err := cty.ParseNumberVal(rv) - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return v, nil - } - case cty.String: - rv, err := dec.DecodeString() - if err != nil { - return cty.DynamicVal, path.NewErrorf("string is required") - } - return cty.StringVal(rv), nil - default: - // should never happen - panic("unsupported primitive type") - } -} - -func unmarshalList(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("a list is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.List(ety)), nil - case length == 0: - return cty.ListValEmpty(ety), nil - } - - vals := make([]cty.Value, 0, length) - path = append(path, nil) - for i := 0; i < length; i++ { - path[len(path)-1] = cty.IndexStep{ - Key: cty.NumberIntVal(int64(i)), - } - - val, err := unmarshal(dec, ety, path) - if err != nil { - return cty.DynamicVal, err - } - - vals = append(vals, val) - } - - return cty.ListVal(vals), nil -} - -func unmarshalSet(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("a set is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.Set(ety)), nil - case length == 0: - return cty.SetValEmpty(ety), nil - } - - vals := make([]cty.Value, 0, length) - path = append(path, nil) - for i := 0; i < length; i++ { - path[len(path)-1] = cty.IndexStep{ - Key: cty.NumberIntVal(int64(i)), - } - - val, err := unmarshal(dec, ety, path) - if err != nil { - return cty.DynamicVal, err - } - - vals = append(vals, val) - } - - return cty.SetVal(vals), nil -} - -func unmarshalMap(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeMapLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("a map is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.Map(ety)), nil - case length == 0: - return cty.MapValEmpty(ety), nil - } - - vals := make(map[string]cty.Value, length) - path = append(path, nil) - for i := 0; i < length; i++ { - key, err := dec.DecodeString() - if err != nil { - path[:len(path)-1].NewErrorf("non-string key in map") - } - - path[len(path)-1] = cty.IndexStep{ - Key: cty.StringVal(key), - } - - val, err := unmarshal(dec, ety, path) - if err != nil { - return cty.DynamicVal, err - } - - vals[key] = val - } - - return cty.MapVal(vals), nil -} - -func unmarshalTuple(dec *msgpack.Decoder, etys []cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("a tuple is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.Tuple(etys)), nil - case length == 0: - return cty.TupleVal(nil), nil - case length != len(etys): - return cty.DynamicVal, path.NewErrorf("a tuple of length %d is required", len(etys)) - } - - vals := make([]cty.Value, 0, length) - path = append(path, nil) - for i := 0; i < length; i++ { - path[len(path)-1] = cty.IndexStep{ - Key: cty.NumberIntVal(int64(i)), - } - ety := etys[i] - - val, err := unmarshal(dec, ety, path) - if err != nil { - return cty.DynamicVal, err - } - - vals = append(vals, val) - } - - return cty.TupleVal(vals), nil -} - -func unmarshalObject(dec *msgpack.Decoder, atys map[string]cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeMapLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("an object is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.Object(atys)), nil - case length == 0: - return cty.ObjectVal(nil), nil - case length != len(atys): - return cty.DynamicVal, path.NewErrorf("an object with %d attributes is required (%d given)", - len(atys), length) - } - - vals := make(map[string]cty.Value, length) - path = append(path, nil) - for i := 0; i < length; i++ { - key, err := dec.DecodeString() - if err != nil { - return cty.DynamicVal, path[:len(path)-1].NewErrorf("all keys must be strings") - } - - path[len(path)-1] = cty.IndexStep{ - Key: cty.StringVal(key), - } - aty, exists := atys[key] - if !exists { - return cty.DynamicVal, path.NewErrorf("unsupported attribute") - } - - val, err := unmarshal(dec, aty, path) - if err != nil { - return cty.DynamicVal, err - } - - vals[key] = val - } - - return cty.ObjectVal(vals), nil -} - -func unmarshalDynamic(dec *msgpack.Decoder, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicVal, path.NewError(err) - } - - switch { - case length == -1: - return cty.NullVal(cty.DynamicPseudoType), nil - case length != 2: - return cty.DynamicVal, path.NewErrorf( - "dynamic value array must have exactly two elements", - ) - } - - typeJSON, err := dec.DecodeBytes() - if err != nil { - return cty.DynamicVal, path.NewError(err) - } - var ty cty.Type - err = (&ty).UnmarshalJSON(typeJSON) - if err != nil { - return cty.DynamicVal, path.NewError(err) - } - - return unmarshal(dec, ty, path) -} diff --git a/vendor/github.com/zclconf/go-cty/cty/path.go b/vendor/github.com/zclconf/go-cty/cty/path.go index 625bfdf8..69bc4819 100644 --- a/vendor/github.com/zclconf/go-cty/cty/path.go +++ b/vendor/github.com/zclconf/go-cty/cty/path.go @@ -136,13 +136,9 @@ type IndexStep struct { // Apply returns the value resulting from indexing the given value with // our key value. func (s IndexStep) Apply(val Value) (Value, error) { - if val == NilVal || val.IsNull() { - return NilVal, errors.New("cannot index a null value") - } - switch s.Key.Type() { case Number: - if !(val.Type().IsListType() || val.Type().IsTupleType()) { + if !val.Type().IsListType() { return NilVal, errors.New("not a list type") } case String: @@ -178,10 +174,6 @@ type GetAttrStep struct { // Apply returns the value of our named attribute from the given value, which // must be of an object type that has a value of that name. func (s GetAttrStep) Apply(val Value) (Value, error) { - if val == NilVal || val.IsNull() { - return NilVal, errors.New("cannot access attributes on a null value") - } - if !val.Type().IsObjectType() { return NilVal, errors.New("not an object type") } diff --git a/vendor/github.com/zclconf/go-cty/cty/type_conform.go b/vendor/github.com/zclconf/go-cty/cty/type_conform.go index 476eeea8..b417dc79 100644 --- a/vendor/github.com/zclconf/go-cty/cty/type_conform.go +++ b/vendor/github.com/zclconf/go-cty/cty/type_conform.go @@ -50,20 +50,23 @@ func testConformance(given Type, want Type, path Path, errs *[]error) { givenAttrs := given.AttributeTypes() wantAttrs := want.AttributeTypes() - for k := range givenAttrs { - if _, exists := wantAttrs[k]; !exists { - *errs = append( - *errs, - errorf(path, "unsupported attribute %q", k), - ) + if len(givenAttrs) != len(wantAttrs) { + // Something is missing from one of them. + for k := range givenAttrs { + if _, exists := wantAttrs[k]; !exists { + *errs = append( + *errs, + errorf(path, "unsupported attribute %q", k), + ) + } } - } - for k := range wantAttrs { - if _, exists := givenAttrs[k]; !exists { - *errs = append( - *errs, - errorf(path, "missing required attribute %q", k), - ) + for k := range wantAttrs { + if _, exists := givenAttrs[k]; !exists { + *errs = append( + *errs, + errorf(path, "missing required attribute %q", k), + ) + } } } diff --git a/vendor/github.com/zclconf/go-cty/cty/value_init.go b/vendor/github.com/zclconf/go-cty/cty/value_init.go index a9abbbb0..495a83e6 100644 --- a/vendor/github.com/zclconf/go-cty/cty/value_init.go +++ b/vendor/github.com/zclconf/go-cty/cty/value_init.go @@ -30,32 +30,6 @@ func NumberVal(v *big.Float) Value { } } -// ParseNumberVal returns a Value of type number produced by parsing the given -// string as a decimal real number. To ensure that two identical strings will -// always produce an equal number, always use this function to derive a number -// from a string; it will ensure that the precision and rounding mode for the -// internal big decimal is configured in a consistent way. -// -// If the given string cannot be parsed as a number, the returned error has -// the message "a number is required", making it suitable to return to an -// end-user to signal a type conversion error. -// -// If the given string contains a number that becomes a recurring fraction -// when expressed in binary then it will be truncated to have a 512-bit -// mantissa. Note that this is a higher precision than that of a float64, -// so coverting the same decimal number first to float64 and then calling -// NumberFloatVal will not produce an equal result; the conversion first -// to float64 will round the mantissa to fewer than 512 bits. -func ParseNumberVal(s string) (Value, error) { - // Base 10, precision 512, and rounding to nearest even is the standard - // way to handle numbers arriving as strings. - f, _, err := big.ParseFloat(s, 10, 512, big.ToNearestEven) - if err != nil { - return NilVal, fmt.Errorf("a number is required") - } - return NumberVal(f), nil -} - // NumberIntVal returns a Value of type Number whose internal value is equal // to the given integer. func NumberIntVal(v int64) Value { diff --git a/vendor/golang.org/x/crypto/blowfish/cipher.go b/vendor/golang.org/x/crypto/blowfish/cipher.go index 213bf204..2641dadd 100644 --- a/vendor/golang.org/x/crypto/blowfish/cipher.go +++ b/vendor/golang.org/x/crypto/blowfish/cipher.go @@ -3,14 +3,6 @@ // license that can be found in the LICENSE file. // Package blowfish implements Bruce Schneier's Blowfish encryption algorithm. -// -// Blowfish is a legacy cipher and its short block size makes it vulnerable to -// birthday bound attacks (see https://sweet32.info). It should only be used -// where compatibility with legacy systems, not security, is the goal. -// -// Deprecated: any new system should use AES (from crypto/aes, if necessary in -// an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from -// golang.org/x/crypto/chacha20poly1305). package blowfish // import "golang.org/x/crypto/blowfish" // The code is a port of Bruce Schneier's C implementation. diff --git a/vendor/golang.org/x/crypto/cast5/cast5.go b/vendor/golang.org/x/crypto/cast5/cast5.go index ddcbeb6f..0b4af37b 100644 --- a/vendor/golang.org/x/crypto/cast5/cast5.go +++ b/vendor/golang.org/x/crypto/cast5/cast5.go @@ -2,15 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package cast5 implements CAST5, as defined in RFC 2144. -// -// CAST5 is a legacy cipher and its short block size makes it vulnerable to -// birthday bound attacks (see https://sweet32.info). It should only be used -// where compatibility with legacy systems, not security, is the goal. -// -// Deprecated: any new system should use AES (from crypto/aes, if necessary in -// an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from -// golang.org/x/crypto/chacha20poly1305). +// Package cast5 implements CAST5, as defined in RFC 2144. CAST5 is a common +// OpenPGP cipher. package cast5 // import "golang.org/x/crypto/cast5" import "errors" diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519.go b/vendor/golang.org/x/crypto/curve25519/curve25519.go index 75f24bab..cb8fbc57 100644 --- a/vendor/golang.org/x/crypto/curve25519/curve25519.go +++ b/vendor/golang.org/x/crypto/curve25519/curve25519.go @@ -86,7 +86,7 @@ func feFromBytes(dst *fieldElement, src *[32]byte) { h6 := load3(src[20:]) << 7 h7 := load3(src[23:]) << 5 h8 := load3(src[26:]) << 4 - h9 := (load3(src[29:]) & 0x7fffff) << 2 + h9 := load3(src[29:]) << 2 var carry [10]int64 carry[9] = (h9 + 1<<24) >> 25 diff --git a/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s b/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s deleted file mode 100644 index b3a16ef7..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright 2018 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.11 -// +build !gccgo,!appengine - -#include "textflag.h" - -#define NUM_ROUNDS 10 - -// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) -TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 - MOVD dst+0(FP), R1 - MOVD src+24(FP), R2 - MOVD src_len+32(FP), R3 - MOVD key+48(FP), R4 - MOVD nonce+56(FP), R6 - MOVD counter+64(FP), R7 - - MOVD $·constants(SB), R10 - MOVD $·incRotMatrix(SB), R11 - - MOVW (R7), R20 - - AND $~255, R3, R13 - ADD R2, R13, R12 // R12 for block end - AND $255, R3, R13 -loop: - MOVD $NUM_ROUNDS, R21 - VLD1 (R11), [V30.S4, V31.S4] - - // load contants - // VLD4R (R10), [V0.S4, V1.S4, V2.S4, V3.S4] - WORD $0x4D60E940 - - // load keys - // VLD4R 16(R4), [V4.S4, V5.S4, V6.S4, V7.S4] - WORD $0x4DFFE884 - // VLD4R 16(R4), [V8.S4, V9.S4, V10.S4, V11.S4] - WORD $0x4DFFE888 - SUB $32, R4 - - // load counter + nonce - // VLD1R (R7), [V12.S4] - WORD $0x4D40C8EC - - // VLD3R (R6), [V13.S4, V14.S4, V15.S4] - WORD $0x4D40E8CD - - // update counter - VADD V30.S4, V12.S4, V12.S4 - -chacha: - // V0..V3 += V4..V7 - // V12..V15 <<<= ((V12..V15 XOR V0..V3), 16) - VADD V0.S4, V4.S4, V0.S4 - VADD V1.S4, V5.S4, V1.S4 - VADD V2.S4, V6.S4, V2.S4 - VADD V3.S4, V7.S4, V3.S4 - VEOR V12.B16, V0.B16, V12.B16 - VEOR V13.B16, V1.B16, V13.B16 - VEOR V14.B16, V2.B16, V14.B16 - VEOR V15.B16, V3.B16, V15.B16 - VREV32 V12.H8, V12.H8 - VREV32 V13.H8, V13.H8 - VREV32 V14.H8, V14.H8 - VREV32 V15.H8, V15.H8 - // V8..V11 += V12..V15 - // V4..V7 <<<= ((V4..V7 XOR V8..V11), 12) - VADD V8.S4, V12.S4, V8.S4 - VADD V9.S4, V13.S4, V9.S4 - VADD V10.S4, V14.S4, V10.S4 - VADD V11.S4, V15.S4, V11.S4 - VEOR V8.B16, V4.B16, V16.B16 - VEOR V9.B16, V5.B16, V17.B16 - VEOR V10.B16, V6.B16, V18.B16 - VEOR V11.B16, V7.B16, V19.B16 - VSHL $12, V16.S4, V4.S4 - VSHL $12, V17.S4, V5.S4 - VSHL $12, V18.S4, V6.S4 - VSHL $12, V19.S4, V7.S4 - VSRI $20, V16.S4, V4.S4 - VSRI $20, V17.S4, V5.S4 - VSRI $20, V18.S4, V6.S4 - VSRI $20, V19.S4, V7.S4 - - // V0..V3 += V4..V7 - // V12..V15 <<<= ((V12..V15 XOR V0..V3), 8) - VADD V0.S4, V4.S4, V0.S4 - VADD V1.S4, V5.S4, V1.S4 - VADD V2.S4, V6.S4, V2.S4 - VADD V3.S4, V7.S4, V3.S4 - VEOR V12.B16, V0.B16, V12.B16 - VEOR V13.B16, V1.B16, V13.B16 - VEOR V14.B16, V2.B16, V14.B16 - VEOR V15.B16, V3.B16, V15.B16 - VTBL V31.B16, [V12.B16], V12.B16 - VTBL V31.B16, [V13.B16], V13.B16 - VTBL V31.B16, [V14.B16], V14.B16 - VTBL V31.B16, [V15.B16], V15.B16 - - // V8..V11 += V12..V15 - // V4..V7 <<<= ((V4..V7 XOR V8..V11), 7) - VADD V12.S4, V8.S4, V8.S4 - VADD V13.S4, V9.S4, V9.S4 - VADD V14.S4, V10.S4, V10.S4 - VADD V15.S4, V11.S4, V11.S4 - VEOR V8.B16, V4.B16, V16.B16 - VEOR V9.B16, V5.B16, V17.B16 - VEOR V10.B16, V6.B16, V18.B16 - VEOR V11.B16, V7.B16, V19.B16 - VSHL $7, V16.S4, V4.S4 - VSHL $7, V17.S4, V5.S4 - VSHL $7, V18.S4, V6.S4 - VSHL $7, V19.S4, V7.S4 - VSRI $25, V16.S4, V4.S4 - VSRI $25, V17.S4, V5.S4 - VSRI $25, V18.S4, V6.S4 - VSRI $25, V19.S4, V7.S4 - - // V0..V3 += V5..V7, V4 - // V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 16) - VADD V0.S4, V5.S4, V0.S4 - VADD V1.S4, V6.S4, V1.S4 - VADD V2.S4, V7.S4, V2.S4 - VADD V3.S4, V4.S4, V3.S4 - VEOR V15.B16, V0.B16, V15.B16 - VEOR V12.B16, V1.B16, V12.B16 - VEOR V13.B16, V2.B16, V13.B16 - VEOR V14.B16, V3.B16, V14.B16 - VREV32 V12.H8, V12.H8 - VREV32 V13.H8, V13.H8 - VREV32 V14.H8, V14.H8 - VREV32 V15.H8, V15.H8 - - // V10 += V15; V5 <<<= ((V10 XOR V5), 12) - // ... - VADD V15.S4, V10.S4, V10.S4 - VADD V12.S4, V11.S4, V11.S4 - VADD V13.S4, V8.S4, V8.S4 - VADD V14.S4, V9.S4, V9.S4 - VEOR V10.B16, V5.B16, V16.B16 - VEOR V11.B16, V6.B16, V17.B16 - VEOR V8.B16, V7.B16, V18.B16 - VEOR V9.B16, V4.B16, V19.B16 - VSHL $12, V16.S4, V5.S4 - VSHL $12, V17.S4, V6.S4 - VSHL $12, V18.S4, V7.S4 - VSHL $12, V19.S4, V4.S4 - VSRI $20, V16.S4, V5.S4 - VSRI $20, V17.S4, V6.S4 - VSRI $20, V18.S4, V7.S4 - VSRI $20, V19.S4, V4.S4 - - // V0 += V5; V15 <<<= ((V0 XOR V15), 8) - // ... - VADD V5.S4, V0.S4, V0.S4 - VADD V6.S4, V1.S4, V1.S4 - VADD V7.S4, V2.S4, V2.S4 - VADD V4.S4, V3.S4, V3.S4 - VEOR V0.B16, V15.B16, V15.B16 - VEOR V1.B16, V12.B16, V12.B16 - VEOR V2.B16, V13.B16, V13.B16 - VEOR V3.B16, V14.B16, V14.B16 - VTBL V31.B16, [V12.B16], V12.B16 - VTBL V31.B16, [V13.B16], V13.B16 - VTBL V31.B16, [V14.B16], V14.B16 - VTBL V31.B16, [V15.B16], V15.B16 - - // V10 += V15; V5 <<<= ((V10 XOR V5), 7) - // ... - VADD V15.S4, V10.S4, V10.S4 - VADD V12.S4, V11.S4, V11.S4 - VADD V13.S4, V8.S4, V8.S4 - VADD V14.S4, V9.S4, V9.S4 - VEOR V10.B16, V5.B16, V16.B16 - VEOR V11.B16, V6.B16, V17.B16 - VEOR V8.B16, V7.B16, V18.B16 - VEOR V9.B16, V4.B16, V19.B16 - VSHL $7, V16.S4, V5.S4 - VSHL $7, V17.S4, V6.S4 - VSHL $7, V18.S4, V7.S4 - VSHL $7, V19.S4, V4.S4 - VSRI $25, V16.S4, V5.S4 - VSRI $25, V17.S4, V6.S4 - VSRI $25, V18.S4, V7.S4 - VSRI $25, V19.S4, V4.S4 - - SUB $1, R21 - CBNZ R21, chacha - - // VLD4R (R10), [V16.S4, V17.S4, V18.S4, V19.S4] - WORD $0x4D60E950 - - // VLD4R 16(R4), [V20.S4, V21.S4, V22.S4, V23.S4] - WORD $0x4DFFE894 - VADD V30.S4, V12.S4, V12.S4 - VADD V16.S4, V0.S4, V0.S4 - VADD V17.S4, V1.S4, V1.S4 - VADD V18.S4, V2.S4, V2.S4 - VADD V19.S4, V3.S4, V3.S4 - // VLD4R 16(R4), [V24.S4, V25.S4, V26.S4, V27.S4] - WORD $0x4DFFE898 - // restore R4 - SUB $32, R4 - - // load counter + nonce - // VLD1R (R7), [V28.S4] - WORD $0x4D40C8FC - // VLD3R (R6), [V29.S4, V30.S4, V31.S4] - WORD $0x4D40E8DD - - VADD V20.S4, V4.S4, V4.S4 - VADD V21.S4, V5.S4, V5.S4 - VADD V22.S4, V6.S4, V6.S4 - VADD V23.S4, V7.S4, V7.S4 - VADD V24.S4, V8.S4, V8.S4 - VADD V25.S4, V9.S4, V9.S4 - VADD V26.S4, V10.S4, V10.S4 - VADD V27.S4, V11.S4, V11.S4 - VADD V28.S4, V12.S4, V12.S4 - VADD V29.S4, V13.S4, V13.S4 - VADD V30.S4, V14.S4, V14.S4 - VADD V31.S4, V15.S4, V15.S4 - - VZIP1 V1.S4, V0.S4, V16.S4 - VZIP2 V1.S4, V0.S4, V17.S4 - VZIP1 V3.S4, V2.S4, V18.S4 - VZIP2 V3.S4, V2.S4, V19.S4 - VZIP1 V5.S4, V4.S4, V20.S4 - VZIP2 V5.S4, V4.S4, V21.S4 - VZIP1 V7.S4, V6.S4, V22.S4 - VZIP2 V7.S4, V6.S4, V23.S4 - VZIP1 V9.S4, V8.S4, V24.S4 - VZIP2 V9.S4, V8.S4, V25.S4 - VZIP1 V11.S4, V10.S4, V26.S4 - VZIP2 V11.S4, V10.S4, V27.S4 - VZIP1 V13.S4, V12.S4, V28.S4 - VZIP2 V13.S4, V12.S4, V29.S4 - VZIP1 V15.S4, V14.S4, V30.S4 - VZIP2 V15.S4, V14.S4, V31.S4 - VZIP1 V18.D2, V16.D2, V0.D2 - VZIP2 V18.D2, V16.D2, V4.D2 - VZIP1 V19.D2, V17.D2, V8.D2 - VZIP2 V19.D2, V17.D2, V12.D2 - VLD1.P 64(R2), [V16.B16, V17.B16, V18.B16, V19.B16] - - VZIP1 V22.D2, V20.D2, V1.D2 - VZIP2 V22.D2, V20.D2, V5.D2 - VZIP1 V23.D2, V21.D2, V9.D2 - VZIP2 V23.D2, V21.D2, V13.D2 - VLD1.P 64(R2), [V20.B16, V21.B16, V22.B16, V23.B16] - VZIP1 V26.D2, V24.D2, V2.D2 - VZIP2 V26.D2, V24.D2, V6.D2 - VZIP1 V27.D2, V25.D2, V10.D2 - VZIP2 V27.D2, V25.D2, V14.D2 - VLD1.P 64(R2), [V24.B16, V25.B16, V26.B16, V27.B16] - VZIP1 V30.D2, V28.D2, V3.D2 - VZIP2 V30.D2, V28.D2, V7.D2 - VZIP1 V31.D2, V29.D2, V11.D2 - VZIP2 V31.D2, V29.D2, V15.D2 - VLD1.P 64(R2), [V28.B16, V29.B16, V30.B16, V31.B16] - VEOR V0.B16, V16.B16, V16.B16 - VEOR V1.B16, V17.B16, V17.B16 - VEOR V2.B16, V18.B16, V18.B16 - VEOR V3.B16, V19.B16, V19.B16 - VST1.P [V16.B16, V17.B16, V18.B16, V19.B16], 64(R1) - VEOR V4.B16, V20.B16, V20.B16 - VEOR V5.B16, V21.B16, V21.B16 - VEOR V6.B16, V22.B16, V22.B16 - VEOR V7.B16, V23.B16, V23.B16 - VST1.P [V20.B16, V21.B16, V22.B16, V23.B16], 64(R1) - VEOR V8.B16, V24.B16, V24.B16 - VEOR V9.B16, V25.B16, V25.B16 - VEOR V10.B16, V26.B16, V26.B16 - VEOR V11.B16, V27.B16, V27.B16 - VST1.P [V24.B16, V25.B16, V26.B16, V27.B16], 64(R1) - VEOR V12.B16, V28.B16, V28.B16 - VEOR V13.B16, V29.B16, V29.B16 - VEOR V14.B16, V30.B16, V30.B16 - VEOR V15.B16, V31.B16, V31.B16 - VST1.P [V28.B16, V29.B16, V30.B16, V31.B16], 64(R1) - - ADD $4, R20 - MOVW R20, (R7) // update counter - - CMP R2, R12 - BGT loop - - RET - - -DATA ·constants+0x00(SB)/4, $0x61707865 -DATA ·constants+0x04(SB)/4, $0x3320646e -DATA ·constants+0x08(SB)/4, $0x79622d32 -DATA ·constants+0x0c(SB)/4, $0x6b206574 -GLOBL ·constants(SB), NOPTR|RODATA, $32 - -DATA ·incRotMatrix+0x00(SB)/4, $0x00000000 -DATA ·incRotMatrix+0x04(SB)/4, $0x00000001 -DATA ·incRotMatrix+0x08(SB)/4, $0x00000002 -DATA ·incRotMatrix+0x0c(SB)/4, $0x00000003 -DATA ·incRotMatrix+0x10(SB)/4, $0x02010003 -DATA ·incRotMatrix+0x14(SB)/4, $0x06050407 -DATA ·incRotMatrix+0x18(SB)/4, $0x0A09080B -DATA ·incRotMatrix+0x1c(SB)/4, $0x0E0D0C0F -GLOBL ·incRotMatrix(SB), NOPTR|RODATA, $32 diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go deleted file mode 100644 index ad74e23a..00000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018 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.11 -// +build !gccgo - -package chacha20 - -const ( - haveAsm = true - bufSize = 256 -) - -//go:noescape -func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) - -func (c *Cipher) xorKeyStreamAsm(dst, src []byte) { - - if len(src) >= bufSize { - xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter) - } - - if len(src)%bufSize != 0 { - i := len(src) - len(src)%bufSize - c.buf = [bufSize]byte{} - copy(c.buf[:], src[i:]) - xorKeyStreamVX(c.buf[:], c.buf[:], &c.key, &c.nonce, &c.counter) - c.len = bufSize - copy(dst[i:], c.buf[:len(src)%bufSize]) - } -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go index 47eac031..91520d1d 100644 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go +++ b/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build !arm64,!s390x arm64,!go1.11 gccgo appengine +// +build !s390x gccgo appengine package chacha20 diff --git a/vendor/golang.org/x/net/html/atom/atom.go b/vendor/golang.org/x/net/html/atom/atom.go new file mode 100644 index 00000000..cd0a8ac1 --- /dev/null +++ b/vendor/golang.org/x/net/html/atom/atom.go @@ -0,0 +1,78 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package atom provides integer codes (also known as atoms) for a fixed set of +// frequently occurring HTML strings: tag names and attribute keys such as "p" +// and "id". +// +// Sharing an atom's name between all elements with the same tag can result in +// fewer string allocations when tokenizing and parsing HTML. Integer +// comparisons are also generally faster than string comparisons. +// +// The value of an atom's particular code is not guaranteed to stay the same +// between versions of this package. Neither is any ordering guaranteed: +// whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to +// be dense. The only guarantees are that e.g. looking up "div" will yield +// atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. +package atom // import "golang.org/x/net/html/atom" + +// Atom is an integer code for a string. The zero value maps to "". +type Atom uint32 + +// String returns the atom's name. +func (a Atom) String() string { + start := uint32(a >> 8) + n := uint32(a & 0xff) + if start+n > uint32(len(atomText)) { + return "" + } + return atomText[start : start+n] +} + +func (a Atom) string() string { + return atomText[a>>8 : a>>8+a&0xff] +} + +// fnv computes the FNV hash with an arbitrary starting value h. +func fnv(h uint32, s []byte) uint32 { + for i := range s { + h ^= uint32(s[i]) + h *= 16777619 + } + return h +} + +func match(s string, t []byte) bool { + for i, c := range t { + if s[i] != c { + return false + } + } + return true +} + +// Lookup returns the atom whose name is s. It returns zero if there is no +// such atom. The lookup is case sensitive. +func Lookup(s []byte) Atom { + if len(s) == 0 || len(s) > maxAtomLen { + return 0 + } + h := fnv(hash0, s) + if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { + return a + } + if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { + return a + } + return 0 +} + +// String returns a string whose contents are equal to s. In that sense, it is +// equivalent to string(s) but may be more efficient. +func String(s []byte) string { + if a := Lookup(s); a != 0 { + return a.String() + } + return string(s) +} diff --git a/vendor/golang.org/x/net/html/atom/gen.go b/vendor/golang.org/x/net/html/atom/gen.go new file mode 100644 index 00000000..5d052781 --- /dev/null +++ b/vendor/golang.org/x/net/html/atom/gen.go @@ -0,0 +1,712 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build ignore + +//go:generate go run gen.go +//go:generate go run gen.go -test + +package main + +import ( + "bytes" + "flag" + "fmt" + "go/format" + "io/ioutil" + "math/rand" + "os" + "sort" + "strings" +) + +// identifier converts s to a Go exported identifier. +// It converts "div" to "Div" and "accept-charset" to "AcceptCharset". +func identifier(s string) string { + b := make([]byte, 0, len(s)) + cap := true + for _, c := range s { + if c == '-' { + cap = true + continue + } + if cap && 'a' <= c && c <= 'z' { + c -= 'a' - 'A' + } + cap = false + b = append(b, byte(c)) + } + return string(b) +} + +var test = flag.Bool("test", false, "generate table_test.go") + +func genFile(name string, buf *bytes.Buffer) { + b, err := format.Source(buf.Bytes()) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + if err := ioutil.WriteFile(name, b, 0644); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func main() { + flag.Parse() + + var all []string + all = append(all, elements...) + all = append(all, attributes...) + all = append(all, eventHandlers...) + all = append(all, extra...) + sort.Strings(all) + + // uniq - lists have dups + w := 0 + for _, s := range all { + if w == 0 || all[w-1] != s { + all[w] = s + w++ + } + } + all = all[:w] + + if *test { + var buf bytes.Buffer + fmt.Fprintln(&buf, "// Code generated by go generate gen.go; DO NOT EDIT.\n") + fmt.Fprintln(&buf, "//go:generate go run gen.go -test\n") + fmt.Fprintln(&buf, "package atom\n") + fmt.Fprintln(&buf, "var testAtomList = []string{") + for _, s := range all { + fmt.Fprintf(&buf, "\t%q,\n", s) + } + fmt.Fprintln(&buf, "}") + + genFile("table_test.go", &buf) + return + } + + // Find hash that minimizes table size. + var best *table + for i := 0; i < 1000000; i++ { + if best != nil && 1<<(best.k-1) < len(all) { + break + } + h := rand.Uint32() + for k := uint(0); k <= 16; k++ { + if best != nil && k >= best.k { + break + } + var t table + if t.init(h, k, all) { + best = &t + break + } + } + } + if best == nil { + fmt.Fprintf(os.Stderr, "failed to construct string table\n") + os.Exit(1) + } + + // Lay out strings, using overlaps when possible. + layout := append([]string{}, all...) + + // Remove strings that are substrings of other strings + for changed := true; changed; { + changed = false + for i, s := range layout { + if s == "" { + continue + } + for j, t := range layout { + if i != j && t != "" && strings.Contains(s, t) { + changed = true + layout[j] = "" + } + } + } + } + + // Join strings where one suffix matches another prefix. + for { + // Find best i, j, k such that layout[i][len-k:] == layout[j][:k], + // maximizing overlap length k. + besti := -1 + bestj := -1 + bestk := 0 + for i, s := range layout { + if s == "" { + continue + } + for j, t := range layout { + if i == j { + continue + } + for k := bestk + 1; k <= len(s) && k <= len(t); k++ { + if s[len(s)-k:] == t[:k] { + besti = i + bestj = j + bestk = k + } + } + } + } + if bestk > 0 { + layout[besti] += layout[bestj][bestk:] + layout[bestj] = "" + continue + } + break + } + + text := strings.Join(layout, "") + + atom := map[string]uint32{} + for _, s := range all { + off := strings.Index(text, s) + if off < 0 { + panic("lost string " + s) + } + atom[s] = uint32(off<<8 | len(s)) + } + + var buf bytes.Buffer + // Generate the Go code. + fmt.Fprintln(&buf, "// Code generated by go generate gen.go; DO NOT EDIT.\n") + fmt.Fprintln(&buf, "//go:generate go run gen.go\n") + fmt.Fprintln(&buf, "package atom\n\nconst (") + + // compute max len + maxLen := 0 + for _, s := range all { + if maxLen < len(s) { + maxLen = len(s) + } + fmt.Fprintf(&buf, "\t%s Atom = %#x\n", identifier(s), atom[s]) + } + fmt.Fprintln(&buf, ")\n") + + fmt.Fprintf(&buf, "const hash0 = %#x\n\n", best.h0) + fmt.Fprintf(&buf, "const maxAtomLen = %d\n\n", maxLen) + + fmt.Fprintf(&buf, "var table = [1<<%d]Atom{\n", best.k) + for i, s := range best.tab { + if s == "" { + continue + } + fmt.Fprintf(&buf, "\t%#x: %#x, // %s\n", i, atom[s], s) + } + fmt.Fprintf(&buf, "}\n") + datasize := (1 << best.k) * 4 + + fmt.Fprintln(&buf, "const atomText =") + textsize := len(text) + for len(text) > 60 { + fmt.Fprintf(&buf, "\t%q +\n", text[:60]) + text = text[60:] + } + fmt.Fprintf(&buf, "\t%q\n\n", text) + + genFile("table.go", &buf) + + fmt.Fprintf(os.Stdout, "%d atoms; %d string bytes + %d tables = %d total data\n", len(all), textsize, datasize, textsize+datasize) +} + +type byLen []string + +func (x byLen) Less(i, j int) bool { return len(x[i]) > len(x[j]) } +func (x byLen) Swap(i, j int) { x[i], x[j] = x[j], x[i] } +func (x byLen) Len() int { return len(x) } + +// fnv computes the FNV hash with an arbitrary starting value h. +func fnv(h uint32, s string) uint32 { + for i := 0; i < len(s); i++ { + h ^= uint32(s[i]) + h *= 16777619 + } + return h +} + +// A table represents an attempt at constructing the lookup table. +// The lookup table uses cuckoo hashing, meaning that each string +// can be found in one of two positions. +type table struct { + h0 uint32 + k uint + mask uint32 + tab []string +} + +// hash returns the two hashes for s. +func (t *table) hash(s string) (h1, h2 uint32) { + h := fnv(t.h0, s) + h1 = h & t.mask + h2 = (h >> 16) & t.mask + return +} + +// init initializes the table with the given parameters. +// h0 is the initial hash value, +// k is the number of bits of hash value to use, and +// x is the list of strings to store in the table. +// init returns false if the table cannot be constructed. +func (t *table) init(h0 uint32, k uint, x []string) bool { + t.h0 = h0 + t.k = k + t.tab = make([]string, 1< len(t.tab) { + return false + } + s := t.tab[i] + h1, h2 := t.hash(s) + j := h1 + h2 - i + if t.tab[j] != "" && !t.push(j, depth+1) { + return false + } + t.tab[j] = s + return true +} + +// The lists of element names and attribute keys were taken from +// https://html.spec.whatwg.org/multipage/indices.html#index +// as of the "HTML Living Standard - Last Updated 16 April 2018" version. + +// "command", "keygen" and "menuitem" have been removed from the spec, +// but are kept here for backwards compatibility. +var elements = []string{ + "a", + "abbr", + "address", + "area", + "article", + "aside", + "audio", + "b", + "base", + "bdi", + "bdo", + "blockquote", + "body", + "br", + "button", + "canvas", + "caption", + "cite", + "code", + "col", + "colgroup", + "command", + "data", + "datalist", + "dd", + "del", + "details", + "dfn", + "dialog", + "div", + "dl", + "dt", + "em", + "embed", + "fieldset", + "figcaption", + "figure", + "footer", + "form", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hgroup", + "hr", + "html", + "i", + "iframe", + "img", + "input", + "ins", + "kbd", + "keygen", + "label", + "legend", + "li", + "link", + "main", + "map", + "mark", + "menu", + "menuitem", + "meta", + "meter", + "nav", + "noscript", + "object", + "ol", + "optgroup", + "option", + "output", + "p", + "param", + "picture", + "pre", + "progress", + "q", + "rp", + "rt", + "ruby", + "s", + "samp", + "script", + "section", + "select", + "slot", + "small", + "source", + "span", + "strong", + "style", + "sub", + "summary", + "sup", + "table", + "tbody", + "td", + "template", + "textarea", + "tfoot", + "th", + "thead", + "time", + "title", + "tr", + "track", + "u", + "ul", + "var", + "video", + "wbr", +} + +// https://html.spec.whatwg.org/multipage/indices.html#attributes-3 +// +// "challenge", "command", "contextmenu", "dropzone", "icon", "keytype", "mediagroup", +// "radiogroup", "spellcheck", "scoped", "seamless", "sortable" and "sorted" have been removed from the spec, +// but are kept here for backwards compatibility. +var attributes = []string{ + "abbr", + "accept", + "accept-charset", + "accesskey", + "action", + "allowfullscreen", + "allowpaymentrequest", + "allowusermedia", + "alt", + "as", + "async", + "autocomplete", + "autofocus", + "autoplay", + "challenge", + "charset", + "checked", + "cite", + "class", + "color", + "cols", + "colspan", + "command", + "content", + "contenteditable", + "contextmenu", + "controls", + "coords", + "crossorigin", + "data", + "datetime", + "default", + "defer", + "dir", + "dirname", + "disabled", + "download", + "draggable", + "dropzone", + "enctype", + "for", + "form", + "formaction", + "formenctype", + "formmethod", + "formnovalidate", + "formtarget", + "headers", + "height", + "hidden", + "high", + "href", + "hreflang", + "http-equiv", + "icon", + "id", + "inputmode", + "integrity", + "is", + "ismap", + "itemid", + "itemprop", + "itemref", + "itemscope", + "itemtype", + "keytype", + "kind", + "label", + "lang", + "list", + "loop", + "low", + "manifest", + "max", + "maxlength", + "media", + "mediagroup", + "method", + "min", + "minlength", + "multiple", + "muted", + "name", + "nomodule", + "nonce", + "novalidate", + "open", + "optimum", + "pattern", + "ping", + "placeholder", + "playsinline", + "poster", + "preload", + "radiogroup", + "readonly", + "referrerpolicy", + "rel", + "required", + "reversed", + "rows", + "rowspan", + "sandbox", + "spellcheck", + "scope", + "scoped", + "seamless", + "selected", + "shape", + "size", + "sizes", + "sortable", + "sorted", + "slot", + "span", + "spellcheck", + "src", + "srcdoc", + "srclang", + "srcset", + "start", + "step", + "style", + "tabindex", + "target", + "title", + "translate", + "type", + "typemustmatch", + "updateviacache", + "usemap", + "value", + "width", + "workertype", + "wrap", +} + +// "onautocomplete", "onautocompleteerror", "onmousewheel", +// "onshow" and "onsort" have been removed from the spec, +// but are kept here for backwards compatibility. +var eventHandlers = []string{ + "onabort", + "onautocomplete", + "onautocompleteerror", + "onauxclick", + "onafterprint", + "onbeforeprint", + "onbeforeunload", + "onblur", + "oncancel", + "oncanplay", + "oncanplaythrough", + "onchange", + "onclick", + "onclose", + "oncontextmenu", + "oncopy", + "oncuechange", + "oncut", + "ondblclick", + "ondrag", + "ondragend", + "ondragenter", + "ondragexit", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onended", + "onerror", + "onfocus", + "onhashchange", + "oninput", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeyup", + "onlanguagechange", + "onload", + "onloadeddata", + "onloadedmetadata", + "onloadend", + "onloadstart", + "onmessage", + "onmessageerror", + "onmousedown", + "onmouseenter", + "onmouseleave", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onwheel", + "onoffline", + "ononline", + "onpagehide", + "onpageshow", + "onpaste", + "onpause", + "onplay", + "onplaying", + "onpopstate", + "onprogress", + "onratechange", + "onreset", + "onresize", + "onrejectionhandled", + "onscroll", + "onsecuritypolicyviolation", + "onseeked", + "onseeking", + "onselect", + "onshow", + "onsort", + "onstalled", + "onstorage", + "onsubmit", + "onsuspend", + "ontimeupdate", + "ontoggle", + "onunhandledrejection", + "onunload", + "onvolumechange", + "onwaiting", +} + +// extra are ad-hoc values not covered by any of the lists above. +var extra = []string{ + "acronym", + "align", + "annotation", + "annotation-xml", + "applet", + "basefont", + "bgsound", + "big", + "blink", + "center", + "color", + "desc", + "face", + "font", + "foreignObject", // HTML is case-insensitive, but SVG-embedded-in-HTML is case-sensitive. + "foreignobject", + "frame", + "frameset", + "image", + "isindex", + "listing", + "malignmark", + "marquee", + "math", + "mglyph", + "mi", + "mn", + "mo", + "ms", + "mtext", + "nobr", + "noembed", + "noframes", + "plaintext", + "prompt", + "public", + "rb", + "rtc", + "spacer", + "strike", + "svg", + "system", + "tt", + "xmp", +} diff --git a/vendor/golang.org/x/net/html/atom/table.go b/vendor/golang.org/x/net/html/atom/table.go new file mode 100644 index 00000000..2a938864 --- /dev/null +++ b/vendor/golang.org/x/net/html/atom/table.go @@ -0,0 +1,783 @@ +// Code generated by go generate gen.go; DO NOT EDIT. + +//go:generate go run gen.go + +package atom + +const ( + A Atom = 0x1 + Abbr Atom = 0x4 + Accept Atom = 0x1a06 + AcceptCharset Atom = 0x1a0e + Accesskey Atom = 0x2c09 + Acronym Atom = 0xaa07 + Action Atom = 0x27206 + Address Atom = 0x6f307 + Align Atom = 0xb105 + Allowfullscreen Atom = 0x2080f + Allowpaymentrequest Atom = 0xc113 + Allowusermedia Atom = 0xdd0e + Alt Atom = 0xf303 + Annotation Atom = 0x1c90a + AnnotationXml Atom = 0x1c90e + Applet Atom = 0x31906 + Area Atom = 0x35604 + Article Atom = 0x3fc07 + As Atom = 0x3c02 + Aside Atom = 0x10705 + Async Atom = 0xff05 + Audio Atom = 0x11505 + Autocomplete Atom = 0x2780c + Autofocus Atom = 0x12109 + Autoplay Atom = 0x13c08 + B Atom = 0x101 + Base Atom = 0x3b04 + Basefont Atom = 0x3b08 + Bdi Atom = 0xba03 + Bdo Atom = 0x14b03 + Bgsound Atom = 0x15e07 + Big Atom = 0x17003 + Blink Atom = 0x17305 + Blockquote Atom = 0x1870a + Body Atom = 0x2804 + Br Atom = 0x202 + Button Atom = 0x19106 + Canvas Atom = 0x10306 + Caption Atom = 0x23107 + Center Atom = 0x22006 + Challenge Atom = 0x29b09 + Charset Atom = 0x2107 + Checked Atom = 0x47907 + Cite Atom = 0x19c04 + Class Atom = 0x56405 + Code Atom = 0x5c504 + Col Atom = 0x1ab03 + Colgroup Atom = 0x1ab08 + Color Atom = 0x1bf05 + Cols Atom = 0x1c404 + Colspan Atom = 0x1c407 + Command Atom = 0x1d707 + Content Atom = 0x58b07 + Contenteditable Atom = 0x58b0f + Contextmenu Atom = 0x3800b + Controls Atom = 0x1de08 + Coords Atom = 0x1ea06 + Crossorigin Atom = 0x1fb0b + Data Atom = 0x4a504 + Datalist Atom = 0x4a508 + Datetime Atom = 0x2b808 + Dd Atom = 0x2d702 + Default Atom = 0x10a07 + Defer Atom = 0x5c705 + Del Atom = 0x45203 + Desc Atom = 0x56104 + Details Atom = 0x7207 + Dfn Atom = 0x8703 + Dialog Atom = 0xbb06 + Dir Atom = 0x9303 + Dirname Atom = 0x9307 + Disabled Atom = 0x16408 + Div Atom = 0x16b03 + Dl Atom = 0x5e602 + Download Atom = 0x46308 + Draggable Atom = 0x17a09 + Dropzone Atom = 0x40508 + Dt Atom = 0x64b02 + Em Atom = 0x6e02 + Embed Atom = 0x6e05 + Enctype Atom = 0x28d07 + Face Atom = 0x21e04 + Fieldset Atom = 0x22608 + Figcaption Atom = 0x22e0a + Figure Atom = 0x24806 + Font Atom = 0x3f04 + Footer Atom = 0xf606 + For Atom = 0x25403 + ForeignObject Atom = 0x2540d + Foreignobject Atom = 0x2610d + Form Atom = 0x26e04 + Formaction Atom = 0x26e0a + Formenctype Atom = 0x2890b + Formmethod Atom = 0x2a40a + Formnovalidate Atom = 0x2ae0e + Formtarget Atom = 0x2c00a + Frame Atom = 0x8b05 + Frameset Atom = 0x8b08 + H1 Atom = 0x15c02 + H2 Atom = 0x2de02 + H3 Atom = 0x30d02 + H4 Atom = 0x34502 + H5 Atom = 0x34f02 + H6 Atom = 0x64d02 + Head Atom = 0x33104 + Header Atom = 0x33106 + Headers Atom = 0x33107 + Height Atom = 0x5206 + Hgroup Atom = 0x2ca06 + Hidden Atom = 0x2d506 + High Atom = 0x2db04 + Hr Atom = 0x15702 + Href Atom = 0x2e004 + Hreflang Atom = 0x2e008 + Html Atom = 0x5604 + HttpEquiv Atom = 0x2e80a + I Atom = 0x601 + Icon Atom = 0x58a04 + Id Atom = 0x10902 + Iframe Atom = 0x2fc06 + Image Atom = 0x30205 + Img Atom = 0x30703 + Input Atom = 0x44b05 + Inputmode Atom = 0x44b09 + Ins Atom = 0x20403 + Integrity Atom = 0x23f09 + Is Atom = 0x16502 + Isindex Atom = 0x30f07 + Ismap Atom = 0x31605 + Itemid Atom = 0x38b06 + Itemprop Atom = 0x19d08 + Itemref Atom = 0x3cd07 + Itemscope Atom = 0x67109 + Itemtype Atom = 0x31f08 + Kbd Atom = 0xb903 + Keygen Atom = 0x3206 + Keytype Atom = 0xd607 + Kind Atom = 0x17704 + Label Atom = 0x5905 + Lang Atom = 0x2e404 + Legend Atom = 0x18106 + Li Atom = 0xb202 + Link Atom = 0x17404 + List Atom = 0x4a904 + Listing Atom = 0x4a907 + Loop Atom = 0x5d04 + Low Atom = 0xc303 + Main Atom = 0x1004 + Malignmark Atom = 0xb00a + Manifest Atom = 0x6d708 + Map Atom = 0x31803 + Mark Atom = 0xb604 + Marquee Atom = 0x32707 + Math Atom = 0x32e04 + Max Atom = 0x33d03 + Maxlength Atom = 0x33d09 + Media Atom = 0xe605 + Mediagroup Atom = 0xe60a + Menu Atom = 0x38704 + Menuitem Atom = 0x38708 + Meta Atom = 0x4b804 + Meter Atom = 0x9805 + Method Atom = 0x2a806 + Mglyph Atom = 0x30806 + Mi Atom = 0x34702 + Min Atom = 0x34703 + Minlength Atom = 0x34709 + Mn Atom = 0x2b102 + Mo Atom = 0xa402 + Ms Atom = 0x67402 + Mtext Atom = 0x35105 + Multiple Atom = 0x35f08 + Muted Atom = 0x36705 + Name Atom = 0x9604 + Nav Atom = 0x1303 + Nobr Atom = 0x3704 + Noembed Atom = 0x6c07 + Noframes Atom = 0x8908 + Nomodule Atom = 0xa208 + Nonce Atom = 0x1a605 + Noscript Atom = 0x21608 + Novalidate Atom = 0x2b20a + Object Atom = 0x26806 + Ol Atom = 0x13702 + Onabort Atom = 0x19507 + Onafterprint Atom = 0x2360c + Onautocomplete Atom = 0x2760e + Onautocompleteerror Atom = 0x27613 + Onauxclick Atom = 0x61f0a + Onbeforeprint Atom = 0x69e0d + Onbeforeunload Atom = 0x6e70e + Onblur Atom = 0x56d06 + Oncancel Atom = 0x11908 + Oncanplay Atom = 0x14d09 + Oncanplaythrough Atom = 0x14d10 + Onchange Atom = 0x41b08 + Onclick Atom = 0x2f507 + Onclose Atom = 0x36c07 + Oncontextmenu Atom = 0x37e0d + Oncopy Atom = 0x39106 + Oncuechange Atom = 0x3970b + Oncut Atom = 0x3a205 + Ondblclick Atom = 0x3a70a + Ondrag Atom = 0x3b106 + Ondragend Atom = 0x3b109 + Ondragenter Atom = 0x3ba0b + Ondragexit Atom = 0x3c50a + Ondragleave Atom = 0x3df0b + Ondragover Atom = 0x3ea0a + Ondragstart Atom = 0x3f40b + Ondrop Atom = 0x40306 + Ondurationchange Atom = 0x41310 + Onemptied Atom = 0x40a09 + Onended Atom = 0x42307 + Onerror Atom = 0x42a07 + Onfocus Atom = 0x43107 + Onhashchange Atom = 0x43d0c + Oninput Atom = 0x44907 + Oninvalid Atom = 0x45509 + Onkeydown Atom = 0x45e09 + Onkeypress Atom = 0x46b0a + Onkeyup Atom = 0x48007 + Onlanguagechange Atom = 0x48d10 + Onload Atom = 0x49d06 + Onloadeddata Atom = 0x49d0c + Onloadedmetadata Atom = 0x4b010 + Onloadend Atom = 0x4c609 + Onloadstart Atom = 0x4cf0b + Onmessage Atom = 0x4da09 + Onmessageerror Atom = 0x4da0e + Onmousedown Atom = 0x4e80b + Onmouseenter Atom = 0x4f30c + Onmouseleave Atom = 0x4ff0c + Onmousemove Atom = 0x50b0b + Onmouseout Atom = 0x5160a + Onmouseover Atom = 0x5230b + Onmouseup Atom = 0x52e09 + Onmousewheel Atom = 0x53c0c + Onoffline Atom = 0x54809 + Ononline Atom = 0x55108 + Onpagehide Atom = 0x5590a + Onpageshow Atom = 0x5730a + Onpaste Atom = 0x57f07 + Onpause Atom = 0x59a07 + Onplay Atom = 0x5a406 + Onplaying Atom = 0x5a409 + Onpopstate Atom = 0x5ad0a + Onprogress Atom = 0x5b70a + Onratechange Atom = 0x5cc0c + Onrejectionhandled Atom = 0x5d812 + Onreset Atom = 0x5ea07 + Onresize Atom = 0x5f108 + Onscroll Atom = 0x60008 + Onsecuritypolicyviolation Atom = 0x60819 + Onseeked Atom = 0x62908 + Onseeking Atom = 0x63109 + Onselect Atom = 0x63a08 + Onshow Atom = 0x64406 + Onsort Atom = 0x64f06 + Onstalled Atom = 0x65909 + Onstorage Atom = 0x66209 + Onsubmit Atom = 0x66b08 + Onsuspend Atom = 0x67b09 + Ontimeupdate Atom = 0x400c + Ontoggle Atom = 0x68408 + Onunhandledrejection Atom = 0x68c14 + Onunload Atom = 0x6ab08 + Onvolumechange Atom = 0x6b30e + Onwaiting Atom = 0x6c109 + Onwheel Atom = 0x6ca07 + Open Atom = 0x1a304 + Optgroup Atom = 0x5f08 + Optimum Atom = 0x6d107 + Option Atom = 0x6e306 + Output Atom = 0x51d06 + P Atom = 0xc01 + Param Atom = 0xc05 + Pattern Atom = 0x6607 + Picture Atom = 0x7b07 + Ping Atom = 0xef04 + Placeholder Atom = 0x1310b + Plaintext Atom = 0x1b209 + Playsinline Atom = 0x1400b + Poster Atom = 0x2cf06 + Pre Atom = 0x47003 + Preload Atom = 0x48607 + Progress Atom = 0x5b908 + Prompt Atom = 0x53606 + Public Atom = 0x58606 + Q Atom = 0xcf01 + Radiogroup Atom = 0x30a + Rb Atom = 0x3a02 + Readonly Atom = 0x35708 + Referrerpolicy Atom = 0x3d10e + Rel Atom = 0x48703 + Required Atom = 0x24c08 + Reversed Atom = 0x8008 + Rows Atom = 0x9c04 + Rowspan Atom = 0x9c07 + Rp Atom = 0x23c02 + Rt Atom = 0x19a02 + Rtc Atom = 0x19a03 + Ruby Atom = 0xfb04 + S Atom = 0x2501 + Samp Atom = 0x7804 + Sandbox Atom = 0x12907 + Scope Atom = 0x67505 + Scoped Atom = 0x67506 + Script Atom = 0x21806 + Seamless Atom = 0x37108 + Section Atom = 0x56807 + Select Atom = 0x63c06 + Selected Atom = 0x63c08 + Shape Atom = 0x1e505 + Size Atom = 0x5f504 + Sizes Atom = 0x5f505 + Slot Atom = 0x1ef04 + Small Atom = 0x20605 + Sortable Atom = 0x65108 + Sorted Atom = 0x33706 + Source Atom = 0x37806 + Spacer Atom = 0x43706 + Span Atom = 0x9f04 + Spellcheck Atom = 0x4740a + Src Atom = 0x5c003 + Srcdoc Atom = 0x5c006 + Srclang Atom = 0x5f907 + Srcset Atom = 0x6f906 + Start Atom = 0x3fa05 + Step Atom = 0x58304 + Strike Atom = 0xd206 + Strong Atom = 0x6dd06 + Style Atom = 0x6ff05 + Sub Atom = 0x66d03 + Summary Atom = 0x70407 + Sup Atom = 0x70b03 + Svg Atom = 0x70e03 + System Atom = 0x71106 + Tabindex Atom = 0x4be08 + Table Atom = 0x59505 + Target Atom = 0x2c406 + Tbody Atom = 0x2705 + Td Atom = 0x9202 + Template Atom = 0x71408 + Textarea Atom = 0x35208 + Tfoot Atom = 0xf505 + Th Atom = 0x15602 + Thead Atom = 0x33005 + Time Atom = 0x4204 + Title Atom = 0x11005 + Tr Atom = 0xcc02 + Track Atom = 0x1ba05 + Translate Atom = 0x1f209 + Tt Atom = 0x6802 + Type Atom = 0xd904 + Typemustmatch Atom = 0x2900d + U Atom = 0xb01 + Ul Atom = 0xa702 + Updateviacache Atom = 0x460e + Usemap Atom = 0x59e06 + Value Atom = 0x1505 + Var Atom = 0x16d03 + Video Atom = 0x2f105 + Wbr Atom = 0x57c03 + Width Atom = 0x64905 + Workertype Atom = 0x71c0a + Wrap Atom = 0x72604 + Xmp Atom = 0x12f03 +) + +const hash0 = 0x81cdf10e + +const maxAtomLen = 25 + +var table = [1 << 9]Atom{ + 0x1: 0xe60a, // mediagroup + 0x2: 0x2e404, // lang + 0x4: 0x2c09, // accesskey + 0x5: 0x8b08, // frameset + 0x7: 0x63a08, // onselect + 0x8: 0x71106, // system + 0xa: 0x64905, // width + 0xc: 0x2890b, // formenctype + 0xd: 0x13702, // ol + 0xe: 0x3970b, // oncuechange + 0x10: 0x14b03, // bdo + 0x11: 0x11505, // audio + 0x12: 0x17a09, // draggable + 0x14: 0x2f105, // video + 0x15: 0x2b102, // mn + 0x16: 0x38704, // menu + 0x17: 0x2cf06, // poster + 0x19: 0xf606, // footer + 0x1a: 0x2a806, // method + 0x1b: 0x2b808, // datetime + 0x1c: 0x19507, // onabort + 0x1d: 0x460e, // updateviacache + 0x1e: 0xff05, // async + 0x1f: 0x49d06, // onload + 0x21: 0x11908, // oncancel + 0x22: 0x62908, // onseeked + 0x23: 0x30205, // image + 0x24: 0x5d812, // onrejectionhandled + 0x26: 0x17404, // link + 0x27: 0x51d06, // output + 0x28: 0x33104, // head + 0x29: 0x4ff0c, // onmouseleave + 0x2a: 0x57f07, // onpaste + 0x2b: 0x5a409, // onplaying + 0x2c: 0x1c407, // colspan + 0x2f: 0x1bf05, // color + 0x30: 0x5f504, // size + 0x31: 0x2e80a, // http-equiv + 0x33: 0x601, // i + 0x34: 0x5590a, // onpagehide + 0x35: 0x68c14, // onunhandledrejection + 0x37: 0x42a07, // onerror + 0x3a: 0x3b08, // basefont + 0x3f: 0x1303, // nav + 0x40: 0x17704, // kind + 0x41: 0x35708, // readonly + 0x42: 0x30806, // mglyph + 0x44: 0xb202, // li + 0x46: 0x2d506, // hidden + 0x47: 0x70e03, // svg + 0x48: 0x58304, // step + 0x49: 0x23f09, // integrity + 0x4a: 0x58606, // public + 0x4c: 0x1ab03, // col + 0x4d: 0x1870a, // blockquote + 0x4e: 0x34f02, // h5 + 0x50: 0x5b908, // progress + 0x51: 0x5f505, // sizes + 0x52: 0x34502, // h4 + 0x56: 0x33005, // thead + 0x57: 0xd607, // keytype + 0x58: 0x5b70a, // onprogress + 0x59: 0x44b09, // inputmode + 0x5a: 0x3b109, // ondragend + 0x5d: 0x3a205, // oncut + 0x5e: 0x43706, // spacer + 0x5f: 0x1ab08, // colgroup + 0x62: 0x16502, // is + 0x65: 0x3c02, // as + 0x66: 0x54809, // onoffline + 0x67: 0x33706, // sorted + 0x69: 0x48d10, // onlanguagechange + 0x6c: 0x43d0c, // onhashchange + 0x6d: 0x9604, // name + 0x6e: 0xf505, // tfoot + 0x6f: 0x56104, // desc + 0x70: 0x33d03, // max + 0x72: 0x1ea06, // coords + 0x73: 0x30d02, // h3 + 0x74: 0x6e70e, // onbeforeunload + 0x75: 0x9c04, // rows + 0x76: 0x63c06, // select + 0x77: 0x9805, // meter + 0x78: 0x38b06, // itemid + 0x79: 0x53c0c, // onmousewheel + 0x7a: 0x5c006, // srcdoc + 0x7d: 0x1ba05, // track + 0x7f: 0x31f08, // itemtype + 0x82: 0xa402, // mo + 0x83: 0x41b08, // onchange + 0x84: 0x33107, // headers + 0x85: 0x5cc0c, // onratechange + 0x86: 0x60819, // onsecuritypolicyviolation + 0x88: 0x4a508, // datalist + 0x89: 0x4e80b, // onmousedown + 0x8a: 0x1ef04, // slot + 0x8b: 0x4b010, // onloadedmetadata + 0x8c: 0x1a06, // accept + 0x8d: 0x26806, // object + 0x91: 0x6b30e, // onvolumechange + 0x92: 0x2107, // charset + 0x93: 0x27613, // onautocompleteerror + 0x94: 0xc113, // allowpaymentrequest + 0x95: 0x2804, // body + 0x96: 0x10a07, // default + 0x97: 0x63c08, // selected + 0x98: 0x21e04, // face + 0x99: 0x1e505, // shape + 0x9b: 0x68408, // ontoggle + 0x9e: 0x64b02, // dt + 0x9f: 0xb604, // mark + 0xa1: 0xb01, // u + 0xa4: 0x6ab08, // onunload + 0xa5: 0x5d04, // loop + 0xa6: 0x16408, // disabled + 0xaa: 0x42307, // onended + 0xab: 0xb00a, // malignmark + 0xad: 0x67b09, // onsuspend + 0xae: 0x35105, // mtext + 0xaf: 0x64f06, // onsort + 0xb0: 0x19d08, // itemprop + 0xb3: 0x67109, // itemscope + 0xb4: 0x17305, // blink + 0xb6: 0x3b106, // ondrag + 0xb7: 0xa702, // ul + 0xb8: 0x26e04, // form + 0xb9: 0x12907, // sandbox + 0xba: 0x8b05, // frame + 0xbb: 0x1505, // value + 0xbc: 0x66209, // onstorage + 0xbf: 0xaa07, // acronym + 0xc0: 0x19a02, // rt + 0xc2: 0x202, // br + 0xc3: 0x22608, // fieldset + 0xc4: 0x2900d, // typemustmatch + 0xc5: 0xa208, // nomodule + 0xc6: 0x6c07, // noembed + 0xc7: 0x69e0d, // onbeforeprint + 0xc8: 0x19106, // button + 0xc9: 0x2f507, // onclick + 0xca: 0x70407, // summary + 0xcd: 0xfb04, // ruby + 0xce: 0x56405, // class + 0xcf: 0x3f40b, // ondragstart + 0xd0: 0x23107, // caption + 0xd4: 0xdd0e, // allowusermedia + 0xd5: 0x4cf0b, // onloadstart + 0xd9: 0x16b03, // div + 0xda: 0x4a904, // list + 0xdb: 0x32e04, // math + 0xdc: 0x44b05, // input + 0xdf: 0x3ea0a, // ondragover + 0xe0: 0x2de02, // h2 + 0xe2: 0x1b209, // plaintext + 0xe4: 0x4f30c, // onmouseenter + 0xe7: 0x47907, // checked + 0xe8: 0x47003, // pre + 0xea: 0x35f08, // multiple + 0xeb: 0xba03, // bdi + 0xec: 0x33d09, // maxlength + 0xed: 0xcf01, // q + 0xee: 0x61f0a, // onauxclick + 0xf0: 0x57c03, // wbr + 0xf2: 0x3b04, // base + 0xf3: 0x6e306, // option + 0xf5: 0x41310, // ondurationchange + 0xf7: 0x8908, // noframes + 0xf9: 0x40508, // dropzone + 0xfb: 0x67505, // scope + 0xfc: 0x8008, // reversed + 0xfd: 0x3ba0b, // ondragenter + 0xfe: 0x3fa05, // start + 0xff: 0x12f03, // xmp + 0x100: 0x5f907, // srclang + 0x101: 0x30703, // img + 0x104: 0x101, // b + 0x105: 0x25403, // for + 0x106: 0x10705, // aside + 0x107: 0x44907, // oninput + 0x108: 0x35604, // area + 0x109: 0x2a40a, // formmethod + 0x10a: 0x72604, // wrap + 0x10c: 0x23c02, // rp + 0x10d: 0x46b0a, // onkeypress + 0x10e: 0x6802, // tt + 0x110: 0x34702, // mi + 0x111: 0x36705, // muted + 0x112: 0xf303, // alt + 0x113: 0x5c504, // code + 0x114: 0x6e02, // em + 0x115: 0x3c50a, // ondragexit + 0x117: 0x9f04, // span + 0x119: 0x6d708, // manifest + 0x11a: 0x38708, // menuitem + 0x11b: 0x58b07, // content + 0x11d: 0x6c109, // onwaiting + 0x11f: 0x4c609, // onloadend + 0x121: 0x37e0d, // oncontextmenu + 0x123: 0x56d06, // onblur + 0x124: 0x3fc07, // article + 0x125: 0x9303, // dir + 0x126: 0xef04, // ping + 0x127: 0x24c08, // required + 0x128: 0x45509, // oninvalid + 0x129: 0xb105, // align + 0x12b: 0x58a04, // icon + 0x12c: 0x64d02, // h6 + 0x12d: 0x1c404, // cols + 0x12e: 0x22e0a, // figcaption + 0x12f: 0x45e09, // onkeydown + 0x130: 0x66b08, // onsubmit + 0x131: 0x14d09, // oncanplay + 0x132: 0x70b03, // sup + 0x133: 0xc01, // p + 0x135: 0x40a09, // onemptied + 0x136: 0x39106, // oncopy + 0x137: 0x19c04, // cite + 0x138: 0x3a70a, // ondblclick + 0x13a: 0x50b0b, // onmousemove + 0x13c: 0x66d03, // sub + 0x13d: 0x48703, // rel + 0x13e: 0x5f08, // optgroup + 0x142: 0x9c07, // rowspan + 0x143: 0x37806, // source + 0x144: 0x21608, // noscript + 0x145: 0x1a304, // open + 0x146: 0x20403, // ins + 0x147: 0x2540d, // foreignObject + 0x148: 0x5ad0a, // onpopstate + 0x14a: 0x28d07, // enctype + 0x14b: 0x2760e, // onautocomplete + 0x14c: 0x35208, // textarea + 0x14e: 0x2780c, // autocomplete + 0x14f: 0x15702, // hr + 0x150: 0x1de08, // controls + 0x151: 0x10902, // id + 0x153: 0x2360c, // onafterprint + 0x155: 0x2610d, // foreignobject + 0x156: 0x32707, // marquee + 0x157: 0x59a07, // onpause + 0x158: 0x5e602, // dl + 0x159: 0x5206, // height + 0x15a: 0x34703, // min + 0x15b: 0x9307, // dirname + 0x15c: 0x1f209, // translate + 0x15d: 0x5604, // html + 0x15e: 0x34709, // minlength + 0x15f: 0x48607, // preload + 0x160: 0x71408, // template + 0x161: 0x3df0b, // ondragleave + 0x162: 0x3a02, // rb + 0x164: 0x5c003, // src + 0x165: 0x6dd06, // strong + 0x167: 0x7804, // samp + 0x168: 0x6f307, // address + 0x169: 0x55108, // ononline + 0x16b: 0x1310b, // placeholder + 0x16c: 0x2c406, // target + 0x16d: 0x20605, // small + 0x16e: 0x6ca07, // onwheel + 0x16f: 0x1c90a, // annotation + 0x170: 0x4740a, // spellcheck + 0x171: 0x7207, // details + 0x172: 0x10306, // canvas + 0x173: 0x12109, // autofocus + 0x174: 0xc05, // param + 0x176: 0x46308, // download + 0x177: 0x45203, // del + 0x178: 0x36c07, // onclose + 0x179: 0xb903, // kbd + 0x17a: 0x31906, // applet + 0x17b: 0x2e004, // href + 0x17c: 0x5f108, // onresize + 0x17e: 0x49d0c, // onloadeddata + 0x180: 0xcc02, // tr + 0x181: 0x2c00a, // formtarget + 0x182: 0x11005, // title + 0x183: 0x6ff05, // style + 0x184: 0xd206, // strike + 0x185: 0x59e06, // usemap + 0x186: 0x2fc06, // iframe + 0x187: 0x1004, // main + 0x189: 0x7b07, // picture + 0x18c: 0x31605, // ismap + 0x18e: 0x4a504, // data + 0x18f: 0x5905, // label + 0x191: 0x3d10e, // referrerpolicy + 0x192: 0x15602, // th + 0x194: 0x53606, // prompt + 0x195: 0x56807, // section + 0x197: 0x6d107, // optimum + 0x198: 0x2db04, // high + 0x199: 0x15c02, // h1 + 0x19a: 0x65909, // onstalled + 0x19b: 0x16d03, // var + 0x19c: 0x4204, // time + 0x19e: 0x67402, // ms + 0x19f: 0x33106, // header + 0x1a0: 0x4da09, // onmessage + 0x1a1: 0x1a605, // nonce + 0x1a2: 0x26e0a, // formaction + 0x1a3: 0x22006, // center + 0x1a4: 0x3704, // nobr + 0x1a5: 0x59505, // table + 0x1a6: 0x4a907, // listing + 0x1a7: 0x18106, // legend + 0x1a9: 0x29b09, // challenge + 0x1aa: 0x24806, // figure + 0x1ab: 0xe605, // media + 0x1ae: 0xd904, // type + 0x1af: 0x3f04, // font + 0x1b0: 0x4da0e, // onmessageerror + 0x1b1: 0x37108, // seamless + 0x1b2: 0x8703, // dfn + 0x1b3: 0x5c705, // defer + 0x1b4: 0xc303, // low + 0x1b5: 0x19a03, // rtc + 0x1b6: 0x5230b, // onmouseover + 0x1b7: 0x2b20a, // novalidate + 0x1b8: 0x71c0a, // workertype + 0x1ba: 0x3cd07, // itemref + 0x1bd: 0x1, // a + 0x1be: 0x31803, // map + 0x1bf: 0x400c, // ontimeupdate + 0x1c0: 0x15e07, // bgsound + 0x1c1: 0x3206, // keygen + 0x1c2: 0x2705, // tbody + 0x1c5: 0x64406, // onshow + 0x1c7: 0x2501, // s + 0x1c8: 0x6607, // pattern + 0x1cc: 0x14d10, // oncanplaythrough + 0x1ce: 0x2d702, // dd + 0x1cf: 0x6f906, // srcset + 0x1d0: 0x17003, // big + 0x1d2: 0x65108, // sortable + 0x1d3: 0x48007, // onkeyup + 0x1d5: 0x5a406, // onplay + 0x1d7: 0x4b804, // meta + 0x1d8: 0x40306, // ondrop + 0x1da: 0x60008, // onscroll + 0x1db: 0x1fb0b, // crossorigin + 0x1dc: 0x5730a, // onpageshow + 0x1dd: 0x4, // abbr + 0x1de: 0x9202, // td + 0x1df: 0x58b0f, // contenteditable + 0x1e0: 0x27206, // action + 0x1e1: 0x1400b, // playsinline + 0x1e2: 0x43107, // onfocus + 0x1e3: 0x2e008, // hreflang + 0x1e5: 0x5160a, // onmouseout + 0x1e6: 0x5ea07, // onreset + 0x1e7: 0x13c08, // autoplay + 0x1e8: 0x63109, // onseeking + 0x1ea: 0x67506, // scoped + 0x1ec: 0x30a, // radiogroup + 0x1ee: 0x3800b, // contextmenu + 0x1ef: 0x52e09, // onmouseup + 0x1f1: 0x2ca06, // hgroup + 0x1f2: 0x2080f, // allowfullscreen + 0x1f3: 0x4be08, // tabindex + 0x1f6: 0x30f07, // isindex + 0x1f7: 0x1a0e, // accept-charset + 0x1f8: 0x2ae0e, // formnovalidate + 0x1fb: 0x1c90e, // annotation-xml + 0x1fc: 0x6e05, // embed + 0x1fd: 0x21806, // script + 0x1fe: 0xbb06, // dialog + 0x1ff: 0x1d707, // command +} + +const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobrb" + + "asefontimeupdateviacacheightmlabelooptgroupatternoembedetail" + + "sampictureversedfnoframesetdirnameterowspanomoduleacronymali" + + "gnmarkbdialogallowpaymentrequestrikeytypeallowusermediagroup" + + "ingaltfooterubyasyncanvasidefaultitleaudioncancelautofocusan" + + "dboxmplaceholderautoplaysinlinebdoncanplaythrough1bgsoundisa" + + "bledivarbigblinkindraggablegendblockquotebuttonabortcitempro" + + "penoncecolgrouplaintextrackcolorcolspannotation-xmlcommandco" + + "ntrolshapecoordslotranslatecrossoriginsmallowfullscreenoscri" + + "ptfacenterfieldsetfigcaptionafterprintegrityfigurequiredfore" + + "ignObjectforeignobjectformactionautocompleteerrorformenctype" + + "mustmatchallengeformmethodformnovalidatetimeformtargethgroup" + + "osterhiddenhigh2hreflanghttp-equivideonclickiframeimageimgly" + + "ph3isindexismappletitemtypemarqueematheadersortedmaxlength4m" + + "inlength5mtextareadonlymultiplemutedoncloseamlessourceoncont" + + "extmenuitemidoncopyoncuechangeoncutondblclickondragendondrag" + + "enterondragexitemreferrerpolicyondragleaveondragoverondragst" + + "articleondropzonemptiedondurationchangeonendedonerroronfocus" + + "paceronhashchangeoninputmodeloninvalidonkeydownloadonkeypres" + + "spellcheckedonkeyupreloadonlanguagechangeonloadeddatalisting" + + "onloadedmetadatabindexonloadendonloadstartonmessageerroronmo" + + "usedownonmouseenteronmouseleaveonmousemoveonmouseoutputonmou" + + "seoveronmouseupromptonmousewheelonofflineononlineonpagehides" + + "classectionbluronpageshowbronpastepublicontenteditableonpaus" + + "emaponplayingonpopstateonprogressrcdocodeferonratechangeonre" + + "jectionhandledonresetonresizesrclangonscrollonsecuritypolicy" + + "violationauxclickonseekedonseekingonselectedonshowidth6onsor" + + "tableonstalledonstorageonsubmitemscopedonsuspendontoggleonun" + + "handledrejectionbeforeprintonunloadonvolumechangeonwaitingon" + + "wheeloptimumanifestrongoptionbeforeunloaddressrcsetstylesumm" + + "arysupsvgsystemplateworkertypewrap" diff --git a/vendor/golang.org/x/net/html/const.go b/vendor/golang.org/x/net/html/const.go new file mode 100644 index 00000000..a3a918f0 --- /dev/null +++ b/vendor/golang.org/x/net/html/const.go @@ -0,0 +1,112 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +// Section 12.2.4.2 of the HTML5 specification says "The following elements +// have varying levels of special parsing rules". +// https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements +var isSpecialElementMap = map[string]bool{ + "address": true, + "applet": true, + "area": true, + "article": true, + "aside": true, + "base": true, + "basefont": true, + "bgsound": true, + "blockquote": true, + "body": true, + "br": true, + "button": true, + "caption": true, + "center": true, + "col": true, + "colgroup": true, + "dd": true, + "details": true, + "dir": true, + "div": true, + "dl": true, + "dt": true, + "embed": true, + "fieldset": true, + "figcaption": true, + "figure": true, + "footer": true, + "form": true, + "frame": true, + "frameset": true, + "h1": true, + "h2": true, + "h3": true, + "h4": true, + "h5": true, + "h6": true, + "head": true, + "header": true, + "hgroup": true, + "hr": true, + "html": true, + "iframe": true, + "img": true, + "input": true, + "isindex": true, // The 'isindex' element has been removed, but keep it for backwards compatibility. + "keygen": true, + "li": true, + "link": true, + "listing": true, + "main": true, + "marquee": true, + "menu": true, + "meta": true, + "nav": true, + "noembed": true, + "noframes": true, + "noscript": true, + "object": true, + "ol": true, + "p": true, + "param": true, + "plaintext": true, + "pre": true, + "script": true, + "section": true, + "select": true, + "source": true, + "style": true, + "summary": true, + "table": true, + "tbody": true, + "td": true, + "template": true, + "textarea": true, + "tfoot": true, + "th": true, + "thead": true, + "title": true, + "tr": true, + "track": true, + "ul": true, + "wbr": true, + "xmp": true, +} + +func isSpecialElement(element *Node) bool { + switch element.Namespace { + case "", "html": + return isSpecialElementMap[element.Data] + case "math": + switch element.Data { + case "mi", "mo", "mn", "ms", "mtext", "annotation-xml": + return true + } + case "svg": + switch element.Data { + case "foreignObject", "desc", "title": + return true + } + } + return false +} diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go new file mode 100644 index 00000000..822ed42a --- /dev/null +++ b/vendor/golang.org/x/net/html/doc.go @@ -0,0 +1,106 @@ +// Copyright 2010 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 html implements an HTML5-compliant tokenizer and parser. + +Tokenization is done by creating a Tokenizer for an io.Reader r. It is the +caller's responsibility to ensure that r provides UTF-8 encoded HTML. + + z := html.NewTokenizer(r) + +Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(), +which parses the next token and returns its type, or an error: + + for { + tt := z.Next() + if tt == html.ErrorToken { + // ... + return ... + } + // Process the current token. + } + +There are two APIs for retrieving the current token. The high-level API is to +call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs +allow optionally calling Raw after Next but before Token, Text, TagName, or +TagAttr. In EBNF notation, the valid call sequence per token is: + + Next {Raw} [ Token | Text | TagName {TagAttr} ] + +Token returns an independent data structure that completely describes a token. +Entities (such as "<") are unescaped, tag names and attribute keys are +lower-cased, and attributes are collected into a []Attribute. For example: + + for { + if z.Next() == html.ErrorToken { + // Returning io.EOF indicates success. + return z.Err() + } + emitToken(z.Token()) + } + +The low-level API performs fewer allocations and copies, but the contents of +the []byte values returned by Text, TagName and TagAttr may change on the next +call to Next. For example, to extract an HTML page's anchor text: + + depth := 0 + for { + tt := z.Next() + switch tt { + case html.ErrorToken: + return z.Err() + case html.TextToken: + if depth > 0 { + // emitBytes should copy the []byte it receives, + // if it doesn't process it immediately. + emitBytes(z.Text()) + } + case html.StartTagToken, html.EndTagToken: + tn, _ := z.TagName() + if len(tn) == 1 && tn[0] == 'a' { + if tt == html.StartTagToken { + depth++ + } else { + depth-- + } + } + } + } + +Parsing is done by calling Parse with an io.Reader, which returns the root of +the parse tree (the document element) as a *Node. It is the caller's +responsibility to ensure that the Reader provides UTF-8 encoded HTML. For +example, to process each anchor node in depth-first order: + + doc, err := html.Parse(r) + if err != nil { + // ... + } + var f func(*html.Node) + f = func(n *html.Node) { + if n.Type == html.ElementNode && n.Data == "a" { + // Do something with n... + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + f(c) + } + } + f(doc) + +The relevant specifications include: +https://html.spec.whatwg.org/multipage/syntax.html and +https://html.spec.whatwg.org/multipage/syntax.html#tokenization +*/ +package html // import "golang.org/x/net/html" + +// The tokenization algorithm implemented by this package is not a line-by-line +// transliteration of the relatively verbose state-machine in the WHATWG +// specification. A more direct approach is used instead, where the program +// counter implies the state, such as whether it is tokenizing a tag or a text +// node. Specification compliance is verified by checking expected and actual +// outputs over a test suite rather than aiming for algorithmic fidelity. + +// TODO(nigeltao): Does a DOM API belong in this package or a separate one? +// TODO(nigeltao): How does parsing interact with a JavaScript engine? diff --git a/vendor/golang.org/x/net/html/doctype.go b/vendor/golang.org/x/net/html/doctype.go new file mode 100644 index 00000000..c484e5a9 --- /dev/null +++ b/vendor/golang.org/x/net/html/doctype.go @@ -0,0 +1,156 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +import ( + "strings" +) + +// parseDoctype parses the data from a DoctypeToken into a name, +// public identifier, and system identifier. It returns a Node whose Type +// is DoctypeNode, whose Data is the name, and which has attributes +// named "system" and "public" for the two identifiers if they were present. +// quirks is whether the document should be parsed in "quirks mode". +func parseDoctype(s string) (n *Node, quirks bool) { + n = &Node{Type: DoctypeNode} + + // Find the name. + space := strings.IndexAny(s, whitespace) + if space == -1 { + space = len(s) + } + n.Data = s[:space] + // The comparison to "html" is case-sensitive. + if n.Data != "html" { + quirks = true + } + n.Data = strings.ToLower(n.Data) + s = strings.TrimLeft(s[space:], whitespace) + + if len(s) < 6 { + // It can't start with "PUBLIC" or "SYSTEM". + // Ignore the rest of the string. + return n, quirks || s != "" + } + + key := strings.ToLower(s[:6]) + s = s[6:] + for key == "public" || key == "system" { + s = strings.TrimLeft(s, whitespace) + if s == "" { + break + } + quote := s[0] + if quote != '"' && quote != '\'' { + break + } + s = s[1:] + q := strings.IndexRune(s, rune(quote)) + var id string + if q == -1 { + id = s + s = "" + } else { + id = s[:q] + s = s[q+1:] + } + n.Attr = append(n.Attr, Attribute{Key: key, Val: id}) + if key == "public" { + key = "system" + } else { + key = "" + } + } + + if key != "" || s != "" { + quirks = true + } else if len(n.Attr) > 0 { + if n.Attr[0].Key == "public" { + public := strings.ToLower(n.Attr[0].Val) + switch public { + case "-//w3o//dtd w3 html strict 3.0//en//", "-/w3d/dtd html 4.0 transitional/en", "html": + quirks = true + default: + for _, q := range quirkyIDs { + if strings.HasPrefix(public, q) { + quirks = true + break + } + } + } + // The following two public IDs only cause quirks mode if there is no system ID. + if len(n.Attr) == 1 && (strings.HasPrefix(public, "-//w3c//dtd html 4.01 frameset//") || + strings.HasPrefix(public, "-//w3c//dtd html 4.01 transitional//")) { + quirks = true + } + } + if lastAttr := n.Attr[len(n.Attr)-1]; lastAttr.Key == "system" && + strings.ToLower(lastAttr.Val) == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" { + quirks = true + } + } + + return n, quirks +} + +// quirkyIDs is a list of public doctype identifiers that cause a document +// to be interpreted in quirks mode. The identifiers should be in lower case. +var quirkyIDs = []string{ + "+//silmaril//dtd html pro v0r11 19970101//", + "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", + "-//as//dtd html 3.0 aswedit + extensions//", + "-//ietf//dtd html 2.0 level 1//", + "-//ietf//dtd html 2.0 level 2//", + "-//ietf//dtd html 2.0 strict level 1//", + "-//ietf//dtd html 2.0 strict level 2//", + "-//ietf//dtd html 2.0 strict//", + "-//ietf//dtd html 2.0//", + "-//ietf//dtd html 2.1e//", + "-//ietf//dtd html 3.0//", + "-//ietf//dtd html 3.2 final//", + "-//ietf//dtd html 3.2//", + "-//ietf//dtd html 3//", + "-//ietf//dtd html level 0//", + "-//ietf//dtd html level 1//", + "-//ietf//dtd html level 2//", + "-//ietf//dtd html level 3//", + "-//ietf//dtd html strict level 0//", + "-//ietf//dtd html strict level 1//", + "-//ietf//dtd html strict level 2//", + "-//ietf//dtd html strict level 3//", + "-//ietf//dtd html strict//", + "-//ietf//dtd html//", + "-//metrius//dtd metrius presentational//", + "-//microsoft//dtd internet explorer 2.0 html strict//", + "-//microsoft//dtd internet explorer 2.0 html//", + "-//microsoft//dtd internet explorer 2.0 tables//", + "-//microsoft//dtd internet explorer 3.0 html strict//", + "-//microsoft//dtd internet explorer 3.0 html//", + "-//microsoft//dtd internet explorer 3.0 tables//", + "-//netscape comm. corp.//dtd html//", + "-//netscape comm. corp.//dtd strict html//", + "-//o'reilly and associates//dtd html 2.0//", + "-//o'reilly and associates//dtd html extended 1.0//", + "-//o'reilly and associates//dtd html extended relaxed 1.0//", + "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", + "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", + "-//spyglass//dtd html 2.0 extended//", + "-//sq//dtd html 2.0 hotmetal + extensions//", + "-//sun microsystems corp.//dtd hotjava html//", + "-//sun microsystems corp.//dtd hotjava strict html//", + "-//w3c//dtd html 3 1995-03-24//", + "-//w3c//dtd html 3.2 draft//", + "-//w3c//dtd html 3.2 final//", + "-//w3c//dtd html 3.2//", + "-//w3c//dtd html 3.2s draft//", + "-//w3c//dtd html 4.0 frameset//", + "-//w3c//dtd html 4.0 transitional//", + "-//w3c//dtd html experimental 19960712//", + "-//w3c//dtd html experimental 970421//", + "-//w3c//dtd w3 html//", + "-//w3o//dtd w3 html 3.0//", + "-//webtechs//dtd mozilla html 2.0//", + "-//webtechs//dtd mozilla html//", +} diff --git a/vendor/golang.org/x/net/html/entity.go b/vendor/golang.org/x/net/html/entity.go new file mode 100644 index 00000000..b628880a --- /dev/null +++ b/vendor/golang.org/x/net/html/entity.go @@ -0,0 +1,2253 @@ +// Copyright 2010 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 html + +// All entities that do not end with ';' are 6 or fewer bytes long. +const longestEntityWithoutSemicolon = 6 + +// entity is a map from HTML entity names to their values. The semicolon matters: +// https://html.spec.whatwg.org/multipage/syntax.html#named-character-references +// lists both "amp" and "amp;" as two separate entries. +// +// Note that the HTML5 list is larger than the HTML4 list at +// http://www.w3.org/TR/html4/sgml/entities.html +var entity = map[string]rune{ + "AElig;": '\U000000C6', + "AMP;": '\U00000026', + "Aacute;": '\U000000C1', + "Abreve;": '\U00000102', + "Acirc;": '\U000000C2', + "Acy;": '\U00000410', + "Afr;": '\U0001D504', + "Agrave;": '\U000000C0', + "Alpha;": '\U00000391', + "Amacr;": '\U00000100', + "And;": '\U00002A53', + "Aogon;": '\U00000104', + "Aopf;": '\U0001D538', + "ApplyFunction;": '\U00002061', + "Aring;": '\U000000C5', + "Ascr;": '\U0001D49C', + "Assign;": '\U00002254', + "Atilde;": '\U000000C3', + "Auml;": '\U000000C4', + "Backslash;": '\U00002216', + "Barv;": '\U00002AE7', + "Barwed;": '\U00002306', + "Bcy;": '\U00000411', + "Because;": '\U00002235', + "Bernoullis;": '\U0000212C', + "Beta;": '\U00000392', + "Bfr;": '\U0001D505', + "Bopf;": '\U0001D539', + "Breve;": '\U000002D8', + "Bscr;": '\U0000212C', + "Bumpeq;": '\U0000224E', + "CHcy;": '\U00000427', + "COPY;": '\U000000A9', + "Cacute;": '\U00000106', + "Cap;": '\U000022D2', + "CapitalDifferentialD;": '\U00002145', + "Cayleys;": '\U0000212D', + "Ccaron;": '\U0000010C', + "Ccedil;": '\U000000C7', + "Ccirc;": '\U00000108', + "Cconint;": '\U00002230', + "Cdot;": '\U0000010A', + "Cedilla;": '\U000000B8', + "CenterDot;": '\U000000B7', + "Cfr;": '\U0000212D', + "Chi;": '\U000003A7', + "CircleDot;": '\U00002299', + "CircleMinus;": '\U00002296', + "CirclePlus;": '\U00002295', + "CircleTimes;": '\U00002297', + "ClockwiseContourIntegral;": '\U00002232', + "CloseCurlyDoubleQuote;": '\U0000201D', + "CloseCurlyQuote;": '\U00002019', + "Colon;": '\U00002237', + "Colone;": '\U00002A74', + "Congruent;": '\U00002261', + "Conint;": '\U0000222F', + "ContourIntegral;": '\U0000222E', + "Copf;": '\U00002102', + "Coproduct;": '\U00002210', + "CounterClockwiseContourIntegral;": '\U00002233', + "Cross;": '\U00002A2F', + "Cscr;": '\U0001D49E', + "Cup;": '\U000022D3', + "CupCap;": '\U0000224D', + "DD;": '\U00002145', + "DDotrahd;": '\U00002911', + "DJcy;": '\U00000402', + "DScy;": '\U00000405', + "DZcy;": '\U0000040F', + "Dagger;": '\U00002021', + "Darr;": '\U000021A1', + "Dashv;": '\U00002AE4', + "Dcaron;": '\U0000010E', + "Dcy;": '\U00000414', + "Del;": '\U00002207', + "Delta;": '\U00000394', + "Dfr;": '\U0001D507', + "DiacriticalAcute;": '\U000000B4', + "DiacriticalDot;": '\U000002D9', + "DiacriticalDoubleAcute;": '\U000002DD', + "DiacriticalGrave;": '\U00000060', + "DiacriticalTilde;": '\U000002DC', + "Diamond;": '\U000022C4', + "DifferentialD;": '\U00002146', + "Dopf;": '\U0001D53B', + "Dot;": '\U000000A8', + "DotDot;": '\U000020DC', + "DotEqual;": '\U00002250', + "DoubleContourIntegral;": '\U0000222F', + "DoubleDot;": '\U000000A8', + "DoubleDownArrow;": '\U000021D3', + "DoubleLeftArrow;": '\U000021D0', + "DoubleLeftRightArrow;": '\U000021D4', + "DoubleLeftTee;": '\U00002AE4', + "DoubleLongLeftArrow;": '\U000027F8', + "DoubleLongLeftRightArrow;": '\U000027FA', + "DoubleLongRightArrow;": '\U000027F9', + "DoubleRightArrow;": '\U000021D2', + "DoubleRightTee;": '\U000022A8', + "DoubleUpArrow;": '\U000021D1', + "DoubleUpDownArrow;": '\U000021D5', + "DoubleVerticalBar;": '\U00002225', + "DownArrow;": '\U00002193', + "DownArrowBar;": '\U00002913', + "DownArrowUpArrow;": '\U000021F5', + "DownBreve;": '\U00000311', + "DownLeftRightVector;": '\U00002950', + "DownLeftTeeVector;": '\U0000295E', + "DownLeftVector;": '\U000021BD', + "DownLeftVectorBar;": '\U00002956', + "DownRightTeeVector;": '\U0000295F', + "DownRightVector;": '\U000021C1', + "DownRightVectorBar;": '\U00002957', + "DownTee;": '\U000022A4', + "DownTeeArrow;": '\U000021A7', + "Downarrow;": '\U000021D3', + "Dscr;": '\U0001D49F', + "Dstrok;": '\U00000110', + "ENG;": '\U0000014A', + "ETH;": '\U000000D0', + "Eacute;": '\U000000C9', + "Ecaron;": '\U0000011A', + "Ecirc;": '\U000000CA', + "Ecy;": '\U0000042D', + "Edot;": '\U00000116', + "Efr;": '\U0001D508', + "Egrave;": '\U000000C8', + "Element;": '\U00002208', + "Emacr;": '\U00000112', + "EmptySmallSquare;": '\U000025FB', + "EmptyVerySmallSquare;": '\U000025AB', + "Eogon;": '\U00000118', + "Eopf;": '\U0001D53C', + "Epsilon;": '\U00000395', + "Equal;": '\U00002A75', + "EqualTilde;": '\U00002242', + "Equilibrium;": '\U000021CC', + "Escr;": '\U00002130', + "Esim;": '\U00002A73', + "Eta;": '\U00000397', + "Euml;": '\U000000CB', + "Exists;": '\U00002203', + "ExponentialE;": '\U00002147', + "Fcy;": '\U00000424', + "Ffr;": '\U0001D509', + "FilledSmallSquare;": '\U000025FC', + "FilledVerySmallSquare;": '\U000025AA', + "Fopf;": '\U0001D53D', + "ForAll;": '\U00002200', + "Fouriertrf;": '\U00002131', + "Fscr;": '\U00002131', + "GJcy;": '\U00000403', + "GT;": '\U0000003E', + "Gamma;": '\U00000393', + "Gammad;": '\U000003DC', + "Gbreve;": '\U0000011E', + "Gcedil;": '\U00000122', + "Gcirc;": '\U0000011C', + "Gcy;": '\U00000413', + "Gdot;": '\U00000120', + "Gfr;": '\U0001D50A', + "Gg;": '\U000022D9', + "Gopf;": '\U0001D53E', + "GreaterEqual;": '\U00002265', + "GreaterEqualLess;": '\U000022DB', + "GreaterFullEqual;": '\U00002267', + "GreaterGreater;": '\U00002AA2', + "GreaterLess;": '\U00002277', + "GreaterSlantEqual;": '\U00002A7E', + "GreaterTilde;": '\U00002273', + "Gscr;": '\U0001D4A2', + "Gt;": '\U0000226B', + "HARDcy;": '\U0000042A', + "Hacek;": '\U000002C7', + "Hat;": '\U0000005E', + "Hcirc;": '\U00000124', + "Hfr;": '\U0000210C', + "HilbertSpace;": '\U0000210B', + "Hopf;": '\U0000210D', + "HorizontalLine;": '\U00002500', + "Hscr;": '\U0000210B', + "Hstrok;": '\U00000126', + "HumpDownHump;": '\U0000224E', + "HumpEqual;": '\U0000224F', + "IEcy;": '\U00000415', + "IJlig;": '\U00000132', + "IOcy;": '\U00000401', + "Iacute;": '\U000000CD', + "Icirc;": '\U000000CE', + "Icy;": '\U00000418', + "Idot;": '\U00000130', + "Ifr;": '\U00002111', + "Igrave;": '\U000000CC', + "Im;": '\U00002111', + "Imacr;": '\U0000012A', + "ImaginaryI;": '\U00002148', + "Implies;": '\U000021D2', + "Int;": '\U0000222C', + "Integral;": '\U0000222B', + "Intersection;": '\U000022C2', + "InvisibleComma;": '\U00002063', + "InvisibleTimes;": '\U00002062', + "Iogon;": '\U0000012E', + "Iopf;": '\U0001D540', + "Iota;": '\U00000399', + "Iscr;": '\U00002110', + "Itilde;": '\U00000128', + "Iukcy;": '\U00000406', + "Iuml;": '\U000000CF', + "Jcirc;": '\U00000134', + "Jcy;": '\U00000419', + "Jfr;": '\U0001D50D', + "Jopf;": '\U0001D541', + "Jscr;": '\U0001D4A5', + "Jsercy;": '\U00000408', + "Jukcy;": '\U00000404', + "KHcy;": '\U00000425', + "KJcy;": '\U0000040C', + "Kappa;": '\U0000039A', + "Kcedil;": '\U00000136', + "Kcy;": '\U0000041A', + "Kfr;": '\U0001D50E', + "Kopf;": '\U0001D542', + "Kscr;": '\U0001D4A6', + "LJcy;": '\U00000409', + "LT;": '\U0000003C', + "Lacute;": '\U00000139', + "Lambda;": '\U0000039B', + "Lang;": '\U000027EA', + "Laplacetrf;": '\U00002112', + "Larr;": '\U0000219E', + "Lcaron;": '\U0000013D', + "Lcedil;": '\U0000013B', + "Lcy;": '\U0000041B', + "LeftAngleBracket;": '\U000027E8', + "LeftArrow;": '\U00002190', + "LeftArrowBar;": '\U000021E4', + "LeftArrowRightArrow;": '\U000021C6', + "LeftCeiling;": '\U00002308', + "LeftDoubleBracket;": '\U000027E6', + "LeftDownTeeVector;": '\U00002961', + "LeftDownVector;": '\U000021C3', + "LeftDownVectorBar;": '\U00002959', + "LeftFloor;": '\U0000230A', + "LeftRightArrow;": '\U00002194', + "LeftRightVector;": '\U0000294E', + "LeftTee;": '\U000022A3', + "LeftTeeArrow;": '\U000021A4', + "LeftTeeVector;": '\U0000295A', + "LeftTriangle;": '\U000022B2', + "LeftTriangleBar;": '\U000029CF', + "LeftTriangleEqual;": '\U000022B4', + "LeftUpDownVector;": '\U00002951', + "LeftUpTeeVector;": '\U00002960', + "LeftUpVector;": '\U000021BF', + "LeftUpVectorBar;": '\U00002958', + "LeftVector;": '\U000021BC', + "LeftVectorBar;": '\U00002952', + "Leftarrow;": '\U000021D0', + "Leftrightarrow;": '\U000021D4', + "LessEqualGreater;": '\U000022DA', + "LessFullEqual;": '\U00002266', + "LessGreater;": '\U00002276', + "LessLess;": '\U00002AA1', + "LessSlantEqual;": '\U00002A7D', + "LessTilde;": '\U00002272', + "Lfr;": '\U0001D50F', + "Ll;": '\U000022D8', + "Lleftarrow;": '\U000021DA', + "Lmidot;": '\U0000013F', + "LongLeftArrow;": '\U000027F5', + "LongLeftRightArrow;": '\U000027F7', + "LongRightArrow;": '\U000027F6', + "Longleftarrow;": '\U000027F8', + "Longleftrightarrow;": '\U000027FA', + "Longrightarrow;": '\U000027F9', + "Lopf;": '\U0001D543', + "LowerLeftArrow;": '\U00002199', + "LowerRightArrow;": '\U00002198', + "Lscr;": '\U00002112', + "Lsh;": '\U000021B0', + "Lstrok;": '\U00000141', + "Lt;": '\U0000226A', + "Map;": '\U00002905', + "Mcy;": '\U0000041C', + "MediumSpace;": '\U0000205F', + "Mellintrf;": '\U00002133', + "Mfr;": '\U0001D510', + "MinusPlus;": '\U00002213', + "Mopf;": '\U0001D544', + "Mscr;": '\U00002133', + "Mu;": '\U0000039C', + "NJcy;": '\U0000040A', + "Nacute;": '\U00000143', + "Ncaron;": '\U00000147', + "Ncedil;": '\U00000145', + "Ncy;": '\U0000041D', + "NegativeMediumSpace;": '\U0000200B', + "NegativeThickSpace;": '\U0000200B', + "NegativeThinSpace;": '\U0000200B', + "NegativeVeryThinSpace;": '\U0000200B', + "NestedGreaterGreater;": '\U0000226B', + "NestedLessLess;": '\U0000226A', + "NewLine;": '\U0000000A', + "Nfr;": '\U0001D511', + "NoBreak;": '\U00002060', + "NonBreakingSpace;": '\U000000A0', + "Nopf;": '\U00002115', + "Not;": '\U00002AEC', + "NotCongruent;": '\U00002262', + "NotCupCap;": '\U0000226D', + "NotDoubleVerticalBar;": '\U00002226', + "NotElement;": '\U00002209', + "NotEqual;": '\U00002260', + "NotExists;": '\U00002204', + "NotGreater;": '\U0000226F', + "NotGreaterEqual;": '\U00002271', + "NotGreaterLess;": '\U00002279', + "NotGreaterTilde;": '\U00002275', + "NotLeftTriangle;": '\U000022EA', + "NotLeftTriangleEqual;": '\U000022EC', + "NotLess;": '\U0000226E', + "NotLessEqual;": '\U00002270', + "NotLessGreater;": '\U00002278', + "NotLessTilde;": '\U00002274', + "NotPrecedes;": '\U00002280', + "NotPrecedesSlantEqual;": '\U000022E0', + "NotReverseElement;": '\U0000220C', + "NotRightTriangle;": '\U000022EB', + "NotRightTriangleEqual;": '\U000022ED', + "NotSquareSubsetEqual;": '\U000022E2', + "NotSquareSupersetEqual;": '\U000022E3', + "NotSubsetEqual;": '\U00002288', + "NotSucceeds;": '\U00002281', + "NotSucceedsSlantEqual;": '\U000022E1', + "NotSupersetEqual;": '\U00002289', + "NotTilde;": '\U00002241', + "NotTildeEqual;": '\U00002244', + "NotTildeFullEqual;": '\U00002247', + "NotTildeTilde;": '\U00002249', + "NotVerticalBar;": '\U00002224', + "Nscr;": '\U0001D4A9', + "Ntilde;": '\U000000D1', + "Nu;": '\U0000039D', + "OElig;": '\U00000152', + "Oacute;": '\U000000D3', + "Ocirc;": '\U000000D4', + "Ocy;": '\U0000041E', + "Odblac;": '\U00000150', + "Ofr;": '\U0001D512', + "Ograve;": '\U000000D2', + "Omacr;": '\U0000014C', + "Omega;": '\U000003A9', + "Omicron;": '\U0000039F', + "Oopf;": '\U0001D546', + "OpenCurlyDoubleQuote;": '\U0000201C', + "OpenCurlyQuote;": '\U00002018', + "Or;": '\U00002A54', + "Oscr;": '\U0001D4AA', + "Oslash;": '\U000000D8', + "Otilde;": '\U000000D5', + "Otimes;": '\U00002A37', + "Ouml;": '\U000000D6', + "OverBar;": '\U0000203E', + "OverBrace;": '\U000023DE', + "OverBracket;": '\U000023B4', + "OverParenthesis;": '\U000023DC', + "PartialD;": '\U00002202', + "Pcy;": '\U0000041F', + "Pfr;": '\U0001D513', + "Phi;": '\U000003A6', + "Pi;": '\U000003A0', + "PlusMinus;": '\U000000B1', + "Poincareplane;": '\U0000210C', + "Popf;": '\U00002119', + "Pr;": '\U00002ABB', + "Precedes;": '\U0000227A', + "PrecedesEqual;": '\U00002AAF', + "PrecedesSlantEqual;": '\U0000227C', + "PrecedesTilde;": '\U0000227E', + "Prime;": '\U00002033', + "Product;": '\U0000220F', + "Proportion;": '\U00002237', + "Proportional;": '\U0000221D', + "Pscr;": '\U0001D4AB', + "Psi;": '\U000003A8', + "QUOT;": '\U00000022', + "Qfr;": '\U0001D514', + "Qopf;": '\U0000211A', + "Qscr;": '\U0001D4AC', + "RBarr;": '\U00002910', + "REG;": '\U000000AE', + "Racute;": '\U00000154', + "Rang;": '\U000027EB', + "Rarr;": '\U000021A0', + "Rarrtl;": '\U00002916', + "Rcaron;": '\U00000158', + "Rcedil;": '\U00000156', + "Rcy;": '\U00000420', + "Re;": '\U0000211C', + "ReverseElement;": '\U0000220B', + "ReverseEquilibrium;": '\U000021CB', + "ReverseUpEquilibrium;": '\U0000296F', + "Rfr;": '\U0000211C', + "Rho;": '\U000003A1', + "RightAngleBracket;": '\U000027E9', + "RightArrow;": '\U00002192', + "RightArrowBar;": '\U000021E5', + "RightArrowLeftArrow;": '\U000021C4', + "RightCeiling;": '\U00002309', + "RightDoubleBracket;": '\U000027E7', + "RightDownTeeVector;": '\U0000295D', + "RightDownVector;": '\U000021C2', + "RightDownVectorBar;": '\U00002955', + "RightFloor;": '\U0000230B', + "RightTee;": '\U000022A2', + "RightTeeArrow;": '\U000021A6', + "RightTeeVector;": '\U0000295B', + "RightTriangle;": '\U000022B3', + "RightTriangleBar;": '\U000029D0', + "RightTriangleEqual;": '\U000022B5', + "RightUpDownVector;": '\U0000294F', + "RightUpTeeVector;": '\U0000295C', + "RightUpVector;": '\U000021BE', + "RightUpVectorBar;": '\U00002954', + "RightVector;": '\U000021C0', + "RightVectorBar;": '\U00002953', + "Rightarrow;": '\U000021D2', + "Ropf;": '\U0000211D', + "RoundImplies;": '\U00002970', + "Rrightarrow;": '\U000021DB', + "Rscr;": '\U0000211B', + "Rsh;": '\U000021B1', + "RuleDelayed;": '\U000029F4', + "SHCHcy;": '\U00000429', + "SHcy;": '\U00000428', + "SOFTcy;": '\U0000042C', + "Sacute;": '\U0000015A', + "Sc;": '\U00002ABC', + "Scaron;": '\U00000160', + "Scedil;": '\U0000015E', + "Scirc;": '\U0000015C', + "Scy;": '\U00000421', + "Sfr;": '\U0001D516', + "ShortDownArrow;": '\U00002193', + "ShortLeftArrow;": '\U00002190', + "ShortRightArrow;": '\U00002192', + "ShortUpArrow;": '\U00002191', + "Sigma;": '\U000003A3', + "SmallCircle;": '\U00002218', + "Sopf;": '\U0001D54A', + "Sqrt;": '\U0000221A', + "Square;": '\U000025A1', + "SquareIntersection;": '\U00002293', + "SquareSubset;": '\U0000228F', + "SquareSubsetEqual;": '\U00002291', + "SquareSuperset;": '\U00002290', + "SquareSupersetEqual;": '\U00002292', + "SquareUnion;": '\U00002294', + "Sscr;": '\U0001D4AE', + "Star;": '\U000022C6', + "Sub;": '\U000022D0', + "Subset;": '\U000022D0', + "SubsetEqual;": '\U00002286', + "Succeeds;": '\U0000227B', + "SucceedsEqual;": '\U00002AB0', + "SucceedsSlantEqual;": '\U0000227D', + "SucceedsTilde;": '\U0000227F', + "SuchThat;": '\U0000220B', + "Sum;": '\U00002211', + "Sup;": '\U000022D1', + "Superset;": '\U00002283', + "SupersetEqual;": '\U00002287', + "Supset;": '\U000022D1', + "THORN;": '\U000000DE', + "TRADE;": '\U00002122', + "TSHcy;": '\U0000040B', + "TScy;": '\U00000426', + "Tab;": '\U00000009', + "Tau;": '\U000003A4', + "Tcaron;": '\U00000164', + "Tcedil;": '\U00000162', + "Tcy;": '\U00000422', + "Tfr;": '\U0001D517', + "Therefore;": '\U00002234', + "Theta;": '\U00000398', + "ThinSpace;": '\U00002009', + "Tilde;": '\U0000223C', + "TildeEqual;": '\U00002243', + "TildeFullEqual;": '\U00002245', + "TildeTilde;": '\U00002248', + "Topf;": '\U0001D54B', + "TripleDot;": '\U000020DB', + "Tscr;": '\U0001D4AF', + "Tstrok;": '\U00000166', + "Uacute;": '\U000000DA', + "Uarr;": '\U0000219F', + "Uarrocir;": '\U00002949', + "Ubrcy;": '\U0000040E', + "Ubreve;": '\U0000016C', + "Ucirc;": '\U000000DB', + "Ucy;": '\U00000423', + "Udblac;": '\U00000170', + "Ufr;": '\U0001D518', + "Ugrave;": '\U000000D9', + "Umacr;": '\U0000016A', + "UnderBar;": '\U0000005F', + "UnderBrace;": '\U000023DF', + "UnderBracket;": '\U000023B5', + "UnderParenthesis;": '\U000023DD', + "Union;": '\U000022C3', + "UnionPlus;": '\U0000228E', + "Uogon;": '\U00000172', + "Uopf;": '\U0001D54C', + "UpArrow;": '\U00002191', + "UpArrowBar;": '\U00002912', + "UpArrowDownArrow;": '\U000021C5', + "UpDownArrow;": '\U00002195', + "UpEquilibrium;": '\U0000296E', + "UpTee;": '\U000022A5', + "UpTeeArrow;": '\U000021A5', + "Uparrow;": '\U000021D1', + "Updownarrow;": '\U000021D5', + "UpperLeftArrow;": '\U00002196', + "UpperRightArrow;": '\U00002197', + "Upsi;": '\U000003D2', + "Upsilon;": '\U000003A5', + "Uring;": '\U0000016E', + "Uscr;": '\U0001D4B0', + "Utilde;": '\U00000168', + "Uuml;": '\U000000DC', + "VDash;": '\U000022AB', + "Vbar;": '\U00002AEB', + "Vcy;": '\U00000412', + "Vdash;": '\U000022A9', + "Vdashl;": '\U00002AE6', + "Vee;": '\U000022C1', + "Verbar;": '\U00002016', + "Vert;": '\U00002016', + "VerticalBar;": '\U00002223', + "VerticalLine;": '\U0000007C', + "VerticalSeparator;": '\U00002758', + "VerticalTilde;": '\U00002240', + "VeryThinSpace;": '\U0000200A', + "Vfr;": '\U0001D519', + "Vopf;": '\U0001D54D', + "Vscr;": '\U0001D4B1', + "Vvdash;": '\U000022AA', + "Wcirc;": '\U00000174', + "Wedge;": '\U000022C0', + "Wfr;": '\U0001D51A', + "Wopf;": '\U0001D54E', + "Wscr;": '\U0001D4B2', + "Xfr;": '\U0001D51B', + "Xi;": '\U0000039E', + "Xopf;": '\U0001D54F', + "Xscr;": '\U0001D4B3', + "YAcy;": '\U0000042F', + "YIcy;": '\U00000407', + "YUcy;": '\U0000042E', + "Yacute;": '\U000000DD', + "Ycirc;": '\U00000176', + "Ycy;": '\U0000042B', + "Yfr;": '\U0001D51C', + "Yopf;": '\U0001D550', + "Yscr;": '\U0001D4B4', + "Yuml;": '\U00000178', + "ZHcy;": '\U00000416', + "Zacute;": '\U00000179', + "Zcaron;": '\U0000017D', + "Zcy;": '\U00000417', + "Zdot;": '\U0000017B', + "ZeroWidthSpace;": '\U0000200B', + "Zeta;": '\U00000396', + "Zfr;": '\U00002128', + "Zopf;": '\U00002124', + "Zscr;": '\U0001D4B5', + "aacute;": '\U000000E1', + "abreve;": '\U00000103', + "ac;": '\U0000223E', + "acd;": '\U0000223F', + "acirc;": '\U000000E2', + "acute;": '\U000000B4', + "acy;": '\U00000430', + "aelig;": '\U000000E6', + "af;": '\U00002061', + "afr;": '\U0001D51E', + "agrave;": '\U000000E0', + "alefsym;": '\U00002135', + "aleph;": '\U00002135', + "alpha;": '\U000003B1', + "amacr;": '\U00000101', + "amalg;": '\U00002A3F', + "amp;": '\U00000026', + "and;": '\U00002227', + "andand;": '\U00002A55', + "andd;": '\U00002A5C', + "andslope;": '\U00002A58', + "andv;": '\U00002A5A', + "ang;": '\U00002220', + "ange;": '\U000029A4', + "angle;": '\U00002220', + "angmsd;": '\U00002221', + "angmsdaa;": '\U000029A8', + "angmsdab;": '\U000029A9', + "angmsdac;": '\U000029AA', + "angmsdad;": '\U000029AB', + "angmsdae;": '\U000029AC', + "angmsdaf;": '\U000029AD', + "angmsdag;": '\U000029AE', + "angmsdah;": '\U000029AF', + "angrt;": '\U0000221F', + "angrtvb;": '\U000022BE', + "angrtvbd;": '\U0000299D', + "angsph;": '\U00002222', + "angst;": '\U000000C5', + "angzarr;": '\U0000237C', + "aogon;": '\U00000105', + "aopf;": '\U0001D552', + "ap;": '\U00002248', + "apE;": '\U00002A70', + "apacir;": '\U00002A6F', + "ape;": '\U0000224A', + "apid;": '\U0000224B', + "apos;": '\U00000027', + "approx;": '\U00002248', + "approxeq;": '\U0000224A', + "aring;": '\U000000E5', + "ascr;": '\U0001D4B6', + "ast;": '\U0000002A', + "asymp;": '\U00002248', + "asympeq;": '\U0000224D', + "atilde;": '\U000000E3', + "auml;": '\U000000E4', + "awconint;": '\U00002233', + "awint;": '\U00002A11', + "bNot;": '\U00002AED', + "backcong;": '\U0000224C', + "backepsilon;": '\U000003F6', + "backprime;": '\U00002035', + "backsim;": '\U0000223D', + "backsimeq;": '\U000022CD', + "barvee;": '\U000022BD', + "barwed;": '\U00002305', + "barwedge;": '\U00002305', + "bbrk;": '\U000023B5', + "bbrktbrk;": '\U000023B6', + "bcong;": '\U0000224C', + "bcy;": '\U00000431', + "bdquo;": '\U0000201E', + "becaus;": '\U00002235', + "because;": '\U00002235', + "bemptyv;": '\U000029B0', + "bepsi;": '\U000003F6', + "bernou;": '\U0000212C', + "beta;": '\U000003B2', + "beth;": '\U00002136', + "between;": '\U0000226C', + "bfr;": '\U0001D51F', + "bigcap;": '\U000022C2', + "bigcirc;": '\U000025EF', + "bigcup;": '\U000022C3', + "bigodot;": '\U00002A00', + "bigoplus;": '\U00002A01', + "bigotimes;": '\U00002A02', + "bigsqcup;": '\U00002A06', + "bigstar;": '\U00002605', + "bigtriangledown;": '\U000025BD', + "bigtriangleup;": '\U000025B3', + "biguplus;": '\U00002A04', + "bigvee;": '\U000022C1', + "bigwedge;": '\U000022C0', + "bkarow;": '\U0000290D', + "blacklozenge;": '\U000029EB', + "blacksquare;": '\U000025AA', + "blacktriangle;": '\U000025B4', + "blacktriangledown;": '\U000025BE', + "blacktriangleleft;": '\U000025C2', + "blacktriangleright;": '\U000025B8', + "blank;": '\U00002423', + "blk12;": '\U00002592', + "blk14;": '\U00002591', + "blk34;": '\U00002593', + "block;": '\U00002588', + "bnot;": '\U00002310', + "bopf;": '\U0001D553', + "bot;": '\U000022A5', + "bottom;": '\U000022A5', + "bowtie;": '\U000022C8', + "boxDL;": '\U00002557', + "boxDR;": '\U00002554', + "boxDl;": '\U00002556', + "boxDr;": '\U00002553', + "boxH;": '\U00002550', + "boxHD;": '\U00002566', + "boxHU;": '\U00002569', + "boxHd;": '\U00002564', + "boxHu;": '\U00002567', + "boxUL;": '\U0000255D', + "boxUR;": '\U0000255A', + "boxUl;": '\U0000255C', + "boxUr;": '\U00002559', + "boxV;": '\U00002551', + "boxVH;": '\U0000256C', + "boxVL;": '\U00002563', + "boxVR;": '\U00002560', + "boxVh;": '\U0000256B', + "boxVl;": '\U00002562', + "boxVr;": '\U0000255F', + "boxbox;": '\U000029C9', + "boxdL;": '\U00002555', + "boxdR;": '\U00002552', + "boxdl;": '\U00002510', + "boxdr;": '\U0000250C', + "boxh;": '\U00002500', + "boxhD;": '\U00002565', + "boxhU;": '\U00002568', + "boxhd;": '\U0000252C', + "boxhu;": '\U00002534', + "boxminus;": '\U0000229F', + "boxplus;": '\U0000229E', + "boxtimes;": '\U000022A0', + "boxuL;": '\U0000255B', + "boxuR;": '\U00002558', + "boxul;": '\U00002518', + "boxur;": '\U00002514', + "boxv;": '\U00002502', + "boxvH;": '\U0000256A', + "boxvL;": '\U00002561', + "boxvR;": '\U0000255E', + "boxvh;": '\U0000253C', + "boxvl;": '\U00002524', + "boxvr;": '\U0000251C', + "bprime;": '\U00002035', + "breve;": '\U000002D8', + "brvbar;": '\U000000A6', + "bscr;": '\U0001D4B7', + "bsemi;": '\U0000204F', + "bsim;": '\U0000223D', + "bsime;": '\U000022CD', + "bsol;": '\U0000005C', + "bsolb;": '\U000029C5', + "bsolhsub;": '\U000027C8', + "bull;": '\U00002022', + "bullet;": '\U00002022', + "bump;": '\U0000224E', + "bumpE;": '\U00002AAE', + "bumpe;": '\U0000224F', + "bumpeq;": '\U0000224F', + "cacute;": '\U00000107', + "cap;": '\U00002229', + "capand;": '\U00002A44', + "capbrcup;": '\U00002A49', + "capcap;": '\U00002A4B', + "capcup;": '\U00002A47', + "capdot;": '\U00002A40', + "caret;": '\U00002041', + "caron;": '\U000002C7', + "ccaps;": '\U00002A4D', + "ccaron;": '\U0000010D', + "ccedil;": '\U000000E7', + "ccirc;": '\U00000109', + "ccups;": '\U00002A4C', + "ccupssm;": '\U00002A50', + "cdot;": '\U0000010B', + "cedil;": '\U000000B8', + "cemptyv;": '\U000029B2', + "cent;": '\U000000A2', + "centerdot;": '\U000000B7', + "cfr;": '\U0001D520', + "chcy;": '\U00000447', + "check;": '\U00002713', + "checkmark;": '\U00002713', + "chi;": '\U000003C7', + "cir;": '\U000025CB', + "cirE;": '\U000029C3', + "circ;": '\U000002C6', + "circeq;": '\U00002257', + "circlearrowleft;": '\U000021BA', + "circlearrowright;": '\U000021BB', + "circledR;": '\U000000AE', + "circledS;": '\U000024C8', + "circledast;": '\U0000229B', + "circledcirc;": '\U0000229A', + "circleddash;": '\U0000229D', + "cire;": '\U00002257', + "cirfnint;": '\U00002A10', + "cirmid;": '\U00002AEF', + "cirscir;": '\U000029C2', + "clubs;": '\U00002663', + "clubsuit;": '\U00002663', + "colon;": '\U0000003A', + "colone;": '\U00002254', + "coloneq;": '\U00002254', + "comma;": '\U0000002C', + "commat;": '\U00000040', + "comp;": '\U00002201', + "compfn;": '\U00002218', + "complement;": '\U00002201', + "complexes;": '\U00002102', + "cong;": '\U00002245', + "congdot;": '\U00002A6D', + "conint;": '\U0000222E', + "copf;": '\U0001D554', + "coprod;": '\U00002210', + "copy;": '\U000000A9', + "copysr;": '\U00002117', + "crarr;": '\U000021B5', + "cross;": '\U00002717', + "cscr;": '\U0001D4B8', + "csub;": '\U00002ACF', + "csube;": '\U00002AD1', + "csup;": '\U00002AD0', + "csupe;": '\U00002AD2', + "ctdot;": '\U000022EF', + "cudarrl;": '\U00002938', + "cudarrr;": '\U00002935', + "cuepr;": '\U000022DE', + "cuesc;": '\U000022DF', + "cularr;": '\U000021B6', + "cularrp;": '\U0000293D', + "cup;": '\U0000222A', + "cupbrcap;": '\U00002A48', + "cupcap;": '\U00002A46', + "cupcup;": '\U00002A4A', + "cupdot;": '\U0000228D', + "cupor;": '\U00002A45', + "curarr;": '\U000021B7', + "curarrm;": '\U0000293C', + "curlyeqprec;": '\U000022DE', + "curlyeqsucc;": '\U000022DF', + "curlyvee;": '\U000022CE', + "curlywedge;": '\U000022CF', + "curren;": '\U000000A4', + "curvearrowleft;": '\U000021B6', + "curvearrowright;": '\U000021B7', + "cuvee;": '\U000022CE', + "cuwed;": '\U000022CF', + "cwconint;": '\U00002232', + "cwint;": '\U00002231', + "cylcty;": '\U0000232D', + "dArr;": '\U000021D3', + "dHar;": '\U00002965', + "dagger;": '\U00002020', + "daleth;": '\U00002138', + "darr;": '\U00002193', + "dash;": '\U00002010', + "dashv;": '\U000022A3', + "dbkarow;": '\U0000290F', + "dblac;": '\U000002DD', + "dcaron;": '\U0000010F', + "dcy;": '\U00000434', + "dd;": '\U00002146', + "ddagger;": '\U00002021', + "ddarr;": '\U000021CA', + "ddotseq;": '\U00002A77', + "deg;": '\U000000B0', + "delta;": '\U000003B4', + "demptyv;": '\U000029B1', + "dfisht;": '\U0000297F', + "dfr;": '\U0001D521', + "dharl;": '\U000021C3', + "dharr;": '\U000021C2', + "diam;": '\U000022C4', + "diamond;": '\U000022C4', + "diamondsuit;": '\U00002666', + "diams;": '\U00002666', + "die;": '\U000000A8', + "digamma;": '\U000003DD', + "disin;": '\U000022F2', + "div;": '\U000000F7', + "divide;": '\U000000F7', + "divideontimes;": '\U000022C7', + "divonx;": '\U000022C7', + "djcy;": '\U00000452', + "dlcorn;": '\U0000231E', + "dlcrop;": '\U0000230D', + "dollar;": '\U00000024', + "dopf;": '\U0001D555', + "dot;": '\U000002D9', + "doteq;": '\U00002250', + "doteqdot;": '\U00002251', + "dotminus;": '\U00002238', + "dotplus;": '\U00002214', + "dotsquare;": '\U000022A1', + "doublebarwedge;": '\U00002306', + "downarrow;": '\U00002193', + "downdownarrows;": '\U000021CA', + "downharpoonleft;": '\U000021C3', + "downharpoonright;": '\U000021C2', + "drbkarow;": '\U00002910', + "drcorn;": '\U0000231F', + "drcrop;": '\U0000230C', + "dscr;": '\U0001D4B9', + "dscy;": '\U00000455', + "dsol;": '\U000029F6', + "dstrok;": '\U00000111', + "dtdot;": '\U000022F1', + "dtri;": '\U000025BF', + "dtrif;": '\U000025BE', + "duarr;": '\U000021F5', + "duhar;": '\U0000296F', + "dwangle;": '\U000029A6', + "dzcy;": '\U0000045F', + "dzigrarr;": '\U000027FF', + "eDDot;": '\U00002A77', + "eDot;": '\U00002251', + "eacute;": '\U000000E9', + "easter;": '\U00002A6E', + "ecaron;": '\U0000011B', + "ecir;": '\U00002256', + "ecirc;": '\U000000EA', + "ecolon;": '\U00002255', + "ecy;": '\U0000044D', + "edot;": '\U00000117', + "ee;": '\U00002147', + "efDot;": '\U00002252', + "efr;": '\U0001D522', + "eg;": '\U00002A9A', + "egrave;": '\U000000E8', + "egs;": '\U00002A96', + "egsdot;": '\U00002A98', + "el;": '\U00002A99', + "elinters;": '\U000023E7', + "ell;": '\U00002113', + "els;": '\U00002A95', + "elsdot;": '\U00002A97', + "emacr;": '\U00000113', + "empty;": '\U00002205', + "emptyset;": '\U00002205', + "emptyv;": '\U00002205', + "emsp;": '\U00002003', + "emsp13;": '\U00002004', + "emsp14;": '\U00002005', + "eng;": '\U0000014B', + "ensp;": '\U00002002', + "eogon;": '\U00000119', + "eopf;": '\U0001D556', + "epar;": '\U000022D5', + "eparsl;": '\U000029E3', + "eplus;": '\U00002A71', + "epsi;": '\U000003B5', + "epsilon;": '\U000003B5', + "epsiv;": '\U000003F5', + "eqcirc;": '\U00002256', + "eqcolon;": '\U00002255', + "eqsim;": '\U00002242', + "eqslantgtr;": '\U00002A96', + "eqslantless;": '\U00002A95', + "equals;": '\U0000003D', + "equest;": '\U0000225F', + "equiv;": '\U00002261', + "equivDD;": '\U00002A78', + "eqvparsl;": '\U000029E5', + "erDot;": '\U00002253', + "erarr;": '\U00002971', + "escr;": '\U0000212F', + "esdot;": '\U00002250', + "esim;": '\U00002242', + "eta;": '\U000003B7', + "eth;": '\U000000F0', + "euml;": '\U000000EB', + "euro;": '\U000020AC', + "excl;": '\U00000021', + "exist;": '\U00002203', + "expectation;": '\U00002130', + "exponentiale;": '\U00002147', + "fallingdotseq;": '\U00002252', + "fcy;": '\U00000444', + "female;": '\U00002640', + "ffilig;": '\U0000FB03', + "fflig;": '\U0000FB00', + "ffllig;": '\U0000FB04', + "ffr;": '\U0001D523', + "filig;": '\U0000FB01', + "flat;": '\U0000266D', + "fllig;": '\U0000FB02', + "fltns;": '\U000025B1', + "fnof;": '\U00000192', + "fopf;": '\U0001D557', + "forall;": '\U00002200', + "fork;": '\U000022D4', + "forkv;": '\U00002AD9', + "fpartint;": '\U00002A0D', + "frac12;": '\U000000BD', + "frac13;": '\U00002153', + "frac14;": '\U000000BC', + "frac15;": '\U00002155', + "frac16;": '\U00002159', + "frac18;": '\U0000215B', + "frac23;": '\U00002154', + "frac25;": '\U00002156', + "frac34;": '\U000000BE', + "frac35;": '\U00002157', + "frac38;": '\U0000215C', + "frac45;": '\U00002158', + "frac56;": '\U0000215A', + "frac58;": '\U0000215D', + "frac78;": '\U0000215E', + "frasl;": '\U00002044', + "frown;": '\U00002322', + "fscr;": '\U0001D4BB', + "gE;": '\U00002267', + "gEl;": '\U00002A8C', + "gacute;": '\U000001F5', + "gamma;": '\U000003B3', + "gammad;": '\U000003DD', + "gap;": '\U00002A86', + "gbreve;": '\U0000011F', + "gcirc;": '\U0000011D', + "gcy;": '\U00000433', + "gdot;": '\U00000121', + "ge;": '\U00002265', + "gel;": '\U000022DB', + "geq;": '\U00002265', + "geqq;": '\U00002267', + "geqslant;": '\U00002A7E', + "ges;": '\U00002A7E', + "gescc;": '\U00002AA9', + "gesdot;": '\U00002A80', + "gesdoto;": '\U00002A82', + "gesdotol;": '\U00002A84', + "gesles;": '\U00002A94', + "gfr;": '\U0001D524', + "gg;": '\U0000226B', + "ggg;": '\U000022D9', + "gimel;": '\U00002137', + "gjcy;": '\U00000453', + "gl;": '\U00002277', + "glE;": '\U00002A92', + "gla;": '\U00002AA5', + "glj;": '\U00002AA4', + "gnE;": '\U00002269', + "gnap;": '\U00002A8A', + "gnapprox;": '\U00002A8A', + "gne;": '\U00002A88', + "gneq;": '\U00002A88', + "gneqq;": '\U00002269', + "gnsim;": '\U000022E7', + "gopf;": '\U0001D558', + "grave;": '\U00000060', + "gscr;": '\U0000210A', + "gsim;": '\U00002273', + "gsime;": '\U00002A8E', + "gsiml;": '\U00002A90', + "gt;": '\U0000003E', + "gtcc;": '\U00002AA7', + "gtcir;": '\U00002A7A', + "gtdot;": '\U000022D7', + "gtlPar;": '\U00002995', + "gtquest;": '\U00002A7C', + "gtrapprox;": '\U00002A86', + "gtrarr;": '\U00002978', + "gtrdot;": '\U000022D7', + "gtreqless;": '\U000022DB', + "gtreqqless;": '\U00002A8C', + "gtrless;": '\U00002277', + "gtrsim;": '\U00002273', + "hArr;": '\U000021D4', + "hairsp;": '\U0000200A', + "half;": '\U000000BD', + "hamilt;": '\U0000210B', + "hardcy;": '\U0000044A', + "harr;": '\U00002194', + "harrcir;": '\U00002948', + "harrw;": '\U000021AD', + "hbar;": '\U0000210F', + "hcirc;": '\U00000125', + "hearts;": '\U00002665', + "heartsuit;": '\U00002665', + "hellip;": '\U00002026', + "hercon;": '\U000022B9', + "hfr;": '\U0001D525', + "hksearow;": '\U00002925', + "hkswarow;": '\U00002926', + "hoarr;": '\U000021FF', + "homtht;": '\U0000223B', + "hookleftarrow;": '\U000021A9', + "hookrightarrow;": '\U000021AA', + "hopf;": '\U0001D559', + "horbar;": '\U00002015', + "hscr;": '\U0001D4BD', + "hslash;": '\U0000210F', + "hstrok;": '\U00000127', + "hybull;": '\U00002043', + "hyphen;": '\U00002010', + "iacute;": '\U000000ED', + "ic;": '\U00002063', + "icirc;": '\U000000EE', + "icy;": '\U00000438', + "iecy;": '\U00000435', + "iexcl;": '\U000000A1', + "iff;": '\U000021D4', + "ifr;": '\U0001D526', + "igrave;": '\U000000EC', + "ii;": '\U00002148', + "iiiint;": '\U00002A0C', + "iiint;": '\U0000222D', + "iinfin;": '\U000029DC', + "iiota;": '\U00002129', + "ijlig;": '\U00000133', + "imacr;": '\U0000012B', + "image;": '\U00002111', + "imagline;": '\U00002110', + "imagpart;": '\U00002111', + "imath;": '\U00000131', + "imof;": '\U000022B7', + "imped;": '\U000001B5', + "in;": '\U00002208', + "incare;": '\U00002105', + "infin;": '\U0000221E', + "infintie;": '\U000029DD', + "inodot;": '\U00000131', + "int;": '\U0000222B', + "intcal;": '\U000022BA', + "integers;": '\U00002124', + "intercal;": '\U000022BA', + "intlarhk;": '\U00002A17', + "intprod;": '\U00002A3C', + "iocy;": '\U00000451', + "iogon;": '\U0000012F', + "iopf;": '\U0001D55A', + "iota;": '\U000003B9', + "iprod;": '\U00002A3C', + "iquest;": '\U000000BF', + "iscr;": '\U0001D4BE', + "isin;": '\U00002208', + "isinE;": '\U000022F9', + "isindot;": '\U000022F5', + "isins;": '\U000022F4', + "isinsv;": '\U000022F3', + "isinv;": '\U00002208', + "it;": '\U00002062', + "itilde;": '\U00000129', + "iukcy;": '\U00000456', + "iuml;": '\U000000EF', + "jcirc;": '\U00000135', + "jcy;": '\U00000439', + "jfr;": '\U0001D527', + "jmath;": '\U00000237', + "jopf;": '\U0001D55B', + "jscr;": '\U0001D4BF', + "jsercy;": '\U00000458', + "jukcy;": '\U00000454', + "kappa;": '\U000003BA', + "kappav;": '\U000003F0', + "kcedil;": '\U00000137', + "kcy;": '\U0000043A', + "kfr;": '\U0001D528', + "kgreen;": '\U00000138', + "khcy;": '\U00000445', + "kjcy;": '\U0000045C', + "kopf;": '\U0001D55C', + "kscr;": '\U0001D4C0', + "lAarr;": '\U000021DA', + "lArr;": '\U000021D0', + "lAtail;": '\U0000291B', + "lBarr;": '\U0000290E', + "lE;": '\U00002266', + "lEg;": '\U00002A8B', + "lHar;": '\U00002962', + "lacute;": '\U0000013A', + "laemptyv;": '\U000029B4', + "lagran;": '\U00002112', + "lambda;": '\U000003BB', + "lang;": '\U000027E8', + "langd;": '\U00002991', + "langle;": '\U000027E8', + "lap;": '\U00002A85', + "laquo;": '\U000000AB', + "larr;": '\U00002190', + "larrb;": '\U000021E4', + "larrbfs;": '\U0000291F', + "larrfs;": '\U0000291D', + "larrhk;": '\U000021A9', + "larrlp;": '\U000021AB', + "larrpl;": '\U00002939', + "larrsim;": '\U00002973', + "larrtl;": '\U000021A2', + "lat;": '\U00002AAB', + "latail;": '\U00002919', + "late;": '\U00002AAD', + "lbarr;": '\U0000290C', + "lbbrk;": '\U00002772', + "lbrace;": '\U0000007B', + "lbrack;": '\U0000005B', + "lbrke;": '\U0000298B', + "lbrksld;": '\U0000298F', + "lbrkslu;": '\U0000298D', + "lcaron;": '\U0000013E', + "lcedil;": '\U0000013C', + "lceil;": '\U00002308', + "lcub;": '\U0000007B', + "lcy;": '\U0000043B', + "ldca;": '\U00002936', + "ldquo;": '\U0000201C', + "ldquor;": '\U0000201E', + "ldrdhar;": '\U00002967', + "ldrushar;": '\U0000294B', + "ldsh;": '\U000021B2', + "le;": '\U00002264', + "leftarrow;": '\U00002190', + "leftarrowtail;": '\U000021A2', + "leftharpoondown;": '\U000021BD', + "leftharpoonup;": '\U000021BC', + "leftleftarrows;": '\U000021C7', + "leftrightarrow;": '\U00002194', + "leftrightarrows;": '\U000021C6', + "leftrightharpoons;": '\U000021CB', + "leftrightsquigarrow;": '\U000021AD', + "leftthreetimes;": '\U000022CB', + "leg;": '\U000022DA', + "leq;": '\U00002264', + "leqq;": '\U00002266', + "leqslant;": '\U00002A7D', + "les;": '\U00002A7D', + "lescc;": '\U00002AA8', + "lesdot;": '\U00002A7F', + "lesdoto;": '\U00002A81', + "lesdotor;": '\U00002A83', + "lesges;": '\U00002A93', + "lessapprox;": '\U00002A85', + "lessdot;": '\U000022D6', + "lesseqgtr;": '\U000022DA', + "lesseqqgtr;": '\U00002A8B', + "lessgtr;": '\U00002276', + "lesssim;": '\U00002272', + "lfisht;": '\U0000297C', + "lfloor;": '\U0000230A', + "lfr;": '\U0001D529', + "lg;": '\U00002276', + "lgE;": '\U00002A91', + "lhard;": '\U000021BD', + "lharu;": '\U000021BC', + "lharul;": '\U0000296A', + "lhblk;": '\U00002584', + "ljcy;": '\U00000459', + "ll;": '\U0000226A', + "llarr;": '\U000021C7', + "llcorner;": '\U0000231E', + "llhard;": '\U0000296B', + "lltri;": '\U000025FA', + "lmidot;": '\U00000140', + "lmoust;": '\U000023B0', + "lmoustache;": '\U000023B0', + "lnE;": '\U00002268', + "lnap;": '\U00002A89', + "lnapprox;": '\U00002A89', + "lne;": '\U00002A87', + "lneq;": '\U00002A87', + "lneqq;": '\U00002268', + "lnsim;": '\U000022E6', + "loang;": '\U000027EC', + "loarr;": '\U000021FD', + "lobrk;": '\U000027E6', + "longleftarrow;": '\U000027F5', + "longleftrightarrow;": '\U000027F7', + "longmapsto;": '\U000027FC', + "longrightarrow;": '\U000027F6', + "looparrowleft;": '\U000021AB', + "looparrowright;": '\U000021AC', + "lopar;": '\U00002985', + "lopf;": '\U0001D55D', + "loplus;": '\U00002A2D', + "lotimes;": '\U00002A34', + "lowast;": '\U00002217', + "lowbar;": '\U0000005F', + "loz;": '\U000025CA', + "lozenge;": '\U000025CA', + "lozf;": '\U000029EB', + "lpar;": '\U00000028', + "lparlt;": '\U00002993', + "lrarr;": '\U000021C6', + "lrcorner;": '\U0000231F', + "lrhar;": '\U000021CB', + "lrhard;": '\U0000296D', + "lrm;": '\U0000200E', + "lrtri;": '\U000022BF', + "lsaquo;": '\U00002039', + "lscr;": '\U0001D4C1', + "lsh;": '\U000021B0', + "lsim;": '\U00002272', + "lsime;": '\U00002A8D', + "lsimg;": '\U00002A8F', + "lsqb;": '\U0000005B', + "lsquo;": '\U00002018', + "lsquor;": '\U0000201A', + "lstrok;": '\U00000142', + "lt;": '\U0000003C', + "ltcc;": '\U00002AA6', + "ltcir;": '\U00002A79', + "ltdot;": '\U000022D6', + "lthree;": '\U000022CB', + "ltimes;": '\U000022C9', + "ltlarr;": '\U00002976', + "ltquest;": '\U00002A7B', + "ltrPar;": '\U00002996', + "ltri;": '\U000025C3', + "ltrie;": '\U000022B4', + "ltrif;": '\U000025C2', + "lurdshar;": '\U0000294A', + "luruhar;": '\U00002966', + "mDDot;": '\U0000223A', + "macr;": '\U000000AF', + "male;": '\U00002642', + "malt;": '\U00002720', + "maltese;": '\U00002720', + "map;": '\U000021A6', + "mapsto;": '\U000021A6', + "mapstodown;": '\U000021A7', + "mapstoleft;": '\U000021A4', + "mapstoup;": '\U000021A5', + "marker;": '\U000025AE', + "mcomma;": '\U00002A29', + "mcy;": '\U0000043C', + "mdash;": '\U00002014', + "measuredangle;": '\U00002221', + "mfr;": '\U0001D52A', + "mho;": '\U00002127', + "micro;": '\U000000B5', + "mid;": '\U00002223', + "midast;": '\U0000002A', + "midcir;": '\U00002AF0', + "middot;": '\U000000B7', + "minus;": '\U00002212', + "minusb;": '\U0000229F', + "minusd;": '\U00002238', + "minusdu;": '\U00002A2A', + "mlcp;": '\U00002ADB', + "mldr;": '\U00002026', + "mnplus;": '\U00002213', + "models;": '\U000022A7', + "mopf;": '\U0001D55E', + "mp;": '\U00002213', + "mscr;": '\U0001D4C2', + "mstpos;": '\U0000223E', + "mu;": '\U000003BC', + "multimap;": '\U000022B8', + "mumap;": '\U000022B8', + "nLeftarrow;": '\U000021CD', + "nLeftrightarrow;": '\U000021CE', + "nRightarrow;": '\U000021CF', + "nVDash;": '\U000022AF', + "nVdash;": '\U000022AE', + "nabla;": '\U00002207', + "nacute;": '\U00000144', + "nap;": '\U00002249', + "napos;": '\U00000149', + "napprox;": '\U00002249', + "natur;": '\U0000266E', + "natural;": '\U0000266E', + "naturals;": '\U00002115', + "nbsp;": '\U000000A0', + "ncap;": '\U00002A43', + "ncaron;": '\U00000148', + "ncedil;": '\U00000146', + "ncong;": '\U00002247', + "ncup;": '\U00002A42', + "ncy;": '\U0000043D', + "ndash;": '\U00002013', + "ne;": '\U00002260', + "neArr;": '\U000021D7', + "nearhk;": '\U00002924', + "nearr;": '\U00002197', + "nearrow;": '\U00002197', + "nequiv;": '\U00002262', + "nesear;": '\U00002928', + "nexist;": '\U00002204', + "nexists;": '\U00002204', + "nfr;": '\U0001D52B', + "nge;": '\U00002271', + "ngeq;": '\U00002271', + "ngsim;": '\U00002275', + "ngt;": '\U0000226F', + "ngtr;": '\U0000226F', + "nhArr;": '\U000021CE', + "nharr;": '\U000021AE', + "nhpar;": '\U00002AF2', + "ni;": '\U0000220B', + "nis;": '\U000022FC', + "nisd;": '\U000022FA', + "niv;": '\U0000220B', + "njcy;": '\U0000045A', + "nlArr;": '\U000021CD', + "nlarr;": '\U0000219A', + "nldr;": '\U00002025', + "nle;": '\U00002270', + "nleftarrow;": '\U0000219A', + "nleftrightarrow;": '\U000021AE', + "nleq;": '\U00002270', + "nless;": '\U0000226E', + "nlsim;": '\U00002274', + "nlt;": '\U0000226E', + "nltri;": '\U000022EA', + "nltrie;": '\U000022EC', + "nmid;": '\U00002224', + "nopf;": '\U0001D55F', + "not;": '\U000000AC', + "notin;": '\U00002209', + "notinva;": '\U00002209', + "notinvb;": '\U000022F7', + "notinvc;": '\U000022F6', + "notni;": '\U0000220C', + "notniva;": '\U0000220C', + "notnivb;": '\U000022FE', + "notnivc;": '\U000022FD', + "npar;": '\U00002226', + "nparallel;": '\U00002226', + "npolint;": '\U00002A14', + "npr;": '\U00002280', + "nprcue;": '\U000022E0', + "nprec;": '\U00002280', + "nrArr;": '\U000021CF', + "nrarr;": '\U0000219B', + "nrightarrow;": '\U0000219B', + "nrtri;": '\U000022EB', + "nrtrie;": '\U000022ED', + "nsc;": '\U00002281', + "nsccue;": '\U000022E1', + "nscr;": '\U0001D4C3', + "nshortmid;": '\U00002224', + "nshortparallel;": '\U00002226', + "nsim;": '\U00002241', + "nsime;": '\U00002244', + "nsimeq;": '\U00002244', + "nsmid;": '\U00002224', + "nspar;": '\U00002226', + "nsqsube;": '\U000022E2', + "nsqsupe;": '\U000022E3', + "nsub;": '\U00002284', + "nsube;": '\U00002288', + "nsubseteq;": '\U00002288', + "nsucc;": '\U00002281', + "nsup;": '\U00002285', + "nsupe;": '\U00002289', + "nsupseteq;": '\U00002289', + "ntgl;": '\U00002279', + "ntilde;": '\U000000F1', + "ntlg;": '\U00002278', + "ntriangleleft;": '\U000022EA', + "ntrianglelefteq;": '\U000022EC', + "ntriangleright;": '\U000022EB', + "ntrianglerighteq;": '\U000022ED', + "nu;": '\U000003BD', + "num;": '\U00000023', + "numero;": '\U00002116', + "numsp;": '\U00002007', + "nvDash;": '\U000022AD', + "nvHarr;": '\U00002904', + "nvdash;": '\U000022AC', + "nvinfin;": '\U000029DE', + "nvlArr;": '\U00002902', + "nvrArr;": '\U00002903', + "nwArr;": '\U000021D6', + "nwarhk;": '\U00002923', + "nwarr;": '\U00002196', + "nwarrow;": '\U00002196', + "nwnear;": '\U00002927', + "oS;": '\U000024C8', + "oacute;": '\U000000F3', + "oast;": '\U0000229B', + "ocir;": '\U0000229A', + "ocirc;": '\U000000F4', + "ocy;": '\U0000043E', + "odash;": '\U0000229D', + "odblac;": '\U00000151', + "odiv;": '\U00002A38', + "odot;": '\U00002299', + "odsold;": '\U000029BC', + "oelig;": '\U00000153', + "ofcir;": '\U000029BF', + "ofr;": '\U0001D52C', + "ogon;": '\U000002DB', + "ograve;": '\U000000F2', + "ogt;": '\U000029C1', + "ohbar;": '\U000029B5', + "ohm;": '\U000003A9', + "oint;": '\U0000222E', + "olarr;": '\U000021BA', + "olcir;": '\U000029BE', + "olcross;": '\U000029BB', + "oline;": '\U0000203E', + "olt;": '\U000029C0', + "omacr;": '\U0000014D', + "omega;": '\U000003C9', + "omicron;": '\U000003BF', + "omid;": '\U000029B6', + "ominus;": '\U00002296', + "oopf;": '\U0001D560', + "opar;": '\U000029B7', + "operp;": '\U000029B9', + "oplus;": '\U00002295', + "or;": '\U00002228', + "orarr;": '\U000021BB', + "ord;": '\U00002A5D', + "order;": '\U00002134', + "orderof;": '\U00002134', + "ordf;": '\U000000AA', + "ordm;": '\U000000BA', + "origof;": '\U000022B6', + "oror;": '\U00002A56', + "orslope;": '\U00002A57', + "orv;": '\U00002A5B', + "oscr;": '\U00002134', + "oslash;": '\U000000F8', + "osol;": '\U00002298', + "otilde;": '\U000000F5', + "otimes;": '\U00002297', + "otimesas;": '\U00002A36', + "ouml;": '\U000000F6', + "ovbar;": '\U0000233D', + "par;": '\U00002225', + "para;": '\U000000B6', + "parallel;": '\U00002225', + "parsim;": '\U00002AF3', + "parsl;": '\U00002AFD', + "part;": '\U00002202', + "pcy;": '\U0000043F', + "percnt;": '\U00000025', + "period;": '\U0000002E', + "permil;": '\U00002030', + "perp;": '\U000022A5', + "pertenk;": '\U00002031', + "pfr;": '\U0001D52D', + "phi;": '\U000003C6', + "phiv;": '\U000003D5', + "phmmat;": '\U00002133', + "phone;": '\U0000260E', + "pi;": '\U000003C0', + "pitchfork;": '\U000022D4', + "piv;": '\U000003D6', + "planck;": '\U0000210F', + "planckh;": '\U0000210E', + "plankv;": '\U0000210F', + "plus;": '\U0000002B', + "plusacir;": '\U00002A23', + "plusb;": '\U0000229E', + "pluscir;": '\U00002A22', + "plusdo;": '\U00002214', + "plusdu;": '\U00002A25', + "pluse;": '\U00002A72', + "plusmn;": '\U000000B1', + "plussim;": '\U00002A26', + "plustwo;": '\U00002A27', + "pm;": '\U000000B1', + "pointint;": '\U00002A15', + "popf;": '\U0001D561', + "pound;": '\U000000A3', + "pr;": '\U0000227A', + "prE;": '\U00002AB3', + "prap;": '\U00002AB7', + "prcue;": '\U0000227C', + "pre;": '\U00002AAF', + "prec;": '\U0000227A', + "precapprox;": '\U00002AB7', + "preccurlyeq;": '\U0000227C', + "preceq;": '\U00002AAF', + "precnapprox;": '\U00002AB9', + "precneqq;": '\U00002AB5', + "precnsim;": '\U000022E8', + "precsim;": '\U0000227E', + "prime;": '\U00002032', + "primes;": '\U00002119', + "prnE;": '\U00002AB5', + "prnap;": '\U00002AB9', + "prnsim;": '\U000022E8', + "prod;": '\U0000220F', + "profalar;": '\U0000232E', + "profline;": '\U00002312', + "profsurf;": '\U00002313', + "prop;": '\U0000221D', + "propto;": '\U0000221D', + "prsim;": '\U0000227E', + "prurel;": '\U000022B0', + "pscr;": '\U0001D4C5', + "psi;": '\U000003C8', + "puncsp;": '\U00002008', + "qfr;": '\U0001D52E', + "qint;": '\U00002A0C', + "qopf;": '\U0001D562', + "qprime;": '\U00002057', + "qscr;": '\U0001D4C6', + "quaternions;": '\U0000210D', + "quatint;": '\U00002A16', + "quest;": '\U0000003F', + "questeq;": '\U0000225F', + "quot;": '\U00000022', + "rAarr;": '\U000021DB', + "rArr;": '\U000021D2', + "rAtail;": '\U0000291C', + "rBarr;": '\U0000290F', + "rHar;": '\U00002964', + "racute;": '\U00000155', + "radic;": '\U0000221A', + "raemptyv;": '\U000029B3', + "rang;": '\U000027E9', + "rangd;": '\U00002992', + "range;": '\U000029A5', + "rangle;": '\U000027E9', + "raquo;": '\U000000BB', + "rarr;": '\U00002192', + "rarrap;": '\U00002975', + "rarrb;": '\U000021E5', + "rarrbfs;": '\U00002920', + "rarrc;": '\U00002933', + "rarrfs;": '\U0000291E', + "rarrhk;": '\U000021AA', + "rarrlp;": '\U000021AC', + "rarrpl;": '\U00002945', + "rarrsim;": '\U00002974', + "rarrtl;": '\U000021A3', + "rarrw;": '\U0000219D', + "ratail;": '\U0000291A', + "ratio;": '\U00002236', + "rationals;": '\U0000211A', + "rbarr;": '\U0000290D', + "rbbrk;": '\U00002773', + "rbrace;": '\U0000007D', + "rbrack;": '\U0000005D', + "rbrke;": '\U0000298C', + "rbrksld;": '\U0000298E', + "rbrkslu;": '\U00002990', + "rcaron;": '\U00000159', + "rcedil;": '\U00000157', + "rceil;": '\U00002309', + "rcub;": '\U0000007D', + "rcy;": '\U00000440', + "rdca;": '\U00002937', + "rdldhar;": '\U00002969', + "rdquo;": '\U0000201D', + "rdquor;": '\U0000201D', + "rdsh;": '\U000021B3', + "real;": '\U0000211C', + "realine;": '\U0000211B', + "realpart;": '\U0000211C', + "reals;": '\U0000211D', + "rect;": '\U000025AD', + "reg;": '\U000000AE', + "rfisht;": '\U0000297D', + "rfloor;": '\U0000230B', + "rfr;": '\U0001D52F', + "rhard;": '\U000021C1', + "rharu;": '\U000021C0', + "rharul;": '\U0000296C', + "rho;": '\U000003C1', + "rhov;": '\U000003F1', + "rightarrow;": '\U00002192', + "rightarrowtail;": '\U000021A3', + "rightharpoondown;": '\U000021C1', + "rightharpoonup;": '\U000021C0', + "rightleftarrows;": '\U000021C4', + "rightleftharpoons;": '\U000021CC', + "rightrightarrows;": '\U000021C9', + "rightsquigarrow;": '\U0000219D', + "rightthreetimes;": '\U000022CC', + "ring;": '\U000002DA', + "risingdotseq;": '\U00002253', + "rlarr;": '\U000021C4', + "rlhar;": '\U000021CC', + "rlm;": '\U0000200F', + "rmoust;": '\U000023B1', + "rmoustache;": '\U000023B1', + "rnmid;": '\U00002AEE', + "roang;": '\U000027ED', + "roarr;": '\U000021FE', + "robrk;": '\U000027E7', + "ropar;": '\U00002986', + "ropf;": '\U0001D563', + "roplus;": '\U00002A2E', + "rotimes;": '\U00002A35', + "rpar;": '\U00000029', + "rpargt;": '\U00002994', + "rppolint;": '\U00002A12', + "rrarr;": '\U000021C9', + "rsaquo;": '\U0000203A', + "rscr;": '\U0001D4C7', + "rsh;": '\U000021B1', + "rsqb;": '\U0000005D', + "rsquo;": '\U00002019', + "rsquor;": '\U00002019', + "rthree;": '\U000022CC', + "rtimes;": '\U000022CA', + "rtri;": '\U000025B9', + "rtrie;": '\U000022B5', + "rtrif;": '\U000025B8', + "rtriltri;": '\U000029CE', + "ruluhar;": '\U00002968', + "rx;": '\U0000211E', + "sacute;": '\U0000015B', + "sbquo;": '\U0000201A', + "sc;": '\U0000227B', + "scE;": '\U00002AB4', + "scap;": '\U00002AB8', + "scaron;": '\U00000161', + "sccue;": '\U0000227D', + "sce;": '\U00002AB0', + "scedil;": '\U0000015F', + "scirc;": '\U0000015D', + "scnE;": '\U00002AB6', + "scnap;": '\U00002ABA', + "scnsim;": '\U000022E9', + "scpolint;": '\U00002A13', + "scsim;": '\U0000227F', + "scy;": '\U00000441', + "sdot;": '\U000022C5', + "sdotb;": '\U000022A1', + "sdote;": '\U00002A66', + "seArr;": '\U000021D8', + "searhk;": '\U00002925', + "searr;": '\U00002198', + "searrow;": '\U00002198', + "sect;": '\U000000A7', + "semi;": '\U0000003B', + "seswar;": '\U00002929', + "setminus;": '\U00002216', + "setmn;": '\U00002216', + "sext;": '\U00002736', + "sfr;": '\U0001D530', + "sfrown;": '\U00002322', + "sharp;": '\U0000266F', + "shchcy;": '\U00000449', + "shcy;": '\U00000448', + "shortmid;": '\U00002223', + "shortparallel;": '\U00002225', + "shy;": '\U000000AD', + "sigma;": '\U000003C3', + "sigmaf;": '\U000003C2', + "sigmav;": '\U000003C2', + "sim;": '\U0000223C', + "simdot;": '\U00002A6A', + "sime;": '\U00002243', + "simeq;": '\U00002243', + "simg;": '\U00002A9E', + "simgE;": '\U00002AA0', + "siml;": '\U00002A9D', + "simlE;": '\U00002A9F', + "simne;": '\U00002246', + "simplus;": '\U00002A24', + "simrarr;": '\U00002972', + "slarr;": '\U00002190', + "smallsetminus;": '\U00002216', + "smashp;": '\U00002A33', + "smeparsl;": '\U000029E4', + "smid;": '\U00002223', + "smile;": '\U00002323', + "smt;": '\U00002AAA', + "smte;": '\U00002AAC', + "softcy;": '\U0000044C', + "sol;": '\U0000002F', + "solb;": '\U000029C4', + "solbar;": '\U0000233F', + "sopf;": '\U0001D564', + "spades;": '\U00002660', + "spadesuit;": '\U00002660', + "spar;": '\U00002225', + "sqcap;": '\U00002293', + "sqcup;": '\U00002294', + "sqsub;": '\U0000228F', + "sqsube;": '\U00002291', + "sqsubset;": '\U0000228F', + "sqsubseteq;": '\U00002291', + "sqsup;": '\U00002290', + "sqsupe;": '\U00002292', + "sqsupset;": '\U00002290', + "sqsupseteq;": '\U00002292', + "squ;": '\U000025A1', + "square;": '\U000025A1', + "squarf;": '\U000025AA', + "squf;": '\U000025AA', + "srarr;": '\U00002192', + "sscr;": '\U0001D4C8', + "ssetmn;": '\U00002216', + "ssmile;": '\U00002323', + "sstarf;": '\U000022C6', + "star;": '\U00002606', + "starf;": '\U00002605', + "straightepsilon;": '\U000003F5', + "straightphi;": '\U000003D5', + "strns;": '\U000000AF', + "sub;": '\U00002282', + "subE;": '\U00002AC5', + "subdot;": '\U00002ABD', + "sube;": '\U00002286', + "subedot;": '\U00002AC3', + "submult;": '\U00002AC1', + "subnE;": '\U00002ACB', + "subne;": '\U0000228A', + "subplus;": '\U00002ABF', + "subrarr;": '\U00002979', + "subset;": '\U00002282', + "subseteq;": '\U00002286', + "subseteqq;": '\U00002AC5', + "subsetneq;": '\U0000228A', + "subsetneqq;": '\U00002ACB', + "subsim;": '\U00002AC7', + "subsub;": '\U00002AD5', + "subsup;": '\U00002AD3', + "succ;": '\U0000227B', + "succapprox;": '\U00002AB8', + "succcurlyeq;": '\U0000227D', + "succeq;": '\U00002AB0', + "succnapprox;": '\U00002ABA', + "succneqq;": '\U00002AB6', + "succnsim;": '\U000022E9', + "succsim;": '\U0000227F', + "sum;": '\U00002211', + "sung;": '\U0000266A', + "sup;": '\U00002283', + "sup1;": '\U000000B9', + "sup2;": '\U000000B2', + "sup3;": '\U000000B3', + "supE;": '\U00002AC6', + "supdot;": '\U00002ABE', + "supdsub;": '\U00002AD8', + "supe;": '\U00002287', + "supedot;": '\U00002AC4', + "suphsol;": '\U000027C9', + "suphsub;": '\U00002AD7', + "suplarr;": '\U0000297B', + "supmult;": '\U00002AC2', + "supnE;": '\U00002ACC', + "supne;": '\U0000228B', + "supplus;": '\U00002AC0', + "supset;": '\U00002283', + "supseteq;": '\U00002287', + "supseteqq;": '\U00002AC6', + "supsetneq;": '\U0000228B', + "supsetneqq;": '\U00002ACC', + "supsim;": '\U00002AC8', + "supsub;": '\U00002AD4', + "supsup;": '\U00002AD6', + "swArr;": '\U000021D9', + "swarhk;": '\U00002926', + "swarr;": '\U00002199', + "swarrow;": '\U00002199', + "swnwar;": '\U0000292A', + "szlig;": '\U000000DF', + "target;": '\U00002316', + "tau;": '\U000003C4', + "tbrk;": '\U000023B4', + "tcaron;": '\U00000165', + "tcedil;": '\U00000163', + "tcy;": '\U00000442', + "tdot;": '\U000020DB', + "telrec;": '\U00002315', + "tfr;": '\U0001D531', + "there4;": '\U00002234', + "therefore;": '\U00002234', + "theta;": '\U000003B8', + "thetasym;": '\U000003D1', + "thetav;": '\U000003D1', + "thickapprox;": '\U00002248', + "thicksim;": '\U0000223C', + "thinsp;": '\U00002009', + "thkap;": '\U00002248', + "thksim;": '\U0000223C', + "thorn;": '\U000000FE', + "tilde;": '\U000002DC', + "times;": '\U000000D7', + "timesb;": '\U000022A0', + "timesbar;": '\U00002A31', + "timesd;": '\U00002A30', + "tint;": '\U0000222D', + "toea;": '\U00002928', + "top;": '\U000022A4', + "topbot;": '\U00002336', + "topcir;": '\U00002AF1', + "topf;": '\U0001D565', + "topfork;": '\U00002ADA', + "tosa;": '\U00002929', + "tprime;": '\U00002034', + "trade;": '\U00002122', + "triangle;": '\U000025B5', + "triangledown;": '\U000025BF', + "triangleleft;": '\U000025C3', + "trianglelefteq;": '\U000022B4', + "triangleq;": '\U0000225C', + "triangleright;": '\U000025B9', + "trianglerighteq;": '\U000022B5', + "tridot;": '\U000025EC', + "trie;": '\U0000225C', + "triminus;": '\U00002A3A', + "triplus;": '\U00002A39', + "trisb;": '\U000029CD', + "tritime;": '\U00002A3B', + "trpezium;": '\U000023E2', + "tscr;": '\U0001D4C9', + "tscy;": '\U00000446', + "tshcy;": '\U0000045B', + "tstrok;": '\U00000167', + "twixt;": '\U0000226C', + "twoheadleftarrow;": '\U0000219E', + "twoheadrightarrow;": '\U000021A0', + "uArr;": '\U000021D1', + "uHar;": '\U00002963', + "uacute;": '\U000000FA', + "uarr;": '\U00002191', + "ubrcy;": '\U0000045E', + "ubreve;": '\U0000016D', + "ucirc;": '\U000000FB', + "ucy;": '\U00000443', + "udarr;": '\U000021C5', + "udblac;": '\U00000171', + "udhar;": '\U0000296E', + "ufisht;": '\U0000297E', + "ufr;": '\U0001D532', + "ugrave;": '\U000000F9', + "uharl;": '\U000021BF', + "uharr;": '\U000021BE', + "uhblk;": '\U00002580', + "ulcorn;": '\U0000231C', + "ulcorner;": '\U0000231C', + "ulcrop;": '\U0000230F', + "ultri;": '\U000025F8', + "umacr;": '\U0000016B', + "uml;": '\U000000A8', + "uogon;": '\U00000173', + "uopf;": '\U0001D566', + "uparrow;": '\U00002191', + "updownarrow;": '\U00002195', + "upharpoonleft;": '\U000021BF', + "upharpoonright;": '\U000021BE', + "uplus;": '\U0000228E', + "upsi;": '\U000003C5', + "upsih;": '\U000003D2', + "upsilon;": '\U000003C5', + "upuparrows;": '\U000021C8', + "urcorn;": '\U0000231D', + "urcorner;": '\U0000231D', + "urcrop;": '\U0000230E', + "uring;": '\U0000016F', + "urtri;": '\U000025F9', + "uscr;": '\U0001D4CA', + "utdot;": '\U000022F0', + "utilde;": '\U00000169', + "utri;": '\U000025B5', + "utrif;": '\U000025B4', + "uuarr;": '\U000021C8', + "uuml;": '\U000000FC', + "uwangle;": '\U000029A7', + "vArr;": '\U000021D5', + "vBar;": '\U00002AE8', + "vBarv;": '\U00002AE9', + "vDash;": '\U000022A8', + "vangrt;": '\U0000299C', + "varepsilon;": '\U000003F5', + "varkappa;": '\U000003F0', + "varnothing;": '\U00002205', + "varphi;": '\U000003D5', + "varpi;": '\U000003D6', + "varpropto;": '\U0000221D', + "varr;": '\U00002195', + "varrho;": '\U000003F1', + "varsigma;": '\U000003C2', + "vartheta;": '\U000003D1', + "vartriangleleft;": '\U000022B2', + "vartriangleright;": '\U000022B3', + "vcy;": '\U00000432', + "vdash;": '\U000022A2', + "vee;": '\U00002228', + "veebar;": '\U000022BB', + "veeeq;": '\U0000225A', + "vellip;": '\U000022EE', + "verbar;": '\U0000007C', + "vert;": '\U0000007C', + "vfr;": '\U0001D533', + "vltri;": '\U000022B2', + "vopf;": '\U0001D567', + "vprop;": '\U0000221D', + "vrtri;": '\U000022B3', + "vscr;": '\U0001D4CB', + "vzigzag;": '\U0000299A', + "wcirc;": '\U00000175', + "wedbar;": '\U00002A5F', + "wedge;": '\U00002227', + "wedgeq;": '\U00002259', + "weierp;": '\U00002118', + "wfr;": '\U0001D534', + "wopf;": '\U0001D568', + "wp;": '\U00002118', + "wr;": '\U00002240', + "wreath;": '\U00002240', + "wscr;": '\U0001D4CC', + "xcap;": '\U000022C2', + "xcirc;": '\U000025EF', + "xcup;": '\U000022C3', + "xdtri;": '\U000025BD', + "xfr;": '\U0001D535', + "xhArr;": '\U000027FA', + "xharr;": '\U000027F7', + "xi;": '\U000003BE', + "xlArr;": '\U000027F8', + "xlarr;": '\U000027F5', + "xmap;": '\U000027FC', + "xnis;": '\U000022FB', + "xodot;": '\U00002A00', + "xopf;": '\U0001D569', + "xoplus;": '\U00002A01', + "xotime;": '\U00002A02', + "xrArr;": '\U000027F9', + "xrarr;": '\U000027F6', + "xscr;": '\U0001D4CD', + "xsqcup;": '\U00002A06', + "xuplus;": '\U00002A04', + "xutri;": '\U000025B3', + "xvee;": '\U000022C1', + "xwedge;": '\U000022C0', + "yacute;": '\U000000FD', + "yacy;": '\U0000044F', + "ycirc;": '\U00000177', + "ycy;": '\U0000044B', + "yen;": '\U000000A5', + "yfr;": '\U0001D536', + "yicy;": '\U00000457', + "yopf;": '\U0001D56A', + "yscr;": '\U0001D4CE', + "yucy;": '\U0000044E', + "yuml;": '\U000000FF', + "zacute;": '\U0000017A', + "zcaron;": '\U0000017E', + "zcy;": '\U00000437', + "zdot;": '\U0000017C', + "zeetrf;": '\U00002128', + "zeta;": '\U000003B6', + "zfr;": '\U0001D537', + "zhcy;": '\U00000436', + "zigrarr;": '\U000021DD', + "zopf;": '\U0001D56B', + "zscr;": '\U0001D4CF', + "zwj;": '\U0000200D', + "zwnj;": '\U0000200C', + "AElig": '\U000000C6', + "AMP": '\U00000026', + "Aacute": '\U000000C1', + "Acirc": '\U000000C2', + "Agrave": '\U000000C0', + "Aring": '\U000000C5', + "Atilde": '\U000000C3', + "Auml": '\U000000C4', + "COPY": '\U000000A9', + "Ccedil": '\U000000C7', + "ETH": '\U000000D0', + "Eacute": '\U000000C9', + "Ecirc": '\U000000CA', + "Egrave": '\U000000C8', + "Euml": '\U000000CB', + "GT": '\U0000003E', + "Iacute": '\U000000CD', + "Icirc": '\U000000CE', + "Igrave": '\U000000CC', + "Iuml": '\U000000CF', + "LT": '\U0000003C', + "Ntilde": '\U000000D1', + "Oacute": '\U000000D3', + "Ocirc": '\U000000D4', + "Ograve": '\U000000D2', + "Oslash": '\U000000D8', + "Otilde": '\U000000D5', + "Ouml": '\U000000D6', + "QUOT": '\U00000022', + "REG": '\U000000AE', + "THORN": '\U000000DE', + "Uacute": '\U000000DA', + "Ucirc": '\U000000DB', + "Ugrave": '\U000000D9', + "Uuml": '\U000000DC', + "Yacute": '\U000000DD', + "aacute": '\U000000E1', + "acirc": '\U000000E2', + "acute": '\U000000B4', + "aelig": '\U000000E6', + "agrave": '\U000000E0', + "amp": '\U00000026', + "aring": '\U000000E5', + "atilde": '\U000000E3', + "auml": '\U000000E4', + "brvbar": '\U000000A6', + "ccedil": '\U000000E7', + "cedil": '\U000000B8', + "cent": '\U000000A2', + "copy": '\U000000A9', + "curren": '\U000000A4', + "deg": '\U000000B0', + "divide": '\U000000F7', + "eacute": '\U000000E9', + "ecirc": '\U000000EA', + "egrave": '\U000000E8', + "eth": '\U000000F0', + "euml": '\U000000EB', + "frac12": '\U000000BD', + "frac14": '\U000000BC', + "frac34": '\U000000BE', + "gt": '\U0000003E', + "iacute": '\U000000ED', + "icirc": '\U000000EE', + "iexcl": '\U000000A1', + "igrave": '\U000000EC', + "iquest": '\U000000BF', + "iuml": '\U000000EF', + "laquo": '\U000000AB', + "lt": '\U0000003C', + "macr": '\U000000AF', + "micro": '\U000000B5', + "middot": '\U000000B7', + "nbsp": '\U000000A0', + "not": '\U000000AC', + "ntilde": '\U000000F1', + "oacute": '\U000000F3', + "ocirc": '\U000000F4', + "ograve": '\U000000F2', + "ordf": '\U000000AA', + "ordm": '\U000000BA', + "oslash": '\U000000F8', + "otilde": '\U000000F5', + "ouml": '\U000000F6', + "para": '\U000000B6', + "plusmn": '\U000000B1', + "pound": '\U000000A3', + "quot": '\U00000022', + "raquo": '\U000000BB', + "reg": '\U000000AE', + "sect": '\U000000A7', + "shy": '\U000000AD', + "sup1": '\U000000B9', + "sup2": '\U000000B2', + "sup3": '\U000000B3', + "szlig": '\U000000DF', + "thorn": '\U000000FE', + "times": '\U000000D7', + "uacute": '\U000000FA', + "ucirc": '\U000000FB', + "ugrave": '\U000000F9', + "uml": '\U000000A8', + "uuml": '\U000000FC', + "yacute": '\U000000FD', + "yen": '\U000000A5', + "yuml": '\U000000FF', +} + +// HTML entities that are two unicode codepoints. +var entity2 = map[string][2]rune{ + // TODO(nigeltao): Handle replacements that are wider than their names. + // "nLt;": {'\u226A', '\u20D2'}, + // "nGt;": {'\u226B', '\u20D2'}, + "NotEqualTilde;": {'\u2242', '\u0338'}, + "NotGreaterFullEqual;": {'\u2267', '\u0338'}, + "NotGreaterGreater;": {'\u226B', '\u0338'}, + "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'}, + "NotHumpDownHump;": {'\u224E', '\u0338'}, + "NotHumpEqual;": {'\u224F', '\u0338'}, + "NotLeftTriangleBar;": {'\u29CF', '\u0338'}, + "NotLessLess;": {'\u226A', '\u0338'}, + "NotLessSlantEqual;": {'\u2A7D', '\u0338'}, + "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'}, + "NotNestedLessLess;": {'\u2AA1', '\u0338'}, + "NotPrecedesEqual;": {'\u2AAF', '\u0338'}, + "NotRightTriangleBar;": {'\u29D0', '\u0338'}, + "NotSquareSubset;": {'\u228F', '\u0338'}, + "NotSquareSuperset;": {'\u2290', '\u0338'}, + "NotSubset;": {'\u2282', '\u20D2'}, + "NotSucceedsEqual;": {'\u2AB0', '\u0338'}, + "NotSucceedsTilde;": {'\u227F', '\u0338'}, + "NotSuperset;": {'\u2283', '\u20D2'}, + "ThickSpace;": {'\u205F', '\u200A'}, + "acE;": {'\u223E', '\u0333'}, + "bne;": {'\u003D', '\u20E5'}, + "bnequiv;": {'\u2261', '\u20E5'}, + "caps;": {'\u2229', '\uFE00'}, + "cups;": {'\u222A', '\uFE00'}, + "fjlig;": {'\u0066', '\u006A'}, + "gesl;": {'\u22DB', '\uFE00'}, + "gvertneqq;": {'\u2269', '\uFE00'}, + "gvnE;": {'\u2269', '\uFE00'}, + "lates;": {'\u2AAD', '\uFE00'}, + "lesg;": {'\u22DA', '\uFE00'}, + "lvertneqq;": {'\u2268', '\uFE00'}, + "lvnE;": {'\u2268', '\uFE00'}, + "nGg;": {'\u22D9', '\u0338'}, + "nGtv;": {'\u226B', '\u0338'}, + "nLl;": {'\u22D8', '\u0338'}, + "nLtv;": {'\u226A', '\u0338'}, + "nang;": {'\u2220', '\u20D2'}, + "napE;": {'\u2A70', '\u0338'}, + "napid;": {'\u224B', '\u0338'}, + "nbump;": {'\u224E', '\u0338'}, + "nbumpe;": {'\u224F', '\u0338'}, + "ncongdot;": {'\u2A6D', '\u0338'}, + "nedot;": {'\u2250', '\u0338'}, + "nesim;": {'\u2242', '\u0338'}, + "ngE;": {'\u2267', '\u0338'}, + "ngeqq;": {'\u2267', '\u0338'}, + "ngeqslant;": {'\u2A7E', '\u0338'}, + "nges;": {'\u2A7E', '\u0338'}, + "nlE;": {'\u2266', '\u0338'}, + "nleqq;": {'\u2266', '\u0338'}, + "nleqslant;": {'\u2A7D', '\u0338'}, + "nles;": {'\u2A7D', '\u0338'}, + "notinE;": {'\u22F9', '\u0338'}, + "notindot;": {'\u22F5', '\u0338'}, + "nparsl;": {'\u2AFD', '\u20E5'}, + "npart;": {'\u2202', '\u0338'}, + "npre;": {'\u2AAF', '\u0338'}, + "npreceq;": {'\u2AAF', '\u0338'}, + "nrarrc;": {'\u2933', '\u0338'}, + "nrarrw;": {'\u219D', '\u0338'}, + "nsce;": {'\u2AB0', '\u0338'}, + "nsubE;": {'\u2AC5', '\u0338'}, + "nsubset;": {'\u2282', '\u20D2'}, + "nsubseteqq;": {'\u2AC5', '\u0338'}, + "nsucceq;": {'\u2AB0', '\u0338'}, + "nsupE;": {'\u2AC6', '\u0338'}, + "nsupset;": {'\u2283', '\u20D2'}, + "nsupseteqq;": {'\u2AC6', '\u0338'}, + "nvap;": {'\u224D', '\u20D2'}, + "nvge;": {'\u2265', '\u20D2'}, + "nvgt;": {'\u003E', '\u20D2'}, + "nvle;": {'\u2264', '\u20D2'}, + "nvlt;": {'\u003C', '\u20D2'}, + "nvltrie;": {'\u22B4', '\u20D2'}, + "nvrtrie;": {'\u22B5', '\u20D2'}, + "nvsim;": {'\u223C', '\u20D2'}, + "race;": {'\u223D', '\u0331'}, + "smtes;": {'\u2AAC', '\uFE00'}, + "sqcaps;": {'\u2293', '\uFE00'}, + "sqcups;": {'\u2294', '\uFE00'}, + "varsubsetneq;": {'\u228A', '\uFE00'}, + "varsubsetneqq;": {'\u2ACB', '\uFE00'}, + "varsupsetneq;": {'\u228B', '\uFE00'}, + "varsupsetneqq;": {'\u2ACC', '\uFE00'}, + "vnsub;": {'\u2282', '\u20D2'}, + "vnsup;": {'\u2283', '\u20D2'}, + "vsubnE;": {'\u2ACB', '\uFE00'}, + "vsubne;": {'\u228A', '\uFE00'}, + "vsupnE;": {'\u2ACC', '\uFE00'}, + "vsupne;": {'\u228B', '\uFE00'}, +} diff --git a/vendor/golang.org/x/net/html/escape.go b/vendor/golang.org/x/net/html/escape.go new file mode 100644 index 00000000..d8561396 --- /dev/null +++ b/vendor/golang.org/x/net/html/escape.go @@ -0,0 +1,258 @@ +// Copyright 2010 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 html + +import ( + "bytes" + "strings" + "unicode/utf8" +) + +// These replacements permit compatibility with old numeric entities that +// assumed Windows-1252 encoding. +// https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference +var replacementTable = [...]rune{ + '\u20AC', // First entry is what 0x80 should be replaced with. + '\u0081', + '\u201A', + '\u0192', + '\u201E', + '\u2026', + '\u2020', + '\u2021', + '\u02C6', + '\u2030', + '\u0160', + '\u2039', + '\u0152', + '\u008D', + '\u017D', + '\u008F', + '\u0090', + '\u2018', + '\u2019', + '\u201C', + '\u201D', + '\u2022', + '\u2013', + '\u2014', + '\u02DC', + '\u2122', + '\u0161', + '\u203A', + '\u0153', + '\u009D', + '\u017E', + '\u0178', // Last entry is 0x9F. + // 0x00->'\uFFFD' is handled programmatically. + // 0x0D->'\u000D' is a no-op. +} + +// unescapeEntity reads an entity like "<" from b[src:] and writes the +// corresponding "<" to b[dst:], returning the incremented dst and src cursors. +// Precondition: b[src] == '&' && dst <= src. +// attribute should be true if parsing an attribute value. +func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { + // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference + + // i starts at 1 because we already know that s[0] == '&'. + i, s := 1, b[src:] + + if len(s) <= 1 { + b[dst] = b[src] + return dst + 1, src + 1 + } + + if s[i] == '#' { + if len(s) <= 3 { // We need to have at least "&#.". + b[dst] = b[src] + return dst + 1, src + 1 + } + i++ + c := s[i] + hex := false + if c == 'x' || c == 'X' { + hex = true + i++ + } + + x := '\x00' + for i < len(s) { + c = s[i] + i++ + if hex { + if '0' <= c && c <= '9' { + x = 16*x + rune(c) - '0' + continue + } else if 'a' <= c && c <= 'f' { + x = 16*x + rune(c) - 'a' + 10 + continue + } else if 'A' <= c && c <= 'F' { + x = 16*x + rune(c) - 'A' + 10 + continue + } + } else if '0' <= c && c <= '9' { + x = 10*x + rune(c) - '0' + continue + } + if c != ';' { + i-- + } + break + } + + if i <= 3 { // No characters matched. + b[dst] = b[src] + return dst + 1, src + 1 + } + + if 0x80 <= x && x <= 0x9F { + // Replace characters from Windows-1252 with UTF-8 equivalents. + x = replacementTable[x-0x80] + } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF { + // Replace invalid characters with the replacement character. + x = '\uFFFD' + } + + return dst + utf8.EncodeRune(b[dst:], x), src + i + } + + // Consume the maximum number of characters possible, with the + // consumed characters matching one of the named references. + + for i < len(s) { + c := s[i] + i++ + // Lower-cased characters are more common in entities, so we check for them first. + if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { + continue + } + if c != ';' { + i-- + } + break + } + + entityName := string(s[1:i]) + if entityName == "" { + // No-op. + } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' { + // No-op. + } else if x := entity[entityName]; x != 0 { + return dst + utf8.EncodeRune(b[dst:], x), src + i + } else if x := entity2[entityName]; x[0] != 0 { + dst1 := dst + utf8.EncodeRune(b[dst:], x[0]) + return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i + } else if !attribute { + maxLen := len(entityName) - 1 + if maxLen > longestEntityWithoutSemicolon { + maxLen = longestEntityWithoutSemicolon + } + for j := maxLen; j > 1; j-- { + if x := entity[entityName[:j]]; x != 0 { + return dst + utf8.EncodeRune(b[dst:], x), src + j + 1 + } + } + } + + dst1, src1 = dst+i, src+i + copy(b[dst:dst1], b[src:src1]) + return dst1, src1 +} + +// unescape unescapes b's entities in-place, so that "a<b" becomes "a': + esc = ">" + case '"': + // """ is shorter than """. + esc = """ + case '\r': + esc = " " + default: + panic("unrecognized escape character") + } + s = s[i+1:] + if _, err := w.WriteString(esc); err != nil { + return err + } + i = strings.IndexAny(s, escapedChars) + } + _, err := w.WriteString(s) + return err +} + +// EscapeString escapes special characters like "<" to become "<". It +// escapes only five such characters: <, >, &, ' and ". +// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't +// always true. +func EscapeString(s string) string { + if strings.IndexAny(s, escapedChars) == -1 { + return s + } + var buf bytes.Buffer + escape(&buf, s) + return buf.String() +} + +// UnescapeString unescapes entities like "<" to become "<". It unescapes a +// larger range of entities than EscapeString escapes. For example, "á" +// unescapes to "á", as does "á" and "&xE1;". +// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't +// always true. +func UnescapeString(s string) string { + for _, c := range s { + if c == '&' { + return string(unescape([]byte(s), false)) + } + } + return s +} diff --git a/vendor/golang.org/x/net/html/foreign.go b/vendor/golang.org/x/net/html/foreign.go new file mode 100644 index 00000000..01477a96 --- /dev/null +++ b/vendor/golang.org/x/net/html/foreign.go @@ -0,0 +1,226 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +import ( + "strings" +) + +func adjustAttributeNames(aa []Attribute, nameMap map[string]string) { + for i := range aa { + if newName, ok := nameMap[aa[i].Key]; ok { + aa[i].Key = newName + } + } +} + +func adjustForeignAttributes(aa []Attribute) { + for i, a := range aa { + if a.Key == "" || a.Key[0] != 'x' { + continue + } + switch a.Key { + case "xlink:actuate", "xlink:arcrole", "xlink:href", "xlink:role", "xlink:show", + "xlink:title", "xlink:type", "xml:base", "xml:lang", "xml:space", "xmlns:xlink": + j := strings.Index(a.Key, ":") + aa[i].Namespace = a.Key[:j] + aa[i].Key = a.Key[j+1:] + } + } +} + +func htmlIntegrationPoint(n *Node) bool { + if n.Type != ElementNode { + return false + } + switch n.Namespace { + case "math": + if n.Data == "annotation-xml" { + for _, a := range n.Attr { + if a.Key == "encoding" { + val := strings.ToLower(a.Val) + if val == "text/html" || val == "application/xhtml+xml" { + return true + } + } + } + } + case "svg": + switch n.Data { + case "desc", "foreignObject", "title": + return true + } + } + return false +} + +func mathMLTextIntegrationPoint(n *Node) bool { + if n.Namespace != "math" { + return false + } + switch n.Data { + case "mi", "mo", "mn", "ms", "mtext": + return true + } + return false +} + +// Section 12.2.6.5. +var breakout = map[string]bool{ + "b": true, + "big": true, + "blockquote": true, + "body": true, + "br": true, + "center": true, + "code": true, + "dd": true, + "div": true, + "dl": true, + "dt": true, + "em": true, + "embed": true, + "h1": true, + "h2": true, + "h3": true, + "h4": true, + "h5": true, + "h6": true, + "head": true, + "hr": true, + "i": true, + "img": true, + "li": true, + "listing": true, + "menu": true, + "meta": true, + "nobr": true, + "ol": true, + "p": true, + "pre": true, + "ruby": true, + "s": true, + "small": true, + "span": true, + "strong": true, + "strike": true, + "sub": true, + "sup": true, + "table": true, + "tt": true, + "u": true, + "ul": true, + "var": true, +} + +// Section 12.2.6.5. +var svgTagNameAdjustments = map[string]string{ + "altglyph": "altGlyph", + "altglyphdef": "altGlyphDef", + "altglyphitem": "altGlyphItem", + "animatecolor": "animateColor", + "animatemotion": "animateMotion", + "animatetransform": "animateTransform", + "clippath": "clipPath", + "feblend": "feBlend", + "fecolormatrix": "feColorMatrix", + "fecomponenttransfer": "feComponentTransfer", + "fecomposite": "feComposite", + "feconvolvematrix": "feConvolveMatrix", + "fediffuselighting": "feDiffuseLighting", + "fedisplacementmap": "feDisplacementMap", + "fedistantlight": "feDistantLight", + "feflood": "feFlood", + "fefunca": "feFuncA", + "fefuncb": "feFuncB", + "fefuncg": "feFuncG", + "fefuncr": "feFuncR", + "fegaussianblur": "feGaussianBlur", + "feimage": "feImage", + "femerge": "feMerge", + "femergenode": "feMergeNode", + "femorphology": "feMorphology", + "feoffset": "feOffset", + "fepointlight": "fePointLight", + "fespecularlighting": "feSpecularLighting", + "fespotlight": "feSpotLight", + "fetile": "feTile", + "feturbulence": "feTurbulence", + "foreignobject": "foreignObject", + "glyphref": "glyphRef", + "lineargradient": "linearGradient", + "radialgradient": "radialGradient", + "textpath": "textPath", +} + +// Section 12.2.6.1 +var mathMLAttributeAdjustments = map[string]string{ + "definitionurl": "definitionURL", +} + +var svgAttributeAdjustments = map[string]string{ + "attributename": "attributeName", + "attributetype": "attributeType", + "basefrequency": "baseFrequency", + "baseprofile": "baseProfile", + "calcmode": "calcMode", + "clippathunits": "clipPathUnits", + "contentscripttype": "contentScriptType", + "contentstyletype": "contentStyleType", + "diffuseconstant": "diffuseConstant", + "edgemode": "edgeMode", + "externalresourcesrequired": "externalResourcesRequired", + "filterres": "filterRes", + "filterunits": "filterUnits", + "glyphref": "glyphRef", + "gradienttransform": "gradientTransform", + "gradientunits": "gradientUnits", + "kernelmatrix": "kernelMatrix", + "kernelunitlength": "kernelUnitLength", + "keypoints": "keyPoints", + "keysplines": "keySplines", + "keytimes": "keyTimes", + "lengthadjust": "lengthAdjust", + "limitingconeangle": "limitingConeAngle", + "markerheight": "markerHeight", + "markerunits": "markerUnits", + "markerwidth": "markerWidth", + "maskcontentunits": "maskContentUnits", + "maskunits": "maskUnits", + "numoctaves": "numOctaves", + "pathlength": "pathLength", + "patterncontentunits": "patternContentUnits", + "patterntransform": "patternTransform", + "patternunits": "patternUnits", + "pointsatx": "pointsAtX", + "pointsaty": "pointsAtY", + "pointsatz": "pointsAtZ", + "preservealpha": "preserveAlpha", + "preserveaspectratio": "preserveAspectRatio", + "primitiveunits": "primitiveUnits", + "refx": "refX", + "refy": "refY", + "repeatcount": "repeatCount", + "repeatdur": "repeatDur", + "requiredextensions": "requiredExtensions", + "requiredfeatures": "requiredFeatures", + "specularconstant": "specularConstant", + "specularexponent": "specularExponent", + "spreadmethod": "spreadMethod", + "startoffset": "startOffset", + "stddeviation": "stdDeviation", + "stitchtiles": "stitchTiles", + "surfacescale": "surfaceScale", + "systemlanguage": "systemLanguage", + "tablevalues": "tableValues", + "targetx": "targetX", + "targety": "targetY", + "textlength": "textLength", + "viewbox": "viewBox", + "viewtarget": "viewTarget", + "xchannelselector": "xChannelSelector", + "ychannelselector": "yChannelSelector", + "zoomandpan": "zoomAndPan", +} diff --git a/vendor/golang.org/x/net/html/node.go b/vendor/golang.org/x/net/html/node.go new file mode 100644 index 00000000..2c1cade6 --- /dev/null +++ b/vendor/golang.org/x/net/html/node.go @@ -0,0 +1,220 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package html + +import ( + "golang.org/x/net/html/atom" +) + +// A NodeType is the type of a Node. +type NodeType uint32 + +const ( + ErrorNode NodeType = iota + TextNode + DocumentNode + ElementNode + CommentNode + DoctypeNode + scopeMarkerNode +) + +// Section 12.2.4.3 says "The markers are inserted when entering applet, +// object, marquee, template, td, th, and caption elements, and are used +// to prevent formatting from "leaking" into applet, object, marquee, +// template, td, th, and caption elements". +var scopeMarker = Node{Type: scopeMarkerNode} + +// A Node consists of a NodeType and some Data (tag name for element nodes, +// content for text) and are part of a tree of Nodes. Element nodes may also +// have a Namespace and contain a slice of Attributes. Data is unescaped, so +// that it looks like "a 0 { + return (*s)[i-1] + } + return nil +} + +// index returns the index of the top-most occurrence of n in the stack, or -1 +// if n is not present. +func (s *nodeStack) index(n *Node) int { + for i := len(*s) - 1; i >= 0; i-- { + if (*s)[i] == n { + return i + } + } + return -1 +} + +// contains returns whether a is within s. +func (s *nodeStack) contains(a atom.Atom) bool { + for _, n := range *s { + if n.DataAtom == a { + return true + } + } + return false +} + +// insert inserts a node at the given index. +func (s *nodeStack) insert(i int, n *Node) { + (*s) = append(*s, nil) + copy((*s)[i+1:], (*s)[i:]) + (*s)[i] = n +} + +// remove removes a node from the stack. It is a no-op if n is not present. +func (s *nodeStack) remove(n *Node) { + i := s.index(n) + if i == -1 { + return + } + copy((*s)[i:], (*s)[i+1:]) + j := len(*s) - 1 + (*s)[j] = nil + *s = (*s)[:j] +} + +type insertionModeStack []insertionMode + +func (s *insertionModeStack) pop() (im insertionMode) { + i := len(*s) + im = (*s)[i-1] + *s = (*s)[:i-1] + return im +} + +func (s *insertionModeStack) top() insertionMode { + if i := len(*s); i > 0 { + return (*s)[i-1] + } + return nil +} diff --git a/vendor/golang.org/x/net/html/parse.go b/vendor/golang.org/x/net/html/parse.go new file mode 100644 index 00000000..64a57937 --- /dev/null +++ b/vendor/golang.org/x/net/html/parse.go @@ -0,0 +1,2311 @@ +// Copyright 2010 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 html + +import ( + "errors" + "fmt" + "io" + "strings" + + a "golang.org/x/net/html/atom" +) + +// A parser implements the HTML5 parsing algorithm: +// https://html.spec.whatwg.org/multipage/syntax.html#tree-construction +type parser struct { + // tokenizer provides the tokens for the parser. + tokenizer *Tokenizer + // tok is the most recently read token. + tok Token + // Self-closing tags like
are treated as start tags, except that + // hasSelfClosingToken is set while they are being processed. + hasSelfClosingToken bool + // doc is the document root element. + doc *Node + // The stack of open elements (section 12.2.4.2) and active formatting + // elements (section 12.2.4.3). + oe, afe nodeStack + // Element pointers (section 12.2.4.4). + head, form *Node + // Other parsing state flags (section 12.2.4.5). + scripting, framesetOK bool + // The stack of template insertion modes + templateStack insertionModeStack + // im is the current insertion mode. + im insertionMode + // originalIM is the insertion mode to go back to after completing a text + // or inTableText insertion mode. + originalIM insertionMode + // fosterParenting is whether new elements should be inserted according to + // the foster parenting rules (section 12.2.6.1). + fosterParenting bool + // quirks is whether the parser is operating in "quirks mode." + quirks bool + // fragment is whether the parser is parsing an HTML fragment. + fragment bool + // context is the context element when parsing an HTML fragment + // (section 12.4). + context *Node +} + +func (p *parser) top() *Node { + if n := p.oe.top(); n != nil { + return n + } + return p.doc +} + +// Stop tags for use in popUntil. These come from section 12.2.4.2. +var ( + defaultScopeStopTags = map[string][]a.Atom{ + "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template}, + "math": {a.AnnotationXml, a.Mi, a.Mn, a.Mo, a.Ms, a.Mtext}, + "svg": {a.Desc, a.ForeignObject, a.Title}, + } +) + +type scope int + +const ( + defaultScope scope = iota + listItemScope + buttonScope + tableScope + tableRowScope + tableBodyScope + selectScope +) + +// popUntil pops the stack of open elements at the highest element whose tag +// is in matchTags, provided there is no higher element in the scope's stop +// tags (as defined in section 12.2.4.2). It returns whether or not there was +// such an element. If there was not, popUntil leaves the stack unchanged. +// +// For example, the set of stop tags for table scope is: "html", "table". If +// the stack was: +// ["html", "body", "font", "table", "b", "i", "u"] +// then popUntil(tableScope, "font") would return false, but +// popUntil(tableScope, "i") would return true and the stack would become: +// ["html", "body", "font", "table", "b"] +// +// If an element's tag is in both the stop tags and matchTags, then the stack +// will be popped and the function returns true (provided, of course, there was +// no higher element in the stack that was also in the stop tags). For example, +// popUntil(tableScope, "table") returns true and leaves: +// ["html", "body", "font"] +func (p *parser) popUntil(s scope, matchTags ...a.Atom) bool { + if i := p.indexOfElementInScope(s, matchTags...); i != -1 { + p.oe = p.oe[:i] + return true + } + return false +} + +// indexOfElementInScope returns the index in p.oe of the highest element whose +// tag is in matchTags that is in scope. If no matching element is in scope, it +// returns -1. +func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { + for i := len(p.oe) - 1; i >= 0; i-- { + tagAtom := p.oe[i].DataAtom + if p.oe[i].Namespace == "" { + for _, t := range matchTags { + if t == tagAtom { + return i + } + } + switch s { + case defaultScope: + // No-op. + case listItemScope: + if tagAtom == a.Ol || tagAtom == a.Ul { + return -1 + } + case buttonScope: + if tagAtom == a.Button { + return -1 + } + case tableScope: + if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { + return -1 + } + case selectScope: + if tagAtom != a.Optgroup && tagAtom != a.Option { + return -1 + } + default: + panic("unreachable") + } + } + switch s { + case defaultScope, listItemScope, buttonScope: + for _, t := range defaultScopeStopTags[p.oe[i].Namespace] { + if t == tagAtom { + return -1 + } + } + } + } + return -1 +} + +// elementInScope is like popUntil, except that it doesn't modify the stack of +// open elements. +func (p *parser) elementInScope(s scope, matchTags ...a.Atom) bool { + return p.indexOfElementInScope(s, matchTags...) != -1 +} + +// clearStackToContext pops elements off the stack of open elements until a +// scope-defined element is found. +func (p *parser) clearStackToContext(s scope) { + for i := len(p.oe) - 1; i >= 0; i-- { + tagAtom := p.oe[i].DataAtom + switch s { + case tableScope: + if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { + p.oe = p.oe[:i+1] + return + } + case tableRowScope: + if tagAtom == a.Html || tagAtom == a.Tr || tagAtom == a.Template { + p.oe = p.oe[:i+1] + return + } + case tableBodyScope: + if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead || tagAtom == a.Template { + p.oe = p.oe[:i+1] + return + } + default: + panic("unreachable") + } + } +} + +// generateImpliedEndTags pops nodes off the stack of open elements as long as +// the top node has a tag name of dd, dt, li, optgroup, option, p, rb, rp, rt or rtc. +// If exceptions are specified, nodes with that name will not be popped off. +func (p *parser) generateImpliedEndTags(exceptions ...string) { + var i int +loop: + for i = len(p.oe) - 1; i >= 0; i-- { + n := p.oe[i] + if n.Type == ElementNode { + switch n.DataAtom { + case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc: + for _, except := range exceptions { + if n.Data == except { + break loop + } + } + continue + } + } + break + } + + p.oe = p.oe[:i+1] +} + +// addChild adds a child node n to the top element, and pushes n onto the stack +// of open elements if it is an element node. +func (p *parser) addChild(n *Node) { + if p.shouldFosterParent() { + p.fosterParent(n) + } else { + p.top().AppendChild(n) + } + + if n.Type == ElementNode { + p.oe = append(p.oe, n) + } +} + +// shouldFosterParent returns whether the next node to be added should be +// foster parented. +func (p *parser) shouldFosterParent() bool { + if p.fosterParenting { + switch p.top().DataAtom { + case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: + return true + } + } + return false +} + +// fosterParent adds a child node according to the foster parenting rules. +// Section 12.2.6.1, "foster parenting". +func (p *parser) fosterParent(n *Node) { + var table, parent, prev, template *Node + var i int + for i = len(p.oe) - 1; i >= 0; i-- { + if p.oe[i].DataAtom == a.Table { + table = p.oe[i] + break + } + } + + var j int + for j = len(p.oe) - 1; j >= 0; j-- { + if p.oe[j].DataAtom == a.Template { + template = p.oe[j] + break + } + } + + if template != nil && (table == nil || j > i) { + template.AppendChild(n) + return + } + + if table == nil { + // The foster parent is the html element. + parent = p.oe[0] + } else { + parent = table.Parent + } + if parent == nil { + parent = p.oe[i-1] + } + + if table != nil { + prev = table.PrevSibling + } else { + prev = parent.LastChild + } + if prev != nil && prev.Type == TextNode && n.Type == TextNode { + prev.Data += n.Data + return + } + + parent.InsertBefore(n, table) +} + +// addText adds text to the preceding node if it is a text node, or else it +// calls addChild with a new text node. +func (p *parser) addText(text string) { + if text == "" { + return + } + + if p.shouldFosterParent() { + p.fosterParent(&Node{ + Type: TextNode, + Data: text, + }) + return + } + + t := p.top() + if n := t.LastChild; n != nil && n.Type == TextNode { + n.Data += text + return + } + p.addChild(&Node{ + Type: TextNode, + Data: text, + }) +} + +// addElement adds a child element based on the current token. +func (p *parser) addElement() { + p.addChild(&Node{ + Type: ElementNode, + DataAtom: p.tok.DataAtom, + Data: p.tok.Data, + Attr: p.tok.Attr, + }) +} + +// Section 12.2.4.3. +func (p *parser) addFormattingElement() { + tagAtom, attr := p.tok.DataAtom, p.tok.Attr + p.addElement() + + // Implement the Noah's Ark clause, but with three per family instead of two. + identicalElements := 0 +findIdenticalElements: + for i := len(p.afe) - 1; i >= 0; i-- { + n := p.afe[i] + if n.Type == scopeMarkerNode { + break + } + if n.Type != ElementNode { + continue + } + if n.Namespace != "" { + continue + } + if n.DataAtom != tagAtom { + continue + } + if len(n.Attr) != len(attr) { + continue + } + compareAttributes: + for _, t0 := range n.Attr { + for _, t1 := range attr { + if t0.Key == t1.Key && t0.Namespace == t1.Namespace && t0.Val == t1.Val { + // Found a match for this attribute, continue with the next attribute. + continue compareAttributes + } + } + // If we get here, there is no attribute that matches a. + // Therefore the element is not identical to the new one. + continue findIdenticalElements + } + + identicalElements++ + if identicalElements >= 3 { + p.afe.remove(n) + } + } + + p.afe = append(p.afe, p.top()) +} + +// Section 12.2.4.3. +func (p *parser) clearActiveFormattingElements() { + for { + n := p.afe.pop() + if len(p.afe) == 0 || n.Type == scopeMarkerNode { + return + } + } +} + +// Section 12.2.4.3. +func (p *parser) reconstructActiveFormattingElements() { + n := p.afe.top() + if n == nil { + return + } + if n.Type == scopeMarkerNode || p.oe.index(n) != -1 { + return + } + i := len(p.afe) - 1 + for n.Type != scopeMarkerNode && p.oe.index(n) == -1 { + if i == 0 { + i = -1 + break + } + i-- + n = p.afe[i] + } + for { + i++ + clone := p.afe[i].clone() + p.addChild(clone) + p.afe[i] = clone + if i == len(p.afe)-1 { + break + } + } +} + +// Section 12.2.5. +func (p *parser) acknowledgeSelfClosingTag() { + p.hasSelfClosingToken = false +} + +// An insertion mode (section 12.2.4.1) is the state transition function from +// a particular state in the HTML5 parser's state machine. It updates the +// parser's fields depending on parser.tok (where ErrorToken means EOF). +// It returns whether the token was consumed. +type insertionMode func(*parser) bool + +// setOriginalIM sets the insertion mode to return to after completing a text or +// inTableText insertion mode. +// Section 12.2.4.1, "using the rules for". +func (p *parser) setOriginalIM() { + if p.originalIM != nil { + panic("html: bad parser state: originalIM was set twice") + } + p.originalIM = p.im +} + +// Section 12.2.4.1, "reset the insertion mode". +func (p *parser) resetInsertionMode() { + for i := len(p.oe) - 1; i >= 0; i-- { + n := p.oe[i] + last := i == 0 + if last && p.context != nil { + n = p.context + } + + switch n.DataAtom { + case a.Select: + if !last { + for ancestor, first := n, p.oe[0]; ancestor != first; { + if ancestor == first { + break + } + ancestor = p.oe[p.oe.index(ancestor)-1] + switch ancestor.DataAtom { + case a.Template: + p.im = inSelectIM + return + case a.Table: + p.im = inSelectInTableIM + return + } + } + } + p.im = inSelectIM + case a.Td, a.Th: + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + p.im = inCellIM + case a.Tr: + p.im = inRowIM + case a.Tbody, a.Thead, a.Tfoot: + p.im = inTableBodyIM + case a.Caption: + p.im = inCaptionIM + case a.Colgroup: + p.im = inColumnGroupIM + case a.Table: + p.im = inTableIM + case a.Template: + // TODO: remove this divergence from the HTML5 spec. + if n.Namespace != "" { + continue + } + p.im = p.templateStack.top() + case a.Head: + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + p.im = inHeadIM + case a.Body: + p.im = inBodyIM + case a.Frameset: + p.im = inFramesetIM + case a.Html: + if p.head == nil { + p.im = beforeHeadIM + } else { + p.im = afterHeadIM + } + default: + if last { + p.im = inBodyIM + return + } + continue + } + return + } +} + +const whitespace = " \t\r\n\f" + +// Section 12.2.6.4.1. +func initialIM(p *parser) bool { + switch p.tok.Type { + case TextToken: + p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) + if len(p.tok.Data) == 0 { + // It was all whitespace, so ignore it. + return true + } + case CommentToken: + p.doc.AppendChild(&Node{ + Type: CommentNode, + Data: p.tok.Data, + }) + return true + case DoctypeToken: + n, quirks := parseDoctype(p.tok.Data) + p.doc.AppendChild(n) + p.quirks = quirks + p.im = beforeHTMLIM + return true + } + p.quirks = true + p.im = beforeHTMLIM + return false +} + +// Section 12.2.6.4.2. +func beforeHTMLIM(p *parser) bool { + switch p.tok.Type { + case DoctypeToken: + // Ignore the token. + return true + case TextToken: + p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) + if len(p.tok.Data) == 0 { + // It was all whitespace, so ignore it. + return true + } + case StartTagToken: + if p.tok.DataAtom == a.Html { + p.addElement() + p.im = beforeHeadIM + return true + } + case EndTagToken: + switch p.tok.DataAtom { + case a.Head, a.Body, a.Html, a.Br: + p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) + return false + default: + // Ignore the token. + return true + } + case CommentToken: + p.doc.AppendChild(&Node{ + Type: CommentNode, + Data: p.tok.Data, + }) + return true + } + p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) + return false +} + +// Section 12.2.6.4.3. +func beforeHeadIM(p *parser) bool { + switch p.tok.Type { + case TextToken: + p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) + if len(p.tok.Data) == 0 { + // It was all whitespace, so ignore it. + return true + } + case StartTagToken: + switch p.tok.DataAtom { + case a.Head: + p.addElement() + p.head = p.top() + p.im = inHeadIM + return true + case a.Html: + return inBodyIM(p) + } + case EndTagToken: + switch p.tok.DataAtom { + case a.Head, a.Body, a.Html, a.Br: + p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) + return false + default: + // Ignore the token. + return true + } + case CommentToken: + p.addChild(&Node{ + Type: CommentNode, + Data: p.tok.Data, + }) + return true + case DoctypeToken: + // Ignore the token. + return true + } + + p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) + return false +} + +// Section 12.2.6.4.4. +func inHeadIM(p *parser) bool { + switch p.tok.Type { + case TextToken: + s := strings.TrimLeft(p.tok.Data, whitespace) + if len(s) < len(p.tok.Data) { + // Add the initial whitespace to the current node. + p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) + if s == "" { + return true + } + p.tok.Data = s + } + case StartTagToken: + switch p.tok.DataAtom { + case a.Html: + return inBodyIM(p) + case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta: + p.addElement() + p.oe.pop() + p.acknowledgeSelfClosingTag() + return true + case a.Script, a.Title, a.Noscript, a.Noframes, a.Style: + p.addElement() + p.setOriginalIM() + p.im = textIM + return true + case a.Head: + // Ignore the token. + return true + case a.Template: + p.addElement() + p.afe = append(p.afe, &scopeMarker) + p.framesetOK = false + p.im = inTemplateIM + p.templateStack = append(p.templateStack, inTemplateIM) + return true + } + case EndTagToken: + switch p.tok.DataAtom { + case a.Head: + p.oe.pop() + p.im = afterHeadIM + return true + case a.Body, a.Html, a.Br: + p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) + return false + case a.Template: + if !p.oe.contains(a.Template) { + return true + } + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + p.generateImpliedEndTags() + for i := len(p.oe) - 1; i >= 0; i-- { + if n := p.oe[i]; n.Namespace == "" && n.DataAtom == a.Template { + p.oe = p.oe[:i] + break + } + } + p.clearActiveFormattingElements() + p.templateStack.pop() + p.resetInsertionMode() + return true + default: + // Ignore the token. + return true + } + case CommentToken: + p.addChild(&Node{ + Type: CommentNode, + Data: p.tok.Data, + }) + return true + case DoctypeToken: + // Ignore the token. + return true + } + + p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) + return false +} + +// Section 12.2.6.4.6. +func afterHeadIM(p *parser) bool { + switch p.tok.Type { + case TextToken: + s := strings.TrimLeft(p.tok.Data, whitespace) + if len(s) < len(p.tok.Data) { + // Add the initial whitespace to the current node. + p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) + if s == "" { + return true + } + p.tok.Data = s + } + case StartTagToken: + switch p.tok.DataAtom { + case a.Html: + return inBodyIM(p) + case a.Body: + p.addElement() + p.framesetOK = false + p.im = inBodyIM + return true + case a.Frameset: + p.addElement() + p.im = inFramesetIM + return true + case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title: + p.oe = append(p.oe, p.head) + defer p.oe.remove(p.head) + return inHeadIM(p) + case a.Head: + // Ignore the token. + return true + } + case EndTagToken: + switch p.tok.DataAtom { + case a.Body, a.Html, a.Br: + // Drop down to creating an implied tag. + case a.Template: + return inHeadIM(p) + default: + // Ignore the token. + return true + } + case CommentToken: + p.addChild(&Node{ + Type: CommentNode, + Data: p.tok.Data, + }) + return true + case DoctypeToken: + // Ignore the token. + return true + } + + p.parseImpliedToken(StartTagToken, a.Body, a.Body.String()) + p.framesetOK = true + return false +} + +// copyAttributes copies attributes of src not found on dst to dst. +func copyAttributes(dst *Node, src Token) { + if len(src.Attr) == 0 { + return + } + attr := map[string]string{} + for _, t := range dst.Attr { + attr[t.Key] = t.Val + } + for _, t := range src.Attr { + if _, ok := attr[t.Key]; !ok { + dst.Attr = append(dst.Attr, t) + attr[t.Key] = t.Val + } + } +} + +// Section 12.2.6.4.7. +func inBodyIM(p *parser) bool { + switch p.tok.Type { + case TextToken: + d := p.tok.Data + switch n := p.oe.top(); n.DataAtom { + case a.Pre, a.Listing: + if n.FirstChild == nil { + // Ignore a newline at the start of a
 block.
+				if d != "" && d[0] == '\r' {
+					d = d[1:]
+				}
+				if d != "" && d[0] == '\n' {
+					d = d[1:]
+				}
+			}
+		}
+		d = strings.Replace(d, "\x00", "", -1)
+		if d == "" {
+			return true
+		}
+		p.reconstructActiveFormattingElements()
+		p.addText(d)
+		if p.framesetOK && strings.TrimLeft(d, whitespace) != "" {
+			// There were non-whitespace characters inserted.
+			p.framesetOK = false
+		}
+	case StartTagToken:
+		switch p.tok.DataAtom {
+		case a.Html:
+			if p.oe.contains(a.Template) {
+				return true
+			}
+			copyAttributes(p.oe[0], p.tok)
+		case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
+			return inHeadIM(p)
+		case a.Body:
+			if p.oe.contains(a.Template) {
+				return true
+			}
+			if len(p.oe) >= 2 {
+				body := p.oe[1]
+				if body.Type == ElementNode && body.DataAtom == a.Body {
+					p.framesetOK = false
+					copyAttributes(body, p.tok)
+				}
+			}
+		case a.Frameset:
+			if !p.framesetOK || len(p.oe) < 2 || p.oe[1].DataAtom != a.Body {
+				// Ignore the token.
+				return true
+			}
+			body := p.oe[1]
+			if body.Parent != nil {
+				body.Parent.RemoveChild(body)
+			}
+			p.oe = p.oe[:1]
+			p.addElement()
+			p.im = inFramesetIM
+			return true
+		case a.Address, a.Article, a.Aside, a.Blockquote, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Menu, a.Nav, a.Ol, a.P, a.Section, a.Summary, a.Ul:
+			p.popUntil(buttonScope, a.P)
+			p.addElement()
+		case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
+			p.popUntil(buttonScope, a.P)
+			switch n := p.top(); n.DataAtom {
+			case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
+				p.oe.pop()
+			}
+			p.addElement()
+		case a.Pre, a.Listing:
+			p.popUntil(buttonScope, a.P)
+			p.addElement()
+			// The newline, if any, will be dealt with by the TextToken case.
+			p.framesetOK = false
+		case a.Form:
+			if p.form != nil && !p.oe.contains(a.Template) {
+				// Ignore the token
+				return true
+			}
+			p.popUntil(buttonScope, a.P)
+			p.addElement()
+			if !p.oe.contains(a.Template) {
+				p.form = p.top()
+			}
+		case a.Li:
+			p.framesetOK = false
+			for i := len(p.oe) - 1; i >= 0; i-- {
+				node := p.oe[i]
+				switch node.DataAtom {
+				case a.Li:
+					p.oe = p.oe[:i]
+				case a.Address, a.Div, a.P:
+					continue
+				default:
+					if !isSpecialElement(node) {
+						continue
+					}
+				}
+				break
+			}
+			p.popUntil(buttonScope, a.P)
+			p.addElement()
+		case a.Dd, a.Dt:
+			p.framesetOK = false
+			for i := len(p.oe) - 1; i >= 0; i-- {
+				node := p.oe[i]
+				switch node.DataAtom {
+				case a.Dd, a.Dt:
+					p.oe = p.oe[:i]
+				case a.Address, a.Div, a.P:
+					continue
+				default:
+					if !isSpecialElement(node) {
+						continue
+					}
+				}
+				break
+			}
+			p.popUntil(buttonScope, a.P)
+			p.addElement()
+		case a.Plaintext:
+			p.popUntil(buttonScope, a.P)
+			p.addElement()
+		case a.Button:
+			p.popUntil(defaultScope, a.Button)
+			p.reconstructActiveFormattingElements()
+			p.addElement()
+			p.framesetOK = false
+		case a.A:
+			for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- {
+				if n := p.afe[i]; n.Type == ElementNode && n.DataAtom == a.A {
+					p.inBodyEndTagFormatting(a.A)
+					p.oe.remove(n)
+					p.afe.remove(n)
+					break
+				}
+			}
+			p.reconstructActiveFormattingElements()
+			p.addFormattingElement()
+		case a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
+			p.reconstructActiveFormattingElements()
+			p.addFormattingElement()
+		case a.Nobr:
+			p.reconstructActiveFormattingElements()
+			if p.elementInScope(defaultScope, a.Nobr) {
+				p.inBodyEndTagFormatting(a.Nobr)
+				p.reconstructActiveFormattingElements()
+			}
+			p.addFormattingElement()
+		case a.Applet, a.Marquee, a.Object:
+			p.reconstructActiveFormattingElements()
+			p.addElement()
+			p.afe = append(p.afe, &scopeMarker)
+			p.framesetOK = false
+		case a.Table:
+			if !p.quirks {
+				p.popUntil(buttonScope, a.P)
+			}
+			p.addElement()
+			p.framesetOK = false
+			p.im = inTableIM
+			return true
+		case a.Area, a.Br, a.Embed, a.Img, a.Input, a.Keygen, a.Wbr:
+			p.reconstructActiveFormattingElements()
+			p.addElement()
+			p.oe.pop()
+			p.acknowledgeSelfClosingTag()
+			if p.tok.DataAtom == a.Input {
+				for _, t := range p.tok.Attr {
+					if t.Key == "type" {
+						if strings.ToLower(t.Val) == "hidden" {
+							// Skip setting framesetOK = false
+							return true
+						}
+					}
+				}
+			}
+			p.framesetOK = false
+		case a.Param, a.Source, a.Track:
+			p.addElement()
+			p.oe.pop()
+			p.acknowledgeSelfClosingTag()
+		case a.Hr:
+			p.popUntil(buttonScope, a.P)
+			p.addElement()
+			p.oe.pop()
+			p.acknowledgeSelfClosingTag()
+			p.framesetOK = false
+		case a.Image:
+			p.tok.DataAtom = a.Img
+			p.tok.Data = a.Img.String()
+			return false
+		case a.Isindex:
+			if p.form != nil {
+				// Ignore the token.
+				return true
+			}
+			action := ""
+			prompt := "This is a searchable index. Enter search keywords: "
+			attr := []Attribute{{Key: "name", Val: "isindex"}}
+			for _, t := range p.tok.Attr {
+				switch t.Key {
+				case "action":
+					action = t.Val
+				case "name":
+					// Ignore the attribute.
+				case "prompt":
+					prompt = t.Val
+				default:
+					attr = append(attr, t)
+				}
+			}
+			p.acknowledgeSelfClosingTag()
+			p.popUntil(buttonScope, a.P)
+			p.parseImpliedToken(StartTagToken, a.Form, a.Form.String())
+			if p.form == nil {
+				// NOTE: The 'isindex' element has been removed,
+				// and the 'template' element has not been designed to be
+				// collaborative with the index element.
+				//
+				// Ignore the token.
+				return true
+			}
+			if action != "" {
+				p.form.Attr = []Attribute{{Key: "action", Val: action}}
+			}
+			p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
+			p.parseImpliedToken(StartTagToken, a.Label, a.Label.String())
+			p.addText(prompt)
+			p.addChild(&Node{
+				Type:     ElementNode,
+				DataAtom: a.Input,
+				Data:     a.Input.String(),
+				Attr:     attr,
+			})
+			p.oe.pop()
+			p.parseImpliedToken(EndTagToken, a.Label, a.Label.String())
+			p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
+			p.parseImpliedToken(EndTagToken, a.Form, a.Form.String())
+		case a.Textarea:
+			p.addElement()
+			p.setOriginalIM()
+			p.framesetOK = false
+			p.im = textIM
+		case a.Xmp:
+			p.popUntil(buttonScope, a.P)
+			p.reconstructActiveFormattingElements()
+			p.framesetOK = false
+			p.addElement()
+			p.setOriginalIM()
+			p.im = textIM
+		case a.Iframe:
+			p.framesetOK = false
+			p.addElement()
+			p.setOriginalIM()
+			p.im = textIM
+		case a.Noembed, a.Noscript:
+			p.addElement()
+			p.setOriginalIM()
+			p.im = textIM
+		case a.Select:
+			p.reconstructActiveFormattingElements()
+			p.addElement()
+			p.framesetOK = false
+			p.im = inSelectIM
+			return true
+		case a.Optgroup, a.Option:
+			if p.top().DataAtom == a.Option {
+				p.oe.pop()
+			}
+			p.reconstructActiveFormattingElements()
+			p.addElement()
+		case a.Rb, a.Rtc:
+			if p.elementInScope(defaultScope, a.Ruby) {
+				p.generateImpliedEndTags()
+			}
+			p.addElement()
+		case a.Rp, a.Rt:
+			if p.elementInScope(defaultScope, a.Ruby) {
+				p.generateImpliedEndTags("rtc")
+			}
+			p.addElement()
+		case a.Math, a.Svg:
+			p.reconstructActiveFormattingElements()
+			if p.tok.DataAtom == a.Math {
+				adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments)
+			} else {
+				adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments)
+			}
+			adjustForeignAttributes(p.tok.Attr)
+			p.addElement()
+			p.top().Namespace = p.tok.Data
+			if p.hasSelfClosingToken {
+				p.oe.pop()
+				p.acknowledgeSelfClosingTag()
+			}
+			return true
+		case a.Caption, a.Col, a.Colgroup, a.Frame, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
+			// Ignore the token.
+		default:
+			p.reconstructActiveFormattingElements()
+			p.addElement()
+		}
+	case EndTagToken:
+		switch p.tok.DataAtom {
+		case a.Body:
+			if p.elementInScope(defaultScope, a.Body) {
+				p.im = afterBodyIM
+			}
+		case a.Html:
+			if p.elementInScope(defaultScope, a.Body) {
+				p.parseImpliedToken(EndTagToken, a.Body, a.Body.String())
+				return false
+			}
+			return true
+		case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul:
+			p.popUntil(defaultScope, p.tok.DataAtom)
+		case a.Form:
+			if p.oe.contains(a.Template) {
+				i := p.indexOfElementInScope(defaultScope, a.Form)
+				if i == -1 {
+					// Ignore the token.
+					return true
+				}
+				p.generateImpliedEndTags()
+				if p.oe[i].DataAtom != a.Form {
+					// Ignore the token.
+					return true
+				}
+				p.popUntil(defaultScope, a.Form)
+			} else {
+				node := p.form
+				p.form = nil
+				i := p.indexOfElementInScope(defaultScope, a.Form)
+				if node == nil || i == -1 || p.oe[i] != node {
+					// Ignore the token.
+					return true
+				}
+				p.generateImpliedEndTags()
+				p.oe.remove(node)
+			}
+		case a.P:
+			if !p.elementInScope(buttonScope, a.P) {
+				p.parseImpliedToken(StartTagToken, a.P, a.P.String())
+			}
+			p.popUntil(buttonScope, a.P)
+		case a.Li:
+			p.popUntil(listItemScope, a.Li)
+		case a.Dd, a.Dt:
+			p.popUntil(defaultScope, p.tok.DataAtom)
+		case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
+			p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6)
+		case a.A, a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.Nobr, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
+			p.inBodyEndTagFormatting(p.tok.DataAtom)
+		case a.Applet, a.Marquee, a.Object:
+			if p.popUntil(defaultScope, p.tok.DataAtom) {
+				p.clearActiveFormattingElements()
+			}
+		case a.Br:
+			p.tok.Type = StartTagToken
+			return false
+		case a.Template:
+			return inHeadIM(p)
+		default:
+			p.inBodyEndTagOther(p.tok.DataAtom)
+		}
+	case CommentToken:
+		p.addChild(&Node{
+			Type: CommentNode,
+			Data: p.tok.Data,
+		})
+	case ErrorToken:
+		// TODO: remove this divergence from the HTML5 spec.
+		if len(p.templateStack) > 0 {
+			p.im = inTemplateIM
+			return false
+		} else {
+			for _, e := range p.oe {
+				switch e.DataAtom {
+				case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc, a.Tbody, a.Td, a.Tfoot, a.Th,
+					a.Thead, a.Tr, a.Body, a.Html:
+				default:
+					return true
+				}
+			}
+		}
+	}
+
+	return true
+}
+
+func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) {
+	// This is the "adoption agency" algorithm, described at
+	// https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency
+
+	// TODO: this is a fairly literal line-by-line translation of that algorithm.
+	// Once the code successfully parses the comprehensive test suite, we should
+	// refactor this code to be more idiomatic.
+
+	// Steps 1-4. The outer loop.
+	for i := 0; i < 8; i++ {
+		// Step 5. Find the formatting element.
+		var formattingElement *Node
+		for j := len(p.afe) - 1; j >= 0; j-- {
+			if p.afe[j].Type == scopeMarkerNode {
+				break
+			}
+			if p.afe[j].DataAtom == tagAtom {
+				formattingElement = p.afe[j]
+				break
+			}
+		}
+		if formattingElement == nil {
+			p.inBodyEndTagOther(tagAtom)
+			return
+		}
+		feIndex := p.oe.index(formattingElement)
+		if feIndex == -1 {
+			p.afe.remove(formattingElement)
+			return
+		}
+		if !p.elementInScope(defaultScope, tagAtom) {
+			// Ignore the tag.
+			return
+		}
+
+		// Steps 9-10. Find the furthest block.
+		var furthestBlock *Node
+		for _, e := range p.oe[feIndex:] {
+			if isSpecialElement(e) {
+				furthestBlock = e
+				break
+			}
+		}
+		if furthestBlock == nil {
+			e := p.oe.pop()
+			for e != formattingElement {
+				e = p.oe.pop()
+			}
+			p.afe.remove(e)
+			return
+		}
+
+		// Steps 11-12. Find the common ancestor and bookmark node.
+		commonAncestor := p.oe[feIndex-1]
+		bookmark := p.afe.index(formattingElement)
+
+		// Step 13. The inner loop. Find the lastNode to reparent.
+		lastNode := furthestBlock
+		node := furthestBlock
+		x := p.oe.index(node)
+		// Steps 13.1-13.2
+		for j := 0; j < 3; j++ {
+			// Step 13.3.
+			x--
+			node = p.oe[x]
+			// Step 13.4 - 13.5.
+			if p.afe.index(node) == -1 {
+				p.oe.remove(node)
+				continue
+			}
+			// Step 13.6.
+			if node == formattingElement {
+				break
+			}
+			// Step 13.7.
+			clone := node.clone()
+			p.afe[p.afe.index(node)] = clone
+			p.oe[p.oe.index(node)] = clone
+			node = clone
+			// Step 13.8.
+			if lastNode == furthestBlock {
+				bookmark = p.afe.index(node) + 1
+			}
+			// Step 13.9.
+			if lastNode.Parent != nil {
+				lastNode.Parent.RemoveChild(lastNode)
+			}
+			node.AppendChild(lastNode)
+			// Step 13.10.
+			lastNode = node
+		}
+
+		// Step 14. Reparent lastNode to the common ancestor,
+		// or for misnested table nodes, to the foster parent.
+		if lastNode.Parent != nil {
+			lastNode.Parent.RemoveChild(lastNode)
+		}
+		switch commonAncestor.DataAtom {
+		case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
+			p.fosterParent(lastNode)
+		default:
+			commonAncestor.AppendChild(lastNode)
+		}
+
+		// Steps 15-17. Reparent nodes from the furthest block's children
+		// to a clone of the formatting element.
+		clone := formattingElement.clone()
+		reparentChildren(clone, furthestBlock)
+		furthestBlock.AppendChild(clone)
+
+		// Step 18. Fix up the list of active formatting elements.
+		if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark {
+			// Move the bookmark with the rest of the list.
+			bookmark--
+		}
+		p.afe.remove(formattingElement)
+		p.afe.insert(bookmark, clone)
+
+		// Step 19. Fix up the stack of open elements.
+		p.oe.remove(formattingElement)
+		p.oe.insert(p.oe.index(furthestBlock)+1, clone)
+	}
+}
+
+// inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM.
+// "Any other end tag" handling from 12.2.6.5 The rules for parsing tokens in foreign content
+// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign
+func (p *parser) inBodyEndTagOther(tagAtom a.Atom) {
+	for i := len(p.oe) - 1; i >= 0; i-- {
+		if p.oe[i].DataAtom == tagAtom {
+			p.oe = p.oe[:i]
+			break
+		}
+		if isSpecialElement(p.oe[i]) {
+			break
+		}
+	}
+}
+
+// Section 12.2.6.4.8.
+func textIM(p *parser) bool {
+	switch p.tok.Type {
+	case ErrorToken:
+		p.oe.pop()
+	case TextToken:
+		d := p.tok.Data
+		if n := p.oe.top(); n.DataAtom == a.Textarea && n.FirstChild == nil {
+			// Ignore a newline at the start of a