go.dedis.ch/onet/v3@v3.2.11-0.20210930124529-e36530bca7ef/cfgpath/cfgpath.go (about) 1 package cfgpath 2 3 import ( 4 "os" 5 "os/user" 6 "path" 7 "runtime" 8 9 "go.dedis.ch/onet/v3/log" 10 ) 11 12 // GetConfigPath returns the location for which the configuration files are stored. 13 // Linux: we follow the XDG Base Directory specification 14 // macOS: $HOME/Library/Application Support/appName 15 // Windows: %AppData%/appName 16 // Other: ./appName (we use current directory) 17 func GetConfigPath(appName string) string { 18 if len(appName) == 0 { 19 log.Panic("appName cannot be empty") 20 } 21 22 home := os.Getenv("HOME") 23 if home == "" { 24 u, err := user.Current() 25 if err != nil { 26 log.Warn("Could not find the home directory. Switching back to current dir.") 27 return getCurrentDir(appName) 28 } 29 home = u.HomeDir 30 } 31 32 switch runtime.GOOS { 33 case "darwin": 34 return path.Join(home, "Library", "Application Support", appName) 35 case "windows": 36 return path.Join(os.Getenv("APPDATA"), appName) 37 case "linux", "freebsd": 38 xdg := os.Getenv("XDG_CONFIG_HOME") 39 if xdg != "" { 40 return path.Join(xdg, appName) 41 } 42 return path.Join(home, ".config", appName) 43 default: 44 return getCurrentDir(appName) 45 } 46 } 47 48 // GetDataPath returns the location for which the data files are stored. 49 // Linux: we follow the XDG Base Directory specification 50 // All others: the "data" directory in the path retunred by GetConfigPath 51 func GetDataPath(appName string) string { 52 switch runtime.GOOS { 53 case "linux", "freebsd": 54 xdg := os.Getenv("XDG_DATA_HOME") 55 if xdg != "" { 56 return path.Join(xdg, appName) 57 } 58 return path.Join(os.Getenv("HOME"), ".local", "share", appName) 59 default: 60 p := GetConfigPath(appName) 61 return path.Join(p, "data") 62 } 63 } 64 65 func getCurrentDir(appName string) string { 66 curr, err := os.Getwd() 67 if err != nil { 68 log.Panic("impossible to get the current directory:", err) 69 } 70 return path.Join(curr, appName) 71 }