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
|
package tracker
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/spf13/afero"
)
var (
ErrEntryAlreadyExists = fmt.Errorf("entry with this title already exists")
ErrActivityNotFound = fmt.Errorf("there is no activity with given id")
)
type Tracker struct {
fs afero.Fs
document *Document
}
const FileName = "gotrack.json"
func New(fs afero.Fs) (*Tracker, error) {
t := &Tracker{fs: fs}
if err := t.load(); err != nil {
return nil, err
}
return t, nil
}
func (t *Tracker) Add(title string, tags []string, contexts []string) (int, error) {
for _, activity := range t.document.Activities {
if strings.ToLower(strings.Trim(activity.Title, " ")) == strings.ToLower(strings.Trim(title, " ")) {
return 0, ErrEntryAlreadyExists
}
}
activity := Activity{
ID: t.document.LastKey + 1,
Title: title,
Tags: tags,
Context: contexts,
Spans: []*Span{},
}
t.document = &Document{
LastKey: activity.ID,
Activities: append(t.document.Activities, &activity),
}
return t.document.LastKey, t.save()
}
func (t *Tracker) Start(id int, comment string) error {
if err := t.Stop(id); err != nil {
return err
}
span := &Span{
Start: time.Now(),
Comment: comment,
}
activity := t.Activity(id)
activity.Spans = append(activity.Spans, span)
return t.save()
}
func (t *Tracker) Stop(id int) error {
activity := t.Activity(id)
if activity == nil {
return ErrActivityNotFound
}
if span := activity.Started(); span != nil {
t := time.Now()
span.Stop = &t
}
return t.save()
}
func (t *Tracker) List(all bool) []*Activity {
if all {
return t.document.Activities
}
return filterActivities(t.document.Activities, func(a *Activity) bool {
return a.Started() != nil
})
}
func (t *Tracker) Activity(id int) *Activity {
for _, activity := range t.document.Activities {
if activity.ID == id {
return activity
}
}
return nil
}
func (t *Tracker) load() (err error) {
t.document = new(Document)
f, err := t.fs.Open(FileName)
defer func() {
err = f.Close()
}()
if err != nil {
f, err = t.fs.Create(FileName)
if err != nil {
return err
}
return nil
}
return json.NewDecoder(f).Decode(t.document)
}
func (t *Tracker) save() (err error) {
f, err := t.fs.Create(FileName)
if err != nil {
return err
}
defer func() {
err = f.Close()
}()
return json.NewEncoder(f).Encode(t.document)
}
func filterActivities(list []*Activity, filter func(activity *Activity) bool) []*Activity {
var filtered []*Activity
for _, activity := range list {
if filter(activity) {
filtered = append(filtered, activity)
}
}
return filtered
}
|