summaryrefslogtreecommitdiff
path: root/qface/watch.py
blob: ca3ec73fafd1b5ef1a3b769719c9fde25f501fa0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import click
from subprocess import call
from path import Path
import time
import sys


def sh(cmd, all=False, **kwargs):
    click.secho('$ {0}'.format(cmd), fg='green')
    return call(cmd, shell=True, **kwargs)


class RunScriptChangeHandler(FileSystemEventHandler):
    def __init__(self, script):
        super().__init__()
        self.script = script
        self.is_running = False

    def on_modified(self, event):
        self.run()

    def run(self):
        if self.is_running:
            return
        self.is_running = True
        cmd = '{0} {1}'.format(sys.executable, self.script)
        sh(cmd, cwd=Path.getcwd())
        self.is_running = False


def monitor(src, script):
    """
    reloads the script when src files changes
    """
    script = Path(script).expand().abspath()
    src = src if isinstance(src, (list, tuple)) else [src]
    src = [Path(entry).expand().abspath() for entry in src]
    event_handler = RunScriptChangeHandler(script)
    observer = Observer()
    path = script.dirname().expand().abspath()
    click.secho('watch recursive: {0}'.format(path), fg='blue')
    observer.schedule(event_handler, path, recursive=True)
    for entry in src:
        entry = entry.dirname().expand().abspath()
        click.secho('watch recursive: {0}'.format(entry), fg='blue')
        observer.schedule(event_handler, entry, recursive=True)
    event_handler.run()  # run always once
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()