diff --git a/.github/labeler-issue-triage.yml b/.github/labeler-issue-triage.yml index cafa691fd661..ba97f5f93250 100644 --- a/.github/labeler-issue-triage.yml +++ b/.github/labeler-issue-triage.yml @@ -27,7 +27,7 @@ service/app-configuration: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_app_configuration((.|\n)*)###' service/app-service: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(app_service_environment_v3\W+|app_service_environment_v3\W+|app_service_source_control\W+|app_service_source_control_slot\W+|function_app_active_slot\W+|function_app_function\W+|function_app_hybrid_connection\W+|linux_function_app\W+|linux_function_app\W+|linux_function_app_slot\W+|linux_web_app\W+|linux_web_app\W+|linux_web_app_slot\W+|service_plan|source_control_token|static_web_app|web_app_|windows_function_app\W+|windows_function_app\W+|windows_function_app_slot\W+|windows_web_app\W+|windows_web_app\W+|windows_web_app_slot\W+)((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(app_service_environment_v3\W+|app_service_environment_v3\W+|app_service_source_control\W+|app_service_source_control_slot\W+|arc_kubernetes_cluster_extension\W+|arc_kubernetes_flux_configuration\W+|function_app_active_slot\W+|function_app_function\W+|function_app_hybrid_connection\W+|linux_function_app\W+|linux_function_app\W+|linux_function_app_slot\W+|linux_web_app\W+|linux_web_app\W+|linux_web_app_slot\W+|service_plan|source_control_token|static_web_app|web_app_|windows_function_app\W+|windows_function_app\W+|windows_function_app_slot\W+|windows_web_app\W+|windows_web_app\W+|windows_web_app_slot\W+)((.|\n)*)###' service/application-insights: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_application_insights((.|\n)*)###' @@ -69,7 +69,7 @@ service/cognitive-services: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(ai_services|cognitive_)((.|\n)*)###' service/communication: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(communication_service|email_communication_service)((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(communication_service|email_communication_service|gallery_application|orchestrated_virtual_machine_scale_set\W+|restore_point_collection|virtual_machine_gallery_application_assignment\W+|virtual_machine_implicit_data_disk_from_source\W+|virtual_machine_restore_point\W+|virtual_machine_restore_point_collection\W+|virtual_machine_run_command\W+)((.|\n)*)###' service/connections: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(api_connection|managed_api)((.|\n)*)###' @@ -240,13 +240,13 @@ service/netapp: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_netapp_((.|\n)*)###' service/network: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(application_gateway\W+|application_security_group\W+|bastion_host|custom_ip_prefix|express_route_|ip_group|local_network_gateway|nat_gateway|network_connection_monitor\W+|network_ddos_protection_plan\W+|network_interface\W+|network_interface_application_gateway_backend_address_pool_association\W+|network_interface_application_security_group_association\W+|network_interface_backend_address_pool_association\W+|network_interface_nat_rule_association\W+|network_interface_security_group_association\W+|network_manager\W+|network_manager\W+|network_manager_admin_rule\W+|network_manager_admin_rule_collection\W+|network_manager_connectivity_configuration\W+|network_manager_connectivity_configuration\W+|network_manager_deployment\W+|network_manager_management_group_connection\W+|network_manager_network_group\W+|network_manager_network_group\W+|network_manager_scope_connection\W+|network_manager_security_admin_configuration\W+|network_manager_static_member\W+|network_manager_subscription_connection\W+|network_packet_capture\W+|network_profile\W+|network_security_group\W+|network_security_rule\W+|network_service_tags\W+|network_watcher\W+|network_watcher_flow_log\W+|point_to_site_vpn_gateway|private_endpoint\W+|private_endpoint_application_security_group_association\W+|private_endpoint_connection\W+|private_link_service\W+|private_link_service_endpoint_connections\W+|public_ip|route|subnet|virtual_hub\W+|virtual_hub_bgp_connection\W+|virtual_hub_connection\W+|virtual_hub_ip\W+|virtual_hub_route_table\W+|virtual_hub_route_table_route\W+|virtual_hub_routing_intent\W+|virtual_hub_security_partner_provider\W+|virtual_machine_packet_capture\W+|virtual_machine_scale_set_packet_capture\W+|virtual_network\W+|virtual_network_dns_servers\W+|virtual_network_gateway\W+|virtual_network_gateway_connection\W+|virtual_network_gateway_nat_rule\W+|virtual_network_peering\W+|virtual_network_peering\W+|virtual_wan\W+|vpn_|web_application_firewall_policy)((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(application_gateway\W+|application_security_group\W+|bastion_host|custom_ip_prefix|express_route_|ip_group|local_network_gateway|nat_gateway|network_|point_to_site_vpn_gateway|private_endpoint\W+|private_endpoint_application_security_group_association\W+|private_endpoint_connection\W+|private_link_service\W+|private_link_service_endpoint_connections\W+|public_ip|route|subnet|virtual_hub\W+|virtual_hub_bgp_connection\W+|virtual_hub_connection\W+|virtual_hub_ip\W+|virtual_hub_route_table\W+|virtual_hub_route_table_route\W+|virtual_hub_routing_intent\W+|virtual_hub_security_partner_provider\W+|virtual_machine_packet_capture\W+|virtual_machine_scale_set_packet_capture\W+|virtual_network\W+|virtual_network_dns_servers\W+|virtual_network_gateway\W+|virtual_network_gateway_connection\W+|virtual_network_gateway_nat_rule\W+|virtual_network_peering\W+|virtual_network_peering\W+|virtual_wan\W+|vpn_|web_application_firewall_policy)((.|\n)*)###' service/network-function: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_network_function_((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(network_function_azure_traffic_collector\W+|network_function_collector_policy\W+|new_relic_monitor\W+|new_relic_tag_rule\W+)((.|\n)*)###' service/nginx: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_nginx_((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(nginx_|oracle_)((.|\n)*)###' service/notifications: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_notification_hub((.|\n)*)###' @@ -282,7 +282,7 @@ service/redhatopenshift: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_redhat_openshift_cluster((.|\n)*)###' service/redis: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_redis_((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(redis_cache\W+|redis_cache_access_policy\W+|redis_cache_access_policy_assignment\W+|redis_enterprise_cluster\W+|redis_enterprise_database\W+|redis_firewall_rule\W+|redis_linked_server\W+|resource_deployment_script_azure_cli\W+|resource_deployment_script_azure_power_shell\W+|resource_management_private_link\W+|resource_management_private_link_association\W+|resource_provider_registration\W+)((.|\n)*)###' service/relay: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_relay_((.|\n)*)###' @@ -318,7 +318,7 @@ service/spring: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(spring_cloud_accelerator\W+|spring_cloud_active_deployment\W+|spring_cloud_api_portal\W+|spring_cloud_api_portal_custom_domain\W+|spring_cloud_app\W+|spring_cloud_app_cosmosdb_association\W+|spring_cloud_app_dynamics_application_performance_monitoring\W+|spring_cloud_app_mysql_association\W+|spring_cloud_app_redis_association\W+|spring_cloud_application_insights_application_performance_monitoring\W+|spring_cloud_application_live_view\W+|spring_cloud_build_deployment\W+|spring_cloud_build_pack_binding\W+|spring_cloud_builder\W+|spring_cloud_certificate\W+|spring_cloud_configuration_service\W+|spring_cloud_container_deployment\W+|spring_cloud_custom_domain\W+|spring_cloud_customized_accelerator\W+|spring_cloud_dev_tool_portal\W+|spring_cloud_dynatrace_application_performance_monitoring\W+|spring_cloud_elastic_application_performance_monitoring\W+|spring_cloud_gateway\W+|spring_cloud_gateway_custom_domain\W+|spring_cloud_gateway_route_config\W+|spring_cloud_java_deployment\W+|spring_cloud_new_relic_application_performance_monitoring\W+|spring_cloud_service\W+|spring_cloud_storage\W+)((.|\n)*)###' service/storage: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(storage_account\W+|storage_account_blob_container_sas\W+|storage_account_customer_managed_key\W+|storage_account_local_user\W+|storage_account_network_rules\W+|storage_account_queue_properties\W+|storage_account_sas\W+|storage_account_static_website\W+|storage_blob\W+|storage_blob_inventory_policy\W+|storage_container\W+|storage_container_immutability_policy\W+|storage_containers\W+|storage_data_lake_gen2_filesystem\W+|storage_data_lake_gen2_path\W+|storage_encryption_scope\W+|storage_management_policy\W+|storage_object_replication\W+|storage_queue\W+|storage_share\W+|storage_share_directory\W+|storage_share_file\W+|storage_sync\W+|storage_sync_cloud_endpoint\W+|storage_sync_group\W+|storage_sync_server_endpoint\W+|storage_table\W+|storage_table\W+|storage_table_entities\W+|storage_table_entity\W+)((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(managed_lustre_file_system|storage_account\W+|storage_account_blob_container_sas\W+|storage_account_customer_managed_key\W+|storage_account_local_user\W+|storage_account_network_rules\W+|storage_account_queue_properties\W+|storage_account_sas\W+|storage_account_static_website\W+|storage_blob\W+|storage_blob_inventory_policy\W+|storage_container\W+|storage_container_immutability_policy\W+|storage_containers\W+|storage_data_lake_gen2_filesystem\W+|storage_data_lake_gen2_path\W+|storage_encryption_scope\W+|storage_management_policy\W+|storage_object_replication\W+|storage_queue\W+|storage_share\W+|storage_share_directory\W+|storage_share_file\W+|storage_sync\W+|storage_sync_cloud_endpoint\W+|storage_sync_group\W+|storage_sync_server_endpoint\W+|storage_table\W+|storage_table\W+|storage_table_entities\W+|storage_table_entity\W+)((.|\n)*)###' service/storagemover: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_storage_mover((.|\n)*)###' @@ -348,7 +348,7 @@ service/virtual-desktops: - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_virtual_desktop_((.|\n)*)###' service/vmware: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_vmware_((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(vmware_cluster\W+|vmware_express_route_authorization\W+|vmware_netapp_volume_attachment\W+|vmware_private_cloud\W+|voice_services_communications_gateway\W+|voice_services_communications_gateway_test_line\W+)((.|\n)*)###' service/workloads: - - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_workloads_sap_((.|\n)*)###' + - '### (|New or )Affected Resource\(s\)\/Data Source\(s\)((.|\n)*)azurerm_(chaos_studio_|container_connected_registry\W+|container_registry_cache_rule\W+|container_registry_cache_rule\W+|container_registry_task\W+|container_registry_task_schedule_run_now\W+|container_registry_token_password\W+|kubernetes_cluster_extension\W+|kubernetes_cluster_trusted_access_role_binding\W+|kubernetes_fleet_manager\W+|kubernetes_fleet_member\W+|kubernetes_fleet_update_run\W+|kubernetes_fleet_update_strategy\W+|kubernetes_flux_configuration\W+|kubernetes_node_pool_snapshot\W+|workloads_sap_)((.|\n)*)###' diff --git a/.github/workflows/golint.yaml b/.github/workflows/golint.yaml index 89a8ea57d50d..e31903312753 100644 --- a/.github/workflows/golint.yaml +++ b/.github/workflows/golint.yaml @@ -26,7 +26,7 @@ jobs: go-version-file: ./.go-version - uses: golangci/golangci-lint-action@971e284b6050e8a5849b72094c50ab08da042db8 # v6.1.1 with: - version: 'v1.55.1' + version: 'v1.61.0' args: -v ./internal/... save-artifacts-on-fail: if: ${{ needs.golint.result }} == 'failure' diff --git a/.golangci.yml b/.golangci.yml index e984b510d608..22d3722c6168 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,29 +17,60 @@ issues: linters: disable-all: true enable: - - asciicheck - - bidichk - - errcheck - - gocritic - - gofmt - - goimports - - gosimple - - govet - - ineffassign - #- nakedret - - misspell - #- nolintlint - #- nlreturn - - reassign - - staticcheck - - typecheck - - unused - - unconvert - - unparam - - vet - - vetshadow - # - wastedassign # disabled because of generics - # - whitespace # Disabled for performance reasons - Ignores cache and takes 12+ minutes to run on the repo for _any_ change + - asasalint # check for pass []any as any in variadic func(...any) + - asciicheck # code does not contain non-ASCII identifiers + - bidichk # Checks for dangerous unicode character sequences + - decorder # Check declaration order and count of types, constants, variables and functions. + - durationcheck # Check for common mistakes when working with time.Duration + - errcheck # checking for unchecked errors + - gocritic # Linter for Go source code that specializes in simplifying code + - gofmt # Gofmt checks whether code was gofmt-ed + #- gofumpt # Gofumpt is a stricter gofmt + - goimports # Check import statements are formatted according to the 'goimport' command + - gosimple # Linter for Go source code that specializes in simplifying code. + #- gosec # Gosec is a security linter for Go source code + - govet # reports suspicious constructs. It is roughly the same as 'go vet' (replaced vet and vetshadow) + - ineffassign # Detects when assignments to existing variables are not used + - misspell # Finds commonly misspelled English words. + #- nakedret # Checks that functions with naked returns are not longer than a maximum size + #- nilerr # Finds the code that returns nil even if it checks that the error is not nil. + #- nlreturn # Nlreturn checks for a new line before return and branch statements to increase code clarity. + #- paralleltest # Detects missing usage of t.Parallel() method in your Go test. + #- perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. + #- prealloc # Finds slice declarations that could potentially be pre-allocated. + #- predeclared # Find code that shadows one of Go's predeclared identifiers. + - reassign # Checks that package variables are not reassigned. + #- revive #Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. + - staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. + #- tparallel # Tparallel detects inappropriate usage of t.Parallel() method in your Go test codes. + - typecheck # doesn't exist?!>?! XXXXXXXXX + - unused # Checks Go code for unused constants, variables, functions and types. + - unconvert # Remove unnecessary type conversions. + - unparam # Reports unused function parameters. + - wastedassign # Finds wasted assignment statements + #- wsl Add or remove empty lines. + + #### DISABLED as parsers generator has a bug with things like SSHAdmin and we get S S H Admin, will fix in a seperate PR ##### + #- dupword #Check for duplicated words in comments + + #### DISABLED TO DO IN ITS OWN PR - should be enabled and done ##### + #- tenv #detects using os.Setenv instead of t.Setenv since Go1.17. + + #### REQUIRES GO 1.22 ##### + #- copyloopvar #Detects range loop variables that are overwritten in the loop body + + #### DISABLED till %+v -> %w ##### + #- err113 #Go linter to check the errors handling expressions. - disabled as it suggests (correctly?) to use %w in fmt.Errorf instead of %+v (1000s of usages in the codebase) + #- errorlint #### DISABLED till %+v -> %w ##### #Errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme used in the github.com/pkg/errors package. + + # disabled as it may be useful but there are a lot of switch statements in the codebase with unhandled inputs + #- exhaustive #Check for missing cases in select statements + + ###### DISABLED because golang will put the space back into //nolint: linter ###### + #- nolintlint #Reports ill-formed or insufficient nolint directives. + + # Disabled for performance reasons - Ignores cache and takes 12+ minutes to run on the repo for _any_ change + #- whitespace #checks for unnecessary newlines at the start and end of functions, if, for, etc. linters-settings: errcheck: diff --git a/internal/clients/builder.go b/internal/clients/builder.go index 318e49b60fef..e278fcd1ae8f 100644 --- a/internal/clients/builder.go +++ b/internal/clients/builder.go @@ -5,6 +5,7 @@ package clients import ( "context" + "errors" "fmt" "log" "time" @@ -48,7 +49,7 @@ func Build(ctx context.Context, builder ClientBuilder) (*Client, error) { // point folks towards the separate Azure Stack Provider when using Azure Stack if builder.AuthConfig.Environment.IsAzureStack() { - return nil, fmt.Errorf(azureStackEnvironmentError) + return nil, errors.New(azureStackEnvironmentError) } var resourceManagerAuth, storageAuth, synapseAuth, batchManagementAuth, keyVaultAuth auth.Authorizer diff --git a/internal/customermanagedkeys/key_vault_or_managed_hsm_key.go b/internal/customermanagedkeys/key_vault_or_managed_hsm_key.go index 97ad72327d00..f692a5ba606b 100644 --- a/internal/customermanagedkeys/key_vault_or_managed_hsm_key.go +++ b/internal/customermanagedkeys/key_vault_or_managed_hsm_key.go @@ -132,7 +132,7 @@ func ExpandKeyVaultOrManagedHSMKey(d interface{}, requireVersion VersionType, ke // ExpandKeyVaultOrManagedHSMKeyWithCustomFieldKey // d: should be one of *pluginsdk.ResourceData or map[string]interface{} -// if return nil, nil, it means no key_vault_key_id or managed_hsm_key_id is specified +// if return nil, nil - it means no key_vault_key_id or managed_hsm_key_id is specified //nolint:dupword func ExpandKeyVaultOrManagedHSMKeyWithCustomFieldKey(d interface{}, requireVersion VersionType, keyVaultFieldName, hsmFieldName string, keyVaultEnv, hsmEnv environments.Api) (*KeyVaultOrManagedHSMKey, error) { key := &KeyVaultOrManagedHSMKey{} var err error diff --git a/internal/sdk/README.md b/internal/sdk/README.md index 3789aabe8000..7d70b86ea62d 100644 --- a/internal/sdk/README.md +++ b/internal/sdk/README.md @@ -28,7 +28,7 @@ import ( "fmt" "time" - "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2020-06-01/resources" // nolint: staticcheck + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2020-06-01/resources" //nolint: staticcheck "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" diff --git a/internal/sdk/wrapper_resource.go b/internal/sdk/wrapper_resource.go index b5b1a286835f..6424fdd6ea09 100644 --- a/internal/sdk/wrapper_resource.go +++ b/internal/sdk/wrapper_resource.go @@ -5,6 +5,7 @@ package sdk import ( "context" + "errors" "fmt" "time" @@ -79,18 +80,18 @@ func (rw *ResourceWrapper) Resource() (*schema.Resource, error) { }, Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { fn := rw.resource.IDValidationFunc() - warnings, errors := fn(id, "id") + warnings, errs := fn(id, "id") if len(warnings) > 0 { for _, warning := range warnings { rw.logger.Warn(warning) } } - if len(errors) > 0 { + if len(errs) > 0 { out := "" - for _, err := range errors { + for _, err := range errs { out += err.Error() } - return fmt.Errorf(out) + return errors.New(out) } return nil diff --git a/internal/services/apimanagement/api_management_api_schema_resource.go b/internal/services/apimanagement/api_management_api_schema_resource.go index 7a1b228433b2..e4e41972afcc 100644 --- a/internal/services/apimanagement/api_management_api_schema_resource.go +++ b/internal/services/apimanagement/api_management_api_schema_resource.go @@ -216,7 +216,7 @@ func resourceApiManagementApiSchemaDelete(d *pluginsdk.ResourceData, meta interf } func convert2Str(rawVal interface{}) (string, error) { - value := "" + var value string if val, ok := rawVal.(string); ok { value = val } else { diff --git a/internal/services/apimanagement/api_management_backend_resource_test.go b/internal/services/apimanagement/api_management_backend_resource_test.go index 970d0bcf0ff2..353a11f4149d 100644 --- a/internal/services/apimanagement/api_management_backend_resource_test.go +++ b/internal/services/apimanagement/api_management_backend_resource_test.go @@ -328,7 +328,8 @@ resource "azurerm_api_management_backend" "test" { } func (r ApiManagementAuthorizationBackendResource) serviceFabric(data acceptance.TestData) string { - return fmt.Sprintf(` + // nolint: dupword + return fmt.Sprintf(` %s resource "azurerm_api_management_certificate" "test" { @@ -394,6 +395,7 @@ resource "azurerm_api_management_backend" "test" { } func (r ApiManagementAuthorizationBackendResource) serviceFabricClientCertificateId(data acceptance.TestData) string { + // nolint: dupword return fmt.Sprintf(` %s diff --git a/internal/services/apimanagement/api_management_resource.go b/internal/services/apimanagement/api_management_resource.go index 4d2102604d0c..f82b093aea1d 100644 --- a/internal/services/apimanagement/api_management_resource.go +++ b/internal/services/apimanagement/api_management_resource.go @@ -5,6 +5,7 @@ package apimanagement import ( "context" + "errors" "fmt" "log" "strconv" @@ -727,7 +728,7 @@ func resourceApiManagementServiceCreate(d *pluginsdk.ResourceData, meta interfac if !response.WasNotFound(softDeleted.HttpResponse) && !response.WasForbidden(softDeleted.HttpResponse) { if !meta.(*clients.Client).Features.ApiManagement.RecoverSoftDeleted { // this exists but the users opted out, so they must import this it out-of-band - return fmt.Errorf(optedOutOfRecoveringSoftDeletedApiManagementErrorFmt(id.ServiceName, location)) + return errors.New(optedOutOfRecoveringSoftDeletedApiManagementErrorFmt(id.ServiceName, location)) } // First recover the deleted API Management, since all other properties are ignored during a restore operation diff --git a/internal/services/apimanagement/schemaz/api_management.go b/internal/services/apimanagement/schemaz/api_management.go index 4ac582ef3a91..644be057a16b 100644 --- a/internal/services/apimanagement/schemaz/api_management.go +++ b/internal/services/apimanagement/schemaz/api_management.go @@ -465,7 +465,7 @@ func CopyCertificateAndPassword(vals []interface{}, hostName string, output map[ } func convert2Json(rawVal interface{}) (string, error) { - value := "" + var value string if val, ok := rawVal.(string); ok { value = val } else { diff --git a/internal/services/appconfiguration/app_configuration_feature_resource.go b/internal/services/appconfiguration/app_configuration_feature_resource.go index 1bf6f113cad4..4903258b022c 100644 --- a/internal/services/appconfiguration/app_configuration_feature_resource.go +++ b/internal/services/appconfiguration/app_configuration_feature_resource.go @@ -383,7 +383,7 @@ func (k FeatureResource) Read() sdk.ResourceFunc { } var fv FeatureValue - err = json.Unmarshal([]byte(utils.NormalizeNilableString(kv.Value)), &fv) + err = json.Unmarshal([]byte(pointer.From(kv.Value)), &fv) if err != nil { return fmt.Errorf("while unmarshalling underlying key's value: %+v", err) } @@ -392,9 +392,9 @@ func (k FeatureResource) Read() sdk.ResourceFunc { ConfigurationStoreId: configurationStoreId.ID(), Description: fv.Description, Enabled: fv.Enabled, - Key: strings.TrimPrefix(utils.NormalizeNilableString(kv.Key), fmt.Sprintf("%s/", FeatureKeyPrefix)), + Key: strings.TrimPrefix(pointer.From(kv.Key), fmt.Sprintf("%s/", FeatureKeyPrefix)), Name: fv.ID, - Label: utils.NormalizeNilableString(kv.Label), + Label: pointer.From(kv.Label), Tags: tags.Flatten(kv.Tags), } @@ -444,7 +444,7 @@ func (k FeatureResource) Update() sdk.ResourceFunc { } var fv FeatureValue - err = json.Unmarshal([]byte(utils.NormalizeNilableString(kv.Value)), &fv) + err = json.Unmarshal([]byte(pointer.From(kv.Value)), &fv) if err != nil { return fmt.Errorf("while unmarshalling underlying key's value: %+v", err) } diff --git a/internal/services/appconfiguration/app_configuration_key_data_source.go b/internal/services/appconfiguration/app_configuration_key_data_source.go index 97144cdad9f2..9453a66d40c1 100644 --- a/internal/services/appconfiguration/app_configuration_key_data_source.go +++ b/internal/services/appconfiguration/app_configuration_key_data_source.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Azure/go-autorest/autorest" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2023-03-01/configurationstores" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/appconfiguration/parse" @@ -123,13 +124,13 @@ func (k KeyDataSource) Read() sdk.ResourceFunc { return fmt.Errorf("while checking for key's %q existence: %+v", model.Key, err) } - if contentType := utils.NormalizeNilableString(kv.ContentType); contentType != VaultKeyContentType { + if contentType := pointer.From(kv.ContentType); contentType != VaultKeyContentType { model.Type = KeyTypeKV model.ContentType = contentType - model.Value = utils.NormalizeNilableString(kv.Value) + model.Value = pointer.From(kv.Value) } else { var ref VaultKeyReference - refBytes := []byte(utils.NormalizeNilableString(kv.Value)) + refBytes := []byte(pointer.From(kv.Value)) err := json.Unmarshal(refBytes, &ref) if err != nil { return fmt.Errorf("while unmarshalling vault reference: %+v", err) @@ -144,7 +145,7 @@ func (k KeyDataSource) Read() sdk.ResourceFunc { if kv.Locked != nil { model.Locked = *kv.Locked } - model.Etag = utils.NormalizeNilableString(kv.Etag) + model.Etag = pointer.From(kv.Etag) metadata.SetID(nestedItemId) return metadata.Encode(&model) diff --git a/internal/services/appconfiguration/app_configuration_key_resource.go b/internal/services/appconfiguration/app_configuration_key_resource.go index 0a3096425f9c..bd9d29a284cc 100644 --- a/internal/services/appconfiguration/app_configuration_key_resource.go +++ b/internal/services/appconfiguration/app_configuration_key_resource.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Azure/go-autorest/autorest" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2023-03-01/configurationstores" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" @@ -302,19 +303,19 @@ func (k KeyResource) Read() sdk.ResourceFunc { model := KeyResourceModel{ ConfigurationStoreId: configurationStoreId.ID(), - Key: utils.NormalizeNilableString(kv.Key), - ContentType: utils.NormalizeNilableString(kv.ContentType), - Etag: utils.NormalizeNilableString(kv.Etag), - Label: utils.NormalizeNilableString(kv.Label), + Key: pointer.From(kv.Key), + ContentType: pointer.From(kv.ContentType), + Etag: pointer.From(kv.Etag), + Label: pointer.From(kv.Label), Tags: tags.Flatten(kv.Tags), } - if utils.NormalizeNilableString(kv.ContentType) != VaultKeyContentType { + if pointer.From(kv.ContentType) != VaultKeyContentType { model.Type = KeyTypeKV - model.Value = utils.NormalizeNilableString(kv.Value) + model.Value = pointer.From(kv.Value) } else { var ref VaultKeyReference - refBytes := []byte(utils.NormalizeNilableString(kv.Value)) + refBytes := []byte(pointer.From(kv.Value)) err := json.Unmarshal(refBytes, &ref) if err != nil { return fmt.Errorf("while unmarshalling vault reference: %+v", err) @@ -323,7 +324,7 @@ func (k KeyResource) Read() sdk.ResourceFunc { model.Type = KeyTypeVault model.VaultKeyReference = ref.URI model.ContentType = VaultKeyContentType - model.Value = utils.NormalizeNilableString(kv.Value) + model.Value = pointer.From(kv.Value) } if kv.Locked != nil { diff --git a/internal/services/appconfiguration/app_configuration_keys_data_source.go b/internal/services/appconfiguration/app_configuration_keys_data_source.go index 8301656334da..917ceeacdb53 100644 --- a/internal/services/appconfiguration/app_configuration_keys_data_source.go +++ b/internal/services/appconfiguration/app_configuration_keys_data_source.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Azure/go-autorest/autorest" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2023-03-01/configurationstores" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/appconfiguration/parse" @@ -164,15 +165,15 @@ func (k KeysDataSource) Read() sdk.ResourceFunc { for iter.NotDone() { kv := iter.Value() var krmodel KeyDataSourceModel - krmodel.Key = utils.NormalizeNilableString(kv.Key) - krmodel.Label = utils.NormalizeNilableString(kv.Label) - if contentType := utils.NormalizeNilableString(kv.ContentType); contentType != VaultKeyContentType { + krmodel.Key = pointer.From(kv.Key) + krmodel.Label = pointer.From(kv.Label) + if contentType := pointer.From(kv.ContentType); contentType != VaultKeyContentType { krmodel.Type = KeyTypeKV krmodel.ContentType = contentType - krmodel.Value = utils.NormalizeNilableString(kv.Value) + krmodel.Value = pointer.From(kv.Value) } else { var ref VaultKeyReference - refBytes := []byte(utils.NormalizeNilableString(kv.Value)) + refBytes := []byte(pointer.From(kv.Value)) err := json.Unmarshal(refBytes, &ref) if err != nil { return fmt.Errorf("while unmarshalling vault reference: %+v", err) @@ -187,7 +188,7 @@ func (k KeysDataSource) Read() sdk.ResourceFunc { if kv.Locked != nil { krmodel.Locked = *kv.Locked } - krmodel.Etag = utils.NormalizeNilableString(kv.Etag) + krmodel.Etag = pointer.From(kv.Etag) model.Items = append(model.Items, krmodel) if err := iter.NextWithContext(ctx); err != nil { diff --git a/internal/services/appconfiguration/app_configuration_resource.go b/internal/services/appconfiguration/app_configuration_resource.go index bb12e7ad97d9..eed5d5f33120 100644 --- a/internal/services/appconfiguration/app_configuration_resource.go +++ b/internal/services/appconfiguration/app_configuration_resource.go @@ -5,6 +5,7 @@ package appconfiguration import ( "context" + "errors" "fmt" "log" "net/http" @@ -298,7 +299,7 @@ func resourceAppConfigurationCreate(d *pluginsdk.ResourceData, meta interface{}) deleted, err := deletedConfigurationStoresClient.ConfigurationStoresGetDeleted(ctx, deletedConfigurationStoresId) if err != nil { if response.WasStatusCode(deleted.HttpResponse, http.StatusForbidden) { - return fmt.Errorf(userIsMissingNecessaryPermission(name, location)) + return errors.New(userIsMissingNecessaryPermission(name, location)) } if !response.WasNotFound(deleted.HttpResponse) { return fmt.Errorf("checking for presence of deleted %s: %+v", deletedConfigurationStoresId, err) diff --git a/internal/services/appservice/app_service_environment_v3_data_source.go b/internal/services/appservice/app_service_environment_v3_data_source.go index ffabe9d07e6f..9a8554ff14a2 100644 --- a/internal/services/appservice/app_service_environment_v3_data_source.go +++ b/internal/services/appservice/app_service_environment_v3_data_source.go @@ -17,7 +17,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/services/web/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) type AppServiceEnvironmentV3DataSource struct{} @@ -232,7 +231,7 @@ func (r AppServiceEnvironmentV3DataSource) Read() sdk.ResourceFunc { state.DedicatedHostCount = pointer.From(props.DedicatedHostCount) state.PricingTier = pointer.From(props.MultiSize) state.ClusterSetting = flattenClusterSettingsModel(props.ClusterSettings) - state.DnsSuffix = utils.NormalizeNilableString(props.DnsSuffix) + state.DnsSuffix = pointer.From(props.DnsSuffix) state.IpSSLAddressCount = pointer.From(props.IPsslAddressCount) state.ZoneRedundant = pointer.From(props.ZoneRedundant) } diff --git a/internal/services/appservice/app_service_environment_v3_resource.go b/internal/services/appservice/app_service_environment_v3_resource.go index 2fb5fb796a70..a66b2493846f 100644 --- a/internal/services/appservice/app_service_environment_v3_resource.go +++ b/internal/services/appservice/app_service_environment_v3_resource.go @@ -529,7 +529,7 @@ func flattenClusterSettingsModel(input *[]appserviceenvironments.NameValuePair) output = append(output, ClusterSettingModel{ Name: *v.Name, - Value: utils.NormalizeNilableString(v.Value), + Value: pointer.From(v.Value), }) } return output diff --git a/internal/services/appservice/helpers/function_app_schema.go b/internal/services/appservice/helpers/function_app_schema.go index ca7d021db965..cea5e72d5936 100644 --- a/internal/services/appservice/helpers/function_app_schema.go +++ b/internal/services/appservice/helpers/function_app_schema.go @@ -1646,7 +1646,7 @@ func ExpandSiteConfigLinuxFunctionApp(siteConfig []SiteConfigLinuxFunctionApp, e expanded.LinuxFxVersion = pointer.To("") // Custom needs an explicit empty string here } - if linuxAppStack.Docker != nil && len(linuxAppStack.Docker) == 1 { + if len(linuxAppStack.Docker) == 1 { dockerConfig := linuxAppStack.Docker[0] appSettings = updateOrAppendAppSettings(appSettings, "DOCKER_REGISTRY_SERVER_URL", dockerConfig.RegistryURL, false) appSettings = updateOrAppendAppSettings(appSettings, "DOCKER_REGISTRY_SERVER_USERNAME", dockerConfig.RegistryUsername, false) diff --git a/internal/services/appservice/helpers/function_app_slot_schema.go b/internal/services/appservice/helpers/function_app_slot_schema.go index a48e5f19a074..3ed1480bc6bf 100644 --- a/internal/services/appservice/helpers/function_app_slot_schema.go +++ b/internal/services/appservice/helpers/function_app_slot_schema.go @@ -1096,7 +1096,7 @@ func ExpandSiteConfigLinuxFunctionAppSlot(siteConfig []SiteConfigLinuxFunctionAp expanded.LinuxFxVersion = pointer.To("") // Custom needs an explicit empty string here } - if linuxAppStack.Docker != nil && len(linuxAppStack.Docker) == 1 { + if len(linuxAppStack.Docker) == 1 { dockerConfig := linuxAppStack.Docker[0] appSettings = append(appSettings, webapps.NameValuePair{ Name: pointer.To("DOCKER_REGISTRY_SERVER_URL"), diff --git a/internal/services/appservice/linux_function_app_resource_test.go b/internal/services/appservice/linux_function_app_resource_test.go index 6da7bf2f976a..0192cba004e9 100644 --- a/internal/services/appservice/linux_function_app_resource_test.go +++ b/internal/services/appservice/linux_function_app_resource_test.go @@ -4282,7 +4282,7 @@ resource "azurerm_user_assigned_identity" "test" { `, r.template(data, planSku), data.RandomInteger) } -// nolint:unparam +//nolint:unparam func (r LinuxFunctionAppResource) vNetIntegration_basic(data acceptance.TestData, planSku string) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/appservice/service_plan_data_source.go b/internal/services/appservice/service_plan_data_source.go index 9c31bc946c56..58425d5f5f4b 100644 --- a/internal/services/appservice/service_plan_data_source.go +++ b/internal/services/appservice/service_plan_data_source.go @@ -17,7 +17,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/services/appservice/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) type ServicePlanDataSource struct{} @@ -158,15 +157,12 @@ func (r ServicePlanDataSource) Read() sdk.ResourceFunc { } if props.HostingEnvironmentProfile != nil && props.HostingEnvironmentProfile.Id != nil { - servicePlan.AppServiceEnvironmentId = utils.NormalizeNilableString(props.HostingEnvironmentProfile.Id) + servicePlan.AppServiceEnvironmentId = pointer.From(props.HostingEnvironmentProfile.Id) } - servicePlan.PerSiteScaling = utils.NormaliseNilableBool(props.PerSiteScaling) - - servicePlan.Reserved = utils.NormaliseNilableBool(props.Reserved) - - servicePlan.ZoneBalancing = utils.NormaliseNilableBool(props.ZoneRedundant) - + servicePlan.PerSiteScaling = pointer.From(props.PerSiteScaling) + servicePlan.Reserved = pointer.From(props.Reserved) + servicePlan.ZoneBalancing = pointer.From(props.ZoneRedundant) servicePlan.MaximumElasticWorkerCount = pointer.From(props.MaximumElasticWorkerCount) } servicePlan.Tags = pointer.From(model.Tags) diff --git a/internal/services/appservice/service_plan_resource.go b/internal/services/appservice/service_plan_resource.go index 85e824352acf..6cbc0170d135 100644 --- a/internal/services/appservice/service_plan_resource.go +++ b/internal/services/appservice/service_plan_resource.go @@ -264,12 +264,9 @@ func (r ServicePlanResource) Read() sdk.ResourceFunc { state.AppServiceEnvironmentId = *ase.Id } - state.PerSiteScaling = utils.NormaliseNilableBool(props.PerSiteScaling) - - state.Reserved = utils.NormaliseNilableBool(props.Reserved) - - state.ZoneBalancing = utils.NormaliseNilableBool(props.ZoneRedundant) - + state.PerSiteScaling = pointer.From(props.PerSiteScaling) + state.Reserved = pointer.From(props.Reserved) + state.ZoneBalancing = pointer.From(props.ZoneRedundant) state.MaximumElasticWorkerCount = pointer.From(props.MaximumElasticWorkerCount) } state.Tags = pointer.From(model.Tags) diff --git a/internal/services/appservice/source_control_token_data_source_test.go b/internal/services/appservice/source_control_token_data_source_test.go index b911413d608f..be5ee767d9e6 100644 --- a/internal/services/appservice/source_control_token_data_source_test.go +++ b/internal/services/appservice/source_control_token_data_source_test.go @@ -15,8 +15,8 @@ import ( type AppServiceGithubTokenDataSource struct{} func TestAccSourceControlGitHubTokenDataSource_basic(t *testing.T) { - token := "" - if token = os.Getenv("ARM_GITHUB_ACCESS_TOKEN"); token == "" { + token := os.Getenv("ARM_GITHUB_ACCESS_TOKEN") + if token == "" { t.Skip("Skipping as `ARM_GITHUB_ACCESS_TOKEN` is not specified") } diff --git a/internal/services/appservice/source_control_token_resource_test.go b/internal/services/appservice/source_control_token_resource_test.go index 175e19856b53..00c6e9facb6b 100644 --- a/internal/services/appservice/source_control_token_resource_test.go +++ b/internal/services/appservice/source_control_token_resource_test.go @@ -23,8 +23,8 @@ import ( type AppServiceGitHubTokenResource struct{} func TestAccSourceControlGitHubToken_basic(t *testing.T) { - token := "" - if token = os.Getenv("ARM_GITHUB_ACCESS_TOKEN"); token == "" { + token := os.Getenv("ARM_GITHUB_ACCESS_TOKEN") + if token == "" { t.Skip("Skipping as `ARM_GITHUB_ACCESS_TOKEN` is not specified") } @@ -44,8 +44,8 @@ func TestAccSourceControlGitHubToken_basic(t *testing.T) { } func TestAccSourceControlGitHubToken_requiresImport(t *testing.T) { - token := "" - if token = os.Getenv("ARM_GITHUB_ACCESS_TOKEN"); token == "" { + token := os.Getenv("ARM_GITHUB_ACCESS_TOKEN") + if token == "" { t.Skip("Skipping as `ARM_GITHUB_ACCESS_TOKEN` is not specified") } diff --git a/internal/services/appservice/static_web_app_data_source.go b/internal/services/appservice/static_web_app_data_source.go index f545252e0cbf..9d92cd7e8574 100644 --- a/internal/services/appservice/static_web_app_data_source.go +++ b/internal/services/appservice/static_web_app_data_source.go @@ -171,10 +171,7 @@ func (s StaticWebAppDataSource) Read() sdk.ResourceFunc { } if secProps := sec.Model.Properties; secProps != nil { - propsMap := pointer.From(secProps) - apiKey := "" - apiKey = propsMap["apiKey"] - state.ApiKey = apiKey + state.ApiKey = pointer.From(secProps)["apiKey"] } } diff --git a/internal/services/appservice/static_web_app_resource.go b/internal/services/appservice/static_web_app_resource.go index e976fd22bc0e..a297b7f9bcf6 100644 --- a/internal/services/appservice/static_web_app_resource.go +++ b/internal/services/appservice/static_web_app_resource.go @@ -293,10 +293,7 @@ func (r StaticWebAppResource) Read() sdk.ResourceFunc { } if secProps := sec.Model.Properties; secProps != nil { - propsMap := pointer.From(secProps) - apiKey := "" - apiKey = propsMap["apiKey"] - state.ApiKey = apiKey + state.ApiKey = pointer.From(secProps)["apiKey"] } } diff --git a/internal/services/appservice/windows_function_app_data_source.go b/internal/services/appservice/windows_function_app_data_source.go index 01c72707e1ff..a3d1da647284 100644 --- a/internal/services/appservice/windows_function_app_data_source.go +++ b/internal/services/appservice/windows_function_app_data_source.go @@ -22,7 +22,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/services/appservice/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) type WindowsFunctionAppDataSource struct{} @@ -310,7 +309,7 @@ func (d WindowsFunctionAppDataSource) Read() sdk.ResourceFunc { return fmt.Errorf("reading Service Plan Id for %s: %+v", id, err) } functionApp.ServicePlanId = servicePlanId.ID() - functionApp.Enabled = utils.NormaliseNilableBool(props.Enabled) + functionApp.Enabled = pointer.From(props.Enabled) functionApp.ClientCertMode = string(pointer.From(props.ClientCertMode)) functionApp.ClientCertExclusionPaths = pointer.From(props.ClientCertExclusionPaths) functionApp.DailyMemoryTimeQuota = pointer.From(props.DailyMemoryTimeQuota) diff --git a/internal/services/appservice/windows_function_app_resource.go b/internal/services/appservice/windows_function_app_resource.go index eafda597c2a3..bd4cec5f62f4 100644 --- a/internal/services/appservice/windows_function_app_resource.go +++ b/internal/services/appservice/windows_function_app_resource.go @@ -30,7 +30,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) type WindowsFunctionAppResource struct{} @@ -757,7 +756,7 @@ func (r WindowsFunctionAppResource) Read() sdk.ResourceFunc { ResourceGroup: id.ResourceGroupName, Location: location.Normalize(model.Location), Tags: pointer.From(model.Tags), - Kind: utils.NormalizeNilableString(model.Kind), + Kind: pointer.From(model.Kind), } if props := model.Properties; props != nil { diff --git a/internal/services/attestation/attestation_provider_resource.go b/internal/services/attestation/attestation_provider_resource.go index 15d3e7456922..bfcaf8234178 100644 --- a/internal/services/attestation/attestation_provider_resource.go +++ b/internal/services/attestation/attestation_provider_resource.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" @@ -294,25 +295,25 @@ func resourceAttestationProviderRead(d *pluginsdk.ResourceData, meta interface{} if err != nil { return fmt.Errorf("parsing OpenEnclave Policy for %s: %+v", *id, err) } - d.Set("open_enclave_policy_base64", utils.NormalizeNilableString(openEnclavePolicyData)) + d.Set("open_enclave_policy_base64", pointer.From(openEnclavePolicyData)) sgxEnclavePolicyData, err := base64DataFromAttestationJWT(sgxEnclavePolicy.Token) if err != nil { return fmt.Errorf("parsing SgxEnclave Policy for %s: %+v", *id, err) } - d.Set("sgx_enclave_policy_base64", utils.NormalizeNilableString(sgxEnclavePolicyData)) + d.Set("sgx_enclave_policy_base64", pointer.From(sgxEnclavePolicyData)) tpmPolicyData, err := base64DataFromAttestationJWT(tpmPolicy.Token) if err != nil { return fmt.Errorf("parsing Tpm Policy for %s: %+v", *id, err) } - d.Set("tpm_policy_base64", utils.NormalizeNilableString(tpmPolicyData)) + d.Set("tpm_policy_base64", pointer.From(tpmPolicyData)) sevSnpPolicyData, err := base64DataFromAttestationJWT(sevSnpPolicy.Token) if err != nil { return fmt.Errorf("parsing SEV-SNP policy for %s: %+v", *id, err) } - d.Set("sev_snp_policy_base64", utils.NormalizeNilableString(sevSnpPolicyData)) + d.Set("sev_snp_policy_base64", pointer.From(sevSnpPolicyData)) if !features.FourPointOhBeta() { if err := d.Set("policy", []interface{}{}); err != nil { diff --git a/internal/services/authorization/client/client.go b/internal/services/authorization/client/client.go index 6fb9cecbb716..34e695bfeac4 100644 --- a/internal/services/authorization/client/client.go +++ b/internal/services/authorization/client/client.go @@ -6,7 +6,7 @@ package client import ( "fmt" - "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2020-04-01-preview/authorization" // nolint: staticcheck // nolint: staticcheck + "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2020-04-01-preview/authorization" // nolint: staticcheck //nolint: staticcheck // To swap sdk for `azurerm_role_definition` without changing API version "github.com/hashicorp/go-azure-sdk/resource-manager/authorization/2020-10-01/roleassignmentscheduleinstances" diff --git a/internal/services/authorization/role_definition_resource.go b/internal/services/authorization/role_definition_resource.go index b264695914b4..a0d0b5e6adbb 100644 --- a/internal/services/authorization/role_definition_resource.go +++ b/internal/services/authorization/role_definition_resource.go @@ -348,7 +348,7 @@ func (r RoleDefinitionResource) Update() sdk.ResourceFunc { // "Updating" a role definition actually creates a new one and these get consolidated a few seconds later // where the "create date" and "update date" match for the newly created record // but eventually switch to being the old create date and the new update date - // ergo we can can for the old create date and the new updated date + // ergo we can for the old create date and the new updated date log.Printf("[DEBUG] Waiting for %s to settle down..", stateId) deadline, ok := ctx.Deadline() if !ok { diff --git a/internal/services/automanage/automanage_configuration_resource.go b/internal/services/automanage/automanage_configuration_resource.go index 080f147d3f82..39177b8c8726 100644 --- a/internal/services/automanage/automanage_configuration_resource.go +++ b/internal/services/automanage/automanage_configuration_resource.go @@ -633,7 +633,7 @@ func expandConfigurationProfile(model ConfigurationModel) *interface{} { // building configuration profile in json format jsonConfig := make(map[string]interface{}) - if model.Antimalware != nil && len(model.Antimalware) > 0 { + if len(model.Antimalware) > 0 { antimalwareConfig := model.Antimalware[0] jsonConfig["Antimalware/Enable"] = true jsonConfig["Antimalware/EnableRealTimeProtection"] = antimalwareConfig.RealTimeProtectionEnabled @@ -641,20 +641,20 @@ func expandConfigurationProfile(model ConfigurationModel) *interface{} { jsonConfig["Antimalware/ScanType"] = antimalwareConfig.ScanType jsonConfig["Antimalware/ScanDay"] = antimalwareConfig.ScanDay jsonConfig["Antimalware/ScanTimeInMinutes"] = antimalwareConfig.ScanTimeInMinutes - if antimalwareConfig.Exclusions != nil && len(antimalwareConfig.Exclusions) > 0 { + if len(antimalwareConfig.Exclusions) > 0 { jsonConfig["Antimalware/Exclusions/Extensions"] = antimalwareConfig.Exclusions[0].Extensions jsonConfig["Antimalware/Exclusions/Paths"] = antimalwareConfig.Exclusions[0].Paths jsonConfig["Antimalware/Exclusions/Processes"] = antimalwareConfig.Exclusions[0].Processes } } - if model.AzureSecurityBaseline != nil && len(model.AzureSecurityBaseline) > 0 { + if len(model.AzureSecurityBaseline) > 0 { azureSecurityBaselineConfig := model.AzureSecurityBaseline[0] jsonConfig["AzureSecurityBaseline/Enable"] = true jsonConfig["AzureSecurityBaseline/AssignmentType"] = azureSecurityBaselineConfig.AssignmentType } - if model.Backup != nil && len(model.Backup) > 0 { + if len(model.Backup) > 0 { backupConfig := model.Backup[0] jsonConfig["Backup/Enable"] = true if backupConfig.PolicyName != "" { @@ -662,40 +662,40 @@ func expandConfigurationProfile(model ConfigurationModel) *interface{} { } jsonConfig["Backup/TimeZone"] = backupConfig.TimeZone jsonConfig["Backup/InstantRpRetentionRangeInDays"] = backupConfig.InstantRpRetentionRangeInDays - if backupConfig.SchedulePolicy != nil && len(backupConfig.SchedulePolicy) > 0 { + if len(backupConfig.SchedulePolicy) > 0 { schedulePolicyConfig := backupConfig.SchedulePolicy[0] jsonConfig["Backup/SchedulePolicy/ScheduleRunFrequency"] = schedulePolicyConfig.ScheduleRunFrequency - if schedulePolicyConfig.ScheduleRunTimes != nil && len(schedulePolicyConfig.ScheduleRunTimes) > 0 { + if len(schedulePolicyConfig.ScheduleRunTimes) > 0 { jsonConfig["Backup/SchedulePolicy/ScheduleRunTimes"] = schedulePolicyConfig.ScheduleRunTimes } - if schedulePolicyConfig.ScheduleRunDays != nil && len(schedulePolicyConfig.ScheduleRunDays) > 0 { + if len(schedulePolicyConfig.ScheduleRunDays) > 0 { jsonConfig["Backup/SchedulePolicy/ScheduleRunDays"] = schedulePolicyConfig.ScheduleRunDays } jsonConfig["Backup/SchedulePolicy/SchedulePolicyType"] = schedulePolicyConfig.SchedulePolicyType } - if backupConfig.RetentionPolicy != nil && len(backupConfig.RetentionPolicy) > 0 { + if len(backupConfig.RetentionPolicy) > 0 { retentionPolicyConfig := backupConfig.RetentionPolicy[0] jsonConfig["Backup/RetentionPolicy/RetentionPolicyType"] = retentionPolicyConfig.RetentionPolicyType - if retentionPolicyConfig.DailySchedule != nil && len(retentionPolicyConfig.DailySchedule) > 0 { + if len(retentionPolicyConfig.DailySchedule) > 0 { dailyScheduleConfig := retentionPolicyConfig.DailySchedule[0] - if dailyScheduleConfig.RetentionTimes != nil && len(dailyScheduleConfig.RetentionTimes) > 0 { + if len(dailyScheduleConfig.RetentionTimes) > 0 { jsonConfig["Backup/RetentionPolicy/DailySchedule/RetentionTimes"] = dailyScheduleConfig.RetentionTimes } - if dailyScheduleConfig.RetentionDuration != nil && len(dailyScheduleConfig.RetentionDuration) > 0 { + if len(dailyScheduleConfig.RetentionDuration) > 0 { jsonConfig["Backup/RetentionPolicy/DailySchedule/RetentionDuration/Count"] = dailyScheduleConfig.RetentionDuration[0].Count jsonConfig["Backup/RetentionPolicy/DailySchedule/RetentionDuration/DurationType"] = dailyScheduleConfig.RetentionDuration[0].DurationType } } - if retentionPolicyConfig.WeeklySchedule != nil && len(retentionPolicyConfig.WeeklySchedule) > 0 { + if len(retentionPolicyConfig.WeeklySchedule) > 0 { weeklyScheduleConfig := retentionPolicyConfig.WeeklySchedule[0] - if weeklyScheduleConfig.RetentionTimes != nil && len(weeklyScheduleConfig.RetentionTimes) > 0 { + if len(weeklyScheduleConfig.RetentionTimes) > 0 { jsonConfig["Backup/RetentionPolicy/WeeklySchedule/RetentionTimes"] = weeklyScheduleConfig.RetentionTimes } - if weeklyScheduleConfig.RetentionDuration != nil && len(weeklyScheduleConfig.RetentionDuration) > 0 { + if len(weeklyScheduleConfig.RetentionDuration) > 0 { jsonConfig["Backup/RetentionPolicy/WeeklySchedule/RetentionDuration/Count"] = weeklyScheduleConfig.RetentionDuration[0].Count jsonConfig["Backup/RetentionPolicy/WeeklySchedule/RetentionDuration/DurationType"] = weeklyScheduleConfig.RetentionDuration[0].DurationType } diff --git a/internal/services/automation/automation_connection_type_resource.go b/internal/services/automation/automation_connection_type_resource.go index 964c7a80b05b..ba390585e0f1 100644 --- a/internal/services/automation/automation_connection_type_resource.go +++ b/internal/services/automation/automation_connection_type_resource.go @@ -8,6 +8,7 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-sdk/resource-manager/automation/2023-11-01/automationaccount" @@ -181,14 +182,14 @@ func (m AutomationConnectionTypeResource) Read() sdk.ResourceFunc { if model := resp.Model; model != nil { if props := model.Properties; props != nil { - output.IsGlobal = utils.NormaliseNilableBool(props.IsGlobal) + output.IsGlobal = pointer.From(props.IsGlobal) if props.FieldDefinitions != nil { for name, field := range *props.FieldDefinitions { output.Field = append(output.Field, Field{ Name: name, Type: field.Type, - IsEncrypted: utils.NormaliseNilableBool(field.IsEncrypted), - IsOptional: utils.NormaliseNilableBool(field.IsOptional), + IsEncrypted: pointer.From(field.IsEncrypted), + IsOptional: pointer.From(field.IsOptional), }) } } diff --git a/internal/services/automation/automation_hybrid_runbook_worker_group_resource.go b/internal/services/automation/automation_hybrid_runbook_worker_group_resource.go index 554d883a8d85..511f0f484701 100644 --- a/internal/services/automation/automation_hybrid_runbook_worker_group_resource.go +++ b/internal/services/automation/automation_hybrid_runbook_worker_group_resource.go @@ -128,7 +128,7 @@ func (m HybridRunbookWorkerGroupResource) Read() sdk.ResourceFunc { } var output HybridRunbookWorkerGroupModel - output.Name = utils.NormalizeNilableString(result.Model.Name) + output.Name = pointer.From(result.Model.Name) output.AutomationAccountName = id.AutomationAccountName if model := result.Model; model != nil { if prop := model.Properties; prop != nil { diff --git a/internal/services/automation/automation_hybrid_runbook_worker_resource.go b/internal/services/automation/automation_hybrid_runbook_worker_resource.go index 3b6b1f21ac6e..f67346b5e325 100644 --- a/internal/services/automation/automation_hybrid_runbook_worker_resource.go +++ b/internal/services/automation/automation_hybrid_runbook_worker_resource.go @@ -9,6 +9,7 @@ import ( "net/http" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-sdk/resource-manager/automation/2023-11-01/hybridrunbookworker" @@ -171,17 +172,17 @@ func (m HybridRunbookWorkerResource) Read() sdk.ResourceFunc { var output HybridRunbookWorkerModel // the name in response corresponding to work_id in request - output.WorkerId = utils.NormalizeNilableString(result.Model.Name) + output.WorkerId = pointer.From(result.Model.Name) output.AutomationAccountName = id.AutomationAccountName output.ResourceGroupName = id.ResourceGroupName output.WorkerGroupName = id.HybridRunbookWorkerGroupName if prop := result.Model.Properties; prop != nil { - output.VmResourceId = utils.NormalizeNilableString(prop.VMResourceId) - output.WorkerType = utils.NormalizeNilableString((*string)(prop.WorkerType)) - output.LastSeenDateTime = utils.NormalizeNilableString(prop.LastSeenDateTime) - output.RegisteredDateTime = utils.NormalizeNilableString(prop.RegisteredDateTime) - output.Ip = utils.NormalizeNilableString(prop.IP) - output.WorkerName = utils.NormalizeNilableString(prop.WorkerName) + output.VmResourceId = pointer.From(prop.VMResourceId) + output.WorkerType = pointer.From((*string)(prop.WorkerType)) + output.LastSeenDateTime = pointer.From(prop.LastSeenDateTime) + output.RegisteredDateTime = pointer.From(prop.RegisteredDateTime) + output.Ip = pointer.From(prop.IP) + output.WorkerName = pointer.From(prop.WorkerName) } return meta.Encode(&output) }, diff --git a/internal/services/automation/automation_module_resource.go b/internal/services/automation/automation_module_resource.go index 8ef915bd2895..9b242a88546c 100644 --- a/internal/services/automation/automation_module_resource.go +++ b/internal/services/automation/automation_module_resource.go @@ -4,6 +4,7 @@ package automation import ( + "errors" "fmt" "log" "time" @@ -160,7 +161,7 @@ func resourceAutomationModuleCreateUpdate(d *pluginsdk.ResourceData, meta interf provisioningState = string(*props.ProvisioningState) } if props.Error != nil && props.Error.Message != nil && *props.Error.Message != "" { - return resp, provisioningState, fmt.Errorf(*props.Error.Message) + return resp, provisioningState, errors.New(*props.Error.Message) } return resp, provisioningState, nil } diff --git a/internal/services/automation/automation_powershell72_module_resource.go b/internal/services/automation/automation_powershell72_module_resource.go index 5d35ec457c5a..06c8b8f2097e 100644 --- a/internal/services/automation/automation_powershell72_module_resource.go +++ b/internal/services/automation/automation_powershell72_module_resource.go @@ -5,6 +5,7 @@ package automation import ( "context" + "errors" "fmt" "time" @@ -189,7 +190,7 @@ func (r PowerShell72ModuleResource) Create() sdk.ResourceFunc { provisioningState = string(*props.ProvisioningState) } if props.Error != nil && props.Error.Message != nil && *props.Error.Message != "" { - return resp, provisioningState, fmt.Errorf(*props.Error.Message) + return resp, provisioningState, errors.New(*props.Error.Message) } return resp, provisioningState, nil } @@ -281,7 +282,7 @@ func (r PowerShell72ModuleResource) Update() sdk.ResourceFunc { provisioningState = string(*props.ProvisioningState) } if props.Error != nil && props.Error.Message != nil && *props.Error.Message != "" { - return resp, provisioningState, fmt.Errorf(*props.Error.Message) + return resp, provisioningState, errors.New(*props.Error.Message) } return resp, provisioningState, nil } diff --git a/internal/services/automation/automation_watcher_resource.go b/internal/services/automation/automation_watcher_resource.go index 07c3127ae756..ab73d1277690 100644 --- a/internal/services/automation/automation_watcher_resource.go +++ b/internal/services/automation/automation_watcher_resource.go @@ -8,6 +8,7 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-sdk/resource-manager/automation/2020-01-13-preview/watcher" @@ -192,11 +193,11 @@ func (m WatcherResource) Read() sdk.ResourceFunc { if model := resp.Model; model != nil { if props := resp.Model.Properties; props != nil { output.AutomationAccountID = watcher.NewAutomationAccountID(id.SubscriptionId, id.ResourceGroupName, id.AutomationAccountName).ID() - output.ExecutionFrequencyInSeconds = utils.NormaliseNilableInt64(props.ExecutionFrequencyInSeconds) - output.ScriptName = utils.NormalizeNilableString(props.ScriptName) - output.ScriptRunOn = utils.NormalizeNilableString(props.ScriptRunOn) - output.Description = utils.NormalizeNilableString(props.Description) - output.Status = utils.NormalizeNilableString(props.Status) + output.ExecutionFrequencyInSeconds = pointer.From(props.ExecutionFrequencyInSeconds) + output.ScriptName = pointer.From(props.ScriptName) + output.ScriptRunOn = pointer.From(props.ScriptRunOn) + output.Description = pointer.From(props.Description) + output.Status = pointer.From(props.Status) if props.ScriptParameters != nil { output.ScriptParameters = flattenMap(*props.ScriptParameters) diff --git a/internal/services/batch/batch_pool.go b/internal/services/batch/batch_pool.go index 195d04a91a05..4c28790fa4a8 100644 --- a/internal/services/batch/batch_pool.go +++ b/internal/services/batch/batch_pool.go @@ -302,7 +302,7 @@ func flattenBatchPoolContainerRegistry(d *pluginsdk.ResourceData, armContainerRe } func findBatchPoolContainerRegistryPassword(d *pluginsdk.ResourceData, armServer string, armUsername string) interface{} { - numContainerRegistries := 0 + var numContainerRegistries int if n, ok := d.GetOk("container_configuration.0.container_registries.#"); ok { numContainerRegistries = n.(int) } else { diff --git a/internal/services/compute/linux_virtual_machine_scale_set_resource_network_test.go b/internal/services/compute/linux_virtual_machine_scale_set_resource_network_test.go index 918b23226561..2fce84eaa0e3 100644 --- a/internal/services/compute/linux_virtual_machine_scale_set_resource_network_test.go +++ b/internal/services/compute/linux_virtual_machine_scale_set_resource_network_test.go @@ -1675,7 +1675,8 @@ resource "azurerm_linux_virtual_machine_scale_set" "test" { } // skipped -// nolint:unused +// +//nolint:unused func (r LinuxVirtualMachineScaleSetResource) networkPublicIPVersion(data acceptance.TestData) string { return fmt.Sprintf(` %s diff --git a/internal/services/compute/orchestrated_virtual_machine_scale_set_resource.go b/internal/services/compute/orchestrated_virtual_machine_scale_set_resource.go index c40cccdd5148..ec21373326b1 100644 --- a/internal/services/compute/orchestrated_virtual_machine_scale_set_resource.go +++ b/internal/services/compute/orchestrated_virtual_machine_scale_set_resource.go @@ -548,7 +548,7 @@ func resourceOrchestratedVirtualMachineScaleSetCreate(d *pluginsdk.ResourceData, } if !hasHealthExtension { - return fmt.Errorf("when 'patch_mode' is set to %q then the 'extension' field must always always contain a 'application health extension'", patchMode) + return fmt.Errorf("when 'patch_mode' is set to %q then the 'extension' field must always contain a 'application health extension'", patchMode) } } diff --git a/internal/services/compute/shared_image_resource_test.go b/internal/services/compute/shared_image_resource_test.go index 0240a9da1e8c..e14536b23617 100644 --- a/internal/services/compute/shared_image_resource_test.go +++ b/internal/services/compute/shared_image_resource_test.go @@ -92,7 +92,7 @@ func TestAccSharedImage_complete(t *testing.T) { check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("os_type").HasValue("Linux"), check.That(data.ResourceName).Key("hyper_v_generation").HasValue("V1"), - check.That(data.ResourceName).Key("description").HasValue("Wubba lubba dub dub"), + check.That(data.ResourceName).Key("description").HasValue("Wubba lubba dub dubs"), check.That(data.ResourceName).Key("eula").HasValue("Do you agree there's infinite Rick's and Infinite Morty's?"), check.That(data.ResourceName).Key("privacy_statement_uri").HasValue("https://council.of.ricks/privacy-statement"), check.That(data.ResourceName).Key("release_note_uri").HasValue("https://council.of.ricks/changelog.md"), diff --git a/internal/services/consumption/consumption_budget_subscription_resource_test.go b/internal/services/consumption/consumption_budget_subscription_resource_test.go index 0aad630c528a..b126f106f739 100644 --- a/internal/services/consumption/consumption_budget_subscription_resource_test.go +++ b/internal/services/consumption/consumption_budget_subscription_resource_test.go @@ -334,6 +334,7 @@ resource "azurerm_consumption_budget_subscription" "test" { } func (ConsumptionBudgetSubscriptionResource) completeUpdate(data acceptance.TestData) string { + // nolint: dupword return fmt.Sprintf(` provider "azurerm" { features {} @@ -430,6 +431,5 @@ resource "azurerm_consumption_budget_subscription" "test" { azurerm_monitor_action_group.test.id, ] } -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, consumptionBudgetTestStartDate().Format(time.RFC3339)) +}`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, consumptionBudgetTestStartDate().Format(time.RFC3339)) } diff --git a/internal/services/containerapps/helpers/container_app_job.go b/internal/services/containerapps/helpers/container_app_job.go index 90f07659ef36..44dae6ddaf65 100644 --- a/internal/services/containerapps/helpers/container_app_job.go +++ b/internal/services/containerapps/helpers/container_app_job.go @@ -439,7 +439,7 @@ func flattenInitContainerAppJobContainers(input *[]jobs.BaseContainer) []BaseCon func expandContainerJobEnvVar(input Container) *[]jobs.EnvironmentVar { envs := make([]jobs.EnvironmentVar, 0) - if input.Env == nil || len(input.Env) == 0 { + if len(input.Env) == 0 { return &envs } @@ -461,7 +461,7 @@ func expandContainerJobEnvVar(input Container) *[]jobs.EnvironmentVar { func expandInitContainerJobEnvVar(input BaseContainer) *[]jobs.EnvironmentVar { envs := make([]jobs.EnvironmentVar, 0) - if input.Env == nil || len(input.Env) == 0 { + if len(input.Env) == 0 { return &envs } diff --git a/internal/services/containerapps/helpers/container_apps.go b/internal/services/containerapps/helpers/container_apps.go index 954e9d4f917d..9f3fee51dbe9 100644 --- a/internal/services/containerapps/helpers/container_apps.go +++ b/internal/services/containerapps/helpers/container_apps.go @@ -1668,7 +1668,7 @@ func ContainerEnvVarSchemaComputed() *pluginsdk.Schema { func expandInitContainerEnvVar(input BaseContainer) *[]containerapps.EnvironmentVar { envs := make([]containerapps.EnvironmentVar, 0) - if input.Env == nil || len(input.Env) == 0 { + if len(input.Env) == 0 { return &envs } @@ -1690,7 +1690,7 @@ func expandInitContainerEnvVar(input BaseContainer) *[]containerapps.Environment func expandContainerEnvVar(input Container) *[]containerapps.EnvironmentVar { envs := make([]containerapps.EnvironmentVar, 0) - if input.Env == nil || len(input.Env) == 0 { + if len(input.Env) == 0 { return &envs } diff --git a/internal/services/datafactory/azuresdkhacks/pipelines.go b/internal/services/datafactory/azuresdkhacks/pipelines.go index 75ef1319861a..bdb784fd0fc1 100644 --- a/internal/services/datafactory/azuresdkhacks/pipelines.go +++ b/internal/services/datafactory/azuresdkhacks/pipelines.go @@ -62,7 +62,7 @@ func (client PipelinesClient) CreateOrUpdate(ctx context.Context, resourceGroupN }}, }, }); err != nil { - return result, validation.NewError("datafactory.PipelinesClient", "CreateOrUpdate", err.Error()) + return result, validation.NewError("datafactory.PipelinesClient", "CreateOrUpdate", err.Error()) // nolint: govet } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, factoryName, pipelineName, pipeline, ifMatch) @@ -152,7 +152,7 @@ func (client PipelinesClient) Get(ctx context.Context, resourceGroupName string, }, }, }); err != nil { - return result, validation.NewError("datafactory.PipelinesClient", "Get", err.Error()) + return result, validation.NewError("datafactory.PipelinesClient", "Get", err.Error()) // nolint: govet } req, err := client.GetPreparer(ctx, resourceGroupName, factoryName, pipelineName, ifNoneMatch) diff --git a/internal/services/datafactory/data_factory_data_flow_resource_test.go b/internal/services/datafactory/data_factory_data_flow_resource_test.go index 4aeb57d4fcae..ce3e3804fa23 100644 --- a/internal/services/datafactory/data_factory_data_flow_resource_test.go +++ b/internal/services/datafactory/data_factory_data_flow_resource_test.go @@ -107,6 +107,7 @@ func (t DataFlowResource) Exists(ctx context.Context, clients *clients.Client, s } func (r DataFlowResource) basic(data acceptance.TestData) string { + // nolint: dupword return fmt.Sprintf(` %s @@ -173,6 +174,7 @@ resource "azurerm_data_factory_data_flow" "import" { } func (r DataFlowResource) complete(data acceptance.TestData) string { + // nolint: dupword return fmt.Sprintf(` %s @@ -331,6 +333,7 @@ EOT } func (DataFlowResource) template(data acceptance.TestData) string { + // nolint: dupword return fmt.Sprintf(` provider "azurerm" { features {} diff --git a/internal/services/datafactory/data_factory_flowlet_data_flow_resource_test.go b/internal/services/datafactory/data_factory_flowlet_data_flow_resource_test.go index 68e3e265d7bd..66c3bba36d77 100644 --- a/internal/services/datafactory/data_factory_flowlet_data_flow_resource_test.go +++ b/internal/services/datafactory/data_factory_flowlet_data_flow_resource_test.go @@ -78,6 +78,7 @@ func (t FlowletDataFlowResource) Exists(ctx context.Context, clients *clients.Cl } func (r FlowletDataFlowResource) basic(data acceptance.TestData) string { + // nolint: dupword return fmt.Sprintf(` %s @@ -144,6 +145,7 @@ resource "azurerm_data_factory_flowlet_data_flow" "import" { } func (r FlowletDataFlowResource) complete(data acceptance.TestData) string { + // nolint: dupword return fmt.Sprintf(` %s diff --git a/internal/services/dataprotection/data_protection_backup_policy_blob_storage_resource.go b/internal/services/dataprotection/data_protection_backup_policy_blob_storage_resource.go index b3efd38f672c..9dd676ec89cd 100644 --- a/internal/services/dataprotection/data_protection_backup_policy_blob_storage_resource.go +++ b/internal/services/dataprotection/data_protection_backup_policy_blob_storage_resource.go @@ -528,7 +528,7 @@ func flattenBackupPolicyBlobStorageDefaultRetentionRuleDuration(input []backuppo for _, item := range input { if retentionRule, ok := item.(backuppolicies.AzureRetentionRule); ok && retentionRule.IsDefault != nil && *retentionRule.IsDefault { - if retentionRule.Lifecycles != nil && len(retentionRule.Lifecycles) > 0 { + if len(retentionRule.Lifecycles) > 0 { if deleteOption, ok := (retentionRule.Lifecycles)[0].DeleteAfter.(backuppolicies.AbsoluteDeleteOption); ok { if (retentionRule.Lifecycles)[0].SourceDataStore.DataStoreType == dsType { return deleteOption.Duration diff --git a/internal/services/dataprotection/data_protection_backup_policy_disk_resource.go b/internal/services/dataprotection/data_protection_backup_policy_disk_resource.go index ba4104b9e855..61e5f577c780 100644 --- a/internal/services/dataprotection/data_protection_backup_policy_disk_resource.go +++ b/internal/services/dataprotection/data_protection_backup_policy_disk_resource.go @@ -382,7 +382,7 @@ func flattenBackupPolicyDiskDefaultRetentionRuleDuration(input *[]backuppolicies for _, item := range *input { if retentionRule, ok := item.(backuppolicies.AzureRetentionRule); ok && retentionRule.IsDefault != nil && *retentionRule.IsDefault { - if retentionRule.Lifecycles != nil && len(retentionRule.Lifecycles) > 0 { + if len(retentionRule.Lifecycles) > 0 { if deleteOption, ok := (retentionRule.Lifecycles)[0].DeleteAfter.(backuppolicies.AbsoluteDeleteOption); ok { return deleteOption.Duration } @@ -421,7 +421,7 @@ func flattenBackupPolicyDiskRetentionRuleArray(input *[]backuppolicies.BasePolic } } var duration string - if retentionRule.Lifecycles != nil && len(retentionRule.Lifecycles) > 0 { + if len(retentionRule.Lifecycles) > 0 { if deleteOption, ok := (retentionRule.Lifecycles)[0].DeleteAfter.(backuppolicies.AbsoluteDeleteOption); ok { duration = deleteOption.Duration } diff --git a/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go b/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go index f8d7c197dae0..86bef5a1c92c 100644 --- a/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go +++ b/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go @@ -488,7 +488,7 @@ func flattenBackupPolicyPostgreSQLDefaultRetentionRuleDuration(input *[]backuppo for _, item := range *input { if retentionRule, ok := item.(backuppolicies.AzureRetentionRule); ok && retentionRule.IsDefault != nil && *retentionRule.IsDefault { - if retentionRule.Lifecycles != nil && len(retentionRule.Lifecycles) > 0 { + if len(retentionRule.Lifecycles) > 0 { if deleteOption, ok := (retentionRule.Lifecycles)[0].DeleteAfter.(backuppolicies.AbsoluteDeleteOption); ok { return deleteOption.Duration } @@ -527,7 +527,7 @@ func flattenBackupPolicyPostgreSQLRetentionRuleArray(input *[]backuppolicies.Bas } } var duration string - if retentionRule.Lifecycles != nil && len(retentionRule.Lifecycles) > 0 { + if len(retentionRule.Lifecycles) > 0 { if deleteOption, ok := (retentionRule.Lifecycles)[0].DeleteAfter.(backuppolicies.AbsoluteDeleteOption); ok { duration = deleteOption.Duration } diff --git a/internal/services/dataprotection/data_protection_backup_vault_data_source.go b/internal/services/dataprotection/data_protection_backup_vault_data_source.go index 0890affdc2ad..67d6ac80e823 100644 --- a/internal/services/dataprotection/data_protection_backup_vault_data_source.go +++ b/internal/services/dataprotection/data_protection_backup_vault_data_source.go @@ -87,7 +87,7 @@ func dataSourceDataProtectionBackupVaultRead(d *pluginsdk.ResourceData, meta int d.Set("location", location.NormalizeNilable(model.Location)) props := model.Properties - if props.StorageSettings != nil && len(props.StorageSettings) > 0 { + if len(props.StorageSettings) > 0 { d.Set("datastore_type", string(pointer.From((props.StorageSettings)[0].DatastoreType))) d.Set("redundancy", string(pointer.From((props.StorageSettings)[0].Type))) } diff --git a/internal/services/dataprotection/data_protection_backup_vault_resource.go b/internal/services/dataprotection/data_protection_backup_vault_resource.go index 8a79df8b268f..6bea62fd29a8 100644 --- a/internal/services/dataprotection/data_protection_backup_vault_resource.go +++ b/internal/services/dataprotection/data_protection_backup_vault_resource.go @@ -244,7 +244,7 @@ func resourceDataProtectionBackupVaultRead(d *pluginsdk.ResourceData, meta inter if model := resp.Model; model != nil { d.Set("location", location.NormalizeNilable(model.Location)) props := model.Properties - if props.StorageSettings != nil && len(props.StorageSettings) > 0 { + if len(props.StorageSettings) > 0 { d.Set("datastore_type", string(pointer.From((props.StorageSettings)[0].DatastoreType))) d.Set("redundancy", string(pointer.From((props.StorageSettings)[0].Type))) } diff --git a/internal/services/eventgrid/event_subscription_funcs.go b/internal/services/eventgrid/event_subscription_funcs.go index 28846ab62447..6eefc2d02960 100644 --- a/internal/services/eventgrid/event_subscription_funcs.go +++ b/internal/services/eventgrid/event_subscription_funcs.go @@ -770,63 +770,63 @@ func expandEventSubscriptionStorageBlobDeadLetterDestination(d *pluginsdk.Resour return nil } -func flattenValue(inputKey *string, inputValue *interface{}) map[string]interface{} { +func flattenValue(inputKey *string, inputValue *any) map[string]any { key := "" if inputKey != nil { key = *inputKey } - var value interface{} + var value any if inputValue != nil { value = inputValue } - return map[string]interface{}{ + return map[string]any{ "key": key, "value": value, } } -func flattenValues(inputKey *string, inputValues *[]interface{}) map[string]interface{} { +func flattenValues(inputKey *string, inputValues *[]any) map[string]any { key := "" if inputKey != nil { key = *inputKey } - values := make([]interface{}, 0) + values := make([]any, 0) if inputValues != nil { values = *inputValues } - return map[string]interface{}{ + return map[string]any{ "key": key, "values": values, } } -func flattenRangeValues(inputKey *string, inputValues *[][]interface{}) map[string]interface{} { +func flattenRangeValues(inputKey *string, inputValues *[][]any) map[string]any { key := "" if inputKey != nil { key = *inputKey } - values := make([]interface{}, 0) + values := make([]any, 0) if inputValues != nil { for _, item := range *inputValues { - values = append(values, item) + values = append(values, item...) } } - return map[string]interface{}{ + return map[string]any{ "key": key, "values": values, } } -func flattenKey(inputKey *string) map[string]interface{} { +func flattenKey(inputKey *string) map[string]any { key := "" if inputKey != nil { key = *inputKey } - return map[string]interface{}{ + return map[string]any{ "key": key, } } diff --git a/internal/services/eventhub/eventhub_consumer_group_resource.go b/internal/services/eventhub/eventhub_consumer_group_resource.go index 0b06448879a3..9f9a2f384e0f 100644 --- a/internal/services/eventhub/eventhub_consumer_group_resource.go +++ b/internal/services/eventhub/eventhub_consumer_group_resource.go @@ -8,6 +8,7 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-11-01/consumergroups" @@ -176,7 +177,7 @@ func (r ConsumerGroupResource) Read() sdk.ResourceFunc { } if model := resp.Model; model != nil && model.Properties != nil { - state.UserMetadata = utils.NormalizeNilableString(model.Properties.UserMetadata) + state.UserMetadata = pointer.From(model.Properties.UserMetadata) } return metadata.Encode(&state) diff --git a/internal/services/firewall/firewall_resource_test.go b/internal/services/firewall/firewall_resource_test.go index 6c9a3382bd02..ca1f5f7edbda 100644 --- a/internal/services/firewall/firewall_resource_test.go +++ b/internal/services/firewall/firewall_resource_test.go @@ -508,11 +508,9 @@ func (FirewallResource) enableDNS(data acceptance.TestData, enableProxy bool, dn } dnsServersStr = fmt.Sprintf("dns_servers = [%s]", strings.Join(servers, ", ")) } - enableProxyStr := "" + enableProxyStr := "dns_proxy_enabled = false" if enableProxy { enableProxyStr = "dns_proxy_enabled = true" - } else { - enableProxyStr = "dns_proxy_enabled = false" } return fmt.Sprintf(` diff --git a/internal/services/fluidrelay/fluid_relay_servers_resource.go b/internal/services/fluidrelay/fluid_relay_servers_resource.go index 7057d59a428e..a675eb2d4b9d 100644 --- a/internal/services/fluidrelay/fluid_relay_servers_resource.go +++ b/internal/services/fluidrelay/fluid_relay_servers_resource.go @@ -21,7 +21,6 @@ import ( keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) type ServerModel struct { @@ -325,8 +324,8 @@ func (s Server) Read() sdk.ResourceFunc { } if model := keys.Model; model != nil { - output.PrimaryKey = utils.NormalizeNilableString(model.Key1) - output.SecondaryKey = utils.NormalizeNilableString(model.Key2) + output.PrimaryKey = pointer.From(model.Key1) + output.SecondaryKey = pointer.From(model.Key2) } return meta.Encode(output) diff --git a/internal/services/frontdoor/frontdoor_custom_https_configuration.go b/internal/services/frontdoor/frontdoor_custom_https_configuration.go index 872bb068678a..b4e610b1a36e 100644 --- a/internal/services/frontdoor/frontdoor_custom_https_configuration.go +++ b/internal/services/frontdoor/frontdoor_custom_https_configuration.go @@ -69,7 +69,6 @@ func flattenCustomHttpsConfiguration(properties *frontdoors.FrontendEndpointProp keyVaultCertificateVaultId := "" keyVaultCertificateSecretName := "" keyVaultCertificateSecretVersion := "" - provisioningState := "" provisioningSubstate := "" if config.CertificateSource == frontdoors.FrontDoorCertificateSourceAzureKeyVault { @@ -91,7 +90,7 @@ func flattenCustomHttpsConfiguration(properties *frontdoors.FrontendEndpointProp } if properties.CustomHTTPSProvisioningState != nil && *properties.CustomHTTPSProvisioningState != "" { - provisioningState = string(*properties.CustomHTTPSProvisioningState) + provisioningState := string(*properties.CustomHTTPSProvisioningState) if properties.CustomHTTPSProvisioningState != nil && *properties.CustomHTTPSProvisioningState == frontdoors.CustomHTTPSProvisioningStateEnabled || *properties.CustomHTTPSProvisioningState == frontdoors.CustomHTTPSProvisioningStateEnabling { result.CustomHTTPSProvisioningEnabled = true diff --git a/internal/services/frontdoor/frontdoor_resource.go b/internal/services/frontdoor/frontdoor_resource.go index 35a5a39145b1..79700285a83e 100644 --- a/internal/services/frontdoor/frontdoor_resource.go +++ b/internal/services/frontdoor/frontdoor_resource.go @@ -906,9 +906,8 @@ func flattenExplicitResourceOrder(backendPools, frontendEndpoints, routingRules, func combineBackendPools(allPools []frontdoors.BackendPool, orderedIds []interface{}, frontDoorId frontdoors.FrontDoorId) ([]interface{}, error) { output := make([]interface{}, 0) - found := false - // first find all of the ones in the ordered mapping list and add them in the correct order + // first find all the ones in the ordered mapping list and add them in the correct order for _, v := range orderedIds { for _, backend := range allPools { if strings.EqualFold(v.(string), *backend.Id) { @@ -925,7 +924,7 @@ func combineBackendPools(allPools []frontdoors.BackendPool, orderedIds []interfa // Now check to see if items were added to the resource via the portal and add them to the state file for _, backend := range allPools { - found = false + found := false for _, orderedId := range orderedIds { if strings.EqualFold(orderedId.(string), *backend.Id) { found = true @@ -1111,9 +1110,8 @@ func retrieveFrontEndEndpointInformation(ctx context.Context, client *frontdoors func combineFrontEndEndpoints(allEndpoints []frontdoors.FrontendEndpoint, orderedIds []interface{}, frontDoorId frontdoors.FrontDoorId) ([]interface{}, error) { output := make([]interface{}, 0) - found := false - // first find all of the ones in the ordered mapping list and add them in the correct order + // first find all the ones in the ordered mapping list and add them in the correct order for _, v := range orderedIds { for _, frontendEndpoint := range allEndpoints { if strings.EqualFold(v.(string), *frontendEndpoint.Id) { @@ -1130,7 +1128,7 @@ func combineFrontEndEndpoints(allEndpoints []frontdoors.FrontendEndpoint, ordere // Now check to see if items were added to the resource via the portal and add them to the state file for _, frontendEndpoint := range allEndpoints { - found = false + found := false for _, orderedId := range orderedIds { if strings.EqualFold(orderedId.(string), *frontendEndpoint.Id) { found = true @@ -1231,9 +1229,8 @@ func flattenSingleFrontEndEndpoints(input frontdoors.FrontendEndpoint, frontDoor func combineHealthProbeSettingsModel(allHealthProbeSettings []frontdoors.HealthProbeSettingsModel, orderedIds []interface{}, frontDoorId frontdoors.FrontDoorId) []interface{} { output := make([]interface{}, 0) - found := false - // first find all of the ones in the ordered mapping list and add them in the correct order + // first find all the ones in the ordered mapping list and add them in the correct order for _, v := range orderedIds { for _, healthProbeSetting := range allHealthProbeSettings { if strings.EqualFold(v.(string), *healthProbeSetting.Id) { @@ -1246,7 +1243,7 @@ func combineHealthProbeSettingsModel(allHealthProbeSettings []frontdoors.HealthP // Now check to see if items were added to the resource via the portal and add them to the state file for _, healthProbeSetting := range allHealthProbeSettings { - found = false + found := false for _, orderedId := range orderedIds { if strings.EqualFold(orderedId.(string), *healthProbeSetting.Id) { found = true @@ -1337,9 +1334,8 @@ func flattenSingleFrontDoorHealthProbeSettingsModel(input *frontdoors.HealthProb func combineLoadBalancingSettingsModel(allLoadBalancingSettings []frontdoors.LoadBalancingSettingsModel, orderedIds []interface{}, frontDoorId frontdoors.FrontDoorId) []interface{} { output := make([]interface{}, 0) - found := false - // first find all of the ones in the ordered mapping list and add them in the correct order + // first find all the ones in the ordered mapping list and add them in the correct order for _, v := range orderedIds { for _, loadBalancingSetting := range allLoadBalancingSettings { if strings.EqualFold(v.(string), *loadBalancingSetting.Id) { @@ -1352,7 +1348,7 @@ func combineLoadBalancingSettingsModel(allLoadBalancingSettings []frontdoors.Loa // Now check to see if items were added to the resource via the portal and add them to the state file for _, loadBalanceSetting := range allLoadBalancingSettings { - found = false + found := false for _, orderedId := range orderedIds { if strings.EqualFold(orderedId.(string), *loadBalanceSetting.Id) { found = true @@ -1431,9 +1427,8 @@ func flattenSingleFrontDoorLoadBalancingSettingsModel(input *frontdoors.LoadBala func combineRoutingRules(allRoutingRules []frontdoors.RoutingRule, oldBlocks interface{}, orderedIds []interface{}, frontDoorId frontdoors.FrontDoorId) ([]interface{}, error) { output := make([]interface{}, 0) - found := false - // first find all of the ones in the ordered mapping list and add them in the correct order + // first find all the ones in the ordered mapping list and add them in the correct order for _, v := range orderedIds { for _, routingRule := range allRoutingRules { if strings.EqualFold(v.(string), *routingRule.Id) { @@ -1450,7 +1445,7 @@ func combineRoutingRules(allRoutingRules []frontdoors.RoutingRule, oldBlocks int // Now check to see if items were added to the resource via the portal and add them to the state file for _, routingRule := range allRoutingRules { - found = false + found := false for _, orderedId := range orderedIds { if strings.EqualFold(orderedId.(string), *routingRule.Id) { found = true diff --git a/internal/services/hdinsight/schema.go b/internal/services/hdinsight/schema.go index 0d7a55054281..19f3faafa07b 100644 --- a/internal/services/hdinsight/schema.go +++ b/internal/services/hdinsight/schema.go @@ -732,11 +732,9 @@ func FlattenHDInsightsConfigurations(input map[string]string, d *pluginsdk.Resou username = v } - password := "" + password := d.Get("gateway.0.password").(string) if v, exists := input["restAuthCredential.password"]; exists { password = v - } else { - password = d.Get("gateway.0.password").(string) } out := map[string]interface{}{ diff --git a/internal/services/keyvault/key_vault_certificate_resource.go b/internal/services/keyvault/key_vault_certificate_resource.go index 90e02d80803f..962e62b0d550 100644 --- a/internal/services/keyvault/key_vault_certificate_resource.go +++ b/internal/services/keyvault/key_vault_certificate_resource.go @@ -188,7 +188,7 @@ func resourceKeyVaultCertificate() *pluginsdk.Resource { }, }, }, - //lintignore:XS003 + // lintignore:XS003 "trigger": { Type: pluginsdk.TypeList, Required: true, @@ -842,7 +842,7 @@ func resourceKeyVaultCertificateDelete(d *pluginsdk.ResourceData, meta interface } shouldPurge := meta.(*clients.Client).Features.KeyVault.PurgeSoftDeletedCertsOnDestroy - if shouldPurge && kv.Model != nil && utils.NormaliseNilableBool(kv.Model.Properties.EnablePurgeProtection) { + if shouldPurge && kv.Model != nil && pointer.From(kv.Model.Properties.EnablePurgeProtection) { log.Printf("[DEBUG] cannot purge certificate %q because vault %q has purge protection enabled", id.Name, keyVaultId.String()) shouldPurge = false } diff --git a/internal/services/keyvault/key_vault_key_resource.go b/internal/services/keyvault/key_vault_key_resource.go index 3c464f59ad72..6fcf2c2a4ea6 100644 --- a/internal/services/keyvault/key_vault_key_resource.go +++ b/internal/services/keyvault/key_vault_key_resource.go @@ -663,7 +663,7 @@ func resourceKeyVaultKeyDelete(d *pluginsdk.ResourceData, meta interface{}) erro } shouldPurge := meta.(*clients.Client).Features.KeyVault.PurgeSoftDeletedKeysOnDestroy - if shouldPurge && kv.Model != nil && utils.NormaliseNilableBool(kv.Model.Properties.EnablePurgeProtection) { + if shouldPurge && kv.Model != nil && pointer.From(kv.Model.Properties.EnablePurgeProtection) { log.Printf("[DEBUG] cannot purge key %q because vault %q has purge protection enabled", id.Name, keyVaultId.String()) shouldPurge = false } diff --git a/internal/services/keyvault/key_vault_resource.go b/internal/services/keyvault/key_vault_resource.go index 056a7478abe1..8bf586ef5876 100644 --- a/internal/services/keyvault/key_vault_resource.go +++ b/internal/services/keyvault/key_vault_resource.go @@ -5,6 +5,7 @@ package keyvault import ( "context" + "errors" "fmt" "log" "net/http" @@ -304,7 +305,7 @@ func resourceKeyVaultCreate(d *pluginsdk.ResourceData, meta interface{}) error { if !response.WasNotFound(softDeletedKeyVault.HttpResponse) && !response.WasStatusCode(softDeletedKeyVault.HttpResponse, http.StatusForbidden) { if !meta.(*clients.Client).Features.KeyVault.RecoverSoftDeletedKeyVaults { // this exists but the users opted out so they must import this it out-of-band - return fmt.Errorf(optedOutOfRecoveringSoftDeletedKeyVaultErrorFmt(id.VaultName, location)) + return errors.New(optedOutOfRecoveringSoftDeletedKeyVaultErrorFmt(id.VaultName, location)) } recoverSoftDeletedKeyVault = true diff --git a/internal/services/keyvault/key_vault_secret_resource.go b/internal/services/keyvault/key_vault_secret_resource.go index e158051b94cf..a09370ad727e 100644 --- a/internal/services/keyvault/key_vault_secret_resource.go +++ b/internal/services/keyvault/key_vault_secret_resource.go @@ -11,6 +11,7 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/date" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" @@ -413,7 +414,7 @@ func resourceKeyVaultSecretDelete(d *pluginsdk.ResourceData, meta interface{}) e } shouldPurge := meta.(*clients.Client).Features.KeyVault.PurgeSoftDeletedSecretsOnDestroy - if shouldPurge && kv.Model != nil && utils.NormaliseNilableBool(kv.Model.Properties.EnablePurgeProtection) { + if shouldPurge && kv.Model != nil && pointer.From(kv.Model.Properties.EnablePurgeProtection) { log.Printf("[DEBUG] cannot purge secret %q because %s has purge protection enabled", id.Name, *keyVaultId) shouldPurge = false } diff --git a/internal/services/loganalytics/validate/log_analytics_storage_insights_workspace_name_test.go b/internal/services/loganalytics/validate/log_analytics_storage_insights_workspace_name_test.go index 176ae14ac98e..ed1327af7c6e 100644 --- a/internal/services/loganalytics/validate/log_analytics_storage_insights_workspace_name_test.go +++ b/internal/services/loganalytics/validate/log_analytics_storage_insights_workspace_name_test.go @@ -25,7 +25,7 @@ func TestLogAnalyticsStorageInsightsWorkspaceName(t *testing.T) { }, { Name: "Invalid characters space", - Input: "invalid Storage Insight Config Name Name", + Input: "invalid Storage Insight Config Name", Expected: false, }, { diff --git a/internal/services/machinelearning/machine_learning_workspace_resource_test.go b/internal/services/machinelearning/machine_learning_workspace_resource_test.go index 49e0c0668e34..ff80b4a9d481 100644 --- a/internal/services/machinelearning/machine_learning_workspace_resource_test.go +++ b/internal/services/machinelearning/machine_learning_workspace_resource_test.go @@ -965,6 +965,7 @@ resource "azurerm_machine_learning_workspace" "test" { } func (r WorkspaceResource) userAssignedAndCustomManagedKey(data acceptance.TestData) string { + // nolint: dupword return fmt.Sprintf(` provider "azurerm" { features { @@ -1094,8 +1095,7 @@ resource "azurerm_machine_learning_workspace" "test" { azurerm_role_assignment.test_sa1, azurerm_key_vault_access_policy.test-policy1, ] -} -`, r.template(data), data.RandomInteger) +}`, r.template(data), data.RandomInteger) } func (r WorkspaceResource) featureStore(data acceptance.TestData) string { diff --git a/internal/services/managedhsm/key_vault_managed_hardware_security_module_key_resource.go b/internal/services/managedhsm/key_vault_managed_hardware_security_module_key_resource.go index d311ddd7eb99..3ef1cf63ad33 100644 --- a/internal/services/managedhsm/key_vault_managed_hardware_security_module_key_resource.go +++ b/internal/services/managedhsm/key_vault_managed_hardware_security_module_key_resource.go @@ -466,7 +466,7 @@ func (r KeyVaultMHSMKeyResource) Delete() sdk.ResourceFunc { } shouldPurge := metadata.Client.Features.KeyVault.PurgeSoftDeletedHSMKeysOnDestroy - if shouldPurge && managedHSM.Model != nil && managedHSM.Model.Properties != nil && utils.NormaliseNilableBool(managedHSM.Model.Properties.EnablePurgeProtection) { + if shouldPurge && managedHSM.Model != nil && managedHSM.Model.Properties != nil && pointer.From(managedHSM.Model.Properties.EnablePurgeProtection) { log.Printf("[DEBUG] cannot purge key %q because Managed HSM %q has purge protection enabled", id.KeyName, id.ManagedHSMName) shouldPurge = false } diff --git a/internal/services/monitor/monitor_data_collection_rule_resource.go b/internal/services/monitor/monitor_data_collection_rule_resource.go index a8c7f79a9afe..83a1989fdd86 100644 --- a/internal/services/monitor/monitor_data_collection_rule_resource.go +++ b/internal/services/monitor/monitor_data_collection_rule_resource.go @@ -1861,7 +1861,7 @@ func flattenDataCollectionRuleDataSourcePerfCounters(input *[]datacollectionrule result = append(result, PerfCounter{ Name: flattenStringPtr(v.Name), CounterSpecifiers: flattenStringSlicePtr(v.CounterSpecifiers), - SamplingFrequencyInSeconds: utils.NormaliseNilableInt64(v.SamplingFrequencyInSeconds), + SamplingFrequencyInSeconds: pointer.From(v.SamplingFrequencyInSeconds), Streams: flattenDataCollectionRuleDataSourcePerfCounterStreams(v.Streams), }) } diff --git a/internal/services/monitor/monitor_diagnostic_setting_resource.go b/internal/services/monitor/monitor_diagnostic_setting_resource.go index 3b9213205f5c..b43cac6f32f6 100644 --- a/internal/services/monitor/monitor_diagnostic_setting_resource.go +++ b/internal/services/monitor/monitor_diagnostic_setting_resource.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" authRuleParse "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-11-01/authorizationrulesnamespaces" @@ -443,7 +444,7 @@ func resourceMonitorDiagnosticSettingRead(d *pluginsdk.ResourceData, meta interf d.Set("eventhub_name", props.EventHubName) eventhubAuthorizationRuleId := "" if props.EventHubAuthorizationRuleId != nil && *props.EventHubAuthorizationRuleId != "" { - authRuleId := utils.NormalizeNilableString(props.EventHubAuthorizationRuleId) + authRuleId := pointer.From(props.EventHubAuthorizationRuleId) parsedId, err := authRuleParse.ParseAuthorizationRuleIDInsensitively(authRuleId) if err != nil { return err @@ -463,21 +464,17 @@ func resourceMonitorDiagnosticSettingRead(d *pluginsdk.ResourceData, meta interf } d.Set("log_analytics_workspace_id", workspaceId) - storageAccountId := "" if props.StorageAccountId != nil && *props.StorageAccountId != "" { parsedId, err := commonids.ParseStorageAccountIDInsensitively(*props.StorageAccountId) if err != nil { return err } - storageAccountId = parsedId.ID() - d.Set("storage_account_id", storageAccountId) + d.Set("storage_account_id", parsedId.ID()) } - partnerSolutionId := "" if props.MarketplacePartnerId != nil && *props.MarketplacePartnerId != "" { - partnerSolutionId = *props.MarketplacePartnerId - d.Set("partner_solution_id", partnerSolutionId) + d.Set("partner_solution_id", props.MarketplacePartnerId) } logAnalyticsDestinationType := "" diff --git a/internal/services/mssql/helper/elasticpool.go b/internal/services/mssql/helper/elasticpool.go index 2432babdd9d7..4955d57836bc 100644 --- a/internal/services/mssql/helper/elasticpool.go +++ b/internal/services/mssql/helper/elasticpool.go @@ -4,6 +4,7 @@ package helper import ( + "errors" "fmt" "math" "sort" @@ -402,7 +403,7 @@ func buildErrorString(stub string, m map[int]float64) string { func doDTUSKUValidation(s sku) error { if s.MaxAllowedGB == 0 { - return fmt.Errorf(getDTUCapacityErrorMsg(s)) + return errors.New(getDTUCapacityErrorMsg(s)) } if strings.EqualFold(s.Name, "BasicPool") { @@ -422,7 +423,7 @@ func doDTUSKUValidation(s sku) error { // Check to see if the max_size_gb value is valid for this SKU type and capacity if supportedDTUMaxGBValues[int(s.MaxSizeGb)] != 1 { - return fmt.Errorf(getDTUNotValidSizeErrorMsg(s)) + return errors.New(getDTUNotValidSizeErrorMsg(s)) } } @@ -440,7 +441,7 @@ func doDTUSKUValidation(s sku) error { func doVCoreSKUValidation(s sku) error { if s.MaxAllowedGB == 0 { - return fmt.Errorf(getVCoreCapacityErrorMsg(s)) + return errors.New(getVCoreCapacityErrorMsg(s)) } if s.MaxSizeGb > s.MaxAllowedGB { diff --git a/internal/services/mssql/mssql_database_resource.go b/internal/services/mssql/mssql_database_resource.go index a49ae464203b..00424f136b28 100644 --- a/internal/services/mssql/mssql_database_resource.go +++ b/internal/services/mssql/mssql_database_resource.go @@ -1140,7 +1140,6 @@ func resourceMsSqlDatabaseRead(d *pluginsdk.ResourceData, meta interface{}) erro geoBackupPolicy := true skuName := "" elasticPoolId := "" - minCapacity := float64(0) ledgerEnabled := false enclaveType := "" @@ -1148,7 +1147,7 @@ func resourceMsSqlDatabaseRead(d *pluginsdk.ResourceData, meta interface{}) erro d.Set("name", id.DatabaseName) if props := model.Properties; props != nil { - minCapacity = pointer.From(props.MinCapacity) + minCapacity := pointer.From(props.MinCapacity) requestedBackupStorageRedundancy := "" if props.RequestedBackupStorageRedundancy != nil { diff --git a/internal/services/mssql/mssql_database_resource_test.go b/internal/services/mssql/mssql_database_resource_test.go index 0c4f92c5d186..389292857ddf 100644 --- a/internal/services/mssql/mssql_database_resource_test.go +++ b/internal/services/mssql/mssql_database_resource_test.go @@ -72,14 +72,12 @@ func TestAccMsSqlDatabase_complete(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mssql_database", "test") r := MsSqlDatabaseResource{} - maintenance_configuration_name := "" + maintenance_configuration_name := "SQL_Default" switch data.Locations.Primary { case "westeurope": maintenance_configuration_name = "SQL_WestEurope_DB_2" case "francecentral": maintenance_configuration_name = "SQL_FranceCentral_DB_1" - default: - maintenance_configuration_name = "SQL_Default" } data.ResourceTest(t, r, []acceptance.TestStep{ @@ -1110,14 +1108,12 @@ resource "azurerm_mssql_database" "import" { } func (r MsSqlDatabaseResource) complete(data acceptance.TestData) string { - configName := "" + configName := "SQL_Default" switch data.Locations.Primary { case "westeurope": configName = "SQL_WestEurope_DB_2" case "francecentral": configName = "SQL_FranceCentral_DB_1" - default: - configName = "SQL_Default" } return fmt.Sprintf(` diff --git a/internal/services/mssql/mssql_elasticpool_resource_test.go b/internal/services/mssql/mssql_elasticpool_resource_test.go index a8684ae06c1f..d8df5694cb62 100644 --- a/internal/services/mssql/mssql_elasticpool_resource_test.go +++ b/internal/services/mssql/mssql_elasticpool_resource_test.go @@ -55,14 +55,12 @@ func TestAccMsSqlElasticPool_standardDTU(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mssql_elasticpool", "test") r := MsSqlElasticPoolResource{} - maintenance_configuration_name := "" + maintenance_configuration_name := "SQL_Default" switch data.Locations.Primary { case "westeurope": maintenance_configuration_name = "SQL_WestEurope_DB_2" case "francecentral": maintenance_configuration_name = "SQL_FranceCentral_DB_1" - default: - maintenance_configuration_name = "SQL_Default" } data.ResourceTest(t, r, []acceptance.TestStep{ diff --git a/internal/services/mssql/mssql_server_dns_alias_resource.go b/internal/services/mssql/mssql_server_dns_alias_resource.go index 37f403103177..7504d97396ad 100644 --- a/internal/services/mssql/mssql_server_dns_alias_resource.go +++ b/internal/services/mssql/mssql_server_dns_alias_resource.go @@ -8,13 +8,13 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-sdk/resource-manager/sql/2023-08-01-preview/serverdnsaliases" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) type ServerDNSAliasModel struct { @@ -120,7 +120,7 @@ func (m ServerDNSAliasResource) Read() sdk.ResourceFunc { } if alias.Model != nil { if prop := alias.Model.Properties; prop != nil { - state.DNSRecord = utils.NormalizeNilableString(prop.AzureDnsRecord) + state.DNSRecord = pointer.From(prop.AzureDnsRecord) } } return metadata.Encode(&state) diff --git a/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource.go b/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource.go index 0759ac5c8230..2a556d4c7407 100644 --- a/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource.go +++ b/internal/services/mssql/mssql_virtual_machine_availability_group_listener_resource.go @@ -281,7 +281,7 @@ func (r MsSqlVirtualMachineAvailabilityGroupListenerResource) Create() sdk.Resou }, } - if model.LoadBalancerConfiguration != nil && len(model.LoadBalancerConfiguration) != 0 { + if len(model.LoadBalancerConfiguration) != 0 { lbConfigs, err := expandMsSqlVirtualMachineAvailabilityGroupListenerLoadBalancerConfigurations(model.LoadBalancerConfiguration) if err != nil { return err @@ -289,7 +289,7 @@ func (r MsSqlVirtualMachineAvailabilityGroupListenerResource) Create() sdk.Resou parameters.Properties.LoadBalancerConfigurations = lbConfigs } - if model.MultiSubnetIpConfiguration != nil && len(model.MultiSubnetIpConfiguration) != 0 { + if len(model.MultiSubnetIpConfiguration) != 0 { parameters.Properties.MultiSubnetIPConfigurations = expandMsSqlVirtualMachineAvailabilityGroupListenerMultiSubnetIpConfiguration(model.MultiSubnetIpConfiguration) } diff --git a/internal/services/mssql/mssql_virtual_machine_group_resource.go b/internal/services/mssql/mssql_virtual_machine_group_resource.go index a4b612db39ae..88428e44d930 100644 --- a/internal/services/mssql/mssql_virtual_machine_group_resource.go +++ b/internal/services/mssql/mssql_virtual_machine_group_resource.go @@ -247,7 +247,7 @@ func (r MsSqlVirtualMachineGroupResource) Read() sdk.ResourceFunc { return err } storageAccountPrimaryKey := "" - if oldModel.WsfcDomainProfile != nil && len(oldModel.WsfcDomainProfile) != 0 { + if len(oldModel.WsfcDomainProfile) != 0 { storageAccountPrimaryKey = oldModel.WsfcDomainProfile[0].StorageAccountPrimaryKey } state.WsfcDomainProfile = flattenMsSqlVirtualMachineGroupWsfcDomainProfile(props.WsfcDomainProfile, storageAccountPrimaryKey) diff --git a/internal/services/mssql/mssql_virtual_machine_resource.go b/internal/services/mssql/mssql_virtual_machine_resource.go index c426ad15aef5..0fc58971e926 100644 --- a/internal/services/mssql/mssql_virtual_machine_resource.go +++ b/internal/services/mssql/mssql_virtual_machine_resource.go @@ -529,7 +529,7 @@ func resourceMsSqlVirtualMachineCreateUpdate(d *pluginsdk.ResourceData, meta int if respvm.Model.Location == "" { return fmt.Errorf("retrieving %s: `location` is empty", vmId) } - sqlVmGroupId := "" + var sqlVmGroupId string if sqlVmGroupId = d.Get("sql_virtual_machine_group_id").(string); sqlVmGroupId != "" { parsedVmGroupId, err := sqlvirtualmachines.ParseSqlVirtualMachineGroupIDInsensitively(sqlVmGroupId) if err != nil { diff --git a/internal/services/netapp/netapp_pool_resource.go b/internal/services/netapp/netapp_pool_resource.go index 65997de9912e..039e5a6527fc 100644 --- a/internal/services/netapp/netapp_pool_resource.go +++ b/internal/services/netapp/netapp_pool_resource.go @@ -241,10 +241,9 @@ func resourceNetAppPoolRead(d *pluginsdk.ResourceData, meta interface{}) error { poolProperties := model.Properties d.Set("service_level", poolProperties.ServiceLevel) - sizeInTB := int64(0) sizeInBytes := poolProperties.Size sizeInMB := sizeInBytes / 1024 / 1024 - sizeInTB = sizeInMB / 1024 / 1024 + sizeInTB := sizeInMB / 1024 / 1024 d.Set("size_in_tb", int(sizeInTB)) qosType := "" if poolProperties.QosType != nil { diff --git a/internal/services/netapp/netapp_volume_group_sap_hana_resource.go b/internal/services/netapp/netapp_volume_group_sap_hana_resource.go index a50240de688e..eb97dbe2839a 100644 --- a/internal/services/netapp/netapp_volume_group_sap_hana_resource.go +++ b/internal/services/netapp/netapp_volume_group_sap_hana_resource.go @@ -571,8 +571,8 @@ func (r NetAppVolumeGroupSapHanaResource) Read() sdk.ResourceFunc { } if props := existing.Model.Properties; props != nil { - model.GroupDescription = utils.NormalizeNilableString(props.GroupMetaData.GroupDescription) - model.ApplicationIdentifier = utils.NormalizeNilableString(props.GroupMetaData.ApplicationIdentifier) + model.GroupDescription = pointer.From(props.GroupMetaData.GroupDescription) + model.ApplicationIdentifier = pointer.From(props.GroupMetaData.ApplicationIdentifier) volumes, err := flattenNetAppVolumeGroupVolumes(ctx, props.Volumes, metadata) if err != nil { diff --git a/internal/services/netapp/netapp_volume_helper.go b/internal/services/netapp/netapp_volume_helper.go index e9e088845dce..ed6d7aab92aa 100644 --- a/internal/services/netapp/netapp_volume_helper.go +++ b/internal/services/netapp/netapp_volume_helper.go @@ -146,7 +146,7 @@ func expandNetAppVolumeGroupVolumes(input []netAppModels.NetAppVolumeGroupVolume } if v := item.ProximityPlacementGroupId; v != "" { - volumeProperties.Properties.ProximityPlacementGroup = pointer.To(utils.NormalizeNilableString(pointer.To(v))) + volumeProperties.Properties.ProximityPlacementGroup = pointer.To(pointer.From(pointer.To(v))) } results = append(results, *volumeProperties) @@ -290,13 +290,13 @@ func flattenNetAppVolumeGroupVolumes(ctx context.Context, input *[]volumegroups. volumeGroupVolume.VolumePath = props.CreationToken volumeGroupVolume.ServiceLevel = string(pointer.From(props.ServiceLevel)) volumeGroupVolume.SubnetId = props.SubnetId - volumeGroupVolume.CapacityPoolId = utils.NormalizeNilableString(props.CapacityPoolResourceId) + volumeGroupVolume.CapacityPoolId = pointer.From(props.CapacityPoolResourceId) volumeGroupVolume.Protocols = pointer.From(props.ProtocolTypes) volumeGroupVolume.SecurityStyle = string(pointer.From(props.SecurityStyle)) volumeGroupVolume.SnapshotDirectoryVisible = pointer.From(props.SnapshotDirectoryVisible) volumeGroupVolume.ThroughputInMibps = pointer.From(props.ThroughputMibps) volumeGroupVolume.Tags = pointer.From(item.Tags) - volumeGroupVolume.ProximityPlacementGroupId = utils.NormalizeNilableString(props.ProximityPlacementGroup) + volumeGroupVolume.ProximityPlacementGroupId = pointer.From(props.ProximityPlacementGroup) volumeGroupVolume.VolumeSpecName = pointer.From(props.VolumeSpecName) if props.UsageThreshold > 0 { diff --git a/internal/services/netapp/netapp_volume_resource.go b/internal/services/netapp/netapp_volume_resource.go index 41f3ccea612f..8199516d8ded 100644 --- a/internal/services/netapp/netapp_volume_resource.go +++ b/internal/services/netapp/netapp_volume_resource.go @@ -999,29 +999,29 @@ func flattenNetAppVolumeExportPolicyRule(input *volumes.VolumePropertiesExportPo } protocolsEnabled := []string{} - if utils.NormaliseNilableBool(item.Cifs) { + if pointer.From(item.Cifs) { protocolsEnabled = append(protocolsEnabled, "CIFS") } - if utils.NormaliseNilableBool(item.Nfsv3) { + if pointer.From(item.Nfsv3) { protocolsEnabled = append(protocolsEnabled, "NFSv3") } - if utils.NormaliseNilableBool(item.Nfsv41) { + if pointer.From(item.Nfsv41) { protocolsEnabled = append(protocolsEnabled, "NFSv4.1") } result := map[string]interface{}{ "allowed_clients": utils.FlattenStringSlice(&allowedClients), - "kerberos_5_read_only_enabled": utils.NormaliseNilableBool(item.Kerberos5ReadOnly), - "kerberos_5_read_write_enabled": utils.NormaliseNilableBool(item.Kerberos5ReadWrite), - "kerberos_5i_read_only_enabled": utils.NormaliseNilableBool(item.Kerberos5iReadOnly), - "kerberos_5i_read_write_enabled": utils.NormaliseNilableBool(item.Kerberos5iReadWrite), - "kerberos_5p_read_only_enabled": utils.NormaliseNilableBool(item.Kerberos5pReadOnly), - "kerberos_5p_read_write_enabled": utils.NormaliseNilableBool(item.Kerberos5pReadWrite), + "kerberos_5_read_only_enabled": pointer.From(item.Kerberos5ReadOnly), + "kerberos_5_read_write_enabled": pointer.From(item.Kerberos5ReadWrite), + "kerberos_5i_read_only_enabled": pointer.From(item.Kerberos5iReadOnly), + "kerberos_5i_read_write_enabled": pointer.From(item.Kerberos5iReadWrite), + "kerberos_5p_read_only_enabled": pointer.From(item.Kerberos5pReadOnly), + "kerberos_5p_read_write_enabled": pointer.From(item.Kerberos5pReadWrite), "protocols_enabled": utils.FlattenStringSlice(&protocolsEnabled), - "root_access_enabled": utils.NormaliseNilableBool(item.HasRootAccess), + "root_access_enabled": pointer.From(item.HasRootAccess), "rule_index": ruleIndex, - "unix_read_only": utils.NormaliseNilableBool(item.UnixReadOnly), - "unix_read_write": utils.NormaliseNilableBool(item.UnixReadWrite), + "unix_read_only": pointer.From(item.UnixReadOnly), + "unix_read_write": pointer.From(item.UnixReadWrite), } results = append(results, result) } diff --git a/internal/services/netapp/validate/volume_group_sap_hana_volumes_validation.go b/internal/services/netapp/validate/volume_group_sap_hana_volumes_validation.go index ec27e6f3add1..f76118b66c7e 100644 --- a/internal/services/netapp/validate/volume_group_sap_hana_volumes_validation.go +++ b/internal/services/netapp/validate/volume_group_sap_hana_volumes_validation.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2023-05-01/volumegroups" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) type VolumeSpecNameSapHana string @@ -142,7 +141,7 @@ func ValidateNetAppVolumeGroupSAPHanaVolumes(volumeList *[]volumegroups.VolumeGr // Validating that data-backup and log-backup don't have PPG defined if (strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaDataBackup)) || strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaLogBackup))) && - utils.NormalizeNilableString(volume.Properties.ProximityPlacementGroup) != "" { + pointer.From(volume.Properties.ProximityPlacementGroup) != "" { errors = append(errors, fmt.Errorf("'%v volume spec type cannot have PPG defined for %v on volume %v'", pointer.From(volume.Properties.VolumeSpecName), applicationType, pointer.From(volume.Name))) } @@ -151,7 +150,7 @@ func ValidateNetAppVolumeGroupSAPHanaVolumes(volumeList *[]volumegroups.VolumeGr if (strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaData)) || strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaLog)) || strings.EqualFold(pointer.From(volume.Properties.VolumeSpecName), string(VolumeSpecNameSapHanaShared))) && - utils.NormalizeNilableString(volume.Properties.ProximityPlacementGroup) == "" { + pointer.From(volume.Properties.ProximityPlacementGroup) == "" { errors = append(errors, fmt.Errorf("'%v volume spec type must have PPG defined for %v on volume %v'", pointer.From(volume.Properties.VolumeSpecName), applicationType, pointer.From(volume.Name))) } diff --git a/internal/services/network/application_gateway_resource.go b/internal/services/network/application_gateway_resource.go index 2b48a7713e03..d236e7b00f6e 100644 --- a/internal/services/network/application_gateway_resource.go +++ b/internal/services/network/application_gateway_resource.go @@ -4819,7 +4819,7 @@ func applicationGatewayHttpListnerHash(v interface{}) int { buf.WriteString(statusCode.(string)) } if pageUrl, ok := customError["custom_error_page_url"]; ok { - buf.WriteString(fmt.Sprintf(pageUrl.(string))) + buf.WriteString(pageUrl.(string)) } } } diff --git a/internal/services/network/deprecated.go b/internal/services/network/deprecated.go index 5e54118fa55d..31bf7cc1f84e 100644 --- a/internal/services/network/deprecated.go +++ b/internal/services/network/deprecated.go @@ -4,7 +4,7 @@ package network import ( - "fmt" + "errors" "strings" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" @@ -13,15 +13,15 @@ import ( // NOTE: these methods are deprecated, but provided to ease compatibility for open PR's func evaluateSchemaValidateFunc(i interface{}, k string, validateFunc pluginsdk.SchemaValidateFunc) (bool, error) { // nolint: unparam - _, errors := validateFunc(i, k) + _, errs := validateFunc(i, k) errorStrings := []string{} - for _, e := range errors { + for _, e := range errs { errorStrings = append(errorStrings, e.Error()) } - if len(errors) > 0 { - return false, fmt.Errorf(strings.Join(errorStrings, "\n")) + if len(errs) > 0 { + return false, errors.New(strings.Join(errorStrings, "\n")) } return true, nil diff --git a/internal/services/network/route_table_resource.go b/internal/services/network/route_table_resource.go index 02052630516a..c5e54d1feafc 100644 --- a/internal/services/network/route_table_resource.go +++ b/internal/services/network/route_table_resource.go @@ -157,12 +157,6 @@ func resourceRouteTableCreate(d *pluginsdk.ResourceData, meta interface{}) error bgpRoutePropagationEnabled := d.Get("bgp_route_propagation_enabled").(bool) - if !features.FourPointOhBeta() { - // need to set default back to true for 3.x, this triggers ineffassign linter, so ignoring for now - bgpRoutePropagationEnabled = true // nolint: ineffassign - bgpRoutePropagationEnabled = !d.Get("disable_bgp_route_propagation").(bool) - } - routeSet := routetables.RouteTable{ Name: &id.RouteTableName, Location: pointer.To(location.Normalize(d.Get("location").(string))), diff --git a/internal/services/network/virtual_network_gateway_connection_resource.go b/internal/services/network/virtual_network_gateway_connection_resource.go index feb955358b11..94a8dc720309 100644 --- a/internal/services/network/virtual_network_gateway_connection_resource.go +++ b/internal/services/network/virtual_network_gateway_connection_resource.go @@ -853,7 +853,7 @@ func getVirtualNetworkGatewayConnectionProperties(d *pluginsdk.ResourceData, vir props.IPsecPolicies = expandVirtualNetworkGatewayConnectionIpsecPolicies(v.([]interface{})) } - if utils.NormaliseNilableBool(props.EnableBgp) { + if pointer.From(props.EnableBgp) { if _, ok := d.GetOk("custom_bgp_addresses"); ok { if virtualNetworkGateway.Properties.BgpSettings == nil || virtualNetworkGateway.Properties.BgpSettings.BgpPeeringAddresses == nil { return nil, fmt.Errorf("retrieving BGP peering address from `virtual_network_gateway` %s (%s) failed: get nil", *virtualNetworkGateway.Name, *virtualNetworkGateway.Id) diff --git a/internal/services/oracle/cloud_vm_cluster_resource.go b/internal/services/oracle/cloud_vm_cluster_resource.go index 1f843f567705..2579011be170 100644 --- a/internal/services/oracle/cloud_vm_cluster_resource.go +++ b/internal/services/oracle/cloud_vm_cluster_resource.go @@ -352,7 +352,7 @@ func (r CloudVmClusterResource) Create() sdk.ResourceFunc { if model.ClusterName != "" { param.Properties.ClusterName = pointer.To(model.ClusterName) } - if model.DataCollectionOptions != nil && len(model.DataCollectionOptions) > 0 { + if len(model.DataCollectionOptions) > 0 { param.Properties.DataCollectionOptions = &cloudvmclusters.DataCollectionOptions{ IsDiagnosticsEventsEnabled: pointer.To(model.DataCollectionOptions[0].IsDiagnosticsEventsEnabled), IsHealthMonitoringEnabled: pointer.To(model.DataCollectionOptions[0].IsHealthMonitoringEnabled), diff --git a/internal/services/paloalto/next_generation_firewall_vhub_local_rulestack_resource.go b/internal/services/paloalto/next_generation_firewall_vhub_local_rulestack_resource.go index ea6923b8cc84..46d7e6101cb6 100644 --- a/internal/services/paloalto/next_generation_firewall_vhub_local_rulestack_resource.go +++ b/internal/services/paloalto/next_generation_firewall_vhub_local_rulestack_resource.go @@ -87,7 +87,6 @@ func (r NextGenerationFirewallVHubLocalRuleStackResource) Create() sdk.ResourceF Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { client := metadata.Client.PaloAlto.PaloAltoClient_v2023_09_01.Firewalls localRuleStackClient := metadata.Client.PaloAlto.Client.LocalRulestacks - loc := "" var model NextGenerationFirewallVHubLocalRuleStackModel if err := metadata.Decode(&model); err != nil { @@ -116,7 +115,7 @@ func (r NextGenerationFirewallVHubLocalRuleStackResource) Create() sdk.ResourceF return fmt.Errorf("reading %s for %s: %+v", ruleStackID, id, err) } - loc = location.Normalize(ruleStack.Model.Location) + loc := location.Normalize(ruleStack.Model.Location) firewall := firewalls.FirewallResource{ Location: loc, diff --git a/internal/services/policy/remediation_resource.go b/internal/services/policy/remediation_resource.go index 10cd04558af6..bbfcbe6ab190 100644 --- a/internal/services/policy/remediation_resource.go +++ b/internal/services/policy/remediation_resource.go @@ -9,6 +9,7 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/remediations" @@ -315,7 +316,7 @@ func setRemediationProperties(d *pluginsdk.ResourceData, prop *remediations.Reme d.Set("policy_assignment_id", prop.PolicyAssignmentId) d.Set("policy_definition_reference_id", prop.PolicyDefinitionReferenceId) - d.Set("resource_discovery_mode", utils.NormalizeNilableString((*string)(prop.ResourceDiscoveryMode))) + d.Set("resource_discovery_mode", pointer.From((*string)(prop.ResourceDiscoveryMode))) d.Set("resource_count", prop.ResourceCount) d.Set("parallel_deployments", prop.ParallelDeployments) diff --git a/internal/services/recoveryservices/backup_policy_vm_workload_resource.go b/internal/services/recoveryservices/backup_policy_vm_workload_resource.go index b2dcccc15633..63a2b595fa8e 100644 --- a/internal/services/recoveryservices/backup_policy_vm_workload_resource.go +++ b/internal/services/recoveryservices/backup_policy_vm_workload_resource.go @@ -630,7 +630,7 @@ func expandBackupProtectionPolicyVMWorkloadProtectionPolicies(input []Protection switch backupBlock.Frequency { case string(protectionpolicies.ScheduleRunTypeDaily): - if item.RetentionDaily == nil || len(item.RetentionDaily) == 0 { + if len(item.RetentionDaily) == 0 { return nil, fmt.Errorf("`retention_daily` must be set when `backup.0.frequency` is `Daily`") } @@ -770,7 +770,7 @@ func expandBackupProtectionPolicyVMWorkloadRetentionPolicy(input ProtectionPolic if input.PolicyType == string(protectionpolicies.PolicyTypeFull) { retentionPolicy := protectionpolicies.LongTermRetentionPolicy{} - if input.RetentionDaily != nil && len(input.RetentionDaily) > 0 { + if len(input.RetentionDaily) > 0 { retentionDaily := input.RetentionDaily[0] retentionPolicy.DailySchedule = &protectionpolicies.DailyRetentionSchedule{ @@ -782,7 +782,7 @@ func expandBackupProtectionPolicyVMWorkloadRetentionPolicy(input ProtectionPolic } } - if input.RetentionWeekly != nil && len(input.RetentionWeekly) > 0 { + if len(input.RetentionWeekly) > 0 { retentionWeekly := input.RetentionWeekly[0] retentionPolicy.WeeklySchedule = &protectionpolicies.WeeklyRetentionSchedule{ @@ -802,18 +802,18 @@ func expandBackupProtectionPolicyVMWorkloadRetentionPolicy(input ProtectionPolic } } - if input.RetentionMonthly != nil && len(input.RetentionMonthly) > 0 { + if len(input.RetentionMonthly) > 0 { retentionMonthly := input.RetentionMonthly[0] if input.Backup[0].Frequency == string(protectionpolicies.ScheduleRunTypeWeekly) && retentionMonthly.FormatType != string(protectionpolicies.RetentionScheduleFormatWeekly) { return nil, fmt.Errorf("`retention_monthly.format_type` must be `Weekly` when `policy_type` is `Full` and `frequency` is `Weekly`") } - if retentionMonthly.FormatType == string(protectionpolicies.RetentionScheduleFormatDaily) && (retentionMonthly.Monthdays == nil || len(retentionMonthly.Monthdays) == 0) { + if retentionMonthly.FormatType == string(protectionpolicies.RetentionScheduleFormatDaily) && (len(retentionMonthly.Monthdays) == 0) { return nil, fmt.Errorf("`retention_monthly.monthdays` must be set when `retention_monthly.format_type` is `Daily`") } - if retentionMonthly.FormatType == string(protectionpolicies.RetentionScheduleFormatWeekly) && ((retentionMonthly.Weeks == nil || len(retentionMonthly.Weeks) == 0) || (retentionMonthly.Weekdays == nil || len(retentionMonthly.Weekdays) == 0)) { + if retentionMonthly.FormatType == string(protectionpolicies.RetentionScheduleFormatWeekly) && (len(retentionMonthly.Weeks) == 0 || len(retentionMonthly.Weekdays) == 0) { return nil, fmt.Errorf("`retention_monthly.weeks` and `retention_monthly.weekdays` must be set when `retention_monthly.format_type` is `Weekly`") } @@ -829,18 +829,18 @@ func expandBackupProtectionPolicyVMWorkloadRetentionPolicy(input ProtectionPolic } } - if input.RetentionYearly != nil && len(input.RetentionYearly) > 0 { + if len(input.RetentionYearly) > 0 { retentionYearly := input.RetentionYearly[0] if input.Backup[0].Frequency == string(protectionpolicies.ScheduleRunTypeWeekly) && retentionYearly.FormatType != string(protectionpolicies.RetentionScheduleFormatWeekly) { return nil, fmt.Errorf("`retention_yearly.format_type` must be `Weekly` when `policy_type` is `Full` and `frequency` is `Weekly`") } - if retentionYearly.FormatType == string(protectionpolicies.RetentionScheduleFormatDaily) && (retentionYearly.Monthdays == nil || len(retentionYearly.Monthdays) == 0) { + if retentionYearly.FormatType == string(protectionpolicies.RetentionScheduleFormatDaily) && (len(retentionYearly.Monthdays) == 0) { return nil, fmt.Errorf("`retention_yearly.monthdays` must be set when `retention_yearly.format_type` is `Daily`") } - if retentionYearly.FormatType == string(protectionpolicies.RetentionScheduleFormatWeekly) && ((retentionYearly.Weeks == nil || len(retentionYearly.Weeks) == 0) || (retentionYearly.Weekdays == nil || len(retentionYearly.Weekdays) == 0)) { + if retentionYearly.FormatType == string(protectionpolicies.RetentionScheduleFormatWeekly) && (len(retentionYearly.Weeks) == 0 || len(retentionYearly.Weekdays) == 0) { return nil, fmt.Errorf("`retention_yearly.weeks` and `retention_yearly.weekdays` must be set when `retention_yearly.format_type` is `Weekly`") } @@ -868,7 +868,7 @@ func expandBackupProtectionPolicyVMWorkloadRetentionPolicy(input ProtectionPolic } else { retentionPolicy := protectionpolicies.SimpleRetentionPolicy{} - if input.SimpleRetention != nil && len(input.SimpleRetention) > 0 { + if len(input.SimpleRetention) > 0 { simpleRetention := input.SimpleRetention[0] retentionPolicy.RetentionDuration = &protectionpolicies.RetentionDuration{ diff --git a/internal/services/recoveryservices/backup_protected_vm_resource.go b/internal/services/recoveryservices/backup_protected_vm_resource.go index 9b82df4f3b72..68b2ec87fa58 100644 --- a/internal/services/recoveryservices/backup_protected_vm_resource.go +++ b/internal/services/recoveryservices/backup_protected_vm_resource.go @@ -5,6 +5,7 @@ package recoveryservices import ( "context" + "errors" "fmt" "log" "net/http" @@ -116,7 +117,7 @@ func resourceRecoveryServicesBackupProtectedVMCreate(d *pluginsdk.ResourceData, return fmt.Errorf("recovering soft deleted %s: %+v", id, err) } } else { - return fmt.Errorf(optedOutOfRecoveringSoftDeletedBackupProtectedVMFmt(parsedVmId.ID(), vaultName)) + return errors.New(optedOutOfRecoveringSoftDeletedBackupProtectedVMFmt(parsedVmId.ID(), vaultName)) } } diff --git a/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource.go b/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource.go index 1427a171087f..ff5ebe6bebfc 100644 --- a/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource.go +++ b/internal/services/recoveryservices/site_recovery_replication_recovery_plan_resource.go @@ -434,7 +434,7 @@ func (r SiteRecoveryReplicationRecoveryPlanResource) Create() sdk.ResourceFunc { }, } - if model.A2ASettings != nil && len(model.A2ASettings) == 1 { + if len(model.A2ASettings) == 1 { parameters.Properties.ProviderSpecificInput = expandA2ASettings(model.A2ASettings[0]) } diff --git a/internal/services/resource/resource_group_resource.go b/internal/services/resource/resource_group_resource.go index 45636d735f9f..472b049b7502 100644 --- a/internal/services/resource/resource_group_resource.go +++ b/internal/services/resource/resource_group_resource.go @@ -4,6 +4,7 @@ package resource import ( + "errors" "fmt" "log" "sort" @@ -268,5 +269,5 @@ delete this using the Azure API directly (which will clear up any nested resourc More information on the 'features' block can be found in the documentation: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/guides/features-block `, name, strings.Join(formattedResourceUris, "\n")) - return fmt.Errorf(strings.ReplaceAll(message, "'", "`")) + return errors.New(strings.ReplaceAll(message, "'", "`")) } diff --git a/internal/services/search/search_service_data_source.go b/internal/services/search/search_service_data_source.go index 8111ac0e912d..7af7aeb8dd23 100644 --- a/internal/services/search/search_service_data_source.go +++ b/internal/services/search/search_service_data_source.go @@ -20,7 +20,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceSearchService() *pluginsdk.Resource { @@ -154,8 +153,8 @@ func dataSourceSearchServiceRead(d *pluginsdk.ResourceData, meta interface{}) er return fmt.Errorf("retrieving Admin Keys for %s: %+v", id, err) } if model := adminKeysResp.Model; model != nil { - primaryKey = utils.NormalizeNilableString(model.PrimaryKey) - secondaryKey = utils.NormalizeNilableString(model.SecondaryKey) + primaryKey = pointer.From(model.PrimaryKey) + secondaryKey = pointer.From(model.SecondaryKey) } d.Set("primary_key", primaryKey) d.Set("secondary_key", secondaryKey) diff --git a/internal/services/search/search_service_resource.go b/internal/services/search/search_service_resource.go index 37a6a261f3d3..f6535699ab91 100644 --- a/internal/services/search/search_service_resource.go +++ b/internal/services/search/search_service_resource.go @@ -24,7 +24,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func resourceSearchService() *pluginsdk.Resource { @@ -653,8 +652,8 @@ func flattenSearchQueryKeys(input *[]querykeys.QueryKey) []interface{} { if input != nil { for _, v := range *input { results = append(results, map[string]interface{}{ - "name": utils.NormalizeNilableString(v.Name), - "key": utils.NormalizeNilableString(v.Key), + "name": pointer.From(v.Name), + "key": pointer.From(v.Key), }) } } @@ -668,7 +667,7 @@ func expandSearchServiceIPRules(input []interface{}) *[]services.IPRule { for _, rule := range input { if rule != nil { output = append(output, services.IPRule{ - Value: utils.String(rule.(string)), + Value: pointer.To(rule.(string)), }) } } diff --git a/internal/services/securitycenter/azuresdkhacks/security_center_contact.go b/internal/services/securitycenter/azuresdkhacks/security_center_contact.go index 439de236a954..a23ccdbce8bb 100644 --- a/internal/services/securitycenter/azuresdkhacks/security_center_contact.go +++ b/internal/services/securitycenter/azuresdkhacks/security_center_contact.go @@ -27,7 +27,7 @@ func CreateSecurityCenterContact(ctx context.Context, client *security.ContactsC }}, }, }); err != nil { - return result, validation.NewError("security.ContactsClient", "Create", err.Error()) + return result, validation.NewError("security.ContactsClient", "Create", err.Error()) // nolint: govet } req, err := client.CreatePreparer(ctx, securityContactName, securityContact) diff --git a/internal/services/securitycenter/security_center_server_vulnerability_assessment_virtual_machine_resource.go b/internal/services/securitycenter/security_center_server_vulnerability_assessment_virtual_machine_resource.go index 4898d0236a9b..10aad7b15e34 100644 --- a/internal/services/securitycenter/security_center_server_vulnerability_assessment_virtual_machine_resource.go +++ b/internal/services/securitycenter/security_center_server_vulnerability_assessment_virtual_machine_resource.go @@ -74,7 +74,7 @@ func resourceServerVulnerabilityAssessmentVirtualMachineCreate(d *pluginsdk.Reso return tf.ImportAsExistsError("azurerm_security_center_server_vulnerability_assessment_virtual_machine", *vulnerabilityAssessment.ID) } - vulnerabilityAssessment, err = client.CreateOrUpdate(ctx, virtualMachineId.ResourceGroupName, computeProvider, vmType, virtualMachineId.VirtualMachineName) + _, err = client.CreateOrUpdate(ctx, virtualMachineId.ResourceGroupName, computeProvider, vmType, virtualMachineId.VirtualMachineName) if err != nil { return fmt.Errorf("create Server Vulnerability Assessment for %s: %+v", *virtualMachineId, err) } diff --git a/internal/services/sentinel/azuresdkhacks/securitymlanalyticssettings.go b/internal/services/sentinel/azuresdkhacks/securitymlanalyticssettings.go index bbf5dbcabd6d..adc14c642d3f 100644 --- a/internal/services/sentinel/azuresdkhacks/securitymlanalyticssettings.go +++ b/internal/services/sentinel/azuresdkhacks/securitymlanalyticssettings.go @@ -27,7 +27,7 @@ func (client SecurityMLAnalyticsSettingsClient) List(ctx context.Context, resour {TargetValue: workspaceName, Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "workspaceName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { - return result, validation.NewError("securityinsight.SecurityMLAnalyticsSettingsClient", "List", err.Error()) + return result, validation.NewError("securityinsight.SecurityMLAnalyticsSettingsClient", "List", err.Error()) // nolint: govet } result.fn = client.listNextResults diff --git a/internal/services/sentinel/azuresdkhacks/threatintelligenceindicator.go b/internal/services/sentinel/azuresdkhacks/threatintelligenceindicator.go index 3a89d4680c5c..4ff407db5d7c 100644 --- a/internal/services/sentinel/azuresdkhacks/threatintelligenceindicator.go +++ b/internal/services/sentinel/azuresdkhacks/threatintelligenceindicator.go @@ -29,7 +29,7 @@ func (client ThreatIntelligenceIndicatorClient) Get(ctx context.Context, resourc Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "workspaceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "workspaceName", Name: validation.Pattern, Rule: `^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("securityinsight.ThreatIntelligenceIndicatorClient", "Get", err.Error()) + return result, validation.NewError("securityinsight.ThreatIntelligenceIndicatorClient", "Get", err.Error()) // nolint: govet } req, err := client.GetPreparer(ctx, resourceGroupName, workspaceName, name) @@ -100,7 +100,7 @@ func (client ThreatIntelligenceIndicatorClient) CreateIndicator(ctx context.Cont Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "workspaceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "workspaceName", Name: validation.Pattern, Rule: `^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("securityinsight.ThreatIntelligenceIndicatorClient", "CreateIndicator", err.Error()) + return result, validation.NewError("securityinsight.ThreatIntelligenceIndicatorClient", "CreateIndicator", err.Error()) // nolint: govet } req, err := client.CreateIndicatorPreparer(ctx, resourceGroupName, workspaceName, threatIntelligenceProperties) @@ -173,7 +173,7 @@ func (client ThreatIntelligenceIndicatorClient) QueryIndicators(ctx context.Cont Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "workspaceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "workspaceName", Name: validation.Pattern, Rule: `^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("securityinsight.ThreatIntelligenceIndicatorClient", "QueryIndicators", err.Error()) + return result, validation.NewError("securityinsight.ThreatIntelligenceIndicatorClient", "QueryIndicators", err.Error()) // nolint: govet } result.fn = client.queryIndicatorsNextResults @@ -284,7 +284,7 @@ func (client ThreatIntelligenceIndicatorClient) Create(ctx context.Context, reso Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "workspaceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "workspaceName", Name: validation.Pattern, Rule: `^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("securityinsight.ThreatIntelligenceIndicatorClient", "Create", err.Error()) + return result, validation.NewError("securityinsight.ThreatIntelligenceIndicatorClient", "Create", err.Error()) // nolint: govet } req, err := client.CreatePreparer(ctx, resourceGroupName, workspaceName, name, threatIntelligenceProperties) diff --git a/internal/services/sentinel/sentinel_threat_intelligence_indicator_resource.go b/internal/services/sentinel/sentinel_threat_intelligence_indicator_resource.go index 73e10f7c44e7..aaad70081239 100644 --- a/internal/services/sentinel/sentinel_threat_intelligence_indicator_resource.go +++ b/internal/services/sentinel/sentinel_threat_intelligence_indicator_resource.go @@ -719,7 +719,7 @@ func (r ThreatIntelligenceIndicator) Read() sdk.ResourceFunc { state.DisplayName = *model.DisplayName } - if model.Extensions != nil && len(model.Extensions) > 0 { + if len(model.Extensions) > 0 { extensionsValue, err := pluginsdk.FlattenJsonToString(model.Extensions) if err != nil { return err diff --git a/internal/services/servicefabricmanaged/service_fabric_managed_cluster_resource.go b/internal/services/servicefabricmanaged/service_fabric_managed_cluster_resource.go index 9fecb69e237b..e29b2a365bdb 100644 --- a/internal/services/servicefabricmanaged/service_fabric_managed_cluster_resource.go +++ b/internal/services/servicefabricmanaged/service_fabric_managed_cluster_resource.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-sdk/resource-manager/servicefabricmanagedcluster/2021-05-01/managedcluster" @@ -558,7 +559,7 @@ func flattenClusterProperties(cluster *managedcluster.ManagedCluster) *ClusterRe return model } - model.Name = utils.NormalizeNilableString(cluster.Name) + model.Name = pointer.From(cluster.Name) model.Location = cluster.Location if sku := cluster.Sku; sku != nil { model.Sku = sku.Name @@ -587,9 +588,9 @@ func flattenClusterProperties(cluster *managedcluster.ManagedCluster) *ClusterRe adModels := make([]ADAuthentication, 0) adModel := ADAuthentication{} - adModel.ClientApp = utils.NormalizeNilableString(aad.ClientApplication) - adModel.ClusterApp = utils.NormalizeNilableString(aad.ClusterApplication) - adModel.TenantId = utils.NormalizeNilableString(aad.TenantId) + adModel.ClientApp = pointer.From(aad.ClientApplication) + adModel.ClusterApp = pointer.From(aad.ClusterApplication) + adModel.TenantId = pointer.From(aad.TenantId) adModels = append(adModels, adModel) model.Authentication[0].ADAuth = adModels @@ -604,8 +605,8 @@ func flattenClusterProperties(cluster *managedcluster.ManagedCluster) *ClusterRe } certs[idx] = ThumbprintAuth{ CertificateType: t, - CommonName: utils.NormalizeNilableString(client.CommonName), - Thumbprint: utils.NormalizeNilableString(client.Thumbprint), + CommonName: pointer.From(client.CommonName), + Thumbprint: pointer.From(client.Thumbprint), } } if len(model.Authentication) == 0 { @@ -628,8 +629,8 @@ func flattenClusterProperties(cluster *managedcluster.ManagedCluster) *ClusterRe model.CustomFabricSettings = cfs } - model.ClientConnectionPort = utils.NormaliseNilableInt64(properties.ClientConnectionPort) - model.HTTPGatewayPort = utils.NormaliseNilableInt64(properties.HTTPGatewayConnectionPort) + model.ClientConnectionPort = pointer.From(properties.ClientConnectionPort) + model.HTTPGatewayPort = pointer.From(properties.HTTPGatewayConnectionPort) if lbrules := properties.LoadBalancingRules; lbrules != nil { model.LBRules = make([]LBRule, len(*lbrules)) @@ -638,7 +639,7 @@ func flattenClusterProperties(cluster *managedcluster.ManagedCluster) *ClusterRe BackendPort: rule.BackendPort, FrontendPort: rule.FrontendPort, ProbeProtocol: rule.ProbeProtocol, - ProbeRequestPath: utils.NormalizeNilableString(rule.ProbeRequestPath), + ProbeRequestPath: pointer.From(rule.ProbeRequestPath), Protocol: rule.Protocol, } } @@ -666,20 +667,20 @@ func flattenClusterProperties(cluster *managedcluster.ManagedCluster) *ClusterRe func flattenNodetypeProperties(nt nodetype.NodeType) NodeType { props := nt.Properties if props == nil { - return NodeType{Name: utils.NormalizeNilableString(nt.Name)} + return NodeType{Name: pointer.From(nt.Name)} } out := NodeType{ DataDiskSize: nt.Properties.DataDiskSizeGB, - Name: utils.NormalizeNilableString(nt.Name), + Name: pointer.From(nt.Name), Primary: props.IsPrimary, - VmImageOffer: utils.NormalizeNilableString(props.VMImageOffer), - VmImagePublisher: utils.NormalizeNilableString(props.VMImagePublisher), - VmImageSku: utils.NormalizeNilableString(props.VMImageSku), - VmImageVersion: utils.NormalizeNilableString(props.VMImageVersion), + VmImageOffer: pointer.From(props.VMImageOffer), + VmImagePublisher: pointer.From(props.VMImagePublisher), + VmImageSku: pointer.From(props.VMImageSku), + VmImageVersion: pointer.From(props.VMImageVersion), VmInstanceCount: props.VMInstanceCount, - VmSize: utils.NormalizeNilableString(props.VMSize), - Id: utils.NormalizeNilableString(nt.Id), + VmSize: pointer.From(props.VMSize), + Id: pointer.From(nt.Id), } if appPorts := props.ApplicationPorts; appPorts != nil { @@ -729,7 +730,7 @@ func flattenNodetypeProperties(nt nodetype.NodeType) NodeType { } } secs[idx] = VmSecrets{ - SourceVault: utils.NormalizeNilableString(sec.SourceVault.Id), + SourceVault: pointer.From(sec.SourceVault.Id), Certificates: certs, } } diff --git a/internal/services/signalr/signalr_service_custom_certificate_resource.go b/internal/services/signalr/signalr_service_custom_certificate_resource.go index 8d12efb06d42..ad9eca1b0127 100644 --- a/internal/services/signalr/signalr_service_custom_certificate_resource.go +++ b/internal/services/signalr/signalr_service_custom_certificate_resource.go @@ -8,6 +8,7 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2023-02-01/signalr" @@ -190,7 +191,7 @@ func (r CustomCertSignalrServiceResource) Read() sdk.ResourceFunc { Name: id.CustomCertificateName, CustomCertId: certId, SignalRServiceId: signalrServiceId, - CertificateVersion: utils.NormalizeNilableString(resp.Model.Properties.KeyVaultSecretVersion), + CertificateVersion: pointer.From(resp.Model.Properties.KeyVaultSecretVersion), } return metadata.Encode(&state) diff --git a/internal/services/signalr/web_pubsub_custom_certificate_resource.go b/internal/services/signalr/web_pubsub_custom_certificate_resource.go index e5f808a02b58..ab99e0c447c9 100644 --- a/internal/services/signalr/web_pubsub_custom_certificate_resource.go +++ b/internal/services/signalr/web_pubsub_custom_certificate_resource.go @@ -8,6 +8,7 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-sdk/resource-manager/webpubsub/2023-02-01/webpubsub" @@ -185,7 +186,7 @@ func (r CustomCertWebPubsubResource) Read() sdk.ResourceFunc { Name: id.CustomCertificateName, CustomCertId: certId, WebPubsubId: webpubsub.NewWebPubSubID(id.SubscriptionId, id.ResourceGroupName, id.WebPubSubName).ID(), - CertificateVersion: utils.NormalizeNilableString(resp.Model.Properties.KeyVaultSecretVersion), + CertificateVersion: pointer.From(resp.Model.Properties.KeyVaultSecretVersion), } return metadata.Encode(&state) diff --git a/internal/services/storage/migration/table.go b/internal/services/storage/migration/table.go index fb6036aabaa0..cbe69d0b6348 100644 --- a/internal/services/storage/migration/table.go +++ b/internal/services/storage/migration/table.go @@ -68,7 +68,7 @@ func (TableV1ToV2) UpgradeFunc() pluginsdk.StateUpgraderFunc { } } -// the schema schema was used for both V0 and V1 +// the schema was used for both V0 and V1 func tableSchemaV0AndV1() map[string]*pluginsdk.Schema { return map[string]*pluginsdk.Schema{ "name": { diff --git a/internal/services/storage/storage_account_data_source.go b/internal/services/storage/storage_account_data_source.go index 8376b0c938d3..efac78a79dd1 100644 --- a/internal/services/storage/storage_account_data_source.go +++ b/internal/services/storage/storage_account_data_source.go @@ -675,18 +675,14 @@ func dataSourceStorageAccountRead(d *pluginsdk.ResourceData, meta interface{}) e secondaryEndpoints = model.Properties.SecondaryEndpoints } endpoints := flattenAccountEndpoints(primaryEndpoints, secondaryEndpoints, routingPreference) - if err := endpoints.set(d); err != nil { - return err - } + endpoints.set(d) storageAccountKeys := make([]storageaccounts.StorageAccountKey, 0) if keys.Model != nil && keys.Model.Keys != nil { storageAccountKeys = *keys.Model.Keys } keysAndConnectionStrings := flattenAccountAccessKeysAndConnectionStrings(id.StorageAccountName, *storageDomainSuffix, storageAccountKeys, endpoints) - if err := keysAndConnectionStrings.set(d); err != nil { - return err - } + keysAndConnectionStrings.set(d) return nil } diff --git a/internal/services/storage/storage_account_helpers_endpoints_credentials.go b/internal/services/storage/storage_account_helpers_endpoints_credentials.go index 3ce095080bdf..7b2798a9350e 100644 --- a/internal/services/storage/storage_account_helpers_endpoints_credentials.go +++ b/internal/services/storage/storage_account_helpers_endpoints_credentials.go @@ -84,7 +84,7 @@ type accountEndpoints struct { secondaryWebMicrosoftHostName string } -func (a accountEndpoints) set(d *pluginsdk.ResourceData) error { +func (a accountEndpoints) set(d *pluginsdk.ResourceData) { d.Set("primary_blob_endpoint", a.primaryBlobEndpoint) d.Set("primary_blob_host", a.primaryBlobHostName) d.Set("primary_blob_internet_endpoint", a.primaryBlobInternetEndpoint) @@ -154,8 +154,6 @@ func (a accountEndpoints) set(d *pluginsdk.ResourceData) error { d.Set("secondary_web_internet_host", a.secondaryWebInternetHostName) d.Set("secondary_web_microsoft_endpoint", a.secondaryWebMicrosoftEndpoint) d.Set("secondary_web_microsoft_host", a.secondaryWebMicrosoftHostName) - - return nil } func flattenAccountEndpoints(primaryEndpoints, secondaryEndpoints *storageaccounts.Endpoints, routingPreference *storageaccounts.RoutingPreference) accountEndpoints { @@ -239,15 +237,13 @@ type accountAccessKeysAndConnectionStrings struct { secondaryAccessKey string } -func (a accountAccessKeysAndConnectionStrings) set(d *pluginsdk.ResourceData) error { +func (a accountAccessKeysAndConnectionStrings) set(d *pluginsdk.ResourceData) { d.Set("primary_connection_string", a.primaryConnectionString) d.Set("secondary_connection_string", a.secondaryConnectionString) d.Set("primary_blob_connection_string", a.primaryBlobConnectionString) d.Set("secondary_blob_connection_string", a.secondaryBlobConnectionString) d.Set("primary_access_key", a.primaryAccessKey) d.Set("secondary_access_key", a.secondaryAccessKey) - - return nil } func flattenAccountAccessKeysAndConnectionStrings(accountName, domainSuffix string, keys []storageaccounts.StorageAccountKey, endpoints accountEndpoints) accountAccessKeysAndConnectionStrings { diff --git a/internal/services/storage/storage_account_resource.go b/internal/services/storage/storage_account_resource.go index 87dda6070658..9c9fe9637835 100644 --- a/internal/services/storage/storage_account_resource.go +++ b/internal/services/storage/storage_account_resource.go @@ -2197,18 +2197,14 @@ func resourceStorageAccountRead(d *pluginsdk.ResourceData, meta interface{}) err } endpoints := flattenAccountEndpoints(primaryEndpoints, secondaryEndpoints, routingPreference) - if err := endpoints.set(d); err != nil { - return err - } + endpoints.set(d) storageAccountKeys := make([]storageaccounts.StorageAccountKey, 0) if keys.Model != nil && keys.Model.Keys != nil { storageAccountKeys = *keys.Model.Keys } keysAndConnectionStrings := flattenAccountAccessKeysAndConnectionStrings(id.StorageAccountName, *storageDomainSuffix, storageAccountKeys, endpoints) - if err := keysAndConnectionStrings.set(d); err != nil { - return err - } + keysAndConnectionStrings.set(d) blobProperties := make([]interface{}, 0) if supportLevel.supportBlob { diff --git a/internal/services/storage/storage_blob_resource_test.go b/internal/services/storage/storage_blob_resource_test.go index 03daa9c46285..8bcbf129196b 100644 --- a/internal/services/storage/storage_blob_resource_test.go +++ b/internal/services/storage/storage_blob_resource_test.go @@ -144,7 +144,7 @@ func TestAccStorageBlob_blockEmptyAccessTier(t *testing.T) { func TestAccStorageBlob_blockFromInlineContent(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_storage_blob", "test") r := StorageBlobResource{} - content := "Wubba Lubba Dub Dub" + content := "Wubba Lubba Dub Dubs" data.ResourceTest(t, r, []acceptance.TestStep{ { @@ -331,7 +331,7 @@ func TestAccStorageBlob_contentTypePremium(t *testing.T) { func TestAccStorageBlob_encryptionScope(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_storage_blob", "test") r := StorageBlobResource{} - content := "Wubba Lubba Dub Dub" + content := "Wubba Lubba Dub Dubs" data.ResourceTest(t, r, []acceptance.TestStep{ { @@ -347,7 +347,7 @@ func TestAccStorageBlob_encryptionScope(t *testing.T) { func TestAccStorageBlob_encryptionScopeUpdate(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_storage_blob", "test") r := StorageBlobResource{} - content := "Wubba Lubba Dub Dub" + content := "Wubba Lubba Dub Dubs" data.ResourceTest(t, r, []acceptance.TestStep{ { diff --git a/internal/services/storage/storage_table_resource.go b/internal/services/storage/storage_table_resource.go index b2c75c8703b0..8a4780065225 100644 --- a/internal/services/storage/storage_table_resource.go +++ b/internal/services/storage/storage_table_resource.go @@ -183,7 +183,7 @@ func resourceStorageTableRead(d *pluginsdk.ResourceData, meta interface{}) error return fmt.Errorf("retrieving Storage Account %q for Table %q: %v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - log.Printf("Unable to determine Resource Group for Storage Storage Table %q (Account %s) - assuming removed & removing from state", id.TableName, id.AccountId.AccountName) + log.Printf("Unable to determine Resource Group for Storage Table %q (Account %s) - assuming removed & removing from state", id.TableName, id.AccountId.AccountName) d.SetId("") return nil } diff --git a/internal/services/storage/storage_table_resource_test.go b/internal/services/storage/storage_table_resource_test.go index bcf5c8a9d6ae..db5918a6172a 100644 --- a/internal/services/storage/storage_table_resource_test.go +++ b/internal/services/storage/storage_table_resource_test.go @@ -92,7 +92,7 @@ func (r StorageTableResource) Exists(ctx context.Context, client *clients.Client return nil, fmt.Errorf("retrieving Account %q for Table %q: %+v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - return nil, fmt.Errorf("unable to determine Resource Group for Storage Storage Table %q (Account %q)", id.TableName, id.AccountId.AccountName) + return nil, fmt.Errorf("unable to determine Resource Group for Storage Table %q (Account %q)", id.TableName, id.AccountId.AccountName) } tablesClient, err := client.Storage.TablesDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { @@ -112,7 +112,7 @@ func (r StorageTableResource) Destroy(ctx context.Context, client *clients.Clien return nil, fmt.Errorf("retrieving Account %q for Table %q: %+v", id.AccountId.AccountName, id.TableName, err) } if account == nil { - return nil, fmt.Errorf("unable to determine Resource Group for Storage Storage Table %q (Account %q)", id.TableName, id.AccountId.AccountName) + return nil, fmt.Errorf("unable to determine Resource Group for Storage Table %q (Account %q)", id.TableName, id.AccountId.AccountName) } tablesClient, err := client.Storage.TablesDataPlaneClient(ctx, *account, client.Storage.DataPlaneOperationSupportingAnyAuthMethod()) if err != nil { diff --git a/internal/services/storagecache/hpc_cache_access_policy_resource.go b/internal/services/storagecache/hpc_cache_access_policy_resource.go index ad79e6b21799..7b21dff19619 100644 --- a/internal/services/storagecache/hpc_cache_access_policy_resource.go +++ b/internal/services/storagecache/hpc_cache_access_policy_resource.go @@ -196,15 +196,12 @@ func resourceHPCCacheAccessPolicyRead(d *pluginsdk.ResourceData, meta interface{ } cacheId := caches.NewCacheID(id.SubscriptionId, id.ResourceGroup, id.CacheName) - clearId := func(msg string) error { - log.Printf("[DEBUG] %s - removing from state!", msg) - d.SetId("") - return nil - } resp, err := client.Get(ctx, cacheId) if err != nil { if response.WasNotFound(resp.HttpResponse) { - return clearId(fmt.Sprintf("The containing HPC Cache %q was not found", cacheId)) + log.Printf("[DEBUG] The containing HPC Cache %q was not found- removing from state!", cacheId) + d.SetId("") + return nil } return fmt.Errorf("retrieving %s: %+v", id, err) @@ -222,17 +219,23 @@ func resourceHPCCacheAccessPolicyRead(d *pluginsdk.ResourceData, meta interface{ setting := prop.SecuritySettings if setting == nil { - return clearId(fmt.Sprintf("The containing HPC Cache %q has nil SecuritySettings", cacheId)) + log.Printf("[DEBUG] The containing HPC Cache %q has nil SecuritySettings- removing from state!", cacheId) + d.SetId("") + return nil } policies := setting.AccessPolicies if policies == nil { - return clearId(fmt.Sprintf("The containing HPC Cache %q has nil AccessPolicies", cacheId)) + log.Printf("[DEBUG] The containing HPC Cache %q has nil AccessPolicies- removing from state!", cacheId) + d.SetId("") + return nil } p := CacheGetAccessPolicyByName(*policies, id.Name) if p == nil { - return clearId(fmt.Sprintf("The %q was not found", id)) + log.Printf("[DEBUG] The %q was not found- removing from state!", cacheId) + d.SetId("") + return nil } d.Set("name", id.Name) diff --git a/internal/services/subscription/subscription_resource.go b/internal/services/subscription/subscription_resource.go index 33c768d6a3f2..eb44a22061f1 100644 --- a/internal/services/subscription/subscription_resource.go +++ b/internal/services/subscription/subscription_resource.go @@ -128,7 +128,7 @@ func resourceSubscriptionCreate(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() - aliasName := "" + var aliasName string if aliasNameRaw, ok := d.GetOk("alias"); ok { aliasName = aliasNameRaw.(string) } else { @@ -163,11 +163,9 @@ func resourceSubscriptionCreate(d *pluginsdk.ResourceData, meta interface{}) err }, } - subscriptionId := "" - // Check if we're adding alias management for an existing subscription if subscriptionIdRaw, ok := d.GetOk("subscription_id"); ok { - subscriptionId = subscriptionIdRaw.(string) + subscriptionId := subscriptionIdRaw.(string) subscriptionResourceId := commonids.NewSubscriptionID(subscriptionId) locks.ByID(subscriptionId) diff --git a/internal/services/voiceservices/voice_services_communications_gateway_resource.go b/internal/services/voiceservices/voice_services_communications_gateway_resource.go index 8e1a9bc31295..28c4ae2889d5 100644 --- a/internal/services/voiceservices/voice_services_communications_gateway_resource.go +++ b/internal/services/voiceservices/voice_services_communications_gateway_resource.go @@ -421,7 +421,7 @@ func (r CommunicationsGatewayResource) Read() sdk.ResourceFunc { state.Connectivity = string(properties.Connectivity) codecsValue := "" - if properties.Codecs != nil && len(properties.Codecs) > 0 { + if len(properties.Codecs) > 0 { codecsValue = string(properties.Codecs[0]) } state.Codecs = codecsValue diff --git a/internal/services/web/app_service_environment_resource.go b/internal/services/web/app_service_environment_resource.go index 2f1be92a0a67..a02e9e71aa91 100644 --- a/internal/services/web/app_service_environment_resource.go +++ b/internal/services/web/app_service_environment_resource.go @@ -401,12 +401,10 @@ func flattenClusterSettings(input *[]web.NameValuePair) interface{} { settings := make([]map[string]interface{}, 0) for _, v := range *input { - name := "" if v.Name == nil { continue - } else { - name = *v.Name } + name := *v.Name value := "" if v.Value != nil { diff --git a/internal/services/web/app_service_managed_certificate_resource.go b/internal/services/web/app_service_managed_certificate_resource.go index 1b2af4df78f3..b58ab54fafda 100644 --- a/internal/services/web/app_service_managed_certificate_resource.go +++ b/internal/services/web/app_service_managed_certificate_resource.go @@ -113,11 +113,11 @@ func resourceAppServiceManagedCertificateCreateUpdate(d *pluginsdk.ResourceData, } name := customHostnameBindingId.Name - appServicePlanIDRaw := "" + if appService.SiteProperties == nil || appService.SiteProperties.ServerFarmID == nil { return fmt.Errorf("could not get App Service Plan ID for Custom Hostname Binding %q (resource group %q)", customHostnameBindingId.Name, customHostnameBindingId.ResourceGroup) } - appServicePlanIDRaw = *appService.SiteProperties.ServerFarmID + appServicePlanIDRaw := *appService.SiteProperties.ServerFarmID appServicePlanID, err := commonids.ParseAppServicePlanIDInsensitively(appServicePlanIDRaw) if err != nil { diff --git a/internal/tools/document-lint/schema/resource_schema_test.go b/internal/tools/document-lint/schema/resource_schema_test.go index 6b1df2f5fdeb..f21277a9e1e4 100644 --- a/internal/tools/document-lint/schema/resource_schema_test.go +++ b/internal/tools/document-lint/schema/resource_schema_test.go @@ -13,7 +13,7 @@ import ( func TestResourceFile(t *testing.T) { p := automation.SoftwareUpdateConfigurationResource{} file := schema.FileForResource(p.Read().Func) - t.Logf(file) + t.Log(file) // inspect schema r := schema.NewResourceByTyped(p) diff --git a/internal/tools/generator-services/main.go b/internal/tools/generator-services/main.go index cb8b11b43841..8de0fe2cc4a7 100644 --- a/internal/tools/generator-services/main.go +++ b/internal/tools/generator-services/main.go @@ -291,7 +291,6 @@ func (githubIssueLabelsGenerator) run(outputFileName string, _ map[string]struct v, ok := service.(sdk.TypedServiceRegistrationWithAGitHubLabel) // keep a record of resources/datasources that don't have labels so they can be used to check that prefixes generated later don't match resources from those services - label = "" if ok { label = v.AssociatedGitHubLabel() } diff --git a/utils/bool.go b/utils/bool.go deleted file mode 100644 index ab2eec6efbdb..000000000000 --- a/utils/bool.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package utils - -// NormaliseNilableBool takes a pointer to a bool and returns a zero value or -// the real value if present -// Deprecated: please use the `From` function in the `pointer` package -func NormaliseNilableBool(input *bool) bool { - if input == nil { - return false - } - - return *input -} diff --git a/utils/float.go b/utils/float.go deleted file mode 100644 index e37ff7015e2b..000000000000 --- a/utils/float.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package utils - -// NormalizeNilableFloat normalizes a nilable float64 into a float64 value -// Deprecated: please use the `From` function in the `pointer` package -func NormalizeNilableFloat(input *float64) float64 { - if input == nil { - return 0 - } - - return *input -} - -// NormalizeNilableFloat32 normalizes a nilable float32 into a float32 value -// Deprecated: please use the `From` function in the `pointer` package -func NormalizeNilableFloat32(input *float32) float32 { - if input == nil { - return 0 - } - - return *input -} diff --git a/utils/int.go b/utils/int.go deleted file mode 100644 index 6e656f1002ec..000000000000 --- a/utils/int.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package utils - -// NormaliseNilableInt takes a pointer to an int and returns a zero value or -// the real value if present -// Deprecated: please use the `From` function in the `pointer` package -func NormaliseNilableInt(input *int) int { - if input == nil { - return 0 - } - - return *input -} - -// NormaliseNilableInt32 takes a pointer to an int32 and returns a zero value or -// the real value if present -// Deprecated: please use the `From` function in the `pointer` package -func NormaliseNilableInt32(input *int32) int32 { - if input == nil { - return 0 - } - - return *input -} - -// NormaliseNilableInt64 takes a pointer to an int64 and returns a zero value or -// the real value if present -// Deprecated: please use the `From` function in the `pointer` package -func NormaliseNilableInt64(input *int64) int64 { - if input == nil { - return 0 - } - - return *input -} diff --git a/utils/string.go b/utils/string.go deleted file mode 100644 index 2e40b0fa07b5..000000000000 --- a/utils/string.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package utils - -// NormalizeNilableString normalizes a nilable string into a string -// that is, if it's nil returns an empty string else the value -// Deprecated: please use the `From` function in the `pointer` package -func NormalizeNilableString(input *string) string { - if input == nil { - return "" - } - - return *input -}