github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/namespacedname/namespacedname.go (about)

     1  package namespacedname
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/pkg/errors"
     8  
     9  	"k8s.io/apimachinery/pkg/types"
    10  )
    11  
    12  const defaultNamespace = "default"
    13  
    14  // Parse is responsible to convert string into NamespacedName structure,
    15  // comprising the resource name and mandatory namespace
    16  func Parse(value string) (types.NamespacedName, error) {
    17  	if value == "" {
    18  		return types.NamespacedName{}, errors.New("the value cannot be empty")
    19  	}
    20  
    21  	parts := strings.Split(value, string(types.Separator))
    22  
    23  	if len(parts) > 2 {
    24  		return types.NamespacedName{}, errors.New(fmt.Sprintf("the given value: %s is not in the expected format - <namespace>/<name>", value))
    25  	}
    26  
    27  	// If a single value is provided we assume that's resource name and the namespace is default
    28  	if len(parts) == 1 && parts[0] != "" {
    29  		return types.NamespacedName{
    30  			Name:      parts[0],
    31  			Namespace: defaultNamespace,
    32  		}, nil
    33  	}
    34  
    35  	if len(parts) == 2 && parts[1] == "" {
    36  		return types.NamespacedName{}, errors.New("resource name should not be empty")
    37  	}
    38  
    39  	namespace := parts[0]
    40  	if namespace == "" {
    41  		namespace = defaultNamespace
    42  	}
    43  
    44  	return types.NamespacedName{
    45  		Namespace: namespace,
    46  		Name:      parts[1],
    47  	}, nil
    48  }