forked from direnv/direnv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_dotenv.go
64 lines (53 loc) · 1.48 KB
/
cmd_dotenv.go
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
package main
import (
"fmt"
"io/ioutil"
"regexp"
"strings"
)
var DOTENV_REG = regexp.MustCompile("([A-Za-z0-9_]+)=(.*)")
var DOTENV_LF_REG = regexp.MustCompile("\\\\n")
var DOTENV_ESC_REG = regexp.MustCompile("\\\\.")
// `direnv private dotenv [PATH_TO_DOTENV]`
// Transforms a .env file to evaluatable `export KEY=PAIR` statements.
//
// See: https://github.com/bkeepers/dotenv and
// https://github.com/ddollar/foreman
var CmdDotEnv = &Cmd{
Name: "dotenv",
Desc: "Transforms a .env file to evaluatable `export KEY=PAIR` statements",
Args: []string{"[PATH_TO_DOTENV]"},
Private: true,
Fn: func(env Env, args []string) (err error) {
var target string
var dotenv = make(Env)
if len(args) > 1 {
target = args[1]
}
if target == "" {
target = ".env"
}
var data []byte
if data, err = ioutil.ReadFile(target); err != nil {
return
}
result := DOTENV_REG.FindAllStringSubmatch(string(data), -1)
for _, match := range result {
key := match[1]
value := strings.TrimSpace(match[2])
if value[0:1] == "'" && value[len(value)-1:len(value)] == "'" {
value = value[1 : len(value)-1]
} else if value[0:1] == `"` && value[len(value)-1:len(value)] == `"` {
value = value[1 : len(value)-1]
value = DOTENV_LF_REG.ReplaceAllString(value, "\n")
value = DOTENV_ESC_REG.ReplaceAllStringFunc(value, func(str string) string {
return str[1:2]
})
}
dotenv[key] = value
}
str := EnvToShell(dotenv, BASH)
fmt.Println(str)
return
},
}