62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
|
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 {
|
||
|
f, err := os.Create(path)
|
||
|
if err != nil {
|
||
|
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 "."
|
||
|
}
|