github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_match.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 "regexp" 11 12 "github.com/GuanceCloud/platypus/pkg/ast" 13 "github.com/GuanceCloud/platypus/pkg/engine/runtime" 14 "github.com/GuanceCloud/platypus/pkg/errchain" 15 ) 16 17 func MatchChecking(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError { 18 if len(funcExpr.Param) != 2 { 19 return runtime.NewRunError(ctx, fmt.Sprintf( 20 "func %s expects 2 args", funcExpr.Name), funcExpr.NamePos) 21 } 22 23 param0 := funcExpr.Param[0] 24 if param0.NodeType != ast.TypeStringLiteral { 25 return runtime.NewRunError(ctx, fmt.Sprintf( 26 "expect StringLiteral, got %s", 27 param0.NodeType), param0.StartPos()) 28 } 29 30 // 预先编译正则表达式 31 re, err := regexp.Compile(param0.StringLiteral().Val) 32 if err != nil { 33 return runtime.NewRunError(ctx, fmt.Sprintf( 34 "func match: regexp compile failed: %s", err.Error()), param0.StartPos()) 35 } 36 funcExpr.Re = re 37 38 param1 := funcExpr.Param[1] 39 if !isPlVarbOrFunc(param1) && param1.NodeType != ast.TypeStringLiteral { 40 return runtime.NewRunError(ctx, fmt.Sprintf("expect StringLiteral, Identifier or AttrExpr, got %s", 41 param1.NodeType), param1.StartPos()) 42 } 43 44 return nil 45 } 46 47 func Match(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError { 48 if len(funcExpr.Param) != 2 { 49 err := fmt.Errorf("func %s expects 2 args", funcExpr.Name) 50 l.Debug(err) 51 ctx.Regs.ReturnAppend(false, ast.Bool) 52 return nil 53 } 54 55 if funcExpr.Re == nil { 56 ctx.Regs.ReturnAppend(false, ast.Bool) 57 return nil 58 } 59 60 cnt, err := getStr(ctx, funcExpr.Param[1]) 61 if err != nil { 62 l.Debug(err) 63 ctx.Regs.ReturnAppend(false, ast.Bool) 64 return nil 65 } 66 67 isMatch := funcExpr.Re.MatchString(cnt) 68 69 ctx.Regs.ReturnAppend(isMatch, ast.Bool) 70 71 return nil 72 }