-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.go
More file actions
67 lines (60 loc) · 1.39 KB
/
Copy pathstore.go
File metadata and controls
67 lines (60 loc) · 1.39 KB
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
package main
import (
"bufio"
"encoding/json"
"os"
"path/filepath"
"time"
)
// Sample is one observation of the foreground window.
type Sample struct {
TS time.Time `json:"ts"`
App string `json:"app"`
Title string `json:"title"`
Idle bool `json:"idle"`
}
func dataDir() string {
return filepath.Join(baseDir(), "data")
}
func dayFile(day string) string {
return filepath.Join(dataDir(), day+".jsonl")
}
// appendSample appends one sample to the JSONL file for its local date.
func appendSample(s Sample) error {
if err := os.MkdirAll(dataDir(), 0o755); err != nil {
return err
}
f, err := os.OpenFile(dayFile(s.TS.Format("2006-01-02")), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer f.Close()
line, err := json.Marshal(s)
if err != nil {
return err
}
_, err = f.Write(append(line, '\n'))
return err
}
// readDay loads all samples recorded on a local date (YYYY-MM-DD).
func readDay(day string) ([]Sample, error) {
f, err := os.Open(dayFile(day))
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
defer f.Close()
var samples []Sample
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for sc.Scan() {
var s Sample
if err := json.Unmarshal(sc.Bytes(), &s); err != nil {
continue // skip torn/corrupt lines
}
samples = append(samples, s)
}
return samples, sc.Err()
}