Skip to content

Commit

Permalink
refactor: introduce 'hasOwner' function to reduce cognitive load (#218)
Browse files Browse the repository at this point in the history
* refactor: introduce hasOwner function

- simplifies resource exclusion logic

* chore: fix typo
  • Loading branch information
thapabishwa authored Sep 11, 2023
1 parent fe986af commit 9e6a159
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions pkg/trivyk8s/trivyk8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (c *client) Resources(resources string) TrivyK8S {
return c
}

func isNamspaced(namespace string, allNamespace bool) bool {
func isNamespaced(namespace string, allNamespace bool) bool {
if len(namespace) != 0 || (len(namespace) == 0 && allNamespace) {
return true
}
Expand All @@ -105,7 +105,7 @@ func isNamspaced(namespace string, allNamespace bool) bool {
func (c *client) ListArtifacts(ctx context.Context) ([]*artifacts.Artifact, error) {
artifactList := make([]*artifacts.Artifact, 0)

namespaced := isNamspaced(c.namespace, c.allNamespaces)
namespaced := isNamespaced(c.namespace, c.allNamespaces)
grvs, err := c.cluster.GetGVRs(namespaced, c.resources)
if err != nil {
return nil, err
Expand Down Expand Up @@ -138,21 +138,9 @@ func (c *client) ListArtifacts(ctx context.Context) ([]*artifacts.Artifact, erro
if c.ignoreResource(resource) {
continue
}
// assume that the owner is a built-in workload by default
ownerIsBuiltIn := true
if len(resource.GetOwnerReferences()) > 0 {
// if the resource has an owner, we check if it is a built-in workload
// this ensures that we don't skip resources that are owned by custom resources
for _, owner := range resource.GetOwnerReferences() {
if !k8s.IsBuiltInWorkload(&owner) {
ownerIsBuiltIn = false
break
}
}
}

// if excludeOwned is enabled and workload is a built-in workload and if ownerExists, we skip it
if c.excludeOwned && ownerIsBuiltIn && len(resource.GetOwnerReferences()) > 0 {
// if excludeOwned is enabled and the resource is owned by built-in workload, then we skip it
if c.excludeOwned && c.hasOwner(resource) {
continue
}

Expand Down Expand Up @@ -313,6 +301,10 @@ func (c *client) ignoreResource(resource unstructured.Unstructured) bool {
return false
}

return c.hasOwner(resource)
}

func (c *client) hasOwner(resource unstructured.Unstructured) bool {
for _, owner := range resource.GetOwnerReferences() {
if k8s.IsBuiltInWorkload(&owner) {
return true
Expand Down

0 comments on commit 9e6a159

Please sign in to comment.