matcher.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package customcost
  2. import (
  3. "fmt"
  4. "github.com/opencost/opencost/core/pkg/filter/ast"
  5. "github.com/opencost/opencost/core/pkg/filter/matcher"
  6. "github.com/opencost/opencost/core/pkg/filter/transform"
  7. )
  8. func NewCustomCostMatchCompiler() *matcher.MatchCompiler[*CustomCost] {
  9. passes := []transform.CompilerPass{
  10. transform.UnallocatedReplacementPass(),
  11. }
  12. return matcher.NewMatchCompiler(
  13. customCostFieldMap,
  14. customCostSliceFieldMap,
  15. customCostMapFieldMap,
  16. passes...,
  17. )
  18. }
  19. // Maps fields from a custom cost to a string value based on an identifier
  20. func customCostFieldMap(cc *CustomCost, identifier ast.Identifier) (string, error) {
  21. if cc == nil {
  22. return "", fmt.Errorf("cannot map to nil custom cost")
  23. }
  24. if identifier.Field == nil {
  25. return "", fmt.Errorf("cannot map field from identifier with nil field")
  26. }
  27. switch CustomCostProperty(identifier.Field.Name) {
  28. case CustomCostZoneProp:
  29. return cc.Zone, nil
  30. case CustomCostAccountNameProp:
  31. return cc.AccountName, nil
  32. case CustomCostChargeCategoryProp:
  33. return cc.ChargeCategory, nil
  34. case CustomCostDescriptionProp:
  35. return cc.Description, nil
  36. case CustomCostResourceNameProp:
  37. return cc.ResourceName, nil
  38. case CustomCostResourceTypeProp:
  39. return cc.ResourceType, nil
  40. case CustomCostProviderIdProp:
  41. return cc.ProviderId, nil
  42. case CustomCostUsageUnitProp:
  43. return cc.UsageUnit, nil
  44. case CustomCostDomainProp:
  45. return cc.Domain, nil
  46. case CustomCostCostSourceProp:
  47. return cc.CostSource, nil
  48. }
  49. return "", fmt.Errorf("failed to find string identifier on CustomCost: %s", identifier.Field.Name)
  50. }
  51. // Maps slice fields from an asset to a []string value based on an identifier
  52. func customCostSliceFieldMap(cc *CustomCost, identifier ast.Identifier) ([]string, error) {
  53. return nil, fmt.Errorf("custom costs have no slice fields")
  54. }
  55. // Maps map fields from a custom cost to a map[string]string value based on an identifier
  56. func customCostMapFieldMap(cc *CustomCost, identifier ast.Identifier) (map[string]string, error) {
  57. return nil, fmt.Errorf("custom costs have no map fields")
  58. }