| 1 | from __future__ import print_function |
|---|
| 2 | from twisted.internet import inotify |
|---|
| 3 | from twisted.python.filepath import FilePath |
|---|
| 4 | from twisted.internet.task import react, deferLater |
|---|
| 5 | from twisted.internet.defer import inlineCallbacks |
|---|
| 6 | |
|---|
| 7 | import shutil |
|---|
| 8 | from os.path import join |
|---|
| 9 | |
|---|
| 10 | @inlineCallbacks |
|---|
| 11 | def main(reactor): |
|---|
| 12 | notifier = inotify.INotify() |
|---|
| 13 | notifier.startReading() |
|---|
| 14 | IN_EXCL_UNLINK = 0x04000000L # copied from tahoe stuff; why not in inotify? |
|---|
| 15 | mask = ( inotify.IN_CREATE |
|---|
| 16 | | inotify.IN_CLOSE_WRITE |
|---|
| 17 | | inotify.IN_MOVED_TO |
|---|
| 18 | | inotify.IN_MOVED_FROM |
|---|
| 19 | | inotify.IN_DELETE |
|---|
| 20 | | inotify.IN_ONLYDIR |
|---|
| 21 | # | IN_EXCL_UNLINK |
|---|
| 22 | ) |
|---|
| 23 | |
|---|
| 24 | notifies = [] |
|---|
| 25 | def notify_callback(_, filepath, mask): |
|---|
| 26 | print("notify callback", inotify.humanReadableMask(mask)) |
|---|
| 27 | notifies.append((filepath, inotify.humanReadableMask(mask))) |
|---|
| 28 | |
|---|
| 29 | local_dir = './foo-inotify' |
|---|
| 30 | fp = FilePath(local_dir) |
|---|
| 31 | print("XXXX", fp) |
|---|
| 32 | z = notifier.watch( |
|---|
| 33 | fp, |
|---|
| 34 | mask=mask, |
|---|
| 35 | callbacks=[notify_callback], |
|---|
| 36 | recursive=True, |
|---|
| 37 | ) |
|---|
| 38 | print("ZZZ", z) |
|---|
| 39 | |
|---|
| 40 | p0 = join(local_dir, 'file0') |
|---|
| 41 | p1 = join(local_dir, 'file1') |
|---|
| 42 | yield deferLater(reactor, 1, lambda: None) |
|---|
| 43 | print("0", notifies) |
|---|
| 44 | with open(p0, 'wb') as f: |
|---|
| 45 | yield deferLater(reactor, 1, lambda: None) |
|---|
| 46 | print("1", notifies) |
|---|
| 47 | f.write('ohai\n') |
|---|
| 48 | yield deferLater(reactor, 1, lambda: None) |
|---|
| 49 | print("2", notifies) |
|---|
| 50 | f.flush() |
|---|
| 51 | yield deferLater(reactor, 1, lambda: None) |
|---|
| 52 | print("3", notifies) |
|---|
| 53 | shutil.move(p0, p1) |
|---|
| 54 | yield deferLater(reactor, 1, lambda: None) |
|---|
| 55 | print("4", notifies) |
|---|
| 56 | yield deferLater(reactor, 1, lambda: None) |
|---|
| 57 | print("5", notifies) |
|---|
| 58 | |
|---|
| 59 | for (path, mask) in notifies: |
|---|
| 60 | print(' {} -> {}'.format(path, mask)) |
|---|
| 61 | |
|---|
| 62 | react(main) |
|---|