go-ethereum/ethutil/config.go

71 lines
1.6 KiB
Go
Raw Normal View History

2014-02-14 16:56:09 -06:00
package ethutil
import (
2014-05-30 12:51:19 -05:00
"flag"
"fmt"
2014-05-30 12:51:19 -05:00
"github.com/rakyll/globalconf"
"os"
2014-02-14 16:56:09 -06:00
)
// Config struct
type ConfigManager struct {
2014-02-14 16:56:09 -06:00
Db Database
ExecPath string
Debug bool
2014-07-11 09:04:09 -05:00
Diff bool
Paranoia bool
2014-05-30 12:51:19 -05:00
conf *globalconf.GlobalConf
2014-02-14 16:56:09 -06:00
}
var Config *ConfigManager
2014-02-14 16:56:09 -06:00
// Read config
//
// Initialize Config from Config File
func ReadConfig(ConfigFile string, Datadir string, EnvPrefix string) *ConfigManager {
2014-02-14 16:56:09 -06:00
if Config == nil {
2014-06-26 12:45:57 -05:00
// create ConfigFile if does not exist, otherwise globalconf panic when trying to persist flags
_, err := os.Stat(ConfigFile)
if err != nil && os.IsNotExist(err) {
fmt.Printf("config file '%s' doesn't exist, creating it\n", ConfigFile)
2014-06-26 12:45:57 -05:00
os.Create(ConfigFile)
}
g, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: ConfigFile,
EnvPrefix: EnvPrefix,
})
if err != nil {
2014-06-26 12:45:57 -05:00
fmt.Println(err)
} else {
g.ParseAll()
}
Config = &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true}
2014-02-14 16:56:09 -06:00
}
return Config
}
// provides persistence for flags
func (c *ConfigManager) Save(key string, value interface{}) {
f := &flag.Flag{Name: key, Value: newConfValue(value)}
2014-05-30 12:51:19 -05:00
c.conf.Set("", f)
}
func (c *ConfigManager) Delete(key string) {
c.conf.Delete("", key)
}
// private type implementing flag.Value
2014-05-30 12:51:19 -05: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 12:51:19 -05:00
func (self confValue) String() string { return self.value }
func (self confValue) Set(s string) error { self.value = s; return nil }