/
hush.go
129 lines (106 loc) · 2.33 KB
/
hush.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package hush
import (
"bufio"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
type Hush struct {
properties map[string]string
}
func Hushfile() Hush {
// open the hushfile
f := openHushfile()
var h Hush
scanner := bufio.NewScanner(f)
h.properties = readHushFile(scanner)
return h
}
func (h Hush) GetString(key string) (string, bool) {
val, ok := h.properties[key]
if !ok {
return "", ok
}
return val, true
}
func (h Hush) GetInt(key string) (int64, bool) {
val, ok := h.properties[key]
var ret int64
if !ok {
return ret, ok
}
ret, err := strconv.ParseInt(val, 0, 64)
if err != nil {
return ret, false
}
return ret, true
}
func (h Hush) GetFloat(key string) (float64, bool) {
val, ok := h.properties[key]
var ret float64
if !ok {
return ret, ok
}
ret, err := strconv.ParseFloat(val, 64)
if err != nil {
return ret, false
}
return ret, true
}
func openHushfile() *os.File {
path, err := os.Getwd()
if err != nil {
log.Fatal(err)
panic(err)
}
// try and open the hushfile if it is in the same
// directory
f, err := os.Open(filepath.Join(path, ".hushfile"))
if err != nil {
// try and open the hushfile if it is in /conf/
f, err = os.Open(filepath.Join(path, "/conf/.hushfile"))
if err != nil {
// try and open the hushfile if it is in /app/
// this is the case with a Revel application
f, err = os.Open(filepath.Join(path, "/app/.hushfile"))
if err != nil {
log.Fatal(err)
panic(err)
}
}
}
return f
}
// read the hushfile line by line
func readHushFile(scanner *bufio.Scanner) map[string]string {
properties := make(map[string]string)
lineno := 1
// read the file and process the lines, splitting them by ':'
for scanner.Scan() {
pair := processLine(scanner.Text())
if len(pair) != 2 {
log.Fatalf("Hushfile line %d was formatted improperly", lineno)
panic("Hushfile Error!")
}
// add the hushfile properties and their values to the properties map
properties[pair[0]] = pair[1]
lineno++
}
err := scanner.Err()
if err != nil {
log.Fatal(err)
panic(err)
}
return properties
}
func processLine(line string) []string {
// trim whitespace from the line
tokens := strings.Split(strings.TrimSpace(line), ":")
// trim whitespace from each token, if there is any
for ind, val := range tokens {
tokens[ind] = strings.TrimSpace(val)
}
return tokens
}