mitmproxy/libmproxy/script/reloader.py

48 lines
1.3 KiB
Python
Raw Normal View History

2015-11-14 04:57:02 +00:00
import os
2016-01-14 01:30:06 +00:00
import sys
from watchdog.events import RegexMatchingEventHandler
2016-01-14 01:30:06 +00:00
if sys.platform == 'darwin':
from watchdog.observers.polling import PollingObserver as Observer
else:
from watchdog.observers import Observer
# The OSX reloader is watchdog 0.8.3 breaks when unobserving paths.
# We use the PollingObserver instead.
2015-11-14 04:57:02 +00:00
_observers = {}
def watch(script, callback):
2015-11-26 13:59:54 +00:00
if script in _observers:
raise RuntimeError("Script already observed")
2015-11-14 04:57:02 +00:00
script_dir = os.path.dirname(os.path.abspath(script.args[0]))
2016-01-12 12:50:33 +00:00
script_name = os.path.basename(script.args[0])
event_handler = _ScriptModificationHandler(callback, filename=script_name)
2016-01-14 01:30:06 +00:00
observer = Observer()
2015-11-14 04:57:02 +00:00
observer.schedule(event_handler, script_dir)
observer.start()
_observers[script] = observer
def unwatch(script):
observer = _observers.pop(script, None)
if observer:
observer.stop()
2015-11-26 13:59:54 +00:00
observer.join()
2015-11-14 04:57:02 +00:00
class _ScriptModificationHandler(RegexMatchingEventHandler):
def __init__(self, callback, filename='.*'):
2015-11-14 04:57:02 +00:00
super(_ScriptModificationHandler, self).__init__(
ignore_directories=True,
regexes=['.*'+filename]
2015-11-14 04:57:02 +00:00
)
self.callback = callback
2016-01-12 12:50:33 +00:00
self.filename = filename
2015-11-14 04:57:02 +00:00
def on_modified(self, event):
self.callback()
2016-01-12 03:45:03 +00:00
__all__ = ["watch", "unwatch"]
2015-11-14 04:57:02 +00:00