github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/types/yaml/yaml.go (about) 1 package yaml 2 3 import ( 4 "context" 5 6 "github.com/lmorg/murex/config" 7 "github.com/lmorg/murex/lang" 8 "github.com/lmorg/murex/lang/stdio" 9 "github.com/lmorg/murex/lang/types" 10 yaml "gopkg.in/yaml.v3" 11 ) 12 13 const typeName = "yaml" 14 15 func init() { 16 stdio.RegisterReadArray(typeName, readArray) 17 stdio.RegisterReadArrayWithType(typeName, readArrayWithType) 18 stdio.RegisterReadMap(typeName, readMap) 19 stdio.RegisterWriteArray(typeName, newArrayWriter) 20 lang.ReadIndexes[typeName] = readIndex 21 lang.ReadNotIndexes[typeName] = readIndex 22 lang.Marshallers[typeName] = marshal 23 lang.Unmarshallers[typeName] = unmarshal 24 25 lang.SetMime(typeName, 26 "application/yaml", // this is preferred but we will include others since not everyone follows standards. 27 "application/x-yaml", 28 "text/yaml", 29 "text/x-yaml", 30 ) 31 32 lang.SetFileExtensions(typeName, "yaml", "yml") 33 } 34 35 func readArray(ctx context.Context, read stdio.Io, callback func([]byte)) error { 36 return lang.ArrayTemplate(ctx, yaml.Marshal, yaml.Unmarshal, read, callback) 37 } 38 39 func readArrayWithType(ctx context.Context, read stdio.Io, callback func(interface{}, string)) error { 40 return lang.ArrayWithTypeTemplate(ctx, typeName, yaml.Marshal, yaml.Unmarshal, read, callback) 41 } 42 43 func noCrLf(b []byte) []byte { 44 if len(b) > 0 && b[len(b)-1] == '\n' { 45 b = b[:len(b)-1] 46 } 47 48 if len(b) > 0 && b[len(b)-1] == '\r' { 49 b = b[:len(b)-1] 50 } 51 52 return b 53 } 54 55 func readMap(read stdio.Io, _ *config.Config, callback func(*stdio.Map)) error { 56 return lang.MapTemplate(typeName, yaml.Marshal, yaml.Unmarshal, read, callback) 57 } 58 59 func readIndex(p *lang.Process, params []string) error { 60 var jInterface interface{} 61 62 b, err := p.Stdin.ReadAll() 63 if err != nil { 64 return err 65 } 66 67 err = yaml.Unmarshal(b, &jInterface) 68 if err != nil { 69 return err 70 } 71 72 return lang.IndexTemplateObject(p, params, &jInterface, yaml.Marshal) 73 } 74 75 func marshal(_ *lang.Process, v interface{}) ([]byte, error) { 76 switch t := v.(type) { 77 case [][]string: 78 var i int 79 table := make([]map[string]any, len(t)-1) 80 err := types.Table2Map(t, func(m map[string]any) error { 81 table[i] = m 82 i++ 83 return nil 84 }) 85 if err != nil { 86 return nil, err 87 } 88 return yaml.Marshal(table) 89 default: 90 return yaml.Marshal(v) 91 } 92 } 93 94 func unmarshal(p *lang.Process) (v interface{}, err error) { 95 b, err := p.Stdin.ReadAll() 96 if err != nil { 97 return 98 } 99 100 err = yaml.Unmarshal(b, &v) 101 return 102 }