-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.go
83 lines (72 loc) · 1.78 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"os"
"os/user"
"path"
"strings"
)
const _configDir = ".config"
const _appDir = "SwitchHosts-Go"
const _globalHostPrefix = "g."
const _normalHostPrefix = "n."
const emptyString = ""
const cliFlagGlobal = "global"
func PathExist(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return true
}
// get SwitchHosts-Go's home directory
func AppDir() string {
curUser, err := user.Current()
if err != nil {
panic(err)
}
userHomeDir := curUser.HomeDir
appDir := path.Join(userHomeDir, _configDir, _appDir)
if _, err := os.Stat(_configDir); os.IsNotExist(err) {
err = os.MkdirAll(appDir, os.ModePerm)
if os.IsExist(err) {
panic(err)
}
}
return appDir
}
func IsGlobalHostFile(filename string) bool {
return strings.HasPrefix(filename, _globalHostPrefix)
}
func IsNormalHostFile(filename string) bool {
return strings.HasPrefix(filename, _normalHostPrefix)
}
func GetConfigFilename(filename string) (bool, string) {
if IsGlobalHostFile(filename) {
return true, strings.Replace(filename, _globalHostPrefix, emptyString, 1)
} else if IsNormalHostFile(filename) {
return false, strings.Replace(filename, _normalHostPrefix, emptyString, 1)
}
return false, emptyString
}
func GetConfigFullPath(name string, global bool) string {
appDir := AppDir()
var fullPath string
if global {
fullPath = path.Join(appDir, _globalHostPrefix+name)
} else {
fullPath = path.Join(appDir, _normalHostPrefix+name)
}
return fullPath
}
func DelHostFileByName(name string, global bool) error {
fullPath := GetConfigFullPath(name, global)
return os.Remove(fullPath)
}
func IsConfigExist(name string, global bool) bool {
fullPath := GetConfigFullPath(name, global)
exists := PathExist(fullPath)
return exists
}