cfg/cmd/cfg/main.go

113 lines
1.9 KiB
Go

package main
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"go.jolheiser.com/cfg"
)
func maine() error {
var unmarshal func([]byte, any) error
var marshal func(any) ([]byte, error)
fs := flag.NewFlagSet("cfg", flag.ExitOnError)
fromFunc := func(s string) error {
e, err := cfg.ParseEncoding(s)
if err != nil {
return err
}
unmarshal = e.Unmarshal
return nil
}
fs.Func("from", "The format to convert from [json(c), jsonnet, yaml, toml, nix, dhall, kdl, cue]", fromFunc)
fs.Func("f", "--from", fromFunc)
toFunc := func(s string) error {
e, err := cfg.ParseEncoding(s)
if err != nil {
return err
}
marshal = e.Marshal
return nil
}
fs.Func("to", "The format to convert to [json, yaml, toml, nix, kdl, cue]", toFunc)
fs.Func("t", "--to", toFunc)
if err := fs.Parse(os.Args[1:]); err != nil {
return err
}
cleanArg := func(arg string) string {
return strings.TrimPrefix(filepath.Ext(arg), ".")
}
in := os.Stdin
if fs.NArg() > 0 {
fi, err := os.Open(fs.Arg(0))
if err != nil {
return err
}
defer fi.Close()
in = fi
if unmarshal == nil {
if err := fromFunc(cleanArg(fs.Arg(0))); err != nil {
return err
}
}
} else if unmarshal == nil {
unmarshal = cfg.JSON.Unmarshal
}
out := os.Stdout
if fs.NArg() > 1 {
fi, err := os.Create(fs.Arg(1))
if err != nil {
return err
}
defer fi.Close()
out = fi
if marshal == nil {
if err := toFunc(cleanArg(fs.Arg(1))); err != nil {
return err
}
}
} else if marshal == nil {
marshal = cfg.JSON.Marshal
}
var data any
inData, err := io.ReadAll(in)
if err != nil {
return err
}
if err := unmarshal(inData, &data); err != nil {
return err
}
outData, err := marshal(data)
if err != nil {
return err
}
if _, err := out.Write(outData); err != nil {
return err
}
return nil
}
func main() {
if err := maine(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}