2021-01-09 17:06:13 +01:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2021-01-31 01:14:00 +01:00
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
|
|
|
|
"github.com/mitchellh/go-homedir"
|
2021-01-09 17:06:13 +01:00
|
|
|
)
|
|
|
|
|
2021-01-31 01:14:00 +01:00
|
|
|
var confFileName = "papero.toml"
|
|
|
|
var ErrConfigNotFound = errors.New("unable to find configuration")
|
2021-01-09 17:06:13 +01:00
|
|
|
var ErrFailedToParseConfig = errors.New("unable to cast into usable configuration")
|
|
|
|
|
|
|
|
func Parse(filePath string) (*MemConfig, error) {
|
|
|
|
fileConfig, err := parseFile(filePath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
memConfig, castingErrs := parseConfig(fileConfig)
|
|
|
|
if !castingErrs.Check() {
|
|
|
|
return nil, ErrFailedToParseConfig
|
|
|
|
}
|
|
|
|
return memConfig, nil
|
|
|
|
}
|
2021-01-31 01:14:00 +01:00
|
|
|
|
|
|
|
// Find looks for the configuration file in the following order:
|
|
|
|
// - $PWD/papero.toml
|
|
|
|
// - ~/.config/papero/papero.toml
|
|
|
|
// - ~/.papero.toml
|
|
|
|
// - /etc/papero.toml
|
|
|
|
// returns and error if no file has been found
|
|
|
|
func Find() (string, error) {
|
|
|
|
var paths []string
|
|
|
|
|
|
|
|
// Try to append $PWD/papero.toml
|
|
|
|
cwd, err := os.Getwd()
|
|
|
|
if err == nil {
|
|
|
|
paths = append(paths, path.Join(cwd, confFileName))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try to append ~/.config/papero/papero.toml and ~/.papero.toml
|
|
|
|
home, err := homedir.Dir()
|
|
|
|
if err == nil {
|
|
|
|
paths = append(paths, path.Join(home, ".config", "papero", confFileName))
|
|
|
|
paths = append(paths, path.Join(home, fmt.Sprintf(".%s", confFileName)))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Append /etc/papero.toml
|
|
|
|
paths = append(paths, path.Join("/etc", confFileName))
|
|
|
|
|
|
|
|
for _, file := range paths {
|
|
|
|
info, err := os.Stat(file)
|
|
|
|
if err == nil && !info.IsDir() {
|
|
|
|
return file, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "", ErrConfigNotFound
|
|
|
|
}
|