Skip to content

Commit

Permalink
Add envfile.Generate
Browse files Browse the repository at this point in the history
  • Loading branch information
roeldev committed May 23, 2024
1 parent b2cef3c commit 9f882d0
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions envfile/envfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,42 @@
// files.
package envfile

import (
"github.com/go-pogo/errors"
"path"
"path/filepath"
"runtime"
)

const (
panicNilFile = "envfile: file must not be nil"
panicNilFsys = "envfile: fs.FS must not be nil"
)

// Generate encodes and writes an env file in dir based on the provided src.
// It is meant to be used with go generate to create .env files based on the
// project's config(s).
func Generate(dir, filename string, src any) error {
if dir == "" {
_, dir, _, _ = runtime.Caller(1)
dir = filepath.Dir(dir)
}

if !path.IsAbs(filename) {
filename = filepath.Join(dir, ".env")
}

enc, err := Create(filename)
if err != nil {
return errors.WithStack(err)
}

enc.TakeValues = true
defer errors.AppendFunc(&err, enc.Close)

if err = enc.Encode(src); err != nil {
err = errors.WithStack(err)
return err
}
return nil
}

0 comments on commit 9f882d0

Please sign in to comment.