Copilot commented on code in PR #181:
URL: 
https://github.com/apache/cloudstack-terraform-provider/pull/181#discussion_r2315183923


##########
cloudstack/data_source_cloudstack_role.go:
##########
@@ -0,0 +1,159 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package cloudstack
+
+import (
+       "encoding/json"
+       "fmt"
+       "log"
+       "regexp"
+       "strings"
+
+       "github.com/apache/cloudstack-go/v2/cloudstack"
+       "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
+)
+
+func dataSourceCloudstackRole() *schema.Resource {
+       return &schema.Resource{
+               Read: dataSourceCloudstackRoleRead,
+               Schema: map[string]*schema.Schema{
+                       "filter": dataSourceFiltersSchema(),
+
+                       //Computed values
+                       "id": {
+                               Type:     schema.TypeString,
+                               Computed: true,
+                       },
+
+                       "name": {
+                               Type:     schema.TypeString,
+                               Computed: true,
+                       },
+
+                       "type": {
+                               Type:     schema.TypeString,
+                               Computed: true,
+                       },
+
+                       "description": {
+                               Type:     schema.TypeString,
+                               Computed: true,
+                       },
+
+                       "is_public": {
+                               Type:     schema.TypeBool,
+                               Computed: true,
+                       },
+               },
+       }
+}
+
+func dataSourceCloudstackRoleRead(d *schema.ResourceData, meta interface{}) 
error {
+       cs := meta.(*cloudstack.CloudStackClient)
+       p := cs.Role.NewListRolesParams()
+
+       csRoles, err := cs.Role.ListRoles(p)
+       if err != nil {
+               return fmt.Errorf("failed to list roles: %s", err)
+       }
+
+       filters := d.Get("filter")
+       var role *cloudstack.Role
+
+       for _, r := range csRoles.Roles {
+               match, err := applyRoleFilters(r, filters.(*schema.Set))
+               if err != nil {
+                       return err
+               }
+               if match {
+                       role = r
+                       break
+               }
+       }
+
+       if role == nil {
+               return fmt.Errorf("no role is matching with the specified 
criteria")
+       }
+       log.Printf("[DEBUG] Selected role: %s\n", role.Name)
+
+       return roleDescriptionAttributes(d, role)
+}
+
+func roleDescriptionAttributes(d *schema.ResourceData, role *cloudstack.Role) 
error {
+       d.SetId(role.Id)
+       d.Set("name", role.Name)
+       d.Set("type", role.Type)
+       d.Set("description", role.Description)
+       d.Set("is_public", role.Ispublic)
+
+       return nil
+}
+
+func latestRole(roles []*cloudstack.Role) (*cloudstack.Role, error) {
+       // Since the Role struct doesn't have a Created field,
+       // we'll just return the first role in the list
+       if len(roles) > 0 {
+               return roles[0], nil
+       }
+       return nil, fmt.Errorf("no roles found")
+}
+

Review Comment:
   The `latestRole` function is defined but never used in the code. Consider 
removing this unused function to reduce code complexity.
   ```suggestion
   
   ```



##########
cloudstack/resource_cloudstack_role_test.go:
##########
@@ -0,0 +1,125 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package cloudstack
+
+import (
+       "fmt"
+       "testing"
+
+       "github.com/apache/cloudstack-go/v2/cloudstack"
+       "github.com/hashicorp/terraform-plugin-testing/helper/resource"
+       "github.com/hashicorp/terraform-plugin-testing/terraform"
+)
+
+func TestAccCloudStackRole_basic(t *testing.T) {
+       var role cloudstack.Role
+
+       resource.Test(t, resource.TestCase{
+               PreCheck:     func() { testAccPreCheck(t) },
+               Providers:    testAccProviders,
+               CheckDestroy: testAccCheckCloudStackRoleDestroy,
+               Steps: []resource.TestStep{
+                       {
+                               Config: testAccCloudStackRole_basic,
+                               Check: resource.ComposeTestCheckFunc(
+                                       
testAccCheckCloudStackRoleExists("cloudstack_role.foo", &role),
+                                       resource.TestCheckResourceAttr(
+                                               "cloudstack_role.foo", "name", 
"terraform-role"),
+                                       resource.TestCheckResourceAttr(
+                                               "cloudstack_role.foo", 
"description", "terraform test role"),
+                                       resource.TestCheckResourceAttr(
+                                               "cloudstack_role.foo", 
"is_public", "true"),
+                               ),
+                       },
+               },
+       })
+}
+
+func testAccCheckCloudStackRoleExists(n string, role *cloudstack.Role) 
resource.TestCheckFunc {
+       return func(s *terraform.State) error {
+               rs, ok := s.RootModule().Resources[n]
+               if !ok {
+                       return fmt.Errorf("Not found: %s", n)
+               }
+
+               if rs.Primary.ID == "" {
+                       return fmt.Errorf("No Role ID is set")
+               }
+
+               cs := testAccProvider.Meta().(*cloudstack.CloudStackClient)
+               r, _, err := cs.Role.GetRoleByID(rs.Primary.ID)
+
+               if err != nil {
+                       return err
+               }
+
+               if r.Id != rs.Primary.ID {
+                       return fmt.Errorf("Role not found")
+               }
+
+               *role = *r
+
+               return nil
+       }
+}
+
+func testAccCheckCloudStackRoleDestroy(s *terraform.State) error {
+       cs := testAccProvider.Meta().(*cloudstack.CloudStackClient)
+
+       for _, rs := range s.RootModule().Resources {
+               if rs.Type != "cloudstack_role" {
+                       continue
+               }
+
+               if rs.Primary.ID == "" {
+                       return fmt.Errorf("No Role ID is set")
+               }
+
+               // Use a defer/recover to catch the panic that might occur when 
trying to access l.Roles[0]
+               var err error
+               func() {
+                       defer func() {
+                               if r := recover(); r != nil {
+                                       // If a panic occurs, it means the role 
doesn't exist, which is what we want
+                                       err = nil
+                               }
+                       }()
+                       r, _, e := cs.Role.GetRoleByID(rs.Primary.ID)
+                       if e == nil && r != nil && r.Id == rs.Primary.ID {
+                               err = fmt.Errorf("Role %s still exists", 
rs.Primary.ID)
+                       }
+               }()
+
+               if err != nil {

Review Comment:
   Using panic/recover for normal error handling is an anti-pattern in Go. 
Instead of catching panics, handle the error returned by `GetRoleByID` 
directly. If the role doesn't exist, the API should return an appropriate error 
that can be checked.
   ```suggestion
                r, _, err := cs.Role.GetRoleByID(rs.Primary.ID)
                if err == nil && r != nil && r.Id == rs.Primary.ID {
                        return fmt.Errorf("Role %s still exists", rs.Primary.ID)
                }
                if err != nil && err.Error() != "Role not found" {
                        // If the error is something other than "Role not 
found", return it
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to