github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_duration_precision.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package funcs 7 8 import ( 9 "fmt" 10 "reflect" 11 "strings" 12 13 "github.com/GuanceCloud/cliutils/pipeline/ptinput" 14 "github.com/GuanceCloud/platypus/pkg/ast" 15 "github.com/GuanceCloud/platypus/pkg/engine/runtime" 16 "github.com/GuanceCloud/platypus/pkg/errchain" 17 "github.com/spf13/cast" 18 ) 19 20 func DurationPrecisionChecking(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError { 21 return nil 22 } 23 24 func DurationPrecision(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError { 25 if len(funcExpr.Param) != 3 { 26 return runtime.NewRunError(ctx, fmt.Sprintf( 27 "func `%s' expected 3 args", funcExpr.Name), funcExpr.NamePos) 28 } 29 30 key, err := getKeyName(funcExpr.Param[0]) 31 if err != nil { 32 return runtime.NewRunError(ctx, err.Error(), funcExpr.Param[0].StartPos()) 33 } 34 varb, err := ctx.GetKey(key) 35 if err != nil { 36 return runtime.NewRunError(ctx, err.Error(), funcExpr.Param[0].StartPos()) 37 } 38 var tValue int64 39 if varb.DType != ast.Int { 40 return runtime.NewRunError(ctx, "param value type expect int", 41 funcExpr.Param[0].StartPos()) 42 } else { 43 tValue = cast.ToInt64(varb.Value) 44 } 45 46 oldNew := [2]int{} 47 for i := 1; i < 3; i += 1 { 48 var err error 49 switch funcExpr.Param[i].NodeType { //nolint:exhaustive 50 case ast.TypeStringLiteral: 51 if oldNew[i-1], err = precision(funcExpr.Param[i].StringLiteral().Val); err != nil { 52 l.Debug(err) 53 return nil 54 } 55 default: 56 return runtime.NewRunError(ctx, fmt.Sprintf( 57 "param key expect Identifier or AttrExpr, got `%s'", 58 reflect.TypeOf(funcExpr.Param[i]).String()), funcExpr.Param[i].StartPos()) 59 } 60 } 61 62 delta := oldNew[1] - oldNew[0] 63 deltaAbs := delta 64 if delta < 0 { 65 deltaAbs = -delta 66 } 67 for i := 0; i < deltaAbs; i++ { 68 if delta < 0 { 69 tValue /= 10 70 } else if delta > 0 { 71 tValue *= 10 72 } 73 } 74 _ = addKey2PtWithVal(ctx.InData(), key, tValue, ast.Int, 75 ptinput.KindPtDefault) 76 return nil 77 } 78 79 func precision(p string) (int, error) { 80 switch strings.ToLower(p) { 81 case "s": 82 return 0, nil 83 case "ms": 84 return 3, nil 85 case "us": 86 return 6, nil 87 case "ns": 88 return 9, nil 89 default: 90 return 0, fmt.Errorf("unknow precision: %s", p) 91 } 92 }