-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime.go
179 lines (150 loc) · 4.24 KB
/
runtime.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
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"time"
)
// Stats holds the runtime statistics for different time periods.
type Stats struct {
Session float32 `json:"session"`
Daily map[string]float32 `json:"daily"`
CurrentDay string `json:"currentDay"`
Weekly map[string]float32 `json:"weekly"`
CurrentWeek string `json:"currentWeek"`
Monthly map[string]float32 `json:"monthly"`
CurrentMonth string `json:"currentMonth"`
Yearly map[string]float32 `json:"yearly"`
CurrentYear string `json:"currentYear"`
LastUpdate string `json:"lastUpdate"`
}
// RuntimeTracker handles program runtime tracking.
type RuntimeTracker struct {
statsFilePath string
startTime time.Time
stats Stats
}
// NewRuntimeTracker creates a new RuntimeTracker instance.
func NewRuntimeTracker(filename string) (*RuntimeTracker, error) {
cfgDir, err := GetConfigDir()
if err != nil {
return nil, err
}
if filename == "" {
filename = "stats.json"
}
path := filepath.Join(cfgDir, filename)
rt := &RuntimeTracker{
statsFilePath: path,
stats: Stats{
Session: 0.0,
Daily: make(map[string]float32),
Weekly: make(map[string]float32),
Monthly: make(map[string]float32),
Yearly: make(map[string]float32),
},
}
if _, err := os.Stat(rt.statsFilePath); errors.Is(err, os.ErrNotExist) {
rt.saveStats()
}
if err := rt.loadStats(); err != nil {
return nil, fmt.Errorf("failed to load stats: %w", err)
}
return rt, nil
}
// loadStats loads existing statistics.
func (rt *RuntimeTracker) loadStats() error {
data, err := os.ReadFile(rt.statsFilePath)
if err != nil {
return fmt.Errorf("failed to read config file: %w", err)
}
return json.Unmarshal(data, &rt.stats)
}
// saveStats saves current statistics.
func (rt *RuntimeTracker) saveStats() error {
if err := os.MkdirAll(filepath.Dir(rt.statsFilePath), 0755); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
data, err := json.MarshalIndent(rt.stats, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal stats: %w", err)
}
return os.WriteFile(rt.statsFilePath, data, 0644)
}
// Start begins tracking runtime.
func (rt *RuntimeTracker) Start() {
rt.startTime = time.Now()
}
// Stop ends tracking runtime and updates statistics.
func (rt *RuntimeTracker) Stop() error {
if rt.startTime.IsZero() {
return fmt.Errorf("tracking was not started")
}
endTime := time.Now()
runtime := float32(endTime.Sub(rt.startTime).Seconds())
// Format time periods
date := endTime.Format("2006-01-02")
// Get ISO week number
y, week := endTime.ISOWeek()
weekStr := fmt.Sprintf("%d-W%02d", y, week)
month := endTime.Format("2006-01")
year := endTime.Format("2006")
// Update statistics
rt.stats.Session = runtime
rt.stats.Daily[date] += runtime
rt.stats.CurrentDay = date
rt.stats.Weekly[weekStr] += runtime
rt.stats.CurrentWeek = weekStr
rt.stats.Monthly[month] += runtime
rt.stats.CurrentMonth = month
rt.stats.Yearly[year] += runtime
rt.stats.CurrentYear = year
rt.stats.LastUpdate = endTime.Format(time.RFC3339)
// Save updated stats
if err := rt.saveStats(); err != nil {
return fmt.Errorf("failed to save stats: %w", err)
}
// Reset start time
rt.startTime = time.Time{}
return nil
}
// CleanupOldData removes data older than the specified number of days
func (rt *RuntimeTracker) CleanupOldData(daysToKeep int) error {
cutoff := time.Now().AddDate(0, 0, -daysToKeep)
// Helper function to check if a date string is before cutoff
isOld := func(dateStr string) bool {
t, err := time.Parse("2006-01-02", dateStr[:10])
if err != nil {
return false
}
return t.Before(cutoff)
}
// Clean up each period
for date := range rt.stats.Daily {
if isOld(date) {
delete(rt.stats.Daily, date)
}
}
for week := range rt.stats.Weekly {
if isOld(week) {
delete(rt.stats.Weekly, week)
}
}
for month := range rt.stats.Monthly {
if isOld(month) {
delete(rt.stats.Monthly, month)
}
}
for year := range rt.stats.Yearly {
if isOld(year) {
delete(rt.stats.Yearly, year)
}
}
return rt.saveStats()
}
// GetStats returns the current statistics
func (rt *RuntimeTracker) GetStats() Stats {
return rt.stats
}