fsnotify.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package fsnotify implements file system notification.
  5. package fsnotify
  6. import "fmt"
  7. const (
  8. FSN_CREATE = 1
  9. FSN_MODIFY = 2
  10. FSN_DELETE = 4
  11. FSN_RENAME = 8
  12. FSN_ALL = FSN_MODIFY | FSN_DELETE | FSN_RENAME | FSN_CREATE
  13. )
  14. // Purge events from interal chan to external chan if passes filter
  15. func (w *Watcher) purgeEvents() {
  16. for ev := range w.internalEvent {
  17. sendEvent := false
  18. w.fsnmut.Lock()
  19. fsnFlags := w.fsnFlags[ev.Name]
  20. w.fsnmut.Unlock()
  21. if (fsnFlags&FSN_CREATE == FSN_CREATE) && ev.IsCreate() {
  22. sendEvent = true
  23. }
  24. if (fsnFlags&FSN_MODIFY == FSN_MODIFY) && ev.IsModify() {
  25. sendEvent = true
  26. }
  27. if (fsnFlags&FSN_DELETE == FSN_DELETE) && ev.IsDelete() {
  28. sendEvent = true
  29. }
  30. if (fsnFlags&FSN_RENAME == FSN_RENAME) && ev.IsRename() {
  31. sendEvent = true
  32. }
  33. if sendEvent {
  34. w.Event <- ev
  35. }
  36. // If there's no file, then no more events for user
  37. // BSD must keep watch for internal use (watches DELETEs to keep track
  38. // what files exist for create events)
  39. if ev.IsDelete() {
  40. w.fsnmut.Lock()
  41. delete(w.fsnFlags, ev.Name)
  42. w.fsnmut.Unlock()
  43. }
  44. }
  45. close(w.Event)
  46. }
  47. // Watch a given file path
  48. func (w *Watcher) Watch(path string) error {
  49. return w.WatchFlags(path, FSN_ALL)
  50. }
  51. // Watch a given file path for a particular set of notifications (FSN_MODIFY etc.)
  52. func (w *Watcher) WatchFlags(path string, flags uint32) error {
  53. w.fsnmut.Lock()
  54. w.fsnFlags[path] = flags
  55. w.fsnmut.Unlock()
  56. return w.watch(path)
  57. }
  58. // Remove a watch on a file
  59. func (w *Watcher) RemoveWatch(path string) error {
  60. w.fsnmut.Lock()
  61. delete(w.fsnFlags, path)
  62. w.fsnmut.Unlock()
  63. return w.removeWatch(path)
  64. }
  65. // String formats the event e in the form
  66. // "filename: DELETE|MODIFY|..."
  67. func (e *FileEvent) String() string {
  68. var events string = ""
  69. if e.IsCreate() {
  70. events += "|" + "CREATE"
  71. }
  72. if e.IsDelete() {
  73. events += "|" + "DELETE"
  74. }
  75. if e.IsModify() {
  76. events += "|" + "MODIFY"
  77. }
  78. if e.IsRename() {
  79. events += "|" + "RENAME"
  80. }
  81. if e.IsAttrib() {
  82. events += "|" + "ATTRIB"
  83. }
  84. if len(events) > 0 {
  85. events = events[1:]
  86. }
  87. return fmt.Sprintf("%q: %s", e.Name, events)
  88. }