github.com/sagernet/sing-box@v1.2.7/constant/path.go (about)

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