github.com/igoogolx/clash@v1.19.8/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  //
    14  // on Unix systems, `$HOME/.config/clash`.
    15  // on Windows, `%USERPROFILE%/.config/clash`.
    16  var Path = func() *path {
    17  	homeDir, err := os.UserHomeDir()
    18  	if err != nil {
    19  		homeDir, _ = os.Getwd()
    20  	}
    21  
    22  	homeDir = P.Join(homeDir, ".config", Name)
    23  
    24  	if _, err = os.Stat(homeDir); err != nil {
    25  		if configHome, ok := os.LookupEnv("XDG_CONFIG_HOME"); ok {
    26  			homeDir = P.Join(configHome, Name)
    27  		}
    28  	}
    29  	return &path{homeDir: homeDir, configFile: "config.yaml"}
    30  }()
    31  
    32  type path struct {
    33  	homeDir    string
    34  	configFile string
    35  }
    36  
    37  // SetHomeDir is used to set the configuration path
    38  func SetHomeDir(root string) {
    39  	Path.homeDir = root
    40  }
    41  
    42  // SetConfig is used to set the configuration file
    43  func SetConfig(file string) {
    44  	Path.configFile = file
    45  }
    46  
    47  func (p *path) HomeDir() string {
    48  	return p.homeDir
    49  }
    50  
    51  func (p *path) Config() string {
    52  	return p.configFile
    53  }
    54  
    55  // Resolve return a absolute path or a relative path with homedir
    56  func (p *path) Resolve(path string) string {
    57  	if !filepath.IsAbs(path) {
    58  		return filepath.Join(p.HomeDir(), path)
    59  	}
    60  
    61  	return path
    62  }
    63  
    64  // IsSubPath return true if path is a subpath of homedir
    65  func (p *path) IsSubPath(path string) bool {
    66  	homedir := p.HomeDir()
    67  	path = p.Resolve(path)
    68  	rel, err := filepath.Rel(homedir, path)
    69  	if err != nil {
    70  		return false
    71  	}
    72  
    73  	return !strings.Contains(rel, "..")
    74  }
    75  
    76  func (p *path) MMDB() string {
    77  	return P.Join(p.homeDir, "Country.mmdb")
    78  }
    79  
    80  func (p *path) OldCache() string {
    81  	return P.Join(p.homeDir, ".cache")
    82  }
    83  
    84  func (p *path) Cache() string {
    85  	return P.Join(p.homeDir, "cache.db")
    86  }