Skip to content

Instantly share code, notes, and snippets.

@reusee
Created September 16, 2016 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reusee/cc61fbbcd9229a89ad01cbb6ed97987e to your computer and use it in GitHub Desktop.
Save reusee/cc61fbbcd9229a89ad01cbb6ed97987e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/fsnotify/fsnotify"
"os"
"path/filepath"
"sync"
)
func main() {
watchDir := "watch-dir"
moveToDir := "move-to-dir"
ce := func(err error) {
if err != nil {
panic(err)
}
}
l := new(sync.Mutex)
moveFiles := func() {
l.Lock()
defer l.Unlock()
dir, err := os.Open(watchDir)
ce(err)
names, err := dir.Readdirnames(-1)
ce(err)
wg := new(sync.WaitGroup)
wg.Add(len(names))
sem := make(chan struct{}, 8)
for _, name := range names {
sem <- struct{}{}
name := name
go func() {
defer func() {
wg.Done()
<-sem
}()
from := filepath.Join(watchDir, name)
to := filepath.Join(moveToDir, name)
fmt.Printf("move %s to %s\n", from, to)
ce(os.Rename(from, to))
}()
}
wg.Wait()
}
watcher, err := fsnotify.NewWatcher()
ce(err)
defer watcher.Close()
ce(watcher.Add(watchDir))
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Create == 0 {
continue
}
moveFiles()
case err := <-watcher.Errors:
ce(err)
}
}
}()
moveFiles()
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment