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
|
diff --git a/nixfig.go b/nixfig.go
index b91d34929c055cd58708980b26f806baee668465..d89e98b2bd19bb7fc9ac5033d11abe738f6a97e4 100644
--- a/nixfig.go
+++ b/nixfig.go
@@ -7,12 +7,14 @@ "errors"
"fmt"
"os"
"os/exec"
+ "strings"
)
var (
- // Nix is the command to call for nix
- Nix string
+ Nix string // Nix is the command to call for nix
+ Fmt []string // Fmt is the command (and args) to call to format the nix output
ErrNixNotFound = errors.New("nix was not found or set. You can set it either with `nixfig.Nix` or the `NIXFIG_NIX` environment variable")
+ ErrFmtNotFound = errors.New("nix formatter was not found or set. You can set it either with `nixfig.Fmt` or the `NIXFIG_FMT` environment variable")
)
func init() {
@@ -20,6 +22,17 @@ nixPath, _ := exec.LookPath("nix")
Nix = nixPath
if envPath, ok := os.LookupEnv("NIXFIG_NIX"); ok {
Nix = envPath
+ }
+
+ for _, formatter := range []string{"alejandra", "nixfmt-rfc-style", "nixfmt"} {
+ fmtPath, _ := exec.LookPath(formatter)
+ if fmtPath != "" {
+ Fmt = []string{fmtPath, "--quiet"}
+ break
+ }
+ }
+ if envPath, ok := os.LookupEnv("NIXFIG_FMT"); ok {
+ Fmt = strings.Split(envPath, " ")
}
}
@@ -70,3 +83,29 @@ }
return stdout.Bytes(), nil
}
+
+// MarshalFormat marshals a struct into a nix expression and formats it with Fmt
+func MarshalFormat(v any) ([]byte, error) {
+ if Fmt == nil {
+ return nil, ErrFmtNotFound
+ }
+
+ data, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+
+ var stdout, stderr bytes.Buffer
+ cmd := exec.Command(Fmt[0], Fmt[1:]...)
+ cmd.Stdin = bytes.NewBuffer(data)
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+ if err := cmd.Run(); err != nil {
+ return nil, fmt.Errorf("could not run %v: %w", Fmt, err)
+ }
+ if stderr.Len() > 0 {
+ return nil, errors.New(stderr.String())
+ }
+
+ return stdout.Bytes(), nil
+}
|