Esempio n. 1
0
func NewConfigFile() (*ConfigFile, error) {
	source, err := ioutil.ReadFile(CLIConfig.ConfigFileLocation)

	if err != nil {
		if CLIConfig.IsPiping || CLIConfig.IsNotifying {
			return &ConfigFile{
				Data:      DataConfig{},
				Graphite:  GraphiteConfig{},
				JobsField: []Job{},
			}, nil
		}

		return nil, errors.New(fmt.Sprintf("Unable to open configuration file at %s. Did you use --config to specify the right path?\n\n", CLIConfig.ConfigFileLocation))
	}

	result := &ConfigFile{}

	_, err = toml.Decode(string(source), result)

	for _, job := range result.FlowField {
		result.JobsField = append(result.JobsField, job)
	}

	return result, err
}
Esempio n. 2
0
// Retuns the configuration data into a generic object for for us.
func (cr *ConfigReader) Export() (interface{}, error) {
	var config interface{}
	buf := new(bytes.Buffer)
	buf.ReadFrom(cr.reader)

	switch cr.Format {
	case "yaml":
		if err := yaml.Unmarshal(buf.Bytes(), &config); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}

	case "json":
		if err := json.Unmarshal(buf.Bytes(), &config); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}

	case "toml":
		if _, err := toml.Decode(buf.String(), &config); err != nil {
			jww.ERROR.Fatalf("Error parsing config: %s", err)
		}
	default:
		return nil, err.UnsupportedConfigError(cr.Format)
	}

	return config, nil
}
Esempio n. 3
0
func main() {
	configFile := flag.String("config", "benchmark_config.sample.toml", "Config file")

	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	data, err := ioutil.ReadFile(*configFile)
	if err != nil {
		panic(err)
	}
	var conf benchmarkConfig
	if _, err := toml.Decode(string(data), &conf); err != nil {
		panic(err)
	}
	logFile, err := os.OpenFile(conf.LogFile, os.O_RDWR|os.O_CREATE, 0660)
	if err != nil {
		panic(fmt.Sprintf("Error opening log file \"%s\": %s", conf.LogFile, err))
	}
	conf.Log = logFile
	defer logFile.Close()
	fmt.Println("Logging benchmark results to ", conf.LogFile)
	logFile.WriteString("Starting benchmark run...\n")

	harness := NewBenchmarkHarness(&conf)

	startTime := time.Now()
	harness.Run()
	elapsed := time.Now().Sub(startTime)

	message := fmt.Sprintf("Finished in %.3f seconds\n", elapsed.Seconds())
	fmt.Printf(message)
	logFile.WriteString(message)
}
Esempio n. 4
0
func ParseDbConfig(path string) (*DbConfig, error) {
	conf := &DbConfig{}
	content, err := ioutil.ReadFile(path + "/config.toml")
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Error while reading config.toml configuration: %v", err))
	}
	_, err = toml.Decode(string(content), &conf)
	if err != nil {
		return nil, err
	}
	if conf.User == "" {
		conf.User = "******"
	}
	if conf.Host == "" {
		conf.Host = "127.0.0.1"
	}
	if conf.Port == 0 {
		conf.Port = 5432
	}
	if conf.SslMode == "" {
		conf.SslMode = "disable"
	}
	return conf, nil

}
Esempio n. 5
0
func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c httpd.Config
	if _, err := toml.Decode(`
enabled = true
bind-address = ":8080"
auth-enabled = true
log-enabled = true
write-tracing = true
pprof-enabled = true
https-enabled = true
https-certificate = "/dev/null"
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	} else if c.BindAddress != ":8080" {
		t.Fatalf("unexpected bind address: %s", c.BindAddress)
	} else if c.AuthEnabled != true {
		t.Fatalf("unexpected auth enabled: %v", c.AuthEnabled)
	} else if c.LogEnabled != true {
		t.Fatalf("unexpected log enabled: %v", c.LogEnabled)
	} else if c.WriteTracing != true {
		t.Fatalf("unexpected write tracing: %v", c.WriteTracing)
	} else if c.PprofEnabled != true {
		t.Fatalf("unexpected pprof enabled: %v", c.PprofEnabled)
	} else if c.HTTPSEnabled != true {
		t.Fatalf("unexpected https enabled: %v", c.HTTPSEnabled)
	} else if c.HTTPSCertificate != "/dev/null" {
		t.Fatalf("unexpected https certificate: %v", c.HTTPSCertificate)
	}
}
Esempio n. 6
0
func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c httpd.Config
	if _, err := toml.Decode(`
enabled = true
bind-address = ":8080"
auth-enabled = true
log-enabled = true
write-tracing = true
pprof-enabled = true
max-connections = 5000
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	} else if c.BindAddress != ":8080" {
		t.Fatalf("unexpected bind address: %s", c.BindAddress)
	} else if c.AuthEnabled != true {
		t.Fatalf("unexpected auth enabled: %v", c.AuthEnabled)
	} else if c.LogEnabled != true {
		t.Fatalf("unexpected log enabled: %v", c.LogEnabled)
	} else if c.WriteTracing != true {
		t.Fatalf("unexpected write tracing: %v", c.WriteTracing)
	} else if c.PprofEnabled != true {
		t.Fatalf("unexpected pprof enabled: %v", c.PprofEnabled)
	} else if c.MaxConnections != 5000 {
		t.Fatalf("unexpected max connections: %v", c.MaxConnections)
	}
}
Esempio n. 7
0
func (page *Page) handleTomlMetaData(datum []byte) (interface{}, error) {
	m := map[string]interface{}{}
	if _, err := toml.Decode(string(datum), &m); err != nil {
		return m, fmt.Errorf("Invalid TOML in %s \nError parsing page meta data: %s", page.FileName, err)
	}
	return m, nil
}
Esempio n. 8
0
// NewConfig reads configuration from path. The format is deductted from file extension
//	* .json    - is decoded as json
//	* .yml     - is decoded as yaml
//	* .toml    - is decoded as toml
func NewConfig(path string) (*Config, error) {
	_, err := os.Stat(path)
	if err != nil {
		return nil, err
	}

	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	cfg := &Config{}
	switch filepath.Ext(path) {
	case ".json":
		jerr := json.Unmarshal(data, cfg)
		if jerr != nil {
			return nil, jerr
		}
	case ".toml":
		_, terr := toml.Decode(string(data), cfg)
		if terr != nil {
			return nil, terr
		}
	case ".yml":
		yerr := yaml.Unmarshal(data, cfg)
		if yerr != nil {
			return nil, yerr
		}

	default:
		return nil, errors.New("utron: config file not supported")
	}
	return cfg, nil
}
Esempio n. 9
0
// 解析toml字符串
func (config *Configuration) FromToml(data string) error {
	config.mutex.Lock()
	defer config.mutex.Unlock()

	_, err := toml.Decode(data, &config.parameters)
	return err
}
Esempio n. 10
0
func parseTomlConfiguration(filename string) (*Configuration, error) {
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	tomlConfiguration := &TomlConfiguration{}
	_, err = toml.Decode(string(body), tomlConfiguration)
	if err != nil {
		return nil, err
	}

	config := &Configuration{
		AdminHttpPort:  tomlConfiguration.Admin.Port,
		AdminAssetsDir: tomlConfiguration.Admin.Assets,
		ApiHttpPort:    tomlConfiguration.Api.Port,
		RaftServerPort: tomlConfiguration.Raft.Port,
		RaftDir:        tomlConfiguration.Raft.Dir,
		ProtobufPort:   tomlConfiguration.Cluster.ProtobufPort,
		SeedServers:    tomlConfiguration.Cluster.SeedServers,
		DataDir:        tomlConfiguration.Storage.Dir,
		LogFile:        tomlConfiguration.Logging.File,
		LogLevel:       tomlConfiguration.Logging.Level,
		Hostname:       tomlConfiguration.Hostname,
	}

	return config, nil
}
Esempio n. 11
0
func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c opentsdb.Config
	if _, err := toml.Decode(`
enabled = true
bind-address = ":9000"
database = "xxx"
consistency-level ="all"
tls-enabled = true
certificate = "/etc/ssl/cert.pem"
log-point-errors = true
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	} else if c.BindAddress != ":9000" {
		t.Fatalf("unexpected bind address: %s", c.BindAddress)
	} else if c.Database != "xxx" {
		t.Fatalf("unexpected database: %s", c.Database)
	} else if c.ConsistencyLevel != "all" {
		t.Fatalf("unexpected consistency-level: %s", c.ConsistencyLevel)
	} else if c.TLSEnabled != true {
		t.Fatalf("unexpected tls-enabled: %v", c.TLSEnabled)
	} else if c.Certificate != "/etc/ssl/cert.pem" {
		t.Fatalf("unexpected certificate: %s", c.Certificate)
	} else if !c.LogPointErrors {
		t.Fatalf("unexpected log-point-errors: %v", c.LogPointErrors)
	}
}
Esempio n. 12
0
// Ensure the configuration can be parsed.
func TestConfig_Parse_EnvOverride(t *testing.T) {
	// Parse configuration.
	var c run.Config
	if _, err := toml.Decode(`
[replay]
dir = "/tmp/replay"

[task]
dir = "/tmp/task"
`, &c); err != nil {
		t.Fatal(err)
	}

	if err := os.Setenv("KAPACITOR_REPLAY_DIR", "/var/lib/kapacitor/replay"); err != nil {
		t.Fatalf("failed to set env var: %v", err)
	}

	if err := os.Setenv("KAPACITOR_TASK_DIR", "/var/lib/kapacitor/task"); err != nil {
		t.Fatalf("failed to set env var: %v", err)
	}

	if err := c.ApplyEnvOverrides(); err != nil {
		t.Fatalf("failed to apply env overrides: %v", err)
	}

	// Validate configuration.
	if c.Replay.Dir != "/var/lib/kapacitor/replay" {
		t.Fatalf("unexpected replay dir: %s", c.Replay.Dir)
	} else if c.Task.Dir != "/var/lib/kapacitor/task" {
		t.Fatalf("unexpected task dir: %s", c.Task.Dir)
	}
}
Esempio n. 13
0
// LoadConfig initializes the confd configuration by first setting defaults,
// then overriding setting from the confd config file, and finally overriding
// settings from flags set on the command line.
// It returns an error if any.
func LoadConfig(path string) error {
	setDefaults()
	if path == "" {
		log.Warning("Skipping confd config file.")
	} else {
		log.Debug("Loading " + path)

		configBytes, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}

		_, err = toml.Decode(string(configBytes), &config)
		if err != nil {
			return err
		}
	}
	processFlags()
	if !isValidateEtcdScheme(config.Confd.EtcdScheme) {
		return errors.New("Invalid etcd scheme: " + config.Confd.EtcdScheme)
	}
	err := setEtcdHosts()
	if err != nil {
		return err
	}
	return nil
}
Esempio n. 14
0
// ParseConfig parses a configuration string into a config object.
func ParseConfig(s string) (*Config, error) {
	c := NewConfig()
	if _, err := toml.Decode(s, &c); err != nil {
		return nil, err
	}
	return c, nil
}
Esempio n. 15
0
func (p *BaseProvider) getConfiguration(defaultTemplateFile string, funcMap template.FuncMap, templateObjects interface{}) (*types.Configuration, error) {
	var (
		buf []byte
		err error
	)
	configuration := new(types.Configuration)
	tmpl := template.New(p.Filename).Funcs(funcMap)
	if len(p.Filename) > 0 {
		buf, err = ioutil.ReadFile(p.Filename)
		if err != nil {
			return nil, err
		}
	} else {
		buf, err = autogen.Asset(defaultTemplateFile)
		if err != nil {
			return nil, err
		}
	}
	_, err = tmpl.Parse(string(buf))
	if err != nil {
		return nil, err
	}

	var buffer bytes.Buffer
	err = tmpl.Execute(&buffer, templateObjects)
	if err != nil {
		return nil, err
	}

	if _, err := toml.Decode(buffer.String(), configuration); err != nil {
		return nil, err
	}
	return configuration, nil
}
Esempio n. 16
0
func main() {
	usage := `goclitool.

Usage:
  goclitool [-c <configfile>]
  goclitool -h
  goclitool -v

Options:
  -c --config=<configfile>    Path to goclitool config file [default: config.toml].
  -h --help                   Show this help message.
  -v --version                Show version.`

	args, err := docopt.Parse(usage, nil, true, "goclitool 0.0", false)
	if err != nil {
		log.Fatal("Error parsing usage string: " + err.Error())
	}
	conffile, err := ioutil.ReadFile(args["--config"].(string))
	if err != nil {
		log.Fatal("Error readin config file: " + err.Error())
	}
	var conf Config
	if _, err := toml.Decode(string(conffile), &conf); err != nil {
		log.Fatal("Error decoding toml config" + err.Error())
	}
}
Esempio n. 17
0
func LoadCmdConfig(configFileName string) (config map[string]toml.Primitive, md *toml.MetaData, err error) {
	exePath, err1 := exec.LookPath(os.Args[0])
	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	exeFullPath, err1 := filepath.Abs(exePath)
	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	configFullPath := fmt.Sprintf("%s/%s", filepath.Dir(exeFullPath), configFileName)

	file, err1 := os.Open(configFullPath)
	defer file.Close()

	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	data, err1 := ioutil.ReadAll(file)
	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	config = make(map[string]toml.Primitive)
	md1, err1 := toml.Decode(string(data), config)
	if err1 != nil {
		fmt.Println(err1.Error())
		return nil, nil, err1
	}
	md = &md1
	return config, md, nil
}
Esempio n. 18
0
func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c continuous_querier.Config
	if _, err := toml.Decode(`
recompute-previous-n = 1
recompute-no-older-than = "10s"
compute-runs-per-interval = 2
compute-no-more-than = "20s"
enabled = true
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.RecomputePreviousN != 1 {
		t.Fatalf("unexpected recompute previous n: %d", c.RecomputePreviousN)
	} else if time.Duration(c.RecomputeNoOlderThan) != 10*time.Second {
		t.Fatalf("unexpected recompute no older than: %v", c.RecomputeNoOlderThan)
	} else if c.ComputeRunsPerInterval != 2 {
		t.Fatalf("unexpected compute runs per interval: %d", c.ComputeRunsPerInterval)
	} else if time.Duration(c.ComputeNoMoreThan) != 20*time.Second {
		t.Fatalf("unexpected compute no more than: %v", c.ComputeNoMoreThan)
	} else if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	}
}
Esempio n. 19
0
func init() {
	currDir, e1 := os.Getwd()
	gjoa.Fatal(e1)
	propPath := currDir
	u, e2 := osuser.Current()
	if e2 == nil {
		propPath = filepath.Join(u.HomeDir, ".config", "gjoa")
	}
	propPath = filepath.Join(propPath, "properties.toml")
	propEnvVar := os.Getenv("GJOA_PROPERTIES")
	if len(propEnvVar) > 0 {
		propPath = propEnvVar
	}

	// Read toml config file from configPath.
	dat, e3 := ioutil.ReadFile(propPath)
	if e3 == nil {
		_, e4 := toml.Decode(string(dat), config)
		gjoa.Fatal(e4)
	} else {
		props = new(Properties)
		glog.V(2).Infof("unable to read properties file - ", e3)
	}
	defaultLogDir := filepath.Join(currDir, "log")
	if len(props.LogDir) > 0 {
		defaultLogDir = props.LogDir
	}
	logDir = app.Flag("log", "Log output dir.").Default(defaultLogDir).String()
}
Esempio n. 20
0
func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c udp.Config
	if _, err := toml.Decode(`
enabled = true
bind-address = ":4444"
database = "awesomedb"
retention-policy = "awesomerp"
batch-size = 100
batch-pending = 9
batch-timeout = "10ms"
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Enabled != true {
		t.Fatalf("unexpected enabled: %v", c.Enabled)
	} else if c.BindAddress != ":4444" {
		t.Fatalf("unexpected bind address: %s", c.BindAddress)
	} else if c.Database != "awesomedb" {
		t.Fatalf("unexpected database: %s", c.Database)
	} else if c.RetentionPolicy != "awesomerp" {
		t.Fatalf("unexpected retention policy: %s", c.RetentionPolicy)
	} else if c.BatchSize != 100 {
		t.Fatalf("unexpected batch size: %d", c.BatchSize)
	} else if c.BatchPending != 9 {
		t.Fatalf("unexpected batch pending: %d", c.BatchPending)
	} else if time.Duration(c.BatchTimeout) != (10 * time.Millisecond) {
		t.Fatalf("unexpected batch timeout: %v", c.BatchTimeout)
	}
}
Esempio n. 21
0
func main() {
	configfn := "nameserver.conf"
	data, err := ioutil.ReadFile(configfn)
	if err != nil {
		log.Fatalf("server: cannot load configuration file[%s] (%v)", configfn, err)
	}

	var conf config.Server
	if _, err := toml.Decode(string(data), &conf); err != nil {
		log.Fatalf("server: configuration file[%s] is not valid (%v)", configfn, err)
	}
	server := NewServer()
	for i, v := range conf.Disks {
		log.Infof("Adding %v to disks", v)
		server.registeredDisks = append(server.registeredDisks, &conf.Disks[i])
	}
	log.Infof("server: starting server...")

	lis, err := net.Listen("tcp", net.JoinHostPort(conf.Bind, conf.Port))

	if err != nil {
		log.Fatalf("server: failed to listen: %v", err)
	}

	log.Infof("server: listening on %s", net.JoinHostPort(conf.Bind, conf.Port))

	s := grpc.NewServer()
	pb.RegisterNameServer(s, server)
	log.Infof("server: ready to serve clients")
	s.Serve(lis)
}
Esempio n. 22
0
func parseConfigTOML() *Config {
	cfg := &Config{}
	if _, err := toml.Decode(defaultTomlConfig, &cfg); err != nil {
		utils.PanicOnError(err)
	}

	configPath := os.Getenv("SKIZZE_CONFIG")
	if configPath != "" {
		_, err := os.Open(configPath)
		if err != nil {
			logger.Warningf("Unable to find config file, using defaults")
			return cfg
		}
		if _, err := toml.DecodeFile(configPath, &cfg); err != nil {
			logger.Warningf("Error parsing config file, using defaults")
		}
	}
	// make paths absolute
	infodir, err := utils.FullPath(cfg.InfoDir)
	if err != nil {
		panic(err)
	}
	datadir, err := utils.FullPath(cfg.DataDir)
	if err != nil {
		panic(err)
	}
	cfg.InfoDir = infodir
	cfg.DataDir = datadir
	return cfg
}
Esempio n. 23
0
func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c meta.Config
	if _, err := toml.Decode(`
dir = "/tmp/foo"
election-timeout = "10s"
heartbeat-timeout = "20s"
leader-lease-timeout = "30h"
commit-timeout = "40m"
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if c.Dir != "/tmp/foo" {
		t.Fatalf("unexpected dir: %s", c.Dir)
	} else if time.Duration(c.ElectionTimeout) != 10*time.Second {
		t.Fatalf("unexpected election timeout: %v", c.ElectionTimeout)
	} else if time.Duration(c.HeartbeatTimeout) != 20*time.Second {
		t.Fatalf("unexpected heartbeat timeout: %v", c.HeartbeatTimeout)
	} else if time.Duration(c.LeaderLeaseTimeout) != 30*time.Hour {
		t.Fatalf("unexpected leader lease timeout: %v", c.LeaderLeaseTimeout)
	} else if time.Duration(c.CommitTimeout) != 40*time.Minute {
		t.Fatalf("unexpected commit timeout: %v", c.CommitTimeout)
	}
}
Esempio n. 24
0
func TestConfigParse(t *testing.T) {
	// Parse configuration.
	var c hh.Config
	if _, err := toml.Decode(`
enabled = false
retry-interval = "10m"
max-size=2048
max-age="20m"
retry-rate-limit=1000
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if exp := true; c.Enabled == true {
		t.Fatalf("unexpected enabled: got %v, exp %v", c.Enabled, exp)
	}

	if exp := 10 * time.Minute; c.RetryInterval.String() != exp.String() {
		t.Fatalf("unexpected retry interval: got %v, exp %v", c.RetryInterval, exp)
	}

	if exp := 20 * time.Minute; c.MaxAge.String() != exp.String() {
		t.Fatalf("unexpected max age: got %v, exp %v", c.MaxAge, exp)
	}

	if exp := int64(2048); c.MaxSize != exp {
		t.Fatalf("unexpected retry interval: got %v, exp %v", c.MaxSize, exp)
	}

	if exp := int64(1000); c.RetryRateLimit != exp {
		t.Fatalf("unexpected retry rate limit: got %v, exp %v", c.RetryRateLimit, exp)
	}

}
Esempio n. 25
0
func loadConfig(homeDir string) *Config {
	rcFilePath := filepath.Join(homeDir, RC_FILE)
	cf := new(Config)

	// read config values if a rc file exists.
	if exists(rcFilePath) {
		f, err := os.Open(rcFilePath)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()

		b, err := ioutil.ReadAll(f)
		if err != nil {
			log.Fatal(err)
		}

		if _, err := toml.Decode(string(b), cf); err != nil {
			log.Fatal(err)
		}
	}

	// set default values if empty.
	if len(cf.SnippetDirectory) == 0 {
		cf.SnippetDirectory = filepath.Join(homeDir, DEFAULT_SNIPPET_DIR)
	}

	return cf
}
Esempio n. 26
0
func LoadConfig(initial bool) {
	config := Configuration{
		Debug: 0,
		Fail:  false,
		Server: serverConfig{
			Hostname: "",
			Port:     9091,
		},
	}
	if initial {
		Config = config
	}

	configData, err := ioutil.ReadFile("config.toml")
	if err != nil {
		fmt.Println("Error opening config.toml:", err)
		Config.Fail = true
		return
	}
	if _, err := toml.Decode(string(configData), &config); err != nil {
		// handle error
		fmt.Println("Error decoding config.toml:", err)
		Config.Fail = true
		return
	}

	config.Fail = false

	// if that worked, swap the config for the new one
	Config = config
	if Config.Debug > 0 {
		DebugConfig()
	}
}
Esempio n. 27
0
File: util.go Progetto: ARodri/hume
func marshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
	buf := new(bytes.Buffer)
	buf.ReadFrom(in)

	switch strings.ToLower(configType) {
	case "yaml", "yml":
		if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "json":
		if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "toml":
		if _, err := toml.Decode(buf.String(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "properties", "props", "prop":
		var p *properties.Properties
		var err error
		if p, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
			return ConfigParseError{err}
		}
		for _, key := range p.Keys() {
			value, _ := p.Get(key)
			c[key] = value
		}
	}

	insensitiviseMap(c)
	return nil
}
Esempio n. 28
0
// parseFile turns a toml-prefixed markdown file into a Node structure
func parseFile(filePath string, name string) (*Node, error) {
	node := Node{
		Name:     name,
		Path:     filePath,
		Children: make(map[string]*Node),
	}

	fileContents, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, err
	}
	fileString := string(fileContents)
	// Read toml header if present
	if len(fileString) > 3 && fileString[0:3] == "+++" {
		parts := strings.Split(fileString, "+++")
		headerString := parts[1]
		fileString = strings.Join(parts[2:], "+++")
		if _, err = toml.Decode(headerString, &node.Config); err != nil {
			return nil, err
		}
	}

	if len(node.Config.Title) > 0 {
		node.Title = node.Config.Title
	} else {
		node.Title = node.Name
	}
	node.Markdown = renderMarkdown(fileString)

	return &node, nil
}
Esempio n. 29
0
func TestConfig_Parse(t *testing.T) {
	// Parse configuration.
	var c monitor.Config
	if _, err := toml.Decode(`
store-enabled=true
store-database="the_db"
store-retention-policy="the_rp"
store-retention-duration="1h"
store-replication-factor=1234
store-interval="10m"
`, &c); err != nil {
		t.Fatal(err)
	}

	// Validate configuration.
	if !c.StoreEnabled {
		t.Fatalf("unexpected store-enabled: %v", c.StoreEnabled)
	} else if c.StoreDatabase != "the_db" {
		t.Fatalf("unexpected store-database: %s", c.StoreDatabase)
	} else if c.StoreRetentionPolicy != "the_rp" {
		t.Fatalf("unexpected store-retention-policy: %s", c.StoreRetentionPolicy)
	} else if time.Duration(c.StoreRetentionDuration) != 1*time.Hour {
		t.Fatalf("unexpected store-retention-duration: %s", c.StoreRetentionDuration)
	} else if c.StoreReplicationFactor != 1234 {
		t.Fatalf("unexpected store-replication-factor: %d", c.StoreReplicationFactor)
	} else if time.Duration(c.StoreInterval) != 10*time.Minute {
		t.Fatalf("unexpected store-interval:  %s", c.StoreInterval)
	}
}
Esempio n. 30
0
// load reads and parses a JSON, YAML, or TOML file.
func load(file string, data interface{}) error {
	bytes, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}

	switch strings.ToLower(filepath.Ext(file)) {
	case ".json":
		if bytes, err = stripJSONComments(bytes); err != nil {
			return err
		}
		if err := json.Unmarshal(bytes, data); err != nil {
			return err
		}
	case ".yaml", ".yml":
		if err := yaml.Unmarshal(bytes, data); err != nil {
			return err
		}
	case ".toml":
		if _, err := toml.Decode(string(bytes), data); err != nil {
			return err
		}
	default:
		return FileTypeError(file)
	}

	return nil
}