rano/config/dotenv/read.go

74 lines
1.6 KiB
Go
Raw Normal View History

package dotenv
import (
"bytes"
"io"
"os"
2024-11-10 09:22:33 +00:00
"path/filepath"
"gitserver.in/patialtech/rano/util/logger"
)
//
2024-11-18 15:23:13 +00:00
// ported from https://github.com/joho/godotenv/blob/main/godotenv.go
//
// Read all env (with same file loading semantics as Load) but return values as
// a map rather than automatically writing values into env
2024-11-10 09:22:33 +00:00
func Read(dir string, filenames ...string) (envMap map[string]string, err error) {
filenames = filenamesOrDefault(filenames)
envMap = make(map[string]string)
for _, filename := range filenames {
2024-11-10 09:22:33 +00:00
logger.Info("read env file %s", filepath.Join(dir, filename))
individualEnvMap, individualErr := readFile(filepath.Join(dir, filename))
if individualErr != nil {
err = individualErr
return // return early on a spazout
}
for key, value := range individualEnvMap {
envMap[key] = value
}
}
return
}
func filenamesOrDefault(filenames []string) []string {
if len(filenames) == 0 {
return []string{".env"}
}
return filenames
}
func readFile(filename string) (envMap map[string]string, err error) {
file, err := os.Open(filename)
if err != nil {
return
}
defer file.Close()
return parse(file)
}
// parse reads an env file from io.Reader, returning a map of keys and values.
func parse(r io.Reader) (map[string]string, error) {
var buf bytes.Buffer
_, err := io.Copy(&buf, r)
if err != nil {
return nil, err
}
return unmarshal(buf.Bytes())
}
// unmarshal parses env file from byte slice of chars, returning a map of keys and values.
func unmarshal(src []byte) (map[string]string, error) {
out := make(map[string]string)
err := parseBytes(src, out)
return out, err
}