2022-06-01 17:55:55 +03:00
|
|
|
package yaml
|
|
|
|
|
|
|
|
// TODO: yaml type eval? walk eval?
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
2022-08-15 13:12:37 +03:00
|
|
|
"errors"
|
|
|
|
"io"
|
2022-06-01 17:55:55 +03:00
|
|
|
|
|
|
|
"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"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed yaml.jq
|
|
|
|
var yamlFS embed.FS
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
interp.RegisterFormat(decode.Format{
|
|
|
|
Name: format.YAML,
|
|
|
|
Description: "YAML Ain't Markup 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: decodeYAML,
|
|
|
|
Functions: []string{"_todisplay"},
|
|
|
|
})
|
2022-07-27 14:20:48 +03:00
|
|
|
interp.RegisterFS(yamlFS)
|
2022-12-21 15:59:54 +03:00
|
|
|
interp.RegisterFunc0("to_yaml", toYAML)
|
2022-06-01 17:55:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func decodeYAML(d *decode.D, _ any) any {
|
|
|
|
br := d.RawLen(d.Len())
|
|
|
|
var r any
|
|
|
|
|
2022-08-15 13:12:37 +03:00
|
|
|
yd := yaml.NewDecoder(bitio.NewIOReader(br))
|
|
|
|
if err := yd.Decode(&r); err != nil {
|
2022-06-01 17:55:55 +03:00
|
|
|
d.Fatalf("%s", err)
|
|
|
|
}
|
2022-08-15 13:12:37 +03:00
|
|
|
if err := yd.Decode(new(any)); !errors.Is(err, io.EOF) {
|
|
|
|
d.Fatalf("trialing data after top-level value")
|
|
|
|
}
|
|
|
|
|
2022-09-30 14:58:23 +03:00
|
|
|
var s scalar.Any
|
2022-10-11 19:45:09 +03:00
|
|
|
s.Actual = gojqex.Normalize(r)
|
2022-06-01 17:55:55 +03:00
|
|
|
|
|
|
|
switch s.Actual.(type) {
|
|
|
|
case map[string]any,
|
|
|
|
[]any:
|
|
|
|
default:
|
|
|
|
d.Fatalf("root not object or array")
|
|
|
|
}
|
|
|
|
|
|
|
|
d.Value.V = &s
|
|
|
|
d.Value.Range.Len = d.Len()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func toYAML(_ *interp.Interp, c any) any {
|
2022-08-12 16:27:51 +03:00
|
|
|
b, err := yaml.Marshal(gojqex.Normalize(c))
|
2022-06-01 17:55:55 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return string(b)
|
|
|
|
}
|