config.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package common
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "github.com/rakyll/globalconf"
  7. )
  8. // Config struct
  9. type ConfigManager struct {
  10. ExecPath string
  11. Debug bool
  12. Diff bool
  13. DiffType string
  14. Paranoia bool
  15. VmType int
  16. conf *globalconf.GlobalConf
  17. }
  18. // Read config
  19. //
  20. // Initialize Config from Config File
  21. func ReadConfig(ConfigFile string, Datadir string, EnvPrefix string) *ConfigManager {
  22. if !FileExist(ConfigFile) {
  23. // create ConfigFile if it does not exist, otherwise
  24. // globalconf will panic when trying to persist flags.
  25. fmt.Printf("config file '%s' doesn't exist, creating it\n", ConfigFile)
  26. os.Create(ConfigFile)
  27. }
  28. g, err := globalconf.NewWithOptions(&globalconf.Options{
  29. Filename: ConfigFile,
  30. EnvPrefix: EnvPrefix,
  31. })
  32. if err != nil {
  33. fmt.Println(err)
  34. } else {
  35. g.ParseAll()
  36. }
  37. cfg := &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true}
  38. return cfg
  39. }
  40. // provides persistence for flags
  41. func (c *ConfigManager) Save(key string, value interface{}) {
  42. f := &flag.Flag{Name: key, Value: newConfValue(value)}
  43. c.conf.Set("", f)
  44. }
  45. func (c *ConfigManager) Delete(key string) {
  46. c.conf.Delete("", key)
  47. }
  48. // private type implementing flag.Value
  49. type confValue struct {
  50. value string
  51. }
  52. // generic constructor to allow persising non-string values directly
  53. func newConfValue(value interface{}) *confValue {
  54. return &confValue{fmt.Sprintf("%v", value)}
  55. }
  56. func (self confValue) String() string { return self.value }
  57. func (self confValue) Set(s string) error { self.value = s; return nil }