quorum/common/config.go

68 lines
1.5 KiB
Go
Raw Normal View History

2015-03-16 03:27:38 -07:00
package common
2014-02-14 14:56:09 -08:00
import (
2014-05-30 10:51:19 -07:00
"flag"
"fmt"
"os"
2014-07-26 02:24:44 -07:00
"github.com/rakyll/globalconf"
2014-02-14 14:56:09 -08:00
)
// Config struct
type ConfigManager struct {
ExecPath string
Debug bool
2014-07-11 07:04:09 -07:00
Diff bool
2014-07-13 15:37:50 -07:00
DiffType string
Paranoia bool
VmType int
2014-05-30 10:51:19 -07:00
conf *globalconf.GlobalConf
2014-02-14 14:56:09 -08:00
}
// 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()
2014-02-14 14:56:09 -08:00
}
cfg := &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true}
return cfg
2014-02-14 14:56:09 -08:00
}
// provides persistence for flags
func (c *ConfigManager) Save(key string, value interface{}) {
f := &flag.Flag{Name: key, Value: newConfValue(value)}
2014-05-30 10:51:19 -07:00
c.conf.Set("", f)
}
func (c *ConfigManager) Delete(key string) {
c.conf.Delete("", key)
}
// private type implementing flag.Value
2014-05-30 10:51:19 -07:00
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)}
}
2014-05-30 10:51:19 -07:00
func (self confValue) String() string { return self.value }
func (self confValue) Set(s string) error { self.value = s; return nil }