github.com/yaling888/clash@v1.53.0/constant/path.go (about)

     1  package constant
     2  
     3  import (
     4  	"os"
     5  	P "path"
     6  	"path/filepath"
     7  	"strings"
     8  )
     9  
    10  const Name = "clash"
    11  
    12  // Path is used to get the configuration path
    13  var Path = func() *path {
    14  	homeDir, err := os.UserHomeDir()
    15  	if err != nil {
    16  		homeDir, _ = os.Getwd()
    17  	}
    18  
    19  	homeDir = P.Join(homeDir, ".config", Name)
    20  	if _, err = os.Stat(homeDir); err != nil {
    21  		if home, ok := os.LookupEnv("XDG_CONFIG_HOME"); ok {
    22  			homeDir = P.Join(home, Name)
    23  		}
    24  	}
    25  
    26  	return &path{homeDir: homeDir, configFile: "config.yaml"}
    27  }()
    28  
    29  type path struct {
    30  	homeDir    string
    31  	configFile string
    32  }
    33  
    34  // SetHomeDir is used to set the configuration path
    35  func SetHomeDir(root string) {
    36  	Path.homeDir = root
    37  }
    38  
    39  // SetConfig is used to set the configuration file
    40  func SetConfig(file string) {
    41  	Path.configFile = file
    42  }
    43  
    44  func (p *path) HomeDir() string {
    45  	return p.homeDir
    46  }
    47  
    48  func (p *path) Config() string {
    49  	return p.configFile
    50  }
    51  
    52  // Resolve return an absolute path or a relative path with homedir
    53  func (p *path) Resolve(path string) string {
    54  	if !filepath.IsAbs(path) {
    55  		return filepath.Join(p.HomeDir(), path)
    56  	}
    57  
    58  	return path
    59  }
    60  
    61  func (p *path) IsSubHomeDir(path string) bool {
    62  	if rel, err := filepath.Rel(p.HomeDir(), p.Resolve(path)); err != nil || strings.Contains(rel, "..") {
    63  		return false
    64  	}
    65  	return true
    66  }
    67  
    68  func (p *path) MMDB() string {
    69  	return P.Join(p.homeDir, "Country.mmdb")
    70  }
    71  
    72  func (p *path) OldCache() string {
    73  	return P.Join(p.homeDir, ".cache")
    74  }
    75  
    76  func (p *path) Cache() string {
    77  	return P.Join(p.homeDir, "cache.db")
    78  }
    79  
    80  func (p *path) GeoIP() string {
    81  	return P.Join(p.homeDir, "geoip.dat")
    82  }
    83  
    84  func (p *path) GeoSite() string {
    85  	return P.Join(p.homeDir, "geosite.dat")
    86  }
    87  
    88  func (p *path) RootCA() string {
    89  	return p.Resolve("mitm_ca.crt")
    90  }
    91  
    92  func (p *path) CAKey() string {
    93  	return p.Resolve("mitm_ca.key")
    94  }