-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogfile.go
More file actions
78 lines (71 loc) · 1.77 KB
/
logfile.go
File metadata and controls
78 lines (71 loc) · 1.77 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
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
)
type LogEntry struct {
Contact string `json:"contact"`
Path string `json:"path,omitempty"`
Time time.Time `json:"time"`
Note string `json:"note,omitempty"`
}
func logFilePath() string {
return filepath.Join(configDir(), "log.jsonl")
}
func appendLog(entry LogEntry) error {
path := logFilePath()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return fmt.Errorf("creating log directory: %w", err)
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return fmt.Errorf("opening log file: %w", err)
}
defer f.Close()
data, err := json.Marshal(entry)
if err != nil {
return fmt.Errorf("marshaling log entry: %w", err)
}
if _, err := f.Write(append(data, '\n')); err != nil {
return fmt.Errorf("writing log entry: %w", err)
}
return nil
}
func readLog() ([]LogEntry, error) {
path := logFilePath()
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("opening log file: %w", err)
}
defer f.Close()
var entries []LogEntry
scanner := bufio.NewScanner(f)
for scanner.Scan() {
var entry LogEntry
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
continue // skip malformed lines
}
entries = append(entries, entry)
}
return entries, scanner.Err()
}
// lastContactTime returns the most recent log time keyed by both contact name and path.
func lastContactTime(entries []LogEntry) map[string]time.Time {
last := make(map[string]time.Time)
for _, e := range entries {
if e.Time.After(last[e.Contact]) {
last[e.Contact] = e.Time
}
if e.Path != "" && e.Time.After(last[e.Path]) {
last[e.Path] = e.Time
}
}
return last
}