Chore: refactoring code of config path

This commit is contained in:
Dreamacro
2018-10-14 21:22:58 +08:00
parent 64e3791654
commit 381f764507
5 changed files with 68 additions and 48 deletions

View File

@ -1,23 +1,5 @@
package constant
import (
"os"
"os/user"
"path"
log "github.com/sirupsen/logrus"
)
const (
Name = "clash"
)
var (
HomeDir string
ConfigPath string
MMDBPath string
)
type General struct {
Mode *string `json:"mode,omitempty"`
AllowLan *bool `json:"allow-lan,omitempty"`
@ -26,26 +8,3 @@ type General struct {
RedirPort *int `json:"redir-port,omitempty"`
LogLevel *string `json:"log-level,omitempty"`
}
func init() {
currentUser, err := user.Current()
if err != nil {
dir := os.Getenv("HOME")
if dir == "" {
log.Fatalf("Can't get current user: %s", err.Error())
}
HomeDir = dir
} else {
HomeDir = currentUser.HomeDir
}
dirPath := path.Join(HomeDir, ".config", Name)
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
if err := os.MkdirAll(dirPath, 0777); err != nil {
log.Fatalf("Can't create config directory %s: %s", dirPath, err.Error())
}
}
ConfigPath = path.Join(dirPath, "config.yml")
MMDBPath = path.Join(dirPath, "Country.mmdb")
}

49
constant/path.go Normal file
View File

@ -0,0 +1,49 @@
package constant
import (
"os"
"os/user"
P "path"
)
const Name = "clash"
// Path is used to get the configuration path
var Path *path
type path struct {
homedir string
}
func init() {
currentUser, err := user.Current()
var homedir string
if err != nil {
dir := os.Getenv("HOME")
if dir == "" {
dir, _ = os.Getwd()
}
homedir = dir
} else {
homedir = currentUser.HomeDir
}
homedir = P.Join(homedir, ".config", Name)
Path = &path{homedir: homedir}
}
// SetHomeDir is used to set the configuration path
func SetHomeDir(root string) {
Path = &path{homedir: root}
}
func (p *path) HomeDir() string {
return p.homedir
}
func (p *path) Config() string {
return P.Join(p.homedir, "config.yml")
}
func (p *path) MMDB() string {
return P.Join(p.homedir, "Country.mmdb")
}