-
Notifications
You must be signed in to change notification settings - Fork 0
/
section.go
116 lines (98 loc) · 2 KB
/
section.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
package counter
import (
"../filesystem"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"time"
)
func NewSection(username string, repository string) *Section {
c := &Section{
Username: username,
Repository: repository,
Total: 0,
CreatedAt: time.Now(),
Entries: make(map[string]*Entry),
}
_ = c.Load("")
return c
}
func (s *Section) GetKey() string {
return s.Username + "/" + s.Repository
}
func (s *Section) String() string {
dateFormat := "2006-01-02 15:04:05"
return strings.Join([]string{
s.Username,
s.Repository,
fmt.Sprintf("%d", s.Total),
s.CreatedAt.Format(dateFormat),
s.UpdatedAt.Format(dateFormat),
}, ",")
}
func (s *Section) GetToken() string {
h := sha256.New()
h.Write([]byte(s.GetKey()))
return fmt.Sprintf("%x", h.Sum(nil))
}
func (s *Section) AddEntry(entry *Entry, duration time.Duration) bool {
if _, ok := s.Entries[entry.Hash]; !ok {
s.Entries[entry.Hash] = entry
s.Increment()
return true
} else {
if time.Now().After(s.Entries[entry.Hash].Timestamp.Add(duration)) {
s.Entries[entry.Hash] = entry
s.Increment()
return true
}
}
return false
}
func (s *Section) Increment() {
s.Total += 1
s.UpdatedAt = time.Now()
}
func (s *Section) initFile(filename string) {
filesystem.CreateDirectory("data")
if len(filename) == 0 {
dir, _ := os.Getwd()
filename = path.Join(dir, "data", s.GetToken() + ".json")
_ = s.Load(filename)
}
s.File = filename
}
func (s *Section) Load(filename string) error {
s.initFile(filename)
if _, err := os.Stat(filename); err == nil {
content, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
err = json.Unmarshal(content, s)
if err != nil {
return err
}
} else {
_ = s.Save()
}
return nil
}
func (s *Section) Save() error {
if len(s.File) == 0 {
s.initFile("")
}
file, err := json.MarshalIndent(s, "", "\t")
if err != nil {
return err
}
err = ioutil.WriteFile(s.File, file, 0644)
if err != nil {
return err
}
return nil
}