validate.go 971 B

123456789101112131415161718192021222324252627282930313233
  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. "department", "environment", "owner", "product", "team":
  16. return f, nil
  17. }
  18. if strings.HasPrefix(f, "label:") {
  19. _, labelKey, _ := strings.Cut(field, ":")
  20. return autocomplete.FormatLabelValueField(autocomplete.LabelPrefix, labelKey), nil
  21. }
  22. if strings.HasPrefix(f, "namespacelabel:") {
  23. _, labelKey, _ := strings.Cut(field, ":")
  24. return autocomplete.FormatLabelValueField(autocomplete.NamespaceLabelPrefix, labelKey), nil
  25. }
  26. return "", fmt.Errorf("unrecognized field: %s", field)
  27. }