github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/types/toml/toml.go (about)

     1  package toml
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/lmorg/murex/lang"
     7  	"github.com/lmorg/murex/lang/stdio"
     8  	"github.com/pelletier/go-toml"
     9  )
    10  
    11  const typeName = "toml"
    12  
    13  var errNakedArrays = errors.New("The TOML specification doesn't support naked arrays")
    14  
    15  func init() {
    16  	stdio.RegisterReadArray(typeName, readArray)
    17  	stdio.RegisterReadArrayWithType(typeName, readArrayWithType)
    18  	stdio.RegisterReadMap(typeName, readMap)
    19  	stdio.RegisterWriteArray(typeName, func(_ stdio.Io) (stdio.ArrayWriter, error) {
    20  		return nil, errNakedArrays
    21  	})
    22  
    23  	lang.ReadIndexes[typeName] = readIndex
    24  	lang.ReadNotIndexes[typeName] = readIndex
    25  	lang.Marshallers[typeName] = marshal
    26  	lang.Unmarshallers[typeName] = unmarshal
    27  
    28  	lang.SetMime(typeName,
    29  		"application/toml", // this is preferred but we will include others since not everyone follows standards.
    30  		"application/x-toml",
    31  		"text/toml",
    32  		"text/x-toml",
    33  	)
    34  
    35  	lang.SetFileExtensions(typeName, "toml")
    36  }
    37  
    38  func readIndex(p *lang.Process, params []string) error {
    39  	var jInterface interface{}
    40  
    41  	b, err := p.Stdin.ReadAll()
    42  	if err != nil {
    43  		return err
    44  	}
    45  
    46  	err = toml.Unmarshal(b, &jInterface)
    47  	if err != nil {
    48  		return err
    49  	}
    50  
    51  	return lang.IndexTemplateObject(p, params, &jInterface, toml.Marshal)
    52  }
    53  
    54  func marshal(_ *lang.Process, v interface{}) ([]byte, error) {
    55  	return toml.Marshal(v)
    56  }
    57  
    58  func unmarshal(p *lang.Process) (v interface{}, err error) {
    59  	b, err := p.Stdin.ReadAll()
    60  	if err != nil {
    61  		return
    62  	}
    63  
    64  	err = toml.Unmarshal(b, &v)
    65  	return
    66  }