Skip to content

Commit

Permalink
feat: suppot find config in ~/.config/appName/config.toml
Browse files Browse the repository at this point in the history
  • Loading branch information
pluveto committed Nov 2, 2023
1 parent 0a67907 commit 46d2208
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
3 changes: 2 additions & 1 deletion cmd/greet/app/conf.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package app


import "github.com/sirupsen/logrus"

const Name = "greet"

type Conf struct {
Log Log `toml:"log"`
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/greet/app/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"example.com/m/pkg/logger"
)

func Run(args Args, conf Conf) {
func Run(args Args, _ Conf) {
logger.Warn("initialize this project")
if args.Seperately {
for _, name := range args.Names {
Expand Down
36 changes: 27 additions & 9 deletions cmd/greet/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,37 @@ func getAppDir() string {
return filepath.Dir(dir)
}

func loadConfValid(path string, defaultConf app.Conf, defaultConfPath string) app.Conf {
if path == "" {
path = defaultConfPath
}
// app executable dir + config.toml has the highest priority
preferredPath := filepath.Join(getAppDir(), path)
if _, err := os.Stat(preferredPath); err == nil {
path = preferredPath
// loadConfValid loads the configuration from the given path.
// If the path is empty, the defaultConfPath is used.
// If the path is relative, the app executable dir is prepended.
//
// Example
func loadConfValid(configFileName string, defaultConf app.Conf, defaultConfPath string) app.Conf {
if configFileName == "" {
configFileName = defaultConfPath
}
path := findSuitablePath(configFileName)

_, err := toml.DecodeFile(path, &defaultConf)
if err != nil {
logger.Warn("failed to load config file: ", err, " using default config")
logger.Info("failed to load config file: ", err, " using default config")
}
logger.WithField("conf", &defaultConf).Debug("configuration loaded")
return defaultConf
}

func findSuitablePath(configFileName string) string {
path := ""
// app executable dir + config.toml has the highest priority
preferredPath := filepath.Join(getAppDir(), configFileName)
if _, err := os.Stat(preferredPath); err == nil {
path = preferredPath
}
if len(path) == 0 {
preferredPathUserConfig := filepath.Join(os.Getenv("HOME"), ".config", app.Name, configFileName)
if _, err := os.Stat(preferredPathUserConfig); err == nil {
path = preferredPathUserConfig
}
}
return path
}

0 comments on commit 46d2208

Please sign in to comment.