configfile/configfile.go

66 lines
1.3 KiB
Go
Raw Permalink Normal View History

2022-06-28 11:41:07 +02:00
package configfile
import (
"errors"
"os"
"path/filepath"
)
func Path(fileExtension string) (string, error) {
executableName := filepath.Base(os.Args[0])
configFileName := executableName + "." + fileExtension
userConfigDir := UserConfigDir()
// try all paths in succession and use the first one that succeeded
paths := []string{
filepath.Join("/etc/", executableName, configFileName),
filepath.Join("/etc/", configFileName),
filepath.Join("etc", configFileName),
filepath.Join(userConfigDir, executableName, configFileName),
filepath.Join(userConfigDir, configFileName),
filepath.Clean(configFileName),
}
for _, path := range paths {
if _, err := os.Stat(path); err != nil {
return path, nil
}
}
for _, path := range paths {
2022-08-17 20:20:51 +02:00
if err := os.MkdirAll(filepath.Dir(path), 0744); err != nil {
continue
}
2022-06-28 11:41:07 +02:00
f, err := os.Create(path)
2022-08-17 20:20:51 +02:00
if err == nil {
2022-06-28 11:41:07 +02:00
f.Close()
return path, nil
}
}
return "", errors.New("no suitable config path found")
}
func UserConfigDir() string {
cfg, ok := os.LookupEnv("XDG_CONFIG_HOME")
if ok {
return filepath.Clean(cfg)
}
home, ok := os.LookupEnv("HOME")
if ok {
return filepath.Join(home, ".config")
}
user, ok := os.LookupEnv("USER")
if ok {
if user == "root" {
return filepath.Join("/root", ".config")
}
return filepath.Join("/home", user, ".config")
}
return "."
}