github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/yamlx/yamlx.go (about) 1 package yamlx 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 8 "gopkg.in/yaml.v3" 9 ) 10 11 // Marshal serializes the value provided into a YAML document. The structure 12 // of the generated document will reflect the structure of the value itself. 13 // Maps and pointers (to struct, string, int, etc.) are accepted as the in value. 14 // 15 // See yaml.Marshal for detail docs. 16 func Marshal(in any) (out []byte, err error) { 17 return yaml.Marshal(in) 18 } 19 20 // Unmarshal decodes the first document found within the in byte slice 21 // and assigns decoded values into the out value. 22 // 23 // Maps and pointers (to a struct, string, int, etc.) are accepted as out 24 // values. If an internal pointer within a struct is not initialized, 25 // the yaml package will initialize it if necessary for unmarshalling 26 // the provided data. The out parameter must not be nil. 27 // 28 // See yaml.Unmarshal for detail docs. 29 // 30 // Note that this package adds extra features on the standard YAML syntax, 31 // such as "reading environment variables", "file including", 32 // "reference using gjson JSON path expression", 33 // "reference using named variables", "function calling", etc. 34 func Unmarshal(in []byte, v any, options ...Option) error { 35 par := newParser(in, options...) 36 err := par.parse() 37 if err != nil { 38 return fmt.Errorf("cannot parse yaml data: %w", err) 39 } 40 err = par.Unmarshal(v) 41 if err != nil { 42 return fmt.Errorf("cannot unmarshal yaml data: %w", err) 43 } 44 return nil 45 } 46 47 // Load is a shortcut function to read YAML data directly from a file. 48 func Load(filename string, v any, options ...Option) error { 49 yamlText, err := os.ReadFile(filename) 50 if err != nil { 51 return fmt.Errorf("cannot read yaml file: %w", err) 52 } 53 absFilename, _ := filepath.Abs(filename) 54 par := newParser(yamlText, options...) 55 if absFilename != "" { 56 par.filename = absFilename 57 par.incStack = []string{absFilename} 58 } 59 err = par.parse() 60 if err != nil { 61 return fmt.Errorf("cannot parse yaml data: %w", err) 62 } 63 err = par.Unmarshal(v) 64 if err != nil { 65 return fmt.Errorf("cannot unmarshal yaml data: %w", err) 66 } 67 return nil 68 }