From d3cc6e8ec27206560c3af4c10dbac6fa6399eac3 Mon Sep 17 00:00:00 2001 From: Timon Ringwald Date: Tue, 28 Jun 2022 11:41:07 +0200 Subject: [PATCH] initial commit --- configfile.go | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++ go.mod | 3 +++ go.sum | 0 3 files changed, 64 insertions(+) create mode 100644 configfile.go create mode 100644 go.mod create mode 100644 go.sum diff --git a/configfile.go b/configfile.go new file mode 100644 index 0000000..30f1c6b --- /dev/null +++ b/configfile.go @@ -0,0 +1,61 @@ +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 "." +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..8cea8ef --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.tordarus.net/Tordarus/configfile + +go 1.18 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e69de29