-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
188 lines (158 loc) · 3.76 KB
/
main.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"time"
)
const HostsFilePath = "/etc/hosts"
const BackupHostsFilePath = "/tmp/hostsBackup"
const HostsConfigFilePath = "hosts"
const IPAddress = "127.0.0.1"
func main() {
go getCancelSignal()
durationArg, err := getDurationArg()
if err != nil {
return
}
// Duplicate the current host file.
err = Copy(HostsFilePath, BackupHostsFilePath)
if err != nil {
log.Fatal(err)
}
defer rollBack()
HostConfig := openAndRead(HostsConfigFilePath)
BlockedHosts := formatHostsConfig(HostConfig)
// Append blocked websites to focus hosts file.
err = appendToHostsFile(HostsFilePath, BlockedHosts)
if err != nil {
log.Fatal(err)
}
flushCache()
fmt.Printf("Go focus!\n")
countDown(os.Stdout, durationArg)
fmt.Printf("\aGo take a break.\n") // \a is the bell system sound literal.
}
// rollBack will place back the original hosts file,
// remove the backup and flush the cache.
func rollBack() {
err := Copy(BackupHostsFilePath, HostsFilePath)
if err != nil {
log.Fatal(err)
}
err = os.Remove(BackupHostsFilePath)
if err != nil {
log.Fatal(err)
}
flushCache()
}
// flushCache on UNIX to refresh the hosts file.
func flushCache() {
exec.Command("dscacheutil", "-flushcache\n")
}
func formatMinutes(t time.Duration) string {
minutes := int(t.Minutes())
seconds := int(t.Seconds()) % 60
return fmt.Sprintf("%02d:%02d", minutes, seconds)
}
func countDown(w io.Writer, duration time.Duration) {
start := time.Now()
c := start.Add(duration)
for range time.Tick(1 * time.Second) {
timeRemaining := -time.Since(c)
_, err := fmt.Fprint(w, "", formatMinutes(timeRemaining), " \r")
if err != nil {
panic(err)
}
if timeRemaining <= 0 {
break
}
}
}
// Copy a source file to destination. Any existing file will be overwritten and will
// not copy file attributes.
func Copy(src, target string) error {
in, err := os.Open(src)
if err != nil {
log.Println("unable to open source file")
return err
}
defer in.Close()
out, err := os.Create(target)
if err != nil {
log.Println("unable to create target file")
return err
}
_, err = io.Copy(out, in)
if err != nil {
log.Println("unable to copy back original hosts file")
return err
}
err = out.Close()
if err != nil {
return err
}
return nil
}
func appendToHostsFile(name string, data string) error {
f, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(data)
content, _ := ioutil.ReadFile(name)
log.Println(string(content))
if err != nil {
return err
}
return nil
}
// formatHostsConfig creates a string block to append to /etc/hosts
func formatHostsConfig(HostUrls []string) string {
builder := strings.Builder{}
builder.WriteString("\n") // start on a newline
for _, e := range HostUrls {
_, err := builder.WriteString(fmt.Sprintf("%s %s\n", IPAddress, e))
if err != nil {
panic(err)
}
}
return builder.String()
}
// openAndRead will read a file and return the content separated in a slice.
func openAndRead(name string) []string {
content, err := ioutil.ReadFile(name)
if err != nil {
log.Fatalf("could not read file: %s", err)
}
return splitContent(content)
}
func splitContent(content []byte) []string {
return strings.Split(string(content), "\n")
}
// getCancelSignal catch user input ctrl+c
// putting back the hosts file in its original state
func getCancelSignal() {
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
fmt.Println("Are you sure?")
<-quit
log.Println("Timer has been cancelled.")
err := Copy(BackupHostsFilePath, HostsFilePath)
if err != nil {
panic(err)
}
err = os.Remove(BackupHostsFilePath)
if err != nil {
panic(err)
}
flushCache()
os.Exit(0)
}