-
Notifications
You must be signed in to change notification settings - Fork 8
/
clean.go
94 lines (87 loc) · 2.18 KB
/
clean.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
package cmd
import (
"github.com/goodhosts/hostsfile"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
func Clean() *cli.Command {
return &cli.Command{
Name: "clean",
Aliases: []string{"cl"},
Usage: "Clean the hostsfile by doing: remove dupe IPs, for each IPs remove dupe hosts and sort, sort all IPs, split hosts per OS limitations",
Action: clean,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "dry-run",
Usage: "Dry run only, will output contents of the cleaned hostsfile without writing the changes",
},
&cli.BoolFlag{
Name: "all",
Usage: "Perform all Cleanup Jobs",
Aliases: []string{"A"},
},
&cli.BoolFlag{
Name: "remove-duplicate-ips",
Usage: "Remove all duplicate ips",
Aliases: []string{"rdi"},
},
&cli.BoolFlag{
Name: "remove-duplicate-hosts",
Usage: "Remove all duplicate hosts",
Aliases: []string{"rdh"},
},
&cli.BoolFlag{
Name: "sort-hosts",
Usage: "Sort each ip's hosts alphabetically",
Aliases: []string{"sh"},
},
&cli.BoolFlag{
Name: "sort-ips",
Usage: "Sort all ips numerically",
Aliases: []string{"si"},
},
&cli.IntFlag{
Name: "hosts-per-line",
Usage: "Number of hosts allowed per line",
Value: hostsfile.HostsPerLine,
Aliases: []string{"hpl"},
},
},
}
}
func clean(c *cli.Context) error {
h, err := loadHostsfile(c, false)
if err != nil {
return err
}
if c.Int("hosts-per-line") != hostsfile.HostsPerLine {
hostsfile.HostsPerLine = c.Int("hosts-per-line")
}
if c.Bool("all") {
h.Clean()
} else {
if c.Bool("remove-duplicate-ips") {
h.CombineDuplicateIPs()
}
if c.Bool("remove-duplicate-hosts") {
h.RemoveDuplicateHosts()
}
if c.Bool("sort-hosts") {
h.SortHosts()
}
if c.Bool("sort-ips") {
h.SortIPs()
}
// needed for windows for 9/line, -1 default for linux will noop but if passed by cli we will run
h.HostsPerLine(hostsfile.HostsPerLine)
}
if c.Bool("dry-run") {
logrus.Debugln("performing a dry run, writing output")
outputHostsfile(h, true)
return debugFooter(c)
}
if err := h.Flush(); err != nil {
return cli.Exit(err.Error(), 2)
}
return debugFooter(c)
}