github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/utils/yaml/yaml.go (about) 1 // Copyright © 2021 Alibaba Group Holding Ltd. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package yaml 16 17 import ( 18 "bytes" 19 "fmt" 20 "os" 21 "path/filepath" 22 "reflect" 23 "strings" 24 25 osi "github.com/sealerio/sealer/utils/os" 26 27 "sigs.k8s.io/yaml" 28 ) 29 30 func UnmarshalFile(file string, obj interface{}) error { 31 data, err := os.ReadFile(filepath.Clean(file)) 32 if err != nil { 33 return err 34 } 35 36 err = yaml.Unmarshal(data, obj) 37 if err != nil { 38 return fmt.Errorf("failed to unmarshal file %s to %s: %v", file, reflect.TypeOf(obj), err) 39 } 40 return nil 41 } 42 43 func MarshalToFile(file string, obj interface{}) error { 44 data, err := yaml.Marshal(obj) 45 if err != nil { 46 return err 47 } 48 49 return osi.NewAtomicWriter(file).WriteFile(data) 50 } 51 52 func MarshalWithDelimiter(configs ...interface{}) ([]byte, error) { 53 var cfgs [][]byte 54 for _, cfg := range configs { 55 data, err := yaml.Marshal(cfg) 56 if err != nil { 57 return nil, err 58 } 59 cfgs = append(cfgs, data) 60 } 61 return bytes.Join(cfgs, []byte("\n---\n")), nil 62 } 63 64 func Matcher(path string) bool { 65 ext := strings.ToLower(filepath.Ext(path)) 66 return ext == ".yaml" || ext == ".yml" 67 }