path.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package constant
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "github.com/sagernet/sing/common/rw"
  7. )
  8. const dirName = "sing-box"
  9. var (
  10. basePath string
  11. resourcePaths []string
  12. )
  13. func BasePath(name string) string {
  14. if basePath == "" || strings.HasPrefix(name, "/") {
  15. return name
  16. }
  17. return filepath.Join(basePath, name)
  18. }
  19. func SetBasePath(path string) {
  20. basePath = path
  21. }
  22. func FindPath(name string) (string, bool) {
  23. name = os.ExpandEnv(name)
  24. if rw.FileExists(name) {
  25. return name, true
  26. }
  27. for _, dir := range resourcePaths {
  28. if path := filepath.Join(dir, dirName, name); rw.FileExists(path) {
  29. return path, true
  30. }
  31. if path := filepath.Join(dir, name); rw.FileExists(path) {
  32. return path, true
  33. }
  34. }
  35. return name, false
  36. }
  37. func init() {
  38. resourcePaths = append(resourcePaths, ".")
  39. if home := os.Getenv("HOME"); home != "" {
  40. resourcePaths = append(resourcePaths, home)
  41. }
  42. if userConfigDir, err := os.UserConfigDir(); err == nil {
  43. resourcePaths = append(resourcePaths, userConfigDir)
  44. }
  45. if userCacheDir, err := os.UserCacheDir(); err == nil {
  46. resourcePaths = append(resourcePaths, userCacheDir)
  47. }
  48. }