github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_append.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 doAppendChecking(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    17  	if len(funcExpr.Param) != 2 {
    18  		return runtime.NewRunError(ctx, "func %s expects 2 args", funcExpr.NamePos)
    19  	}
    20  	if funcExpr.Param[0].NodeType != ast.TypeIdentifier {
    21  		return runtime.NewRunError(ctx, fmt.Sprintf(
    22  			"the first param expects Identifier, got %s", funcExpr.Param[0].NodeType),
    23  			funcExpr.Param[0].StartPos())
    24  	}
    25  	switch funcExpr.Param[1].NodeType { //nolint:exhaustive
    26  	case ast.TypeIdentifier, ast.TypeAttrExpr, ast.TypeBoolLiteral,
    27  		ast.TypeIntegerLiteral, ast.TypeFloatLiteral, ast.TypeStringLiteral:
    28  	default:
    29  		return runtime.NewRunError(ctx, fmt.Sprintf(
    30  			"the second param expects Identifier, AttrExpr, BoolLiteral, NumberLiteral or StringLiteral, got %s",
    31  			funcExpr.Param[1].NodeType), funcExpr.Param[1].StartPos(),
    32  		)
    33  	}
    34  	return nil
    35  }
    36  
    37  func AppendChecking(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    38  	return doAppendChecking(ctx, funcExpr)
    39  }
    40  
    41  func Append(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    42  	if errR := doAppendChecking(ctx, funcExpr); errR != nil {
    43  		return errR
    44  	}
    45  
    46  	elem, _, errR := runtime.RunStmt(ctx, funcExpr.Param[1])
    47  	if errR != nil {
    48  		return errR
    49  	}
    50  
    51  	key, err := getKeyName(funcExpr.Param[0])
    52  	if err != nil {
    53  		return runtime.NewRunError(ctx, err.Error(), funcExpr.Param[0].StartPos())
    54  	}
    55  	val, err := ctx.GetKey(key)
    56  	if err != nil {
    57  		l.Debugf("key `%v` does not exist, ignored", key)
    58  		return nil //nolint:nilerr
    59  	}
    60  	if val.DType != ast.List {
    61  		l.Debugf("cannot append to a %s", val.DType.String())
    62  		return nil
    63  	}
    64  	var arr []any
    65  	switch v := val.Value.(type) {
    66  	case []any:
    67  		arr = v
    68  	default:
    69  		l.Debugf("expect []any, got %T", v)
    70  		return nil
    71  	}
    72  	arr = append(arr, elem)
    73  	ctx.Regs.ReturnAppend(arr, ast.List)
    74  	return nil
    75  }