-
Notifications
You must be signed in to change notification settings - Fork 1
/
switch.go
104 lines (91 loc) · 2.18 KB
/
switch.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"errors"
"fmt"
"github.com/urfave/cli"
"io"
"io/ioutil"
"log"
"os"
"path"
"strings"
)
func SwitchConfig(global bool, configs ...string) error {
configPaths := make([]string, len(configs))
for i, ele := range configs {
if strings.Contains(ele, ".") {
return errors.New("config name cannot contains \".\"")
}
configPaths[i] = GetConfigFullPath(ele, global)
}
hostsFile, err := os.OpenFile(GetHostFilename(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if os.IsExist(err) {
return errors.New("open hosts file failed\n" + err.Error())
}
defer hostsFile.Close()
// add head
hostsFile.WriteString("# ****************** SwitchHosts-go ******************")
FprintNewLine(hostsFile)
FprintNewLine(hostsFile)
// add global config at first
appDir := AppDir()
files, err := ioutil.ReadDir(appDir)
if err != nil {
panic(err)
}
for _, f := range files {
if f.IsDir() {
continue
}
if IsGlobalHostFile(f.Name()) {
file, err := os.Open(path.Join(appDir, f.Name()))
if os.IsExist(err) {
return errors.New("write " + path.Ext(f.Name()) + " failed")
}
io.Copy(hostsFile, file)
hostsFile.WriteString("\n\n")
file.Close()
}
}
// and then add normal configs
for _, filename := range configPaths {
if !PathExist(filename) {
fmt.Printf("Config file %s not exist, ignored\n", path.Ext(filename))
continue
}
file, err := os.Open(filename)
if os.IsExist(err) {
return errors.New("write " + path.Ext(filename) + " failed")
}
io.Copy(hostsFile, file)
hostsFile.WriteString("\n\n")
file.Close()
}
return nil
}
func OnSwitch(c *cli.Context) error {
global := c.GlobalBool(cliFlagGlobal)
if !c.Args().Present() {
return errors.New("env cannot be null")
}
configMap := map[string]bool{}
for _, ele := range c.Args() {
configMap[ele] = true
}
configArray := make([]string, len(configMap))
i := 0
for key := range configMap {
configArray[i] = key
i++
}
if global {
log.Println("global flag is ignored when switch configs")
}
return SwitchConfig(global, configArray...)
}
var switchCommand = cli.Command{
Name: "switch",
Aliases: []string{"s", "sw"},
Usage: "Switch to hosts",
Action: OnSwitch,
}