Skip to content
This repository was archived by the owner on Feb 3, 2023. It is now read-only.

Commit 17fd588

Browse files
committed
add base host
1 parent 16509da commit 17fd588

File tree

10 files changed

+103
-46
lines changed

10 files changed

+103
-46
lines changed

cmd/root.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ var rootCmd = &cobra.Command{
1717
func Execute() {
1818
rootCmd.AddCommand(listCmd)
1919
rootCmd.AddCommand(editCmd)
20-
rootCmd.AddCommand(applyCmd)
20+
rootCmd.AddCommand(useCmd)
2121
rootCmd.AddCommand(newCmd)
2222
rootCmd.AddCommand(renameCmd)
2323
rootCmd.AddCommand(sysCmd)

cmd/use.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,18 @@ import (
1010
)
1111

1212
var (
13-
applyCmd = &cobra.Command{
13+
useSimulateFlag bool
14+
15+
useCmd = &cobra.Command{
1416
Use: "use",
15-
Short: "apply group host to system host",
17+
Short: "use group host as system host",
1618
Args: cobra.ExactArgs(1),
1719
Run: func(cmd *cobra.Command, args []string) {
18-
host.Manager.ApplyGroup(args[0])
20+
host.Manager.ApplyGroup(args[0], useSimulateFlag)
1921
},
2022
}
2123
)
24+
25+
func init() {
26+
useCmd.PersistentFlags().BoolVarP(&useSimulateFlag, "simulate", "s", false, "just print host content")
27+
}

conf/const.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,23 @@ import (
66
)
77

88
const (
9-
SepGroupInFile = "_"
10-
SepGroupInCmd = ","
11-
TmpCombinedHost = ".tmp_combined"
9+
SepGroupInFile = "_"
10+
SepGroupInCmd = ","
11+
TmpCombinedHost = ".tmp_combined"
12+
BaseHostFileName = "base"
1213
)
1314

1415
var (
15-
BaseHostFile string
1616
BaseDir string
17-
ConfigFile string
17+
BaseHostFile string
1818
)
1919

2020
func init() {
2121
curr, err := user.Current()
2222
if err != nil {
2323
panic(err)
2424
}
25+
2526
BaseDir = filepath.Join(curr.HomeDir, ".gohost")
26-
BaseHostFile = filepath.Join(BaseDir, "base")
27-
ConfigFile = filepath.Join(BaseDir, ".conf")
27+
BaseHostFile = filepath.Join(BaseDir, "."+BaseHostFileName)
2828
}

display/display.go renamed to display/logger.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ package display
66

77
import (
88
"fmt"
9-
"github.com/olekukonko/tablewriter"
109
"os"
1110
)
1211

@@ -29,9 +28,7 @@ func ErrExit(err error) {
2928
}
3029
}
3130

32-
func Table(header []string, data [][]string) {
33-
table := tablewriter.NewWriter(os.Stdout)
34-
table.SetHeader(header)
35-
table.AppendBulk(data)
36-
table.Render()
31+
func Panic(msg string, err error) {
32+
fmt.Printf("[panic] %s\n", msg)
33+
ErrExit(err)
3734
}

display/table.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/*
2+
@Author: ingbyr
3+
*/
4+
5+
package display
6+
7+
import (
8+
"github.com/olekukonko/tablewriter"
9+
"os"
10+
)
11+
12+
func Table(header []string, data [][]string) {
13+
table := tablewriter.NewWriter(os.Stdout)
14+
table.SetHeader(header)
15+
table.AppendBulk(data)
16+
table.Render()
17+
}

editor/vim.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,9 @@ import (
66
"os/exec"
77
)
88

9-
const (
10-
vim = "vim"
11-
noSwap = "-n"
12-
)
13-
149
func OpenByVim(filePath string) error {
10+
const vim = "vim"
11+
const noSwap = "-n"
1512
if _, err := exec.LookPath(vim); err != nil {
1613
return fmt.Errorf("please install vim before editing file\n")
1714
}

host/manger.go

Lines changed: 62 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -19,32 +19,45 @@ import (
1919
)
2020

2121
type manager struct {
22-
BaseDir string
23-
BaseHostFile string
24-
Hosts map[string]*Host
25-
Groups map[string][]*Host
22+
BaseDir string
23+
BaseHost *Host
24+
Hosts map[string]*Host
25+
Groups map[string][]*Host
2626
}
2727

2828
var Manager *manager
2929

3030
func init() {
31+
// init manager
3132
Manager = &manager{
32-
BaseDir: conf.BaseDir,
33-
BaseHostFile: conf.BaseHostFile,
34-
Hosts: map[string]*Host{},
35-
Groups: map[string][]*Host{},
33+
BaseDir: conf.BaseDir,
34+
BaseHost: &Host{
35+
Name: conf.BaseHostFileName,
36+
FileName: conf.BaseHostFileName,
37+
Path: conf.BaseHostFile,
38+
Groups: nil,
39+
},
40+
Hosts: map[string]*Host{},
41+
Groups: map[string][]*Host{},
3642
}
43+
44+
// create base dir
3745
if _, err := os.Stat(Manager.BaseDir); os.IsNotExist(err) {
3846
if err := os.Mkdir(Manager.BaseDir, os.ModePerm); err != nil {
39-
panic("can not create dir " + Manager.BaseDir)
47+
display.Panic("can not create dir "+Manager.BaseDir, err)
4048
}
41-
fmt.Println("create host dir", Manager.BaseDir)
4249
}
43-
if _, err := os.Stat(Manager.BaseHostFile); os.IsNotExist(err) {
44-
if _, err := os.Create(Manager.BaseHostFile); err != nil {
45-
panic("can not create base host file")
50+
51+
// create base host file
52+
if _, err := os.Stat(Manager.BaseHost.Path); os.IsNotExist(err) {
53+
var content bytes.Buffer
54+
content.WriteString("127.0.0.1 localhost")
55+
content.WriteByte(NewLine)
56+
content.WriteString("::1 localhost")
57+
content.WriteByte(NewLine)
58+
if err := os.WriteFile(Manager.BaseHost.Path, content.Bytes(), 0644); err != nil {
59+
display.Panic("can not create base host file", err)
4660
}
47-
fmt.Println("create base host file", Manager.BaseHostFile)
4861
}
4962
Manager.LoadHosts()
5063
}
@@ -54,8 +67,9 @@ func (m *manager) LoadHosts() {
5467
if err != nil {
5568
display.ErrExit(fmt.Errorf("failed to load gohost dir"))
5669
}
70+
// load host files
5771
for _, file := range files {
58-
// skip dir and .* files
72+
// skip dir and files started with '.'
5973
if file.IsDir() || strings.HasPrefix(file.Name(), ".") {
6074
continue
6175
}
@@ -70,7 +84,6 @@ func (m *manager) PrintGroups() {
7084
fmt.Println("no host group")
7185
return
7286
}
73-
7487
header := []string{"Group", "Hosts"}
7588
data := make([][]string, 0, len(m.Groups))
7689
for group, hosts := range m.Groups {
@@ -145,9 +158,11 @@ func (m *manager) AddGroup(hostName string, groups []string) {
145158
}
146159

147160
func (m *manager) CreateNewHost(name string, groups []string) {
161+
if name == m.BaseHost.Name {
162+
display.ErrExit(fmt.Errorf("host file '%s' already exists\n", name))
163+
}
148164
if _, exist := m.Hosts[name]; exist {
149-
display.ErrExit(fmt.Errorf("host file '%s' is existed\n", name))
150-
return
165+
display.ErrExit(fmt.Errorf("host file '%s' already exists\n", name))
151166
}
152167
filePath := m.fullFilePath(m.hostName(name, groups))
153168
err := editor.OpenByVim(filePath)
@@ -172,6 +187,9 @@ func (m *manager) DeleteHostsByNames(hostNames []string) {
172187
}
173188

174189
func (m *manager) ChangeHostName(hostName string, newHostName string) {
190+
if hostName == m.BaseHost.Name || newHostName == m.BaseHost.Name {
191+
display.ErrExit(fmt.Errorf("can not change base host file name"))
192+
}
175193
h := m.mustHost(hostName)
176194
_newHostName := m.hostName(newHostName, h.Groups)
177195
if err := os.Rename(h.Path, m.fullFilePath(_newHostName)); err != nil {
@@ -187,28 +205,41 @@ func (m *manager) EditHostFile(hostName string) {
187205
}
188206
}
189207

190-
func (m *manager) ApplyGroup(group string) {
208+
func (m *manager) ApplyGroup(group string, simulate bool) {
191209
hosts, exist := m.Groups[group]
192210
if !exist {
193211
display.ErrExit(fmt.Errorf("not found group '%s'", group))
194212
return
195213
}
214+
hosts = append(hosts, m.BaseHost)
196215
combinedHostContent := m.combineHosts(hosts, "# Auto generated from group "+group)
216+
217+
// just print
218+
if simulate {
219+
fmt.Println(string(combinedHostContent))
220+
return
221+
}
222+
223+
// write to tmp file
197224
combinedHost := m.fullFilePath(conf.TmpCombinedHost)
198225
if err := ioutil.WriteFile(combinedHost, combinedHostContent, 0664); err != nil {
199226
display.ErrExit(err)
200227
}
201-
if err := os.Rename(combinedHost, sysHost); err != nil {
228+
229+
// replace system host
230+
if err := os.Rename(combinedHost, SysHost); err != nil {
202231
display.ErrExit(err)
203232
}
204233
fmt.Printf("applied group '%s' to system host:\n", group)
234+
235+
// display system host
205236
m.PrintSysHost(10)
206237
}
207238

208239
func (m *manager) PrintSysHost(max int) {
209-
host, err := os.Open(sysHost)
240+
host, err := os.Open(SysHost)
210241
if err != nil {
211-
panic(err)
242+
display.Panic("can not read system host file", err)
212243
}
213244
defer host.Close()
214245
scanner := bufio.NewScanner(host)
@@ -226,6 +257,10 @@ func (m *manager) PrintSysHost(max int) {
226257
}
227258

228259
func (m *manager) host(hostName string) (*Host, bool) {
260+
if hostName == m.BaseHost.Name {
261+
return m.BaseHost, true
262+
}
263+
229264
host, exist := m.Hosts[hostName]
230265
if !exist {
231266
display.ErrExit(fmt.Errorf("host file '%s' is not existed\n", hostName))
@@ -235,6 +270,10 @@ func (m *manager) host(hostName string) (*Host, bool) {
235270
}
236271

237272
func (m *manager) mustHost(hostName string) *Host {
273+
if hostName == m.BaseHost.Name {
274+
return m.BaseHost
275+
}
276+
238277
host, exist := m.Hosts[hostName]
239278
if !exist {
240279
display.ErrExit(fmt.Errorf("host file '%s' is not existed\n", hostName))
@@ -293,7 +332,7 @@ func (m *manager) combineHosts(hosts []*Host, head string) []byte {
293332
for _, host := range hosts {
294333
file, err := os.Open(host.Path)
295334
if err != nil {
296-
panic(err)
335+
display.Panic("can not combine host", err)
297336
}
298337
scanner := bufio.NewScanner(file)
299338
b.WriteString("# Host section from " + host.Name + "\n")

host/unix.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@
77
package host
88

99
const (
10-
sysHost = "/etc/hosts"
10+
SysHost = "/etc/hosts"
11+
NewLine = '\n'
1112
)
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)