Created
September 16, 2016 11:43
-
-
Save reusee/cc61fbbcd9229a89ad01cbb6ed97987e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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