github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_hash.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  	"crypto/md5"
    10  	"crypto/sha1"
    11  	"crypto/sha256"
    12  	"crypto/sha512"
    13  	_ "embed"
    14  	"encoding/hex"
    15  	"unsafe"
    16  
    17  	"github.com/GuanceCloud/platypus/pkg/ast"
    18  	"github.com/GuanceCloud/platypus/pkg/engine/runtime"
    19  	"github.com/GuanceCloud/platypus/pkg/errchain"
    20  )
    21  
    22  // embed docs.
    23  var (
    24  	//go:embed md/hash.md
    25  	docHash string
    26  
    27  	//go:embed md/hash.en.md
    28  	docHashEN string
    29  
    30  	_ = "fn hash(text: str, method: str) -> str"
    31  
    32  	FnHash = NewFunc(
    33  		"hash",
    34  		[]*Param{
    35  			{
    36  				Name: "text",
    37  				Type: []ast.DType{ast.String},
    38  			},
    39  			{
    40  				Name: "method",
    41  				Type: []ast.DType{ast.String},
    42  			},
    43  		},
    44  		[]ast.DType{ast.String},
    45  		[2]*PLDoc{
    46  			{
    47  				Language: langTagZhCN, Doc: docHash,
    48  				FnCategory: map[string][]string{
    49  					langTagZhCN: {cStringOp}},
    50  			},
    51  			{
    52  				Language: langTagEnUS, Doc: docHashEN,
    53  				FnCategory: map[string][]string{
    54  					langTagEnUS: {eStringOp},
    55  				},
    56  			},
    57  		},
    58  		hashFn,
    59  	)
    60  )
    61  
    62  func hashFn(ctx *runtime.Task, funcExpr *ast.CallExpr, vals ...any) *errchain.PlError {
    63  	text := vals[0].(string)
    64  	txt := *(*[]byte)(unsafe.Pointer(&text))
    65  	// todo: go1.20+
    66  	// textSlice := unsafe.Slice(unsafe.StringData(text), len(text))
    67  	method := vals[1].(string)
    68  
    69  	var sum string
    70  	switch method {
    71  	case "md5":
    72  		b := md5.Sum(txt)
    73  		sum = hex.EncodeToString(b[:])
    74  	case "sha1":
    75  		b := sha1.Sum(txt)
    76  		sum = hex.EncodeToString(b[:])
    77  	case "sha256":
    78  		b := sha256.Sum256(txt)
    79  		sum = hex.EncodeToString(b[:])
    80  	case "sha512":
    81  		b := sha512.Sum512(txt)
    82  		sum = hex.EncodeToString(b[:])
    83  	default:
    84  	}
    85  
    86  	ctx.Regs.ReturnAppend(sum, ast.String)
    87  	return nil
    88  }