github.com/amazechain/amc@v0.1.3/common/paths/paths.go (about) 1 // Copyright 2023 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The AmazeChain library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package paths 18 19 import ( 20 "os" 21 "os/user" 22 "path/filepath" 23 "runtime" 24 "strings" 25 ) 26 27 const dirname = "Amc" 28 29 // DefaultDataDir is the default data directory to use for the databases and other 30 // persistence requirements. 31 func DefaultDataDir() string { 32 // Try to place the data folder in the user's home dir 33 home := homeDir() 34 if home != "" { 35 switch runtime.GOOS { 36 case "darwin": 37 return filepath.Join(home, "Library", dirname) 38 case "windows": 39 // We used to put everything in %HOME%\AppData\Roaming, but this caused 40 // problems with non-typical setups. If this fallback location exists and 41 // is non-empty, use it, otherwise DTRT and check %LOCALAPPDATA%. 42 fallback := filepath.Join(home, "AppData", "Roaming", dirname) 43 appdata := windowsAppData() 44 if appdata == "" || isNonEmptyDir(fallback) { 45 return fallback 46 } 47 return filepath.Join(appdata, dirname) 48 default: 49 if xdgDataDir := os.Getenv("XDG_DATA_HOME"); xdgDataDir != "" { 50 return filepath.Join(xdgDataDir, strings.ToLower(dirname)) 51 } 52 return filepath.Join(home, ".local/share", strings.ToLower(dirname)) 53 } 54 } 55 // As we cannot guess a stable location, return empty and handle later 56 return "" 57 } 58 59 func windowsAppData() string { 60 v := os.Getenv("LOCALAPPDATA") 61 if v == "" { 62 // Windows XP and below don't have LocalAppData. Crash here because 63 // we don't support Windows XP and undefining the variable will cause 64 // other issues. 65 panic("environment variable LocalAppData is undefined") 66 } 67 return v 68 } 69 70 func isNonEmptyDir(dir string) bool { 71 f, err := os.Open(dir) 72 if err != nil { 73 return false 74 } 75 names, _ := f.Readdir(1) 76 f.Close() 77 return len(names) > 0 78 } 79 80 func homeDir() string { 81 if home := os.Getenv("HOME"); home != "" { 82 return home 83 } 84 if usr, err := user.Current(); err == nil { 85 return usr.HomeDir 86 } 87 return "" 88 }