github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_len.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/platypus/pkg/ast"
    12  	"github.com/GuanceCloud/platypus/pkg/engine/runtime"
    13  	"github.com/GuanceCloud/platypus/pkg/errchain"
    14  )
    15  
    16  func LenChecking(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    17  	if len(funcExpr.Param) != 1 {
    18  		return runtime.NewRunError(ctx, fmt.Sprintf(
    19  			"func %s expected 1", funcExpr.Name), funcExpr.NamePos)
    20  	}
    21  	return nil
    22  }
    23  
    24  func Len(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    25  	val, dtype, err := runtime.RunStmt(ctx, funcExpr.Param[0])
    26  	if err != nil {
    27  		return err
    28  	}
    29  
    30  	switch dtype { //nolint:exhaustive
    31  	case ast.Map:
    32  		ctx.Regs.ReturnAppend(int64(len(val.(map[string]any))), ast.Int)
    33  	case ast.List:
    34  		ctx.Regs.ReturnAppend(int64(len(val.([]any))), ast.Int)
    35  	case ast.String:
    36  		ctx.Regs.ReturnAppend(int64(len(val.(string))), ast.Int)
    37  	default:
    38  		ctx.Regs.ReturnAppend(int64(0), ast.Int)
    39  	}
    40  	return nil
    41  }