Debian Codegraph @

basedir/basedir.go

raw
1 // Package basedir provides access to XDG base directory spec. For more
2 // information, please see the spec:
3 // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
4 package basedir
5
6 import (
7 "os"
8 "os/user"
9 "path/filepath"
10 )
11
12 var (
13 // Home is the user's home directory.
14 Home string
15
16 // DataHome is the path to the directory where user data files
17 // should be written.
18 DataHome string
19
20 // ConfigHome is the path to the directory where user
21 // configuration files should be written.
22 ConfigHome string
23
24 // CacheHome is the path to the directory where non-essential
25 // (cached) data should be written.
26 CacheHome string
27
28 // RuntimeDir is the path to the directory where runtime files
29 // should be placed.
30 RuntimeDir string
31
32 // DataDirs is a slice of paths that should be searched for data
33 // files.
34 DataDirs []string
35
36 // ConfigDirs is a slice of paths that should be searched for
37 // configuration files.
38 ConfigDirs []string
39 )
40
41 func init() {
42 Home = os.Getenv("HOME")
43 if Home == "" {
44 u, err := user.Current()
45 if err == nil {
46 Home = u.HomeDir
47 } else {
48 Home = filepath.Join(os.TempDir(), os.Args[0])
49 }
50 }
51
52 DataHome = getPath("XDG_DATA_HOME", filepath.Join(Home, ".local/share"))
53 ConfigHome = getPath("XDG_CONFIG_HOME", filepath.Join(Home, ".config"))
54 CacheHome = getPath("XDG_CACHE_HOME", filepath.Join(Home, ".cache"))
55 RuntimeDir = getPath("XDG_RUNTIME_DIR", CacheHome)
56 DataDirs = getPathList("XDG_DATA_DIRS", []string{"/usr/local/share", "/usr/share"})
57 ConfigDirs = getPathList("XDG_CONFIG_DIRS", []string{"/etc/xdg"})
58 }
59
60 func getPath(env, def string) string {
61 path := os.Getenv(env)
62 if path == "" || !filepath.IsAbs(path) {
63 return def
64 }
65 return path
66 }
67
68 func getPathList(env string, def []string) []string {
69 paths := filepath.SplitList(os.Getenv(env))
70 for i := 0; i < len(paths); i++ {
71 // If the path isn't absolute, we need to ignore it.
72 if !filepath.IsAbs(paths[i]) {
73 paths = append(paths[:i], paths[i+1:]...)
74 }
75 }
76 if len(paths) == 0 {
77 return def
78 }
79 return paths
80 }