Feature: can set specify config file path in cli (#360)

This commit is contained in:
gVisor bot 2019-10-14 18:11:22 +08:00
parent f7f76fb8b6
commit 69ecc51998
2 changed files with 35 additions and 16 deletions

View file

@ -11,32 +11,38 @@ const Name = "clash"
var Path *path var Path *path
type path struct { type path struct {
homedir string homeDir string
configFile string
} }
func init() { func init() {
homedir, err := os.UserHomeDir() homeDir, err := os.UserHomeDir()
if err != nil { if err != nil {
homedir, _ = os.Getwd() homeDir, _ = os.Getwd()
} }
homedir = P.Join(homedir, ".config", Name) homeDir = P.Join(homeDir, ".config", Name)
Path = &path{homedir: homedir} Path = &path{homeDir: homeDir, configFile: "config.yaml"}
} }
// SetHomeDir is used to set the configuration path // SetHomeDir is used to set the configuration path
func SetHomeDir(root string) { func SetHomeDir(root string) {
Path = &path{homedir: root} Path.homeDir = root
}
// SetConfig is used to set the configuration file
func SetConfig(file string) {
Path.configFile = file
} }
func (p *path) HomeDir() string { func (p *path) HomeDir() string {
return p.homedir return p.homeDir
} }
func (p *path) Config() string { func (p *path) Config() string {
return P.Join(p.homedir, "config.yaml") return p.configFile
} }
func (p *path) MMDB() string { func (p *path) MMDB() string {
return P.Join(p.homedir, "Country.mmdb") return P.Join(p.homeDir, "Country.mmdb")
} }

27
main.go
View file

@ -17,12 +17,14 @@ import (
) )
var ( var (
version bool version bool
homedir string homeDir string
configFile string
) )
func init() { func init() {
flag.StringVar(&homedir, "d", "", "set configuration directory") flag.StringVar(&homeDir, "d", "", "set configuration directory")
flag.StringVar(&configFile, "f", "", "specify configuration file")
flag.BoolVar(&version, "v", false, "show current version of clash") flag.BoolVar(&version, "v", false, "show current version of clash")
flag.Parse() flag.Parse()
} }
@ -33,12 +35,23 @@ func main() {
return return
} }
if homedir != "" { if homeDir != "" {
if !filepath.IsAbs(homedir) { if !filepath.IsAbs(homeDir) {
currentDir, _ := os.Getwd() currentDir, _ := os.Getwd()
homedir = filepath.Join(currentDir, homedir) homeDir = filepath.Join(currentDir, homeDir)
} }
C.SetHomeDir(homedir) C.SetHomeDir(homeDir)
}
if configFile != "" {
if !filepath.IsAbs(configFile) {
currentDir, _ := os.Getwd()
configFile = filepath.Join(currentDir, configFile)
}
C.SetConfig(configFile)
} else {
configFile := filepath.Join(C.Path.HomeDir(), C.Path.Config())
C.SetConfig(configFile)
} }
if err := config.Init(C.Path.HomeDir()); err != nil { if err := config.Init(C.Path.HomeDir()); err != nil {