package main import ( "encoding/json" "errors" "flag" "fmt" "os" "strings" "github.com/pelletier/go-toml/v2" "go.jolheiser.com/nixfig" "gopkg.in/yaml.v3" ) func maine() error { fs := flag.NewFlagSet("nixgen", flag.ExitOnError) format := func(v any) ([]byte, error) { return json.MarshalIndent(v, "", "\t") } formatFunc := func(s string) error { switch strings.ToLower(s) { case "json": // Default case "yaml": format = yaml.Marshal case "toml": format = toml.Marshal default: return fmt.Errorf("unknown format %q, should be one of [json yaml toml]", s) } return nil } fs.Func("format", "Output format [json, yaml, toml]: default 'json'", formatFunc) fs.Func("f", "--format", formatFunc) if err := fs.Parse(os.Args[1:]); err != nil { return err } if len(fs.Args()) < 1 { return errors.New("nixgen requires a file") } fp := fs.Arg(0) data, err := os.ReadFile(fp) if err != nil { return err } var nix map[string]any if err := nixfig.Unmarshal(data, &nix); err != nil { return err } out, err := format(nix) if err != nil { return err } fmt.Println(string(out)) return nil } func main() { if err := maine(); err != nil { fmt.Println(err) os.Exit(1) } }