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