-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.go
54 lines (51 loc) · 1.08 KB
/
common.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
package common
import (
"bufio"
"io/ioutil"
"log"
"os"
"strings"
)
func appendToDoku(envParam string) {
err := writeLines(envParam, "./env.md")
if err != nil {
panic(err)
}
}
func fileContainsText(textToAppend string, path string) bool {
file, err := ioutil.ReadFile(path)
FailOnError(err, "not able to read File")
return strings.Contains(string(file), textToAppend)
}
func writeLines(textToAppend string, path string) error {
// overwrite file if it exists
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
if fileContainsText(textToAppend, path) {
return nil
}
defer file.Close()
// new writer w/ default 4096 buffer size
w := bufio.NewWriter(file)
_, err = w.WriteString(textToAppend + "\n")
if err != nil {
return err
}
// flush outstanding data
return w.Flush()
}
func Getenv(key, fallback string) string {
appendToDoku(key)
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
func FailOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}