1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
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)
}
}
|