github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/controllerutil/cue_value.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package controllerutil 21 22 import ( 23 "encoding/json" 24 "os" 25 26 "cuelang.org/go/cue" 27 "cuelang.org/go/cue/cuecontext" 28 cuejson "cuelang.org/go/encoding/json" 29 ) 30 31 func NewCUETplFromPath(filePathString string) (*CUETpl, error) { 32 return NewCUETplFromBytes(os.ReadFile(filePathString)) 33 } 34 35 func NewCUETplFromBytes(b []byte, err error) (*CUETpl, error) { 36 if err != nil { 37 return nil, err 38 } 39 return NewCUETpl(b), nil 40 } 41 42 func NewCUETpl(templateContents []byte) *CUETpl { 43 cueValue := CUETpl{ 44 Ctx: cuecontext.New(), 45 } 46 temValue := cueValue.Ctx.CompileBytes(templateContents) 47 cueValue.Value = temValue 48 return &cueValue 49 } 50 51 type CUETpl struct { 52 Ctx *cue.Context 53 Value cue.Value 54 } 55 56 type CUEBuilder struct { 57 cueTplValue CUETpl 58 Value cue.Value 59 } 60 61 func NewCUEBuilder(cueTpl CUETpl) CUEBuilder { 62 return CUEBuilder{ 63 cueTplValue: cueTpl, 64 Value: cueTpl.Value, 65 } 66 } 67 68 func (v *CUEBuilder) FillObj(path string, obj any) error { 69 b, err := json.Marshal(obj) 70 if err != nil { 71 return err 72 } 73 return v.Fill(path, b) 74 } 75 76 func (v *CUEBuilder) Fill(path string, jsonByte []byte) error { 77 expr, err := cuejson.Extract("", jsonByte) 78 if err != nil { 79 return err 80 } 81 cueValue := v.cueTplValue.Ctx.BuildExpr(expr) 82 v.Value = v.Value.FillPath(cue.ParsePath(path), cueValue) 83 return nil 84 } 85 86 func (v *CUEBuilder) Lookup(path string) ([]byte, error) { 87 cueValue := v.Value.LookupPath(cue.ParsePath(path)) 88 return cueValue.MarshalJSON() 89 } 90 91 // func (v *CueValue) Render() (string, error) { 92 // b, err := v.Value.MarshalJSON() 93 // str := string(b) 94 // return str, err 95 // }