github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_cast.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  
    11  	"github.com/GuanceCloud/cliutils/pipeline/ptinput"
    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 CastChecking(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    18  	if len(funcExpr.Param) != 2 {
    19  		return runtime.NewRunError(ctx, fmt.Sprintf(
    20  			"func `%s' expected 2 args", funcExpr.Name), funcExpr.NamePos)
    21  	}
    22  	if _, err := getKeyName(funcExpr.Param[0]); err != nil {
    23  		return runtime.NewRunError(ctx, err.Error(), funcExpr.Param[1].StartPos())
    24  	}
    25  
    26  	switch funcExpr.Param[1].NodeType { //nolint:exhaustive
    27  	case ast.TypeStringLiteral:
    28  		switch funcExpr.Param[1].StringLiteral().Val {
    29  		case "bool", "int", "float", "str", "string":
    30  		default:
    31  			return runtime.NewRunError(ctx, fmt.Sprintf("unsupported data type: %s",
    32  				funcExpr.Param[1].StringLiteral().Val), funcExpr.Param[1].StartPos())
    33  		}
    34  	default:
    35  		return runtime.NewRunError(ctx, fmt.Sprintf("param type expect StringLiteral, got `%s'",
    36  			funcExpr.Param[1].NodeType), funcExpr.Param[1].StartPos())
    37  	}
    38  	return nil
    39  }
    40  
    41  func Cast(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    42  	if len(funcExpr.Param) != 2 {
    43  		return runtime.NewRunError(ctx, fmt.Sprintf(
    44  			"func `%s' expected 2 args", funcExpr.Name), funcExpr.NamePos)
    45  	}
    46  
    47  	key, err := getKeyName(funcExpr.Param[0])
    48  	if err != nil {
    49  		return runtime.NewRunError(ctx, err.Error(), funcExpr.Param[0].StartPos())
    50  	}
    51  
    52  	var castType string
    53  
    54  	switch funcExpr.Param[1].NodeType { //nolint:exhaustive
    55  	case ast.TypeStringLiteral:
    56  		castType = funcExpr.Param[1].StringLiteral().Val
    57  	default:
    58  		return runtime.NewRunError(ctx, fmt.Sprintf("param type expect StringLiteral, got `%s'",
    59  			funcExpr.Param[1].NodeType), funcExpr.Param[1].StartPos())
    60  	}
    61  
    62  	v, err := ctx.GetKey(key)
    63  	if err != nil {
    64  		l.Debug(err)
    65  		return nil
    66  	}
    67  
    68  	val, dtype := doCast(v.Value, castType)
    69  	_ = addKey2PtWithVal(ctx.InData(), key, val, dtype, ptinput.KindPtDefault)
    70  	return nil
    71  }