2020-08-03 02:52:24 +00:00
|
|
|
package pathutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2020-08-13 21:09:36 +00:00
|
|
|
// UserPreferredConfigDir returns the preferred config directory for the user
|
|
|
|
func UserPreferredConfigDir() string {
|
|
|
|
defaultConfigDir := "~/.config"
|
|
|
|
|
|
|
|
config, err := os.UserConfigDir()
|
|
|
|
if err != nil {
|
|
|
|
return defaultConfigDir
|
|
|
|
}
|
|
|
|
|
|
|
|
if config == "" {
|
|
|
|
return defaultConfigDir
|
|
|
|
}
|
2020-08-03 02:52:24 +00:00
|
|
|
|
2020-08-13 21:09:36 +00:00
|
|
|
return config
|
|
|
|
}
|
2020-08-03 02:52:24 +00:00
|
|
|
|
2021-04-19 05:38:49 +00:00
|
|
|
// UserPreferredCacheDir returns the preferred cache directory for the user
|
|
|
|
func UserPreferredCacheDir() string {
|
|
|
|
defaultCacheDir := "/tmp"
|
|
|
|
|
|
|
|
cache, err := os.UserCacheDir()
|
|
|
|
if err != nil {
|
|
|
|
return defaultCacheDir
|
|
|
|
}
|
|
|
|
|
|
|
|
if cache == "" {
|
|
|
|
return defaultCacheDir
|
|
|
|
}
|
|
|
|
|
|
|
|
return cache
|
|
|
|
}
|
|
|
|
|
2020-08-13 21:09:36 +00:00
|
|
|
// UserPreferredHomeDir returns the preferred home directory for the user
|
|
|
|
func UserPreferredHomeDir() string {
|
|
|
|
home, err := os.UserHomeDir()
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
2020-08-03 02:52:24 +00:00
|
|
|
}
|
|
|
|
|
2020-08-13 21:09:36 +00:00
|
|
|
return home
|
2020-08-03 02:52:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NormalizePath normalizes and extends the path string
|
|
|
|
func NormalizePath(path string) string {
|
2020-08-13 21:09:36 +00:00
|
|
|
userHome := UserPreferredHomeDir()
|
|
|
|
userConfigHome := UserPreferredConfigDir()
|
2021-04-19 05:38:49 +00:00
|
|
|
userCacheHome := UserPreferredCacheDir()
|
2020-08-13 21:09:36 +00:00
|
|
|
|
2020-08-03 02:52:24 +00:00
|
|
|
// expand tilde
|
|
|
|
if strings.HasPrefix(path, "~/") {
|
2020-08-13 21:09:36 +00:00
|
|
|
path = filepath.Join(userHome, path[2:])
|
2020-08-03 02:52:24 +00:00
|
|
|
}
|
|
|
|
|
2020-08-13 21:09:36 +00:00
|
|
|
path = strings.Replace(path, ":HOME:", userHome, -1)
|
|
|
|
path = strings.Replace(path, ":PREFERRED_CONFIG_HOME:", userConfigHome, -1)
|
2021-04-19 05:38:49 +00:00
|
|
|
path = strings.Replace(path, ":PREFERRED_CACHE_HOME:", userCacheHome, -1)
|
2020-08-03 02:52:24 +00:00
|
|
|
path = strings.Replace(path, "/", string(filepath.Separator), -1)
|
|
|
|
|
2020-08-22 05:27:40 +00:00
|
|
|
return filepath.Clean(path)
|
2020-08-03 02:52:24 +00:00
|
|
|
}
|