Skip to content

Commit 9f882d0

Browse files
committed
Add envfile.Generate
1 parent b2cef3c commit 9f882d0

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

envfile/envfile.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,42 @@
66
// files.
77
package envfile
88

9+
import (
10+
"github.com/go-pogo/errors"
11+
"path"
12+
"path/filepath"
13+
"runtime"
14+
)
15+
916
const (
1017
panicNilFile = "envfile: file must not be nil"
1118
panicNilFsys = "envfile: fs.FS must not be nil"
1219
)
20+
21+
// Generate encodes and writes an env file in dir based on the provided src.
22+
// It is meant to be used with go generate to create .env files based on the
23+
// project's config(s).
24+
func Generate(dir, filename string, src any) error {
25+
if dir == "" {
26+
_, dir, _, _ = runtime.Caller(1)
27+
dir = filepath.Dir(dir)
28+
}
29+
30+
if !path.IsAbs(filename) {
31+
filename = filepath.Join(dir, ".env")
32+
}
33+
34+
enc, err := Create(filename)
35+
if err != nil {
36+
return errors.WithStack(err)
37+
}
38+
39+
enc.TakeValues = true
40+
defer errors.AppendFunc(&err, enc.Close)
41+
42+
if err = enc.Encode(src); err != nil {
43+
err = errors.WithStack(err)
44+
return err
45+
}
46+
return nil
47+
}

0 commit comments

Comments
 (0)