-
Notifications
You must be signed in to change notification settings - Fork 0
/
direnv.go
80 lines (62 loc) · 1.51 KB
/
direnv.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package direnv
import (
"fmt"
"os/exec"
"github.com/sirupsen/logrus"
"github.com/sunny-b/cryptkeeper/internal/fileutils"
)
const evalExportCmd = "eval $(cryptkeeper export %s)"
const envrc = ".envrc"
func EnvrcPath() string {
envrcPath, err := fileutils.FindPathTo(envrc)
if err != nil {
logrus.Debugf("failed to find path to .envrc: %s", err)
return ""
}
return envrcPath
}
func Reload() error {
return exec.Command("direnv", "reload").Run()
}
func IsInstalled() bool {
_, err := exec.LookPath("direnv")
return err == nil
}
func Integrate(envrcPath, shell string) error {
cmd := evalStatement(shell)
exists, err := fileutils.TextExistsInFile(envrcPath, cmd)
if err != nil {
return err
}
if exists {
return nil
}
envrcBytes, err := fileutils.ReadFile(envrcPath)
if err != nil {
return err
}
// Check if file ends in newline
if envrcBytes[len(envrcBytes)-1] != '\n' {
envrcBytes = append(envrcBytes, '\n')
}
// Append eval export to end of file
envrcBytes = append(envrcBytes, []byte(cmd)...)
return fileutils.WriteFile(envrcPath, envrcBytes, 0644)
}
func evalStatement(shell string) string {
return fmt.Sprintf(evalExportCmd, shell)
}
func EvalStatement(shell string) string {
return evalStatement(shell)
}
func ReloadEnv() error {
if !IsInstalled() {
logrus.Error("'direnv' is not installed - install it here: https://direnv.net/docs/installation.html")
return nil
}
if EnvrcPath() == "" {
logrus.Warn(".envrc not found - skipping reload")
return nil
}
return Reload()
}