-
Notifications
You must be signed in to change notification settings - Fork 8
/
remove.go
108 lines (91 loc) · 2.23 KB
/
remove.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
105
106
107
108
package cmd
import (
"errors"
"net"
"strings"
"github.com/goodhosts/hostsfile"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
func Remove() *cli.Command {
return &cli.Command{
Name: "remove",
Aliases: []string{"rm", "r"},
Usage: "Remove ip or host(s) if exists",
Action: remove,
ArgsUsage: "[IP|HOST] or [IP] [HOST] ([HOST]...)",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "clean",
Aliases: []string{"c"},
Usage: "Clean the hostsfile after adding an entry. See clean command for more details",
},
&cli.BoolFlag{
Name: "dry-run",
Usage: "Dry run only, will output contents of the new hostsfile without writing the changes.",
},
},
}
}
func remove(c *cli.Context) error {
args := c.Args()
if args.Len() == 0 {
return errors.New("no input")
}
hf, err := loadHostsfile(c, false)
if err != nil {
return err
}
if args.Len() == 1 { //could be ip or hostname
return processSingleArg(hf, args.Slice()[0])
}
uniqueHosts := map[string]bool{}
var hostEntries []string
for i := 1; i < args.Len(); i++ {
uniqueHosts[args.Slice()[i]] = true
}
for key := range uniqueHosts {
hostEntries = append(hostEntries, key)
}
if net.ParseIP(args.Slice()[0]) != nil {
if hf.HasIP(args.Slice()[0]) {
err = hf.Remove(args.Slice()[0], hostEntries...)
if err != nil {
return err
}
}
} else {
hostEntries = append([]string{args.Slice()[0]}, hostEntries...)
for _, value := range hostEntries {
if err := hf.RemoveByHostname(value); err != nil {
return err
}
}
}
if c.Bool("clean") {
hf.Clean()
}
if c.Bool("dry-run") {
logrus.Debugln("performing a dry run, writing output")
outputHostsfile(hf, true)
return debugFooter(c)
}
logrus.Debugln("flushing hosts file to disk")
if err := hf.Flush(); err != nil {
return cli.Exit(err.Error(), 2)
}
logrus.Infof("entry removed: %s\n", strings.Join(hostEntries, " "))
return debugFooter(c)
}
func processSingleArg(hf *hostsfile.Hosts, arg string) error {
if net.ParseIP(arg) != nil {
logrus.Infof("removing ip %s\n", arg)
hf.RemoveByIP(arg)
return hf.Flush()
}
logrus.Infof("removing hostname %s\n", arg)
if err := hf.RemoveByHostname(arg); err != nil {
return err
}
return hf.Flush()
}