github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_trim.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  	"strings"
    11  
    12  	"github.com/GuanceCloud/cliutils/pipeline/ptinput"
    13  	"github.com/GuanceCloud/platypus/pkg/ast"
    14  	"github.com/GuanceCloud/platypus/pkg/engine/runtime"
    15  	"github.com/GuanceCloud/platypus/pkg/errchain"
    16  )
    17  
    18  func TrimChecking(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    19  	if len(funcExpr.Param) < 1 || len(funcExpr.Param) > 2 {
    20  		return runtime.NewRunError(ctx, fmt.Sprintf(
    21  			"func `%s' expected 1 or 2 args", funcExpr.Name), funcExpr.NamePos)
    22  	}
    23  	if _, err := getKeyName(funcExpr.Param[0]); err != nil {
    24  		return runtime.NewRunError(ctx, err.Error(), funcExpr.Param[0].StartPos())
    25  	}
    26  	if len(funcExpr.Param) == 2 {
    27  		switch funcExpr.Param[1].NodeType { //nolint:exhaustive
    28  		case ast.TypeStringLiteral:
    29  		default:
    30  			return runtime.NewRunError(ctx, fmt.Sprintf("param type expect StringLiteral, got `%s'",
    31  				funcExpr.Param[1].NodeType), funcExpr.Param[1].StartPos())
    32  		}
    33  	}
    34  	return nil
    35  }
    36  
    37  func Trim(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    38  	key, err := getKeyName(funcExpr.Param[0])
    39  	if err != nil {
    40  		return runtime.NewRunError(ctx, err.Error(), funcExpr.Param[0].StartPos())
    41  	}
    42  
    43  	cont, err := ctx.GetKeyConv2Str(key)
    44  	if err != nil {
    45  		l.Debug(err)
    46  		return nil
    47  	}
    48  
    49  	var cutset string
    50  	if len(funcExpr.Param) == 2 {
    51  		switch funcExpr.Param[1].NodeType { //nolint:exhaustive
    52  		case ast.TypeStringLiteral:
    53  			cutset = funcExpr.Param[1].StringLiteral().Val
    54  		default:
    55  			return runtime.NewRunError(ctx, fmt.Sprintf("param type expect StringLiteral, got `%s'",
    56  				funcExpr.Param[1].NodeType), funcExpr.Param[1].StartPos())
    57  		}
    58  	}
    59  
    60  	var val string
    61  	if cutset == "" {
    62  		val = strings.TrimSpace(cont)
    63  	} else {
    64  		val = strings.Trim(cont, cutset)
    65  	}
    66  
    67  	_ = addKey2PtWithVal(ctx.InData(), key, val, ast.String, ptinput.KindPtDefault)
    68  
    69  	return nil
    70  }