-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
100 lines (88 loc) · 2.1 KB
/
config.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 main
import (
"encoding/json"
"errors"
"github.com/igm/cf"
"os"
)
type Config struct {
filename string
trace bool
data struct {
ActiveTarget int `json:"selected"`
Targets []*Target `json:"targets"`
}
}
func NewConfig(filename string) (ret *Config, err error) {
ret = new(Config)
ret.filename = filename
file, err := os.Open(filename)
if err != nil {
return
}
defer file.Close()
decoder := json.NewDecoder(file)
err = decoder.Decode(&ret.data)
return
}
func (c *Config) Save() (err error) {
file, err := os.Create(c.filename)
if err != nil {
return
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.Encode(&c.data)
return
}
func NewTarget(host, alias string) *Target {
return &Target{Target: cf.NewTarget(host), Alias: alias}
}
func (c *Config) AddTarget(target *Target) error {
for _, existing := range c.data.Targets {
if existing.Alias == target.Alias {
return errors.New("Duplicate alias.")
}
}
c.data.Targets = append(c.data.Targets, target)
return nil
}
func (c *Config) RemoveTarget(target *Target) {
for i, existing := range c.data.Targets {
if existing.TargetUrl == target.TargetUrl {
c.data.Targets = append(c.data.Targets[:i], c.data.Targets[i+1:]...)
}
}
}
func (c *Config) SelectedTarget() (*Target, error) {
if c.data.ActiveTarget >= len(c.data.Targets) {
return nil, errors.New("Not target selected.")
}
ret := c.data.Targets[c.data.ActiveTarget]
return ret, nil
}
func (c *Config) Select(host string) error {
for i, existing := range c.data.Targets {
if existing.TargetUrl == host {
c.data.ActiveTarget = i
return nil
}
}
return errors.New("Target does not exist")
}
func (c *Config) GetTarget(host string) (*Target, error) {
for _, existing := range c.data.Targets {
if existing.TargetUrl == host {
return existing, nil
}
}
return nil, errors.New("Target does not exist")
}
func (c *Config) GetTargetByAlias(alias string) (*Target, error) {
for _, existing := range c.data.Targets {
if existing.Alias == alias {
return existing, nil
}
}
return nil, errors.New("Target does not exist")
}