fix(watch): watch for dir instead of file to work on all scenarios (#734)

Co-authored-by: Andrey Nering <andreynering@users.noreply.github.com>
This commit is contained in:
Ktrod 2025-04-02 08:47:04 -04:00 committed by GitHub
commit 05872a506a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -3,7 +3,6 @@ package ui
import (
"fmt"
"math"
"os"
"path/filepath"
"strings"
"time"
@ -477,44 +476,48 @@ func (m *pagerModel) initWatcher() {
}
func (m *pagerModel) watchFile() tea.Msg {
path := m.relFilePath()
dir := m.localDir()
if err := m.watcher.Add(path); err != nil {
log.Error("error adding file to fsnotify watcher", "error", err)
if err := m.watcher.Add(dir); err != nil {
log.Error("error adding dir to fsnotify watcher", "error", err)
return nil
}
log.Info("fsnotify watching file", "file", path)
log.Info("fsnotify watching dir", "dir", dir)
for {
select {
case event, ok := <-m.watcher.Events:
if !ok || !event.Has(fsnotify.Write) {
if !ok || event.Name != m.currentDocument.localPath {
continue
}
log.Debug("fsnotify event", "file", path, "event", event.Op)
if !event.Has(fsnotify.Write) && !event.Has(fsnotify.Create) {
continue
}
log.Debug("fsnotify event", "file", event.Name, "event", event.Op)
return reloadMsg{}
case err, ok := <-m.watcher.Errors:
if !ok {
continue
}
log.Debug("fsnotify error", "file", path, "error", err)
log.Debug("fsnotify error", "dir", dir, "error", err)
}
}
}
func (m *pagerModel) unwatchFile() {
path := m.relFilePath()
dir := m.localDir()
err := m.watcher.Remove(path)
err := m.watcher.Remove(dir)
if err == nil {
log.Debug("fsnotify file unwatched", "file", path)
log.Debug("fsnotify dir unwatched", "dir", dir)
} else {
log.Error("fsnotify fail to unwatch file", "file", path, "error", err)
log.Error("fsnotify fail to unwatch dir", "dir", dir, "error", err)
}
}
func (m *pagerModel) relFilePath() string {
wd, _ := os.Getwd()
return stripAbsolutePath(m.currentDocument.localPath, wd)
func (m *pagerModel) localDir() string {
return filepath.Dir(m.currentDocument.localPath)
}