github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/signature/transformer.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package signature 19 20 import ( 21 "errors" 22 "fmt" 23 "strings" 24 25 "github.com/zntrio/harp/v2/pkg/sdk/types" 26 "github.com/zntrio/harp/v2/pkg/sdk/value" 27 ) 28 29 // FromKey returns the value transformer that match the value format. 30 func FromKey(keyValue string) (value.Transformer, error) { 31 var ( 32 transformer value.Transformer 33 err error 34 ) 35 36 // Check arguments 37 if keyValue == "" { 38 return nil, fmt.Errorf("unable to select a value transformer with blank value") 39 } 40 41 // Extract prefix 42 parts := strings.SplitN(keyValue, ":", 2) 43 if len(parts) != 2 { 44 // Fallback to fernet 45 parts = []string{"fernet", keyValue} 46 } 47 48 // Clean prefix 49 prefix := strings.ToLower(strings.TrimSpace(parts[0])) 50 51 // Build the value transformer according to used prefix. 52 tf, ok := registry[prefix] 53 if !ok { 54 return nil, fmt.Errorf("no transformer registered for %q as prefix", prefix) 55 } 56 57 // Build the transformer instance 58 transformer, err = tf(keyValue) 59 60 // Check transformer initialization error 61 if transformer == nil || err != nil { 62 return nil, fmt.Errorf("unable to initialize value transformer: %w", err) 63 } 64 65 // No error 66 return transformer, nil 67 } 68 69 // Must is used to panic when a transformer initialization failed. 70 func Must(t value.Transformer, err error) value.Transformer { 71 if err != nil { 72 panic(err) 73 } 74 if types.IsNil(t) { 75 panic(errors.New("transformer is nil with a nil error")) 76 } 77 78 return t 79 }