path.go raw
1 package scw
2
3 import (
4 "errors"
5 "os"
6 "path/filepath"
7 )
8
9 const (
10 // XDG wiki: https://wiki.archlinux.org/index.php/XDG_Base_Directory
11 xdgConfigDirEnv = "XDG_CONFIG_HOME"
12 xdgCacheDirEnv = "XDG_CACHE_HOME"
13
14 unixHomeDirEnv = "HOME"
15 windowsHomeDirEnv = "USERPROFILE"
16
17 defaultConfigFileName = "config.yaml"
18 )
19
20 // ErrNoHomeDir errors when no user directory is found
21 var ErrNoHomeDir = errors.New("user home directory not found")
22
23 // GetCacheDirectory returns the default cache directory.
24 // Cache directory is based on the following priority order:
25 // - $SCW_CACHE_DIR
26 // - $XDG_CACHE_HOME/scw
27 // - $HOME/.cache/scw
28 // - $USERPROFILE/.cache/scw
29 func GetCacheDirectory() string {
30 cacheDir := ""
31 switch {
32 case os.Getenv(ScwCacheDirEnv) != "":
33 cacheDir = os.Getenv(ScwCacheDirEnv)
34 case os.Getenv(xdgCacheDirEnv) != "":
35 cacheDir = filepath.Join(os.Getenv(xdgCacheDirEnv), "scw")
36 case os.Getenv(unixHomeDirEnv) != "":
37 cacheDir = filepath.Join(os.Getenv(unixHomeDirEnv), ".cache", "scw")
38 case os.Getenv(windowsHomeDirEnv) != "":
39 cacheDir = filepath.Join(os.Getenv(windowsHomeDirEnv), ".cache", "scw")
40 default:
41 // TODO: fallback on local folder?
42 }
43
44 // Clean the cache directory path when exiting the function
45 return filepath.Clean(cacheDir)
46 }
47
48 // GetConfigPath returns the default path.
49 // Default path is based on the following priority order:
50 // - $SCW_CONFIG_PATH
51 // - $XDG_CONFIG_HOME/scw/config.yaml
52 // - $HOME/.config/scw/config.yaml
53 // - $USERPROFILE/.config/scw/config.yaml
54 func GetConfigPath() string {
55 configPath := os.Getenv(ScwConfigPathEnv)
56 if configPath == "" {
57 configPath, _ = getConfigV2FilePath()
58 }
59 return filepath.Clean(configPath)
60 }
61
62 // getConfigV2FilePath returns the path to the v2 config file
63 func getConfigV2FilePath() (string, bool) {
64 configDir, err := GetScwConfigDir()
65 if err != nil {
66 return "", false
67 }
68 return filepath.Clean(filepath.Join(configDir, defaultConfigFileName)), true
69 }
70
71 // GetScwConfigDir returns the path to scw config folder
72 func GetScwConfigDir() (string, error) {
73 if xdgPath := os.Getenv(xdgConfigDirEnv); xdgPath != "" {
74 return filepath.Join(xdgPath, "scw"), nil
75 }
76
77 homeDir, err := os.UserHomeDir()
78 if err != nil {
79 return "", err
80 }
81 return filepath.Join(homeDir, ".config", "scw"), nil
82 }
83