config.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package common
  17. import (
  18. "flag"
  19. "fmt"
  20. "os"
  21. "github.com/rakyll/globalconf"
  22. )
  23. // Config struct
  24. type ConfigManager struct {
  25. ExecPath string
  26. Debug bool
  27. Diff bool
  28. DiffType string
  29. Paranoia bool
  30. VmType int
  31. conf *globalconf.GlobalConf
  32. }
  33. // Read config
  34. //
  35. // Initialize Config from Config File
  36. func ReadConfig(ConfigFile string, Datadir string, EnvPrefix string) *ConfigManager {
  37. if !FileExist(ConfigFile) {
  38. // create ConfigFile if it does not exist, otherwise
  39. // globalconf will panic when trying to persist flags.
  40. fmt.Printf("config file '%s' doesn't exist, creating it\n", ConfigFile)
  41. os.Create(ConfigFile)
  42. }
  43. g, err := globalconf.NewWithOptions(&globalconf.Options{
  44. Filename: ConfigFile,
  45. EnvPrefix: EnvPrefix,
  46. })
  47. if err != nil {
  48. fmt.Println(err)
  49. } else {
  50. g.ParseAll()
  51. }
  52. cfg := &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true}
  53. return cfg
  54. }
  55. // provides persistence for flags
  56. func (c *ConfigManager) Save(key string, value interface{}) {
  57. f := &flag.Flag{Name: key, Value: newConfValue(value)}
  58. c.conf.Set("", f)
  59. }
  60. func (c *ConfigManager) Delete(key string) {
  61. c.conf.Delete("", key)
  62. }
  63. // private type implementing flag.Value
  64. type confValue struct {
  65. value string
  66. }
  67. // generic constructor to allow persising non-string values directly
  68. func newConfValue(value interface{}) *confValue {
  69. return &confValue{fmt.Sprintf("%v", value)}
  70. }
  71. func (self confValue) String() string { return self.value }
  72. func (self confValue) Set(s string) error { self.value = s; return nil }