validate.go 912 B

1234567891011121314151617181920212223242526272829303132
  1. package allocation
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/opencost/opencost/core/pkg/autocomplete"
  6. )
  7. // ValidateField normalizes and validates an allocation autocomplete field name.
  8. func ValidateField(field string) (string, error) {
  9. if field == "" {
  10. return "", fmt.Errorf("field is required")
  11. }
  12. f := strings.ToLower(field)
  13. switch f {
  14. case "account", "cluster", "namespace", "node", "controllerkind", "controllername", "pod", "container", "label", "namespacelabel":
  15. return f, nil
  16. }
  17. if strings.HasPrefix(f, "label:") {
  18. _, labelKey, _ := strings.Cut(field, ":")
  19. return autocomplete.FormatLabelValueField(autocomplete.LabelPrefix, labelKey), nil
  20. }
  21. if strings.HasPrefix(f, "namespacelabel:") {
  22. _, labelKey, _ := strings.Cut(field, ":")
  23. return autocomplete.FormatLabelValueField(autocomplete.NamespaceLabelPrefix, labelKey), nil
  24. }
  25. return "", fmt.Errorf("unrecognized field: %s", field)
  26. }