2022-06-01 17:55:55 +03:00
|
|
|
package toml
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"embed"
|
|
|
|
|
|
|
|
"github.com/BurntSushi/toml"
|
|
|
|
"github.com/wader/fq/format"
|
2022-08-12 16:27:51 +03:00
|
|
|
"github.com/wader/fq/internal/gojqex"
|
2022-06-01 17:55:55 +03:00
|
|
|
"github.com/wader/fq/pkg/bitio"
|
|
|
|
"github.com/wader/fq/pkg/decode"
|
|
|
|
"github.com/wader/fq/pkg/interp"
|
|
|
|
"github.com/wader/fq/pkg/scalar"
|
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed toml.jq
|
|
|
|
var tomlFS embed.FS
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
interp.RegisterFormat(decode.Format{
|
|
|
|
Name: format.TOML,
|
|
|
|
Description: "Tom's Obvious, Minimal Language",
|
2022-08-15 13:12:37 +03:00
|
|
|
ProbeOrder: format.ProbeOrderTextFuzzy,
|
2022-06-01 17:55:55 +03:00
|
|
|
Groups: []string{format.PROBE},
|
|
|
|
DecodeFn: decodeTOML,
|
|
|
|
Functions: []string{"_todisplay"},
|
|
|
|
})
|
2022-07-27 14:20:48 +03:00
|
|
|
interp.RegisterFS(tomlFS)
|
2022-06-01 17:55:55 +03:00
|
|
|
interp.RegisterFunc0("totoml", toTOML)
|
|
|
|
}
|
|
|
|
|
|
|
|
func decodeTOML(d *decode.D, _ any) any {
|
|
|
|
br := d.RawLen(d.Len())
|
|
|
|
var r any
|
|
|
|
|
|
|
|
if _, err := toml.NewDecoder(bitio.NewIOReader(br)).Decode(&r); err != nil {
|
|
|
|
d.Fatalf("%s", err)
|
|
|
|
}
|
2022-09-30 14:58:23 +03:00
|
|
|
var s scalar.Any
|
2022-08-12 16:27:51 +03:00
|
|
|
s.Actual = gojqex.Normalize(r)
|
2022-06-01 17:55:55 +03:00
|
|
|
|
|
|
|
// TODO: better way to handle that an empty file is valid toml and parsed as an object
|
|
|
|
switch v := s.Actual.(type) {
|
|
|
|
case map[string]any:
|
|
|
|
if len(v) == 0 {
|
|
|
|
d.Fatalf("root object has no values")
|
|
|
|
}
|
|
|
|
case []any:
|
|
|
|
default:
|
|
|
|
d.Fatalf("root not object or array")
|
|
|
|
}
|
|
|
|
|
|
|
|
d.Value.V = &s
|
|
|
|
d.Value.Range.Len = d.Len()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func toTOML(_ *interp.Interp, c any) any {
|
|
|
|
if c == nil {
|
2022-08-12 16:27:51 +03:00
|
|
|
return gojqex.FuncTypeError{Name: "totoml", V: c}
|
2022-06-01 17:55:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
b := &bytes.Buffer{}
|
2022-08-12 16:27:51 +03:00
|
|
|
if err := toml.NewEncoder(b).Encode(gojqex.Normalize(c)); err != nil {
|
2022-06-01 17:55:55 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return b.String()
|
|
|
|
}
|