aboutsummaryrefslogtreecommitdiffstats
path: root/common/config.go
blob: 23a902bc11e3621e64c84f9253bb8d6f9ce0c396 (plain) (blame)
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
package common

import (
    "flag"
    "fmt"
    "os"

    "github.com/rakyll/globalconf"
)

// Config struct
type ConfigManager struct {
    ExecPath string
    Debug    bool
    Diff     bool
    DiffType string
    Paranoia bool
    VmType   int

    conf *globalconf.GlobalConf
}

// Read config
//
// Initialize Config from Config File
func ReadConfig(ConfigFile string, Datadir string, EnvPrefix string) *ConfigManager {
    if !FileExist(ConfigFile) {
        // create ConfigFile if it does not exist, otherwise
        // globalconf will panic when trying to persist flags.
        fmt.Printf("config file '%s' doesn't exist, creating it\n", ConfigFile)
        os.Create(ConfigFile)
    }
    g, err := globalconf.NewWithOptions(&globalconf.Options{
        Filename:  ConfigFile,
        EnvPrefix: EnvPrefix,
    })
    if err != nil {
        fmt.Println(err)
    } else {
        g.ParseAll()
    }
    cfg := &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true}
    return cfg
}

// provides persistence for flags
func (c *ConfigManager) Save(key string, value interface{}) {
    f := &flag.Flag{Name: key, Value: newConfValue(value)}
    c.conf.Set("", f)
}

func (c *ConfigManager) Delete(key string) {
    c.conf.Delete("", key)
}

// private type implementing flag.Value
type confValue struct {
    value string
}

// generic constructor to allow persising non-string values directly
func newConfValue(value interface{}) *confValue {
    return &confValue{fmt.Sprintf("%v", value)}
}

func (self confValue) String() string     { return self.value }
func (self confValue) Set(s string) error { self.value = s; return nil }