dotenv.go 2.55 KB
Newer Older
1
/*Package dotenv for interacting with a .env file
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Copyright © 2020 Addshore

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
18
package dotenv
19
20

import (
21
	"os"
22
	"path/filepath"
23
	"strings"
24
25
26
27

	"github.com/joho/godotenv"
)

28
29
/*File location of the .env file to work on*/
type File string
30

31
32
33
/*FileForDirectory returns the File for the given directory*/
func FileForDirectory(directory string) File {
	return File(directory + string(os.PathSeparator) + ".env")
34
35
}

36
/*Path the path of the .env file*/
37
func (f File) Path() string {
38
	return string(f)
39
40
}

41
42
/*EnsureExists ensures that the File exists, creating an empty one if not*/
func (f File) EnsureExists() {
43
	if _, err := os.Stat(f.Path()); err != nil {
44
		err := os.MkdirAll(strings.Replace(f.Path(), filepath.Base(f.Path()), "", -1), 0700)
45
		if err != nil {
46
			panic(err)
47
48
49
		}
		_, err = os.OpenFile(f.Path(), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
		if err != nil {
50
			panic(err)
51
		}
52
	}
53
54
}

55
func (f File) read() map[string]string {
56
57
	f.EnsureExists()
	envMap, _ := godotenv.Read(f.Path())
58
59
60
	return envMap
}

61
func (f File) write(envMap map[string]string) {
Addshore's avatar
Addshore committed
62
63
64
65
66
	// Override the regular gotdotenv Write method to avoid adding quotes
	// https://github.com/joho/godotenv/issues/50#issuecomment-364873528
	// https://github.com/moby/moby/issues/12997
	//godotenv.Write(envMap, f.Path())
	writeOverride(envMap, f.Path())
67
68
69
}

/*Delete a value from the env*/
70
func (f File) Delete(name string) {
71
	envMap := f.read()
72
	delete(envMap, name)
73
	f.write(envMap)
74
75
76
}

/*Set a value in the env*/
77
func (f File) Set(name string, value string) {
78
	envMap := f.read()
79
	envMap[name] = value
80
	f.write(envMap)
81
82
83
}

/*Get a value from the env*/
84
func (f File) Get(name string) string {
85
	envMap := f.read()
86
87
88
	return envMap[name]
}

89
/*Has a value in the env*/
90
func (f File) Has(name string) bool {
91
92
93
94
95
96
	envMap := f.read()
	_, ok := envMap[name]
	return ok
}

/*Missing a value in the env*/
97
func (f File) Missing(name string) bool {
98
99
100
	return !f.Has(name)
}

101
/*List all values from the env*/
102
func (f File) List() map[string]string {
103
	return f.read()
104
}