TopList.py 1.9 KB
Newer Older
1
#!/usr/bin/python
2 3 4 5 6 7 8 9 10
import os, os.path
from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent, IN_DONT_FOLLOW, IN_CREATE, IN_MODIFY
import pwd

COUNT=5

wm = WatchManager()
mask = IN_CREATE | IN_MODIFY | IN_DONT_FOLLOW

Őry Máté committed
11 12 13
"""
Register given file to ~/../.top dir as a symbolic link.
"""
14
def update_new(name):
15
    norm = os.path.realpath(name)
Őry Máté committed
16 17 18 19 20 21 22
    if norm != name:
        return # link
    name = norm

    if name.find("/.") != -1:
        return # hidden file (or file in hidden dir)

23
    home = pwd.getpwuid(os.stat(name).st_uid).pw_dir
24
    if not name.startswith(home):
Őry Máté committed
25 26
        return # outside home

27
    top_dir = os.path.realpath(os.path.join(home, "../.top"))
28 29 30
    try:
        os.mkdir(top_dir)
    except OSError:
31 32
        for f in os.listdir(top_dir):
            if os.readlink(os.path.join(top_dir, f)) == name:
Őry Máté committed
33 34
                return # duplicate

35 36 37
    for i in range(1, COUNT):
        try:
            os.rename(os.path.join(top_dir, str(i+1)), os.path.join(top_dir, str(i)))
38
        except OSError as e:
Őry Máté committed
39
            pass
Őry Máté committed
40

41 42
    os.symlink(name, os.path.join(top_dir, str(COUNT)))

Őry Máté committed
43 44 45
"""
Process inotify event.
"""
46 47 48 49 50
class Process(ProcessEvent):
    def process_default(self, event):
        if event.name:
            update_new(os.path.join(event.path, event.name))

Őry Máté committed
51 52 53
"""
Watch continuously file modifications in /home.
"""
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
def main():
    notifier = Notifier(wm, Process())
    wdd = wm.add_watch('/home', mask, rec=True)
    while True:  # loop forever
        try:
            # process the queue of events as explained above
            notifier.process_events()
            if notifier.check_events():
                # read notified events and enqeue them
                notifier.read_events()
        except KeyboardInterrupt:
            # destroy the inotify's instance on this interrupt (stop monitoring)
            notifier.stop()
            break

if __name__ == "__main__":
        main()