github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/controllers/indexer/list.go (about)

     1  package indexer
     2  
     3  import (
     4  	"context"
     5  
     6  	"k8s.io/apimachinery/pkg/api/meta"
     7  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
     8  	"k8s.io/apimachinery/pkg/runtime"
     9  	"k8s.io/apimachinery/pkg/types"
    10  	ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
    11  )
    12  
    13  // List all the objects owned by the given object type.
    14  //
    15  // This allows us to use owner-based indexing in tests without
    16  // incurring the overhead of caching.
    17  //
    18  // See discussion here:
    19  // https://github.com/tilt-dev/tilt/issues/4719
    20  func ListOwnedBy(ctx context.Context, client ctrlclient.Client, list ctrlclient.ObjectList, nn types.NamespacedName, ownerType metav1.TypeMeta) error {
    21  	err := client.List(ctx, list, ctrlclient.InNamespace(nn.Namespace))
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	items, err := meta.ExtractList(list)
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	result := []runtime.Object{}
    32  	for _, item := range items {
    33  		clientObj, ok := item.(ctrlclient.Object)
    34  		if !ok {
    35  			continue
    36  		}
    37  		owner := metav1.GetControllerOf(clientObj)
    38  		if owner == nil {
    39  			continue
    40  		}
    41  		if owner.APIVersion != ownerType.APIVersion || owner.Kind != ownerType.Kind {
    42  			continue
    43  		}
    44  		if owner.Name != nn.Name {
    45  			continue
    46  		}
    47  		result = append(result, item)
    48  	}
    49  	return meta.SetList(list, result)
    50  }