gosuki/watcher.go

89 lines
1.5 KiB
Go
Raw Normal View History

2017-10-20 10:51:56 +00:00
package main
import (
"database/sql"
2017-10-20 10:51:56 +00:00
"log"
"path"
"time"
2017-10-20 10:51:56 +00:00
"github.com/fsnotify/fsnotify"
)
2017-11-16 14:46:06 +00:00
type bMarkTypes int
const (
2017-11-16 14:46:06 +00:00
Chrome bMarkTypes = iota
Firefox
)
type bookmarkWatcher struct {
watcher *fsnotify.Watcher
baseDir string
bkFile string
parseFunc func(*bookmarkWatcher)
bufferDB *sql.DB
}
func (bw *bookmarkWatcher) Close() error {
if err := bw.watcher.Close(); err != nil {
return err
}
return nil
}
2017-11-16 14:46:06 +00:00
func (bw *bookmarkWatcher) Init(basedir string, bkfile string, bkType bMarkTypes) *bookmarkWatcher {
var err error
bw.baseDir = basedir
bw.bkFile = bkfile
bw.watcher, err = fsnotify.NewWatcher()
logPanic(err)
switch bkType {
case Chrome:
bw.parseFunc = googleParseBookmarks
}
return bw
}
func (bw *bookmarkWatcher) Start() error {
if err := bw.watcher.Add(bw.baseDir); err != nil {
return err
}
go bWatcherThread(bw, bw.parseFunc)
return nil
}
func bWatcherThread(bw *bookmarkWatcher, parseFunc func(bw *bookmarkWatcher)) {
bookmarkPath := path.Join(bw.baseDir, bw.bkFile)
debugPrint("watching %s", bookmarkPath)
for {
select {
case event := <-bw.watcher.Events:
2017-10-20 10:51:56 +00:00
if event.Op&fsnotify.Create == fsnotify.Create &&
event.Name == bookmarkPath {
2017-10-20 10:51:56 +00:00
2017-11-16 14:43:09 +00:00
debugPrint("event: %v | eventName: %v", event.Op, event.Name)
debugPrint("modified file: %s", event.Name)
start := time.Now()
parseFunc(bw)
elapsed := time.Since(start)
2017-11-17 14:18:53 +00:00
debugPrint("parsed in %s", elapsed)
2017-10-20 10:51:56 +00:00
}
case err := <-bw.watcher.Errors:
2017-10-20 10:51:56 +00:00
log.Println("error:", err)
}
}
debugPrint("Exiting watch thread")
2017-10-20 10:51:56 +00:00
}