github.com/oam-dev/kubevela@v1.9.11/pkg/builtin/registry/registry.go (about) 1 /* 2 Copyright 2021 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package registry 18 19 import ( 20 "strings" 21 22 "github.com/pkg/errors" 23 24 "github.com/oam-dev/kubevela/pkg/utils/util" 25 ) 26 27 var ( 28 tasks = map[string]Task{} 29 ) 30 31 // Task process app-file 32 type Task func(ctx CallCtx, params interface{}) error 33 34 // RegisterTask register task for appfile 35 func RegisterTask(name string, task Task) { 36 tasks[name] = task 37 } 38 39 func GetTasks() map[string]Task { 40 return tasks 41 } 42 43 // CallCtx is task handle context 44 type CallCtx interface { 45 LookUp(...string) (interface{}, error) 46 IO() util.IOStreams 47 } 48 49 type callContext struct { 50 data map[string]interface{} 51 ioStreams util.IOStreams 52 } 53 54 // IO return io streams handler 55 func (ctx *callContext) IO() util.IOStreams { 56 return ctx.ioStreams 57 } 58 59 // LookUp find value by paths 60 func (ctx *callContext) LookUp(paths ...string) (interface{}, error) { 61 var walkData interface{} = ctx.data 62 63 for _, path := range paths { 64 walkData = lookup(walkData, path) 65 if walkData == nil { 66 return nil, errors.Errorf("lookup field '%s' : not found", strings.Join(paths, ".")) 67 } 68 } 69 return walkData, nil 70 } 71 72 func lookup(v interface{}, key string) interface{} { 73 val, ok := v.(map[string]interface{}) 74 if ok { 75 return val[key] 76 } 77 return nil 78 } 79 80 func newCallCtx(io util.IOStreams, data map[string]interface{}) CallCtx { 81 return &callContext{ 82 ioStreams: io, 83 data: data, 84 } 85 } 86 87 // Run executes tasks 88 // Deprecated: Run is deprecated, you should use DoTasks is builtin package, it will automatically register all internal functions 89 func Run(spec map[string]interface{}, io util.IOStreams) (map[string]interface{}, error) { 90 var ( 91 ctx = newCallCtx(io, spec) 92 retSpec = map[string]interface{}{} 93 ) 94 95 tasks := GetTasks() 96 97 for key, params := range spec { 98 if do, ok := tasks[key]; ok { 99 if err := do(ctx, params); err != nil { 100 return nil, errors.WithMessagef(err, "do task %s", key) 101 } 102 } else { 103 retSpec[key] = params 104 } 105 } 106 return retSpec, nil 107 }