mitmproxy/libmproxy/script/reloader.py

57 lines
1.7 KiB
Python
Raw Normal View History

2015-11-14 04:57:02 +00:00
import os
2016-01-12 03:45:03 +00:00
import fnmatch
2015-11-14 04:57:02 +00:00
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers.polling import PollingObserver
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)
observer = PollingObserver()
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(PatternMatchingEventHandler):
2016-01-12 12:50:33 +00:00
def __init__(self, callback, filename='*'):
2015-11-14 04:57:02 +00:00
super(_ScriptModificationHandler, self).__init__(
ignore_directories=True,
)
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):
2016-01-12 03:45:03 +00:00
if event.is_directory:
files_in_dir = [event.src_path + "/" +
2016-01-12 03:45:03 +00:00
f for f in os.listdir(event.src_path)]
if len(files_in_dir) > 0:
2016-01-12 12:50:33 +00:00
modified_filepath = max(files_in_dir, key=os.path.getmtime)
2016-01-12 03:45:03 +00:00
else:
return
else:
2016-01-12 12:50:33 +00:00
modified_filepath = event.src_path
2016-01-12 03:45:03 +00:00
if fnmatch.fnmatch(os.path.basename(modified_filepath), self.filename):
2016-01-12 03:45:03 +00:00
self.callback()
def on_created(self, event):
if fnmatch.fnmatch(os.path.basename(event.src_path), self.filename):
self.callback()
2016-01-12 03:45:03 +00:00
__all__ = ["watch", "unwatch"]
2015-11-14 04:57:02 +00:00