Browse Source

implemented package config

Benton Edmondson 1 year ago
parent
commit
97742ab7bc
3 changed files with 69 additions and 0 deletions
  1. 66 0
      config/config.go
  2. 1 0
      go.mod
  3. 2 0
      go.sum

+ 66 - 0
config/config.go

@@ -0,0 +1,66 @@
+package config
+
+import (
+	"fmt"
+	"errors"
+	"os"
+	"github.com/BurntSushi/toml"
+)
+
+type Config struct {
+	General general
+	Feeds feeds
+	Algos algos
+}
+
+type general = struct {
+	Context int
+	Timeout int
+}
+type feeds = map[string][]string
+type algos = map[string]struct {
+	Server string
+	Query string
+}
+
+func Parse() (*Config, error) {
+	config := &Config {
+		General: general{
+			Context: 5,
+			Timeout: 10,
+		},
+		Feeds: feeds{},
+		Algos: algos{},
+	}
+
+	location := location()
+	if location == "" {
+		return config, nil
+	}
+
+	metadata, err := toml.DecodeFile(location, config)
+	if errors.Is(err, os.ErrNotExist) {
+		return config, nil
+	}
+	if err != nil {
+		return nil, err
+	}
+
+	if undecoded := metadata.Undecoded(); len(undecoded) != 0 {
+		return nil, fmt.Errorf("config file %s contained unexpected keys: %v", location, undecoded)
+	}
+
+	return config, nil
+}
+
+func location() string {
+	if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" {
+		return xdg + "/mimicry/config.toml"
+	}
+
+	if home := os.Getenv("HOME"); home != "" {
+		return home + "/.config/mimicry/config.toml"
+	}
+
+	return ""
+}

+ 1 - 0
go.mod

@@ -3,6 +3,7 @@ module mimicry
 go 1.20
 
 require (
+	github.com/BurntSushi/toml v1.3.0
 	github.com/hashicorp/golang-lru/v2 v2.0.2
 	github.com/yuin/goldmark v1.5.4
 	golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea

+ 2 - 0
go.sum

@@ -1,3 +1,5 @@
+github.com/BurntSushi/toml v1.3.0 h1:Ws8e5YmnrGEHzZEzg0YvK/7COGYtTC5PbaH9oSSbgfA=
+github.com/BurntSushi/toml v1.3.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
 github.com/hashicorp/golang-lru/v2 v2.0.2 h1:Dwmkdr5Nc/oBiXgJS3CDHNhJtIHkuZ3DZF5twqnfBdU=
 github.com/hashicorp/golang-lru/v2 v2.0.2/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
 github.com/yuin/goldmark v1.5.4 h1:2uY/xC0roWy8IBEGLgB1ywIoEJFGmRrX21YQcvGZzjU=