gunk-dev/the-valley

log.go

source4cbb5ec9c5dbmain's published tip history
1.4 KiB
1package projectsync
2
3import (
4 "fmt"
5 "io"
6 "os"
7 "path/filepath"
8 "time"
9
10 "the-valley/flow/internal/location"
11)
12
13// LogPath returns the absolute path of the sync log new syncs append to
14// (location's SyncLog).
15func LogPath() (string, error) {
16 l, err := location.Host()
17 if err != nil {
18 return "", err
19 }
20 return l.SyncLog()
21}
22
23// WriteLog appends a single block of timestamped sync results to the klaus
24// sync log. The source argument tags where the sync was triggered from (e.g.
25// "session", "launch", "cli") so a tail of the log explains who started it.
26// Failures to write are swallowed — a background sync that can't log should
27// not affect the foreground caller.
28func WriteLog(source string, results []SyncResult) {
29 path, err := LogPath()
30 if err != nil {
31 return
32 }
33 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
34 return
35 }
36 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
37 if err != nil {
38 return
39 }
40 defer f.Close()
41 writeLog(f, source, time.Now(), results)
42}
43
44func writeLog(w io.Writer, source string, now time.Time, results []SyncResult) {
45 fmt.Fprintf(w, "[%s] sync source=%s projects=%d\n", now.UTC().Format(time.RFC3339), source, len(results))
46 for _, r := range results {
47 line := fmt.Sprintf(" %-20s %-14s %s", r.Name, r.Status, r.Branch)
48 if r.Detail != "" {
49 line += " " + r.Detail
50 }
51 fmt.Fprintln(w, line)
52 }
53}