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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
|
package main
import (
"context"
"crypto/sha256"
"log"
"os"
"path/filepath"
tea "github.com/charmbracelet/bubbletea"
"github.com/fsnotify/fsnotify"
)
// fileChangedMsg indicates the watched file has been modified on disk.
// Sent by fsnotify watcher when file content changes.
type fileChangedMsg struct {
newHash [32]byte // SHA256 hash of the changed file content
}
// FileWatcher monitors a file for changes using fsnotify and SHA256 hashing.
// Detects actual content changes (not just metadata) and sends messages to Bubble Tea.
type FileWatcher struct {
originalHash [32]byte // SHA256 hash of file contents at load time (for change detection)
currentHash [32]byte // SHA256 hash of current file contents (updated by file watcher)
msgChan chan tea.Msg // Channel receiving file change notifications from fsnotify watcher
cancel context.CancelFunc // Function to cancel file watch goroutine
filepath string // Absolute path to the watched file
}
// NewFileWatcher creates a new file watcher for the given filepath.
// Returns the FileWatcher. Use fw.waitForMessage() to get a command that starts listening.
// The context is used to cancel the watcher goroutine when no longer needed.
func NewFileWatcher(ctx context.Context, filePath string) FileWatcher {
// Get absolute path
absPath, err := filepath.Abs(filePath)
if err != nil {
log.Printf("Warning: failed to get absolute path for watching: %v", err)
absPath = filePath
}
// Calculate initial hash
initialHash := calculateFileHash(absPath)
// Create cancellable context for the watcher
watchCtx, cancel := context.WithCancel(ctx)
// Start the file watcher goroutine
msgChan := startFileWatcher(watchCtx, absPath)
return FileWatcher{
originalHash: initialHash,
currentHash: initialHash,
msgChan: msgChan,
cancel: cancel,
filepath: absPath,
}
}
// Update handles file change messages and updates the current hash.
// Returns true if the message was handled, false otherwise.
// Also returns a tea.Cmd to continue listening for file changes.
func (fw *FileWatcher) Update(msg tea.Msg) (bool, tea.Cmd) {
switch msg := msg.(type) {
case fileChangedMsg:
// File has changed on disk - update current hash
fw.currentHash = msg.newHash
// Return command to wait for next file change notification
return true, fw.waitForMessage()
}
return false, nil
}
// HasChanged returns true if the file content has changed since the watcher was created.
// Compares the current hash with the original hash.
func (fw FileWatcher) HasChanged() bool {
return fw.currentHash != fw.originalHash
}
// Stop cancels the file watcher goroutine and cleans up resources.
func (fw *FileWatcher) Stop() {
if fw.cancel != nil {
fw.cancel()
}
}
// ResetBaseline updates both the original and current hash to the given hash.
// Used when reloading a file to establish a new baseline for change detection.
func (fw *FileWatcher) ResetBaseline(newHash [32]byte) {
fw.originalHash = newHash
fw.currentHash = newHash
}
// waitForMessage returns a tea.Cmd that waits for the next file change message.
func (fw FileWatcher) waitForMessage() tea.Cmd {
return func() tea.Msg {
return <-fw.msgChan
}
}
// calculateFileHash reads a file and returns its SHA256 hash.
// Returns a zero hash if the file cannot be read.
func calculateFileHash(filepath string) [32]byte {
content, err := os.ReadFile(filepath)
if err != nil {
return [32]byte{} // Return zero hash on error
}
return sha256.Sum256(content)
}
// startFileWatcher starts watching a file for changes and sends fileChangedMsg when changes occur.
// Uses fsnotify to watch both the file and its parent directory (for atomic writes).
// Calculates SHA256 hash to detect actual content changes vs. metadata changes.
func startFileWatcher(ctx context.Context, filename string) chan tea.Msg {
msgChan := make(chan tea.Msg)
go func() {
defer close(msgChan)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Printf("Warning: failed to create file watcher: %v", err)
return
}
defer watcher.Close()
// Get absolute path for watching
absPath, err := filepath.Abs(filename)
if err != nil {
log.Printf("Warning: failed to get absolute path for watching: %v", err)
return
}
// Watch both the file and its parent directory
// This catches atomic writes (temp file → rename in directory)
if err := watcher.Add(absPath); err != nil {
log.Printf("Warning: failed to watch file: %v", err)
return
}
parentDir := filepath.Dir(absPath)
if err := watcher.Add(parentDir); err != nil {
log.Printf("Warning: failed to watch parent directory: %v", err)
return
}
for {
select {
case <-ctx.Done():
return
case event, ok := <-watcher.Events:
if !ok {
return
}
// Only process events for our specific file (ignore other files in directory)
if event.Name != absPath {
continue
}
// Watch for Write, Create, and Rename events (covers most editor save patterns)
// Many editors use atomic writes: write to temp file, then rename to target
if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) {
// Hash file to detect actual changes
fileContent, err := os.ReadFile(absPath)
if err != nil {
continue
}
newHash := sha256.Sum256(fileContent)
msgChan <- fileChangedMsg{newHash: newHash}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Printf("Warning: file watcher error: %v", err)
}
}
}()
return msgChan
}
|