ReadObjectTree reads all objects owned by the root object which is type of 'T' with key in 'req'.
(ctx context.Context, reader client.Reader, req ctrl.Request, ml client.MatchingLabels, kinds ...client.ObjectList)
| 38 | |
| 39 | // ReadObjectTree reads all objects owned by the root object which is type of 'T' with key in 'req'. |
| 40 | func ReadObjectTree[T client.Object](ctx context.Context, reader client.Reader, req ctrl.Request, ml client.MatchingLabels, kinds ...client.ObjectList) (*ObjectTree, error) { |
| 41 | tree := NewObjectTree() |
| 42 | |
| 43 | // read root object |
| 44 | var obj T |
| 45 | t := reflect.TypeOf(obj) |
| 46 | if t.Kind() == reflect.Ptr { |
| 47 | t = t.Elem() |
| 48 | } |
| 49 | rootObj := reflect.New(t).Interface() |
| 50 | root, _ := rootObj.(T) |
| 51 | if err := reader.Get(ctx, req.NamespacedName, root); err != nil { |
| 52 | if apierrors.IsNotFound(err) { |
| 53 | return tree, nil |
| 54 | } |
| 55 | return nil, err |
| 56 | } |
| 57 | tree.SetRoot(root) |
| 58 | |
| 59 | // init placement |
| 60 | ctx = intoContext(ctx, placement(root)) |
| 61 | |
| 62 | // read child objects |
| 63 | inNS := client.InNamespace(req.Namespace) |
| 64 | for _, list := range kinds { |
| 65 | if err := reader.List(ctx, list, inNS, ml, inDataContext4C()); err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | // reflect get list.Items |
| 69 | items := reflect.ValueOf(list).Elem().FieldByName("Items") |
| 70 | l := items.Len() |
| 71 | for i := 0; i < l; i++ { |
| 72 | // get the underlying object |
| 73 | object := items.Index(i).Addr().Interface().(client.Object) |
| 74 | if len(object.GetOwnerReferences()) > 0 && !model.IsOwnerOf(root, object) { |
| 75 | continue |
| 76 | } |
| 77 | if err := tree.Add(object); err != nil { |
| 78 | return nil, err |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | return tree, nil |
| 84 | } |
| 85 | |
| 86 | func placement(obj client.Object) string { |
| 87 | if obj == nil || obj.GetAnnotations() == nil { |
no test coverage detected
searching dependent graphs…