-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
124 lines (96 loc) · 2.5 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
package main
import (
"fmt"
"net/http"
"io/ioutil"
"os"
"time"
"hacker-laws-cli/lib/repo"
"hacker-laws-cli/lib/parser"
)
func main() {
hackerLaws := repo.New()
arguments := os.Args[1:]
if len(arguments) == 0 {
DisplayHelp()
return
}
if arguments[0] == "help" {
DisplayHelp()
return
}
responseString := ParseHackerLawsRepo()
parser.Parse(responseString, &hackerLaws)
if arguments[0] == "list" {
hackerLaws.DisplayContentList()
return
}
if arguments[0] == "random" {
randomContent := hackerLaws.RandomContent()
randomContent.Display()
return
}
}
func DisplayHelp() {
fmt.Println("Options for the command:")
fmt.Println(PadLeft("help", " ", 12), " ", "To display argument list.")
fmt.Println(PadLeft("list", " ", 12), " ", "To list the laws and principles.")
fmt.Println(PadLeft("random", " ", 12), " ", "To display random law or principles.")
}
func PadLeft(str, pad string, lenght int) string {
for {
str = pad + str
if len(str) >= lenght {
return str[0:lenght]
}
}
}
func ParseHackerLawsRepo() string {
home, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
return ""
}
cacheFile := home + string(os.PathSeparator) + ".hlcache"
if FileExists(cacheFile) && FileUptoDate(cacheFile) {
content, err := ioutil.ReadFile(cacheFile)
if err != nil {
fmt.Println(err)
} else {
return string(content)
}
}
response, err := http.Get("https://raw.githubusercontent.com/dwmkerr/hacker-laws/master/README.md")
if err != nil {
fmt.Println(err)
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
return ""
}
responseString := string(responseData)
file, err := os.Create(cacheFile)
if err != nil {
fmt.Println(err)
return ""
}
file.WriteString(responseString)
return responseString
}
func FileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func FileUptoDate(filename string) bool {
info, _ := os.Stat(filename)
modifiedtime := info.ModTime()
return !IsOlderThanOneDay(modifiedtime)
}
func IsOlderThanOneDay(t time.Time) bool {
return time.Now().Sub(t) > 24*time.Hour
}