-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterm2_bg.go
More file actions
78 lines (67 loc) · 2.06 KB
/
iterm2_bg.go
File metadata and controls
78 lines (67 loc) · 2.06 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 (
"fmt"
"io"
"os"
"path/filepath"
)
const iterm2BGDir = "/tmp/dev-image-chat-bg"
// ITerm2BGPath returns the background image path for a given project key and slot.
func ITerm2BGPath(projectKey string, slot int) string {
return filepath.Join(iterm2BGDir, fmt.Sprintf("%s_%d.png", projectKey, slot))
}
// chooseSlot picks the slot to write next by selecting the older of the two files.
// If neither exists, returns 0.
func chooseSlot(projectKey string) int {
info0, err0 := os.Stat(ITerm2BGPath(projectKey, 0))
info1, err1 := os.Stat(ITerm2BGPath(projectKey, 1))
switch {
case err0 != nil && err1 != nil:
return 0 // neither exists
case err0 != nil:
return 0 // slot 0 doesn't exist, write there
case err1 != nil:
return 1 // slot 1 doesn't exist, write there
default:
// Both exist — overwrite the older one
if info0.ModTime().Before(info1.ModTime()) {
return 0
}
return 1
}
}
// CopyImageForProject copies the generated image to a per-project path,
// alternating between two slots so that iTerm2 detects the path change
// and reloads the image.
func CopyImageForProject(srcPath, projectKey string) error {
if err := os.MkdirAll(iterm2BGDir, 0700); err != nil {
return fmt.Errorf("failed to create bg dir: %w", err)
}
src, err := os.Open(srcPath)
if err != nil {
return fmt.Errorf("failed to open source image: %w", err)
}
defer src.Close()
slot := chooseSlot(projectKey)
dstPath := ITerm2BGPath(projectKey, slot)
dst, err := os.CreateTemp(iterm2BGDir, "tmp-*.png")
if err != nil {
return fmt.Errorf("failed to create temp file: %w", err)
}
tmpPath := dst.Name()
if _, err := io.Copy(dst, src); err != nil {
_ = dst.Close()
os.Remove(tmpPath)
return fmt.Errorf("failed to copy image: %w", err)
}
if err := dst.Close(); err != nil {
os.Remove(tmpPath)
return fmt.Errorf("failed to close temp file: %w", err)
}
// Atomic rename to avoid partial reads by the watcher.
if err := os.Rename(tmpPath, dstPath); err != nil {
os.Remove(tmpPath)
return fmt.Errorf("failed to rename temp file: %w", err)
}
return nil
}