|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "log/syslog" |
| 5 | + "log" |
| 6 | + "os" |
| 7 | + "github.com/fsnotify/fsnotify" |
| 8 | +) |
| 9 | + |
| 10 | +var logger *log.Logger = getSyslog() |
| 11 | + |
| 12 | +type Watcher interface { |
| 13 | + start(string) |
| 14 | +} |
| 15 | + |
| 16 | +type FsnotifyWatcher struct { |
| 17 | +} |
| 18 | + |
| 19 | +func (f FsnotifyWatcher) start(filePath string) { |
| 20 | + // Create new watcher. |
| 21 | + watcher, err := fsnotify.NewWatcher() |
| 22 | + if err != nil { |
| 23 | + logger.Fatal(err) |
| 24 | + } |
| 25 | + defer watcher.Close() |
| 26 | + |
| 27 | + // Start listening for events. |
| 28 | + go func() { |
| 29 | + for { |
| 30 | + select { |
| 31 | + case event, ok := <-watcher.Events: |
| 32 | + if !ok { |
| 33 | + return |
| 34 | + } |
| 35 | + logger.Println("[filewatcher] event:", event) |
| 36 | + if event.Has(fsnotify.Write) { |
| 37 | + logger.Println("[filewatcher] modified file:", event.Name) |
| 38 | + } |
| 39 | + fileInfo, err := os.Stat(filePath) |
| 40 | + if (err != nil) { |
| 41 | + logger.Println("[filewatcher] Error:", err) |
| 42 | + } |
| 43 | + if (fileInfo.Size() != 0) { |
| 44 | + logger.Printf("[filewatcher] file %s has content now.\n", filePath) |
| 45 | + os.Exit(0) |
| 46 | + } |
| 47 | + case err, ok := <-watcher.Errors: |
| 48 | + if !ok { |
| 49 | + return |
| 50 | + } |
| 51 | + logger.Println("[filewatcher] error:", err) |
| 52 | + } |
| 53 | + } |
| 54 | + }() |
| 55 | + |
| 56 | + // Add a path. |
| 57 | + err = watcher.Add(filePath) |
| 58 | + if err != nil { |
| 59 | + logger.Fatal(err) |
| 60 | + } |
| 61 | + |
| 62 | + // Block main goroutine forever. |
| 63 | + <-make(chan struct{}) |
| 64 | +} |
| 65 | + |
| 66 | +func getFilePath(args []string) string { |
| 67 | + if (len(args) < 1) { |
| 68 | + log.Fatalln("You must specify a file path to watch!") |
| 69 | + os.Exit(1) |
| 70 | + } |
| 71 | + |
| 72 | + return args[0] |
| 73 | +} |
| 74 | + |
| 75 | +func getSyslog() *log.Logger { |
| 76 | + logger,err := syslog.NewLogger(syslog.LOG_INFO, 0) |
| 77 | + if err != nil { |
| 78 | + log.Fatal(err) |
| 79 | + os.Exit(2) |
| 80 | + } |
| 81 | + |
| 82 | + return logger |
| 83 | +} |
| 84 | + |
| 85 | +func start(watcher Watcher, filePath string) { |
| 86 | + watcher.start(filePath) |
| 87 | +} |
| 88 | + |
| 89 | +func main() { |
| 90 | + filePath := getFilePath(os.Args[1:]) |
| 91 | + fsWatcher := FsnotifyWatcher {} |
| 92 | + start(fsWatcher, filePath) |
| 93 | +} |
0 commit comments