This repository has been archived by the owner on Jul 28, 2020. It is now read-only.
/
toggle.go
100 lines (85 loc) · 2.04 KB
/
toggle.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
package toggle
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
type Toggle struct {
defined bool
CfAnalyticsEnabled bool `json:"cfAnalyticsEnabled"`
CustomAnalyticsEnabled bool `json:"customAnalyticsEnabled"`
path string
props map[string]interface{}
}
func New(path string) *Toggle {
t := &Toggle{
defined: false,
CfAnalyticsEnabled: false,
CustomAnalyticsEnabled: false,
path: path,
props: make(map[string]interface{}, 1),
}
if txt, err := ioutil.ReadFile(path); err == nil {
if err := json.Unmarshal(txt, &t); err == nil {
t.path = path
t.defined = true
} else {
fmt.Printf("Error unmarshalling json: %v", err)
}
}
return t
}
func (t *Toggle) Defined() bool {
return t.defined
}
func (t *Toggle) CustomAnalyticsDefined() bool {
if !t.defined {
return false
} else {
return !(t.CfAnalyticsEnabled && !t.CustomAnalyticsEnabled)
}
}
func (t *Toggle) Enabled() bool {
return t.CfAnalyticsEnabled || t.CustomAnalyticsEnabled
}
func (t *Toggle) IsCustom() bool {
return t.CustomAnalyticsEnabled
}
func (t *Toggle) SetCFAnalyticsEnabled(value bool) error {
t.defined = true
if !value {
t.CfAnalyticsEnabled = value
t.CustomAnalyticsEnabled = value
} else {
t.CfAnalyticsEnabled = value
}
return t.save()
}
func (t *Toggle) SetCustomAnalyticsEnabled(value bool) error {
t.defined = true
t.CfAnalyticsEnabled = value
t.CustomAnalyticsEnabled = value
return t.save()
}
func (t *Toggle) GetProps() map[string]interface{} {
return t.props
}
func (t *Toggle) SetProp(k, v string) error {
t.props[k] = v
return t.save()
}
func (t *Toggle) save() error {
os.MkdirAll(filepath.Dir(t.path), 0755)
hash := map[string]interface{}{"props": t.props}
if t.defined {
hash["cfAnalyticsEnabled"] = t.CfAnalyticsEnabled
hash["customAnalyticsEnabled"] = t.CustomAnalyticsEnabled
}
txt, err := json.Marshal(hash)
if err != nil {
return err
}
return ioutil.WriteFile(t.path, txt, 0644)
}