config.go 1.5 KB
Newer Older
obscuren's avatar
obscuren committed
1
package common
obscuren's avatar
obscuren committed
2 3

import (
obscuren's avatar
obscuren committed
4
	"flag"
5
	"fmt"
6
	"os"
obscuren's avatar
obscuren committed
7 8

	"github.com/rakyll/globalconf"
obscuren's avatar
obscuren committed
9 10
)

11
// Config struct
zelig's avatar
zelig committed
12 13 14
type ConfigManager struct {
	ExecPath string
	Debug    bool
15
	Diff     bool
obscuren's avatar
obscuren committed
16
	DiffType string
zelig's avatar
zelig committed
17
	Paranoia bool
18
	VmType   int
obscuren's avatar
obscuren committed
19 20

	conf *globalconf.GlobalConf
obscuren's avatar
obscuren committed
21 22
}

23 24
// Read config
//
25
// Initialize Config from Config File
zelig's avatar
zelig committed
26
func ReadConfig(ConfigFile string, Datadir string, EnvPrefix string) *ConfigManager {
27 28 29 30 31 32 33 34 35 36 37 38 39 40
	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()
obscuren's avatar
obscuren committed
41
	}
42 43
	cfg := &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true}
	return cfg
obscuren's avatar
obscuren committed
44 45
}

46
// provides persistence for flags
zelig's avatar
zelig committed
47 48
func (c *ConfigManager) Save(key string, value interface{}) {
	f := &flag.Flag{Name: key, Value: newConfValue(value)}
obscuren's avatar
obscuren committed
49 50 51
	c.conf.Set("", f)
}

zelig's avatar
zelig committed
52 53 54 55 56
func (c *ConfigManager) Delete(key string) {
	c.conf.Delete("", key)
}

// private type implementing flag.Value
obscuren's avatar
obscuren committed
57 58 59 60
type confValue struct {
	value string
}

zelig's avatar
zelig committed
61 62 63 64 65
// generic constructor to allow persising non-string values directly
func newConfValue(value interface{}) *confValue {
	return &confValue{fmt.Sprintf("%v", value)}
}

obscuren's avatar
obscuren committed
66 67
func (self confValue) String() string     { return self.value }
func (self confValue) Set(s string) error { self.value = s; return nil }