Files
LuPhoto/internal/watch/watch.go
T
2026-11-04 04:58:48 -08:00

131 lines
2.6 KiB
Go

package watch
import (
"context"
"errors"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/fsnotify/fsnotify"
)
const retryMissing = 5 * time.Second
func Ignored(name string) bool {
base := filepath.Base(name)
if base == "" || strings.HasPrefix(base, ".") || strings.HasPrefix(base, "~") || strings.HasSuffix(base, "~") {
return true
}
lower := strings.ToLower(base)
for _, suffix := range []string{".part", ".tmp", ".partial", ".crdownload", ".swp"} {
if strings.HasSuffix(lower, suffix) {
return true
}
}
return false
}
func Run(ctx context.Context, root string, debounce time.Duration, changed func(string), logger *log.Logger) error {
for {
info, err := os.Stat(root)
if err == nil && info.IsDir() {
break
}
logger.Printf("watch: %s is not a folder yet, retrying", root)
select {
case <-ctx.Done():
return nil
case <-time.After(retryMissing):
}
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
count, err := addTree(watcher, root)
if err != nil {
return err
}
logger.Printf("watch: %d folders under %s, debounce %s", count, root, debounce)
timer := time.NewTimer(time.Hour)
if !timer.Stop() {
<-timer.C
}
pending := ""
for {
select {
case <-ctx.Done():
timer.Stop()
return nil
case event, ok := <-watcher.Events:
if !ok {
return errors.New("watch: event channel closed")
}
if Ignored(event.Name) {
continue
}
if event.Has(fsnotify.Create) {
if info, err := os.Stat(event.Name); err == nil && info.IsDir() {
if _, err := addTree(watcher, event.Name); err != nil {
logger.Printf("watch: %v", err)
}
}
}
if event.Has(fsnotify.Chmod) && !event.Has(fsnotify.Write) {
continue
}
if pending == "" {
pending = event.Name
}
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer.Reset(debounce)
case <-timer.C:
if pending != "" {
reason := pending
pending = ""
changed(reason)
}
case err, ok := <-watcher.Errors:
if !ok {
return errors.New("watch: error channel closed")
}
logger.Printf("watch: %v", err)
}
}
}
func addTree(watcher *fsnotify.Watcher, root string) (int, error) {
count := 0
err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
if path == root {
return err
}
return nil
}
if !entry.IsDir() {
return nil
}
if path != root && Ignored(path) {
return filepath.SkipDir
}
if err := watcher.Add(path); err != nil {
return err
}
count++
return nil
})
return count, err
}