Skip to content

Commit

Permalink
Refactor depends-on code
Browse files Browse the repository at this point in the history
- Move from pkg/object to pkg/object/dependson
- Add DependencySet type to abstract some complexity
- Add Marshal/Unmarshal funcs for ObjMetadata and DependencySet
- Refactor primary API to ReadAnnotation and WriteAnnotation
- Move Write/Marshal behavior from testutil into dependson pkg
- Make constants private to encourage using functions as primary API
  • Loading branch information
karlkfi committed Sep 13, 2021
1 parent 2941a62 commit 3255372
Show file tree
Hide file tree
Showing 9 changed files with 717 additions and 327 deletions.
99 changes: 0 additions & 99 deletions pkg/object/annotations.go

This file was deleted.

199 changes: 0 additions & 199 deletions pkg/object/annotations_test.go

This file was deleted.

74 changes: 74 additions & 0 deletions pkg/object/dependson/annotation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright 2021 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
//

package dependson

import (
"errors"
"fmt"

"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/klog/v2"
)

const (
Annotation = "config.kubernetes.io/depends-on"
)

// HasAnnotation returns true if the config.kubernetes.io/depends-on annotation
// is present, false if not.
func HasAnnotation(u *unstructured.Unstructured) bool {
if u == nil {
return false
}
_, found := u.GetAnnotations()[Annotation]
return found
}

// ReadAnnotation reads the depends-on annotation and parses the the set of
// object references.
func ReadAnnotation(u *unstructured.Unstructured) (DependencySet, error) {
depSet := DependencySet{}
if u == nil {
return depSet, nil
}
depSetStr, found := u.GetAnnotations()[Annotation]
if !found {
return depSet, nil
}
klog.V(5).Infof("depends-on annotation found for %s/%s: %q",
u.GetNamespace(), u.GetName(), depSetStr)

depSet, err := UnmarshalDependencySet(depSetStr)
if err != nil {
return depSet, fmt.Errorf("failed to parse dependency set: %w", err)
}
return depSet, nil
}

// WriteAnnotation updates the supplied unstructured object to add the
// depends-on annotation. The value is a string of objmetas delimited by commas.
// Each objmeta is formatted as "${group}/${kind}/${name}" if cluster-scoped or
// "${group}/namespaces/${namespace}/${kind}/${name}" if namespace-scoped.
func WriteAnnotation(obj *unstructured.Unstructured, depSet DependencySet) error {
if obj == nil {
return errors.New("object is nil")
}
if depSet.Equal(DependencySet{}) {
return errors.New("dependency set is empty")
}

depSetStr, err := MarshalDependencySet(depSet)
if err != nil {
return fmt.Errorf("failed to format dependency set: %w", err)
}

a := obj.GetAnnotations()
if a == nil {
a = map[string]string{}
}
a[Annotation] = depSetStr
obj.SetAnnotations(a)
return nil
}
Loading

0 comments on commit 3255372

Please sign in to comment.