Skip to content

Commit

Permalink
use SlicePtrToSlice and NonEmptySliceToPtrSlice
Browse files Browse the repository at this point in the history
  • Loading branch information
lantoli committed Jan 12, 2024
1 parent 1ba0568 commit eae0000
Show file tree
Hide file tree
Showing 40 changed files with 179 additions and 162 deletions.
14 changes: 14 additions & 0 deletions internal/common/conversion/type_conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,17 @@ func IsStringPresent(strPtr *string) bool {
func MongoDBRegionToAWSRegion(region string) string {
return strings.ReplaceAll(strings.ToLower(region), "_", "-")
}

func SlicePtrToSlice[T any](v *[]T) []T {
if v == nil {
return nil
}
return *v
}

func NonEmptySliceToPtrSlice[T any](v []T) *[]T {
if len(v) == 0 {
return nil
}
return &v
}
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ func outputAlertConfigurationResourceHcl(label string, alert *admin.GroupAlertsC
resource.SetAttributeValue("enabled", cty.BoolVal(*alert.Enabled))
}

for _, matcher := range alert.Matchers {
for _, matcher := range conversion.SlicePtrToSlice(alert.Matchers) {
appendBlockWithCtyValues(resource, "matcher", []string{}, convertMatcherToCtyValues(matcher))
}

Expand All @@ -331,8 +331,9 @@ func outputAlertConfigurationResourceHcl(label string, alert *admin.GroupAlertsC
appendBlockWithCtyValues(resource, "threshold_config", []string{}, convertThresholdToCtyValues(alert.Threshold))
}

for i := 0; i < len(alert.Notifications); i++ {
appendBlockWithCtyValues(resource, "notification", []string{}, convertNotificationToCtyValues(&alert.Notifications[i]))
notifications := conversion.SlicePtrToSlice(alert.Notifications)
for i := 0; i < len(notifications); i++ {
appendBlockWithCtyValues(resource, "notification", []string{}, convertNotificationToCtyValues(&notifications[i]))
}

return string(f.Bytes())
Expand Down Expand Up @@ -438,16 +439,14 @@ func convertNotificationToCtyValues(notification *admin.AlertsNotificationRootFo
values["sms_enabled"] = cty.BoolVal(*notification.SmsEnabled)
}

if len(notification.Roles) > 0 {
roles := make([]cty.Value, 0)

for _, r := range notification.Roles {
if roles := conversion.SlicePtrToSlice(notification.Roles); len(roles) > 0 {
roleList := make([]cty.Value, 0)
for _, r := range roles {
if r != "" {
roles = append(roles, cty.StringVal(r))
roleList = append(roleList, cty.StringVal(r))
}
}

values["roles"] = cty.TupleVal(roles)
values["roles"] = cty.TupleVal(roleList)
}

return values
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func (d *AlertConfigurationsDS) Read(ctx context.Context, req datasource.ReadReq
alertConfigurationsConfig.ID = types.StringValue(conversion.EncodeStateID(map[string]string{
"project_id": projectID,
}))
alertConfigurationsConfig.Results = NewTFAlertConfigurationDSModelList(alerts.Results, projectID, alertConfigurationsConfig.OutputType)
alertConfigurationsConfig.Results = NewTFAlertConfigurationDSModelList(conversion.SlicePtrToSlice(alerts.Results), projectID, alertConfigurationsConfig.OutputType)
if *params.IncludeCount {
alertConfigurationsConfig.TotalCount = types.Int64Value(int64(*alerts.TotalCount))
}
Expand Down
14 changes: 7 additions & 7 deletions internal/service/alertconfiguration/model_alert_configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func NewNotificationList(tfNotificationSlice []TfNotificationModel) ([]admin.Ale
Username: n.Username.ValueStringPointer(),
VictorOpsApiKey: n.VictorOpsAPIKey.ValueStringPointer(),
VictorOpsRoutingKey: n.VictorOpsRoutingKey.ValueStringPointer(),
Roles: n.Roles,
Roles: conversion.NonEmptySliceToPtrSlice(n.Roles),
MicrosoftTeamsWebhookUrl: n.MicrosoftTeamsWebhookURL.ValueStringPointer(),
WebhookSecret: n.WebhookSecret.ValueStringPointer(),
WebhookUrl: n.WebhookURL.ValueStringPointer(),
Expand Down Expand Up @@ -108,8 +108,8 @@ func NewTFAlertConfigurationModel(apiRespConfig *admin.GroupAlertsConfig, currSt
Enabled: types.BoolPointerValue(apiRespConfig.Enabled),
MetricThresholdConfig: NewTFMetricThresholdConfigModel(apiRespConfig.MetricThreshold, currState.MetricThresholdConfig),
ThresholdConfig: NewTFThresholdConfigModel(apiRespConfig.Threshold, currState.ThresholdConfig),
Notification: NewTFNotificationModelList(apiRespConfig.Notifications, currState.Notification),
Matcher: NewTFMatcherModelList(apiRespConfig.Matchers, currState.Matcher),
Notification: NewTFNotificationModelList(conversion.SlicePtrToSlice(apiRespConfig.Notifications), currState.Notification),
Matcher: NewTFMatcherModelList(conversion.SlicePtrToSlice(apiRespConfig.Matchers), currState.Matcher),
}
}

Expand All @@ -121,7 +121,7 @@ func NewTFNotificationModelList(n []admin.AlertsNotificationRootForGroup, currSt
value := n[i]
notifications[i] = TfNotificationModel{
TeamName: conversion.StringPtrNullIfEmpty(value.TeamName),
Roles: value.Roles,
Roles: conversion.SlicePtrToSlice(value.Roles),
ChannelName: conversion.StringPtrNullIfEmpty(value.ChannelName),
DatadogRegion: conversion.StringPtrNullIfEmpty(value.DatadogRegion),
DelayMin: types.Int64PointerValue(conversion.IntPtrToInt64Ptr(value.DelayMin)),
Expand All @@ -145,7 +145,7 @@ func NewTFNotificationModelList(n []admin.AlertsNotificationRootForGroup, currSt
currState := currStateNotifications[i]
newState := TfNotificationModel{
TeamName: conversion.StringPtrNullIfEmpty(value.TeamName),
Roles: value.Roles,
Roles: conversion.SlicePtrToSlice(value.Roles),
// sentive attributes do not use value returned from API
APIToken: conversion.StringNullIfEmpty(currState.APIToken.ValueString()),
DatadogAPIKey: conversion.StringNullIfEmpty(currState.DatadogAPIKey.ValueString()),
Expand Down Expand Up @@ -303,8 +303,8 @@ func NewTfAlertConfigurationDSModel(apiRespConfig *admin.GroupAlertsConfig, proj
Enabled: types.BoolPointerValue(apiRespConfig.Enabled),
MetricThresholdConfig: NewTFMetricThresholdConfigModel(apiRespConfig.MetricThreshold, []TfMetricThresholdConfigModel{}),
ThresholdConfig: NewTFThresholdConfigModel(apiRespConfig.Threshold, []TfThresholdConfigModel{}),
Notification: NewTFNotificationModelList(apiRespConfig.Notifications, []TfNotificationModel{}),
Matcher: NewTFMatcherModelList(apiRespConfig.Matchers, []TfMatcherModel{}),
Notification: NewTFNotificationModelList(conversion.SlicePtrToSlice(apiRespConfig.Notifications), []TfNotificationModel{}),
Matcher: NewTFMatcherModelList(conversion.SlicePtrToSlice(apiRespConfig.Matchers), []TfMatcherModel{}),
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestNotificationSDKToTFModel(t *testing.T) {
SmsEnabled: admin.PtrBool(disabled),
EmailEnabled: admin.PtrBool(enabled),
ChannelName: admin.PtrString("#channel"),
Roles: roles,
Roles: conversion.NonEmptySliceToPtrSlice(roles),
ApiToken: admin.PtrString("newApiToken"),
},
},
Expand Down Expand Up @@ -290,7 +290,7 @@ func TestNotificationTFModelToSDK(t *testing.T) {
DelayMin: admin.PtrInt(delayMin),
SmsEnabled: admin.PtrBool(disabled),
EmailEnabled: admin.PtrBool(enabled),
Roles: roles,
Roles: conversion.NonEmptySliceToPtrSlice(roles),
},
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ func (r *alertConfigurationRS) Create(ctx context.Context, req resource.CreateRe
apiReq := &admin.GroupAlertsConfig{
EventTypeName: alertConfigPlan.EventType.ValueStringPointer(),
Enabled: alertConfigPlan.Enabled.ValueBoolPointer(),
Matchers: NewMatcherList(alertConfigPlan.Matcher),
Matchers: conversion.NonEmptySliceToPtrSlice(NewMatcherList(alertConfigPlan.Matcher)),
MetricThreshold: NewMetricThreshold(alertConfigPlan.MetricThresholdConfig),
Threshold: NewThreshold(alertConfigPlan.ThresholdConfig),
}
Expand All @@ -390,7 +390,7 @@ func (r *alertConfigurationRS) Create(ctx context.Context, req resource.CreateRe
resp.Diagnostics.AddError(errorCreateAlertConf, err.Error())
return
}
apiReq.Notifications = notifications
apiReq.Notifications = conversion.NonEmptySliceToPtrSlice(notifications)

apiResp, _, err := connV2.AlertConfigurationsApi.CreateAlertConfiguration(ctx, projectID, apiReq).Execute()
if err != nil {
Expand Down Expand Up @@ -482,7 +482,7 @@ func (r *alertConfigurationRS) Update(ctx context.Context, req resource.UpdateRe
}

if !reflect.DeepEqual(alertConfigPlan.Matcher, alertConfigState.Matcher) {
apiReq.Matchers = NewMatcherList(alertConfigPlan.Matcher)
apiReq.Matchers = conversion.NonEmptySliceToPtrSlice(NewMatcherList(alertConfigPlan.Matcher))
}

// Always refresh structure to handle service keys being obfuscated coming back from read API call
Expand All @@ -491,7 +491,7 @@ func (r *alertConfigurationRS) Update(ctx context.Context, req resource.UpdateRe
resp.Diagnostics.AddError(errorUpdateAlertConf, err.Error())
return
}
apiReq.Notifications = notifications
apiReq.Notifications = conversion.NonEmptySliceToPtrSlice(notifications)

var updatedAlertConfigResp *admin.GroupAlertsConfig

Expand Down
6 changes: 3 additions & 3 deletions internal/service/atlasuser/data_source_atlas_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,9 @@ func newTFAtlasUserDSModel(user *admin.CloudAppUser) tfAtlasUserDSModel {
LastAuth: types.StringPointerValue(conversion.TimePtrToStringPtr(user.LastAuth)),
LastName: types.StringValue(user.LastName),
MobileNumber: types.StringValue(user.MobileNumber),
TeamIDs: user.TeamIds,
Links: newTFLinksList(user.Links),
Roles: newTFRolesList(user.Roles),
TeamIDs: conversion.SlicePtrToSlice(user.TeamIds),
Links: newTFLinksList(conversion.SlicePtrToSlice(user.Links)),
Roles: newTFRolesList(conversion.SlicePtrToSlice(user.Roles)),
}
}

Expand Down
4 changes: 2 additions & 2 deletions internal/service/atlasuser/data_source_atlas_user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ func dataSourceChecksForUser(dataSourceName, attrPrefix string, user *admin.Clou
resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%smobile_number", attrPrefix), user.MobileNumber),
resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%scountry", attrPrefix), user.Country),
resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%screated_at", attrPrefix), *conversion.TimePtrToStringPtr(user.CreatedAt)),
resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%steam_ids.#", attrPrefix), fmt.Sprintf("%d", len(user.TeamIds))),
resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%slinks.#", attrPrefix), fmt.Sprintf("%d", len(user.Links))),
resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%steam_ids.#", attrPrefix), fmt.Sprintf("%d", len(*user.TeamIds))),
resource.TestCheckResourceAttr(dataSourceName, fmt.Sprintf("%slinks.#", attrPrefix), fmt.Sprintf("%d", len(*user.Links))),
// for assertion of roles the values of `user.Roles` must not be used as it has the risk of flaky executions. CLOUDP-220377
resource.TestCheckResourceAttrWith(dataSourceName, fmt.Sprintf("%sroles.#", attrPrefix), acc.IntGreatThan(0)),
resource.TestCheckResourceAttrSet(dataSourceName, fmt.Sprintf("%sroles.0.role_name", attrPrefix)),
Expand Down
6 changes: 3 additions & 3 deletions internal/service/atlasuser/data_source_atlas_users.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func (d *atlasUsersDS) Read(ctx context.Context, req datasource.ReadRequest, res
resp.Diagnostics.AddError("error when getting users from Atlas", fmt.Sprintf(errorUsersRead, "project", projectID, err.Error()))
return
}
users = apiResp.Results
users = conversion.SlicePtrToSlice(apiResp.Results)
totalCount = *apiResp.TotalCount
case !atlasUsersConfig.TeamID.IsNull() && !atlasUsersConfig.OrgID.IsNull():
teamID := atlasUsersConfig.TeamID.ValueString()
Expand All @@ -205,7 +205,7 @@ func (d *atlasUsersDS) Read(ctx context.Context, req datasource.ReadRequest, res
resp.Diagnostics.AddError("error when getting users from Atlas", fmt.Sprintf(errorUsersRead, "team", teamID, err.Error()))
return
}
users = apiResp.Results
users = conversion.SlicePtrToSlice(apiResp.Results)
totalCount = *apiResp.TotalCount
default: // only org_id is defined
orgID := atlasUsersConfig.OrgID.ValueString()
Expand All @@ -218,7 +218,7 @@ func (d *atlasUsersDS) Read(ctx context.Context, req datasource.ReadRequest, res
resp.Diagnostics.AddError("error when getting users from Atlas", fmt.Sprintf(errorUsersRead, "org", orgID, err.Error()))
return
}
users = apiResp.Results
users = conversion.SlicePtrToSlice(apiResp.Results)
totalCount = *apiResp.TotalCount
}

Expand Down
4 changes: 2 additions & 2 deletions internal/service/atlasuser/data_source_atlas_users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,8 @@ func dataSourceChecksForUsers(dataSourceName, orgID string, users *admin.Paginat
resource.TestCheckResourceAttr(dataSourceName, "org_id", orgID),
resource.TestCheckResourceAttr(dataSourceName, "total_count", fmt.Sprintf("%d", totalCountValue)),
}
for i := range users.Results {
checks = append(checks, dataSourceChecksForUser(dataSourceName, fmt.Sprintf("results.%d.", i), &users.Results[i])...)
for i := range *users.Results {
checks = append(checks, dataSourceChecksForUser(dataSourceName, fmt.Sprintf("results.%d.", i), &(*users.Results)[i])...)
}

return checks
Expand Down
18 changes: 9 additions & 9 deletions internal/service/databaseuser/model_database_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,24 @@ func NewMongoDBDatabaseUser(ctx context.Context, dbUserModel *TfDatabaseUserMode
OidcAuthType: dbUserModel.OIDCAuthType.ValueStringPointer(),
LdapAuthType: dbUserModel.LDAPAuthType.ValueStringPointer(),
DatabaseName: dbUserModel.AuthDatabaseName.ValueString(),
Roles: NewMongoDBAtlasRoles(rolesModel),
Labels: NewMongoDBAtlasLabels(labelsModel),
Scopes: NewMongoDBAtlasScopes(scopesModel),
Roles: conversion.NonEmptySliceToPtrSlice(NewMongoDBAtlasRoles(rolesModel)),
Labels: conversion.NonEmptySliceToPtrSlice(NewMongoDBAtlasLabels(labelsModel)),
Scopes: conversion.NonEmptySliceToPtrSlice(NewMongoDBAtlasScopes(scopesModel)),
}, nil
}

func NewTfDatabaseUserModel(ctx context.Context, model *TfDatabaseUserModel, dbUser *admin.CloudDatabaseUser) (*TfDatabaseUserModel, diag.Diagnostics) {
rolesSet, diagnostic := types.SetValueFrom(ctx, RoleObjectType, NewTFRolesModel(dbUser.Roles))
rolesSet, diagnostic := types.SetValueFrom(ctx, RoleObjectType, NewTFRolesModel(conversion.SlicePtrToSlice(dbUser.Roles)))
if diagnostic.HasError() {
return nil, diagnostic
}

labelsSet, diagnostic := types.SetValueFrom(ctx, LabelObjectType, NewTFLabelsModel(dbUser.Labels))
labelsSet, diagnostic := types.SetValueFrom(ctx, LabelObjectType, NewTFLabelsModel(conversion.SlicePtrToSlice(dbUser.Labels)))
if diagnostic.HasError() {
return nil, diagnostic
}

scopesSet, diagnostic := types.SetValueFrom(ctx, ScopeObjectType, NewTFScopesModel(dbUser.Scopes))
scopesSet, diagnostic := types.SetValueFrom(ctx, ScopeObjectType, NewTFScopesModel(conversion.SlicePtrToSlice(dbUser.Scopes)))
if diagnostic.HasError() {
return nil, diagnostic
}
Expand Down Expand Up @@ -102,9 +102,9 @@ func NewTFDatabaseDSUserModel(ctx context.Context, dbUser *admin.CloudDatabaseUs
OIDCAuthType: types.StringValue(dbUser.GetOidcAuthType()),
LDAPAuthType: types.StringValue(dbUser.GetLdapAuthType()),
AWSIAMType: types.StringValue(dbUser.GetAwsIAMType()),
Roles: NewTFRolesModel(dbUser.Roles),
Labels: NewTFLabelsModel(dbUser.Labels),
Scopes: NewTFScopesModel(dbUser.Scopes),
Roles: NewTFRolesModel(conversion.SlicePtrToSlice(dbUser.Roles)),
Labels: NewTFLabelsModel(conversion.SlicePtrToSlice(dbUser.Labels)),
Scopes: NewTFScopesModel(conversion.SlicePtrToSlice(dbUser.Scopes)),
}

return databaseUserModel, nil
Expand Down
6 changes: 3 additions & 3 deletions internal/service/databaseuser/model_database_user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ var (
OidcAuthType: &oidCAuthType,
LdapAuthType: &ldapAuthType,
AwsIAMType: &awsIAMType,
Roles: []admin.DatabaseUserRole{sdkRole},
Labels: []admin.ComponentLabel{sdkLabel},
Scopes: []admin.UserScope{sdkScope},
Roles: &[]admin.DatabaseUserRole{sdkRole},
Labels: &[]admin.ComponentLabel{sdkLabel},
Scopes: &[]admin.UserScope{sdkScope},
}
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,13 +347,13 @@ func dataSourceMongoDBAtlasFederatedDatabaseInstanceRead(ctx context.Context, d
return diag.FromErr(fmt.Errorf(errorFederatedDatabaseInstanceSetting, "data_process_region", name, err))
}

if storageDatabaseField := flattenDataFederationDatabase(dataFederationInstance.Storage.Databases); storageDatabaseField != nil {
if storageDatabaseField := flattenDataFederationDatabase(conversion.SlicePtrToSlice(dataFederationInstance.Storage.Databases)); storageDatabaseField != nil {
if err := d.Set("storage_databases", storageDatabaseField); err != nil {
return diag.FromErr(fmt.Errorf(errorFederatedDatabaseInstanceSetting, "storage_databases", name, err))
}
}

if err := d.Set("storage_stores", flattenDataFederationStores(dataFederationInstance.Storage.Stores)); err != nil {
if err := d.Set("storage_stores", flattenDataFederationStores(conversion.SlicePtrToSlice(dataFederationInstance.Storage.Stores))); err != nil {
return diag.FromErr(fmt.Errorf(errorFederatedDatabaseInstanceSetting, "storage_stores", name, err))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/id"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
)

Expand Down Expand Up @@ -146,8 +147,8 @@ func flattenFederatedDatabaseInstances(d *schema.ResourceData, projectID string,
"hostnames": federatedDatabaseInstances[i].GetHostnames(),
"cloud_provider_config": flattenCloudProviderConfig(d, federatedDatabaseInstances[i].CloudProviderConfig),
"data_process_region": flattenDataProcessRegion(federatedDatabaseInstances[i].DataProcessRegion),
"storage_databases": flattenDataFederationDatabase(federatedDatabaseInstances[i].Storage.Databases),
"storage_stores": flattenDataFederationStores(federatedDatabaseInstances[i].Storage.Stores),
"storage_databases": flattenDataFederationDatabase(conversion.SlicePtrToSlice(federatedDatabaseInstances[i].Storage.Databases)),
"storage_stores": flattenDataFederationStores(conversion.SlicePtrToSlice(federatedDatabaseInstances[i].Storage.Stores)),
}
}
}
Expand Down
Loading

0 comments on commit eae0000

Please sign in to comment.