cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/parser/utils/conditions.go
64lines · modecode
| 1 | package utils |
| 2 | |
| 3 | import ( |
| 4 | promParser "github.com/prometheus/prometheus/promql/parser" |
| 5 | ) |
| 6 | |
| 7 | func RemoveConditions(source string) promParser.Node { |
| 8 | node, _ := promParser.ParseExpr(source) |
| 9 | switch n := node.(type) { |
| 10 | case *promParser.AggregateExpr: |
| 11 | n.Expr = RemoveConditions(n.Expr.String()).(promParser.Expr) |
| 12 | return n |
| 13 | case *promParser.BinaryExpr: |
| 14 | lhs := RemoveConditions(n.LHS.String()) |
| 15 | rhs := RemoveConditions(n.RHS.String()) |
| 16 | _, ln := lhs.(*promParser.NumberLiteral) |
| 17 | if v, ok := lhs.(*promParser.VectorSelector); ok && v.Name == "" { |
| 18 | ln = true |
| 19 | } |
| 20 | _, rn := rhs.(*promParser.NumberLiteral) |
| 21 | if v, ok := rhs.(*promParser.VectorSelector); ok && v.Name == "" { |
| 22 | rn = true |
| 23 | } |
| 24 | if ln && rn { |
| 25 | return &promParser.VectorSelector{} |
| 26 | } |
| 27 | if ln { |
| 28 | return rhs |
| 29 | } |
| 30 | if rn { |
| 31 | return lhs |
| 32 | } |
| 33 | n.LHS = lhs.(promParser.Expr) |
| 34 | n.RHS = rhs.(promParser.Expr) |
| 35 | return n |
| 36 | case *promParser.Call: |
| 37 | ret := promParser.Expressions{} |
| 38 | for _, e := range n.Args { |
| 39 | ret = append(ret, RemoveConditions(e.String()).(promParser.Expr)) |
| 40 | } |
| 41 | n.Args = ret |
| 42 | return n |
| 43 | case *promParser.SubqueryExpr: |
| 44 | n.Expr = RemoveConditions(n.Expr.String()).(promParser.Expr) |
| 45 | return n |
| 46 | case *promParser.ParenExpr: |
| 47 | n.Expr = RemoveConditions(n.Expr.String()).(promParser.Expr) |
| 48 | switch n.Expr.(type) { |
| 49 | case *promParser.NumberLiteral, *promParser.StringLiteral, *promParser.VectorSelector, *promParser.MatrixSelector: |
| 50 | return n.Expr |
| 51 | } |
| 52 | return n |
| 53 | case *promParser.UnaryExpr: |
| 54 | n.Expr = RemoveConditions(n.Expr.String()).(promParser.Expr) |
| 55 | return n |
| 56 | case *promParser.StepInvariantExpr: |
| 57 | n.Expr = RemoveConditions(n.Expr.String()).(promParser.Expr) |
| 58 | return n |
| 59 | case *promParser.NumberLiteral, *promParser.StringLiteral, *promParser.VectorSelector, *promParser.MatrixSelector: |
| 60 | return node |
| 61 | default: |
| 62 | return node |
| 63 | } |
| 64 | } |
| 65 | |