|
| 1 | +import os |
| 2 | +import sys |
| 3 | + |
| 4 | +__all__ = [ |
| 5 | + "DevTools", |
| 6 | +] |
| 7 | + |
| 8 | + |
| 9 | +class DevTools(object): |
| 10 | + """Tools for working with Python code in development mode, unloading, and reloading code.""" |
| 11 | + |
| 12 | + def __init__(self): |
| 13 | + """Initializes a new instance of the DevTools class.""" |
| 14 | + self.watcher = None |
| 15 | + |
| 16 | + @staticmethod |
| 17 | + def unload_modules(top_level_module_name): |
| 18 | + """Unloads all modules named starting with the specified string. |
| 19 | +
|
| 20 | + This function eases the development workflow when editing a library that is |
| 21 | + used from Rhino/Grasshopper. |
| 22 | +
|
| 23 | + Parameters |
| 24 | + ---------- |
| 25 | + top_level_module_name : :obj:`str` |
| 26 | + Name of the top-level module to unload. |
| 27 | +
|
| 28 | + Returns |
| 29 | + ------- |
| 30 | + list |
| 31 | + List of unloaded module names. |
| 32 | + """ |
| 33 | + to_remove = [name for name in sys.modules if name.startswith(top_level_module_name)] |
| 34 | + |
| 35 | + for module in to_remove: |
| 36 | + sys.modules.pop(module) |
| 37 | + |
| 38 | + return to_remove |
| 39 | + |
| 40 | + @classmethod |
| 41 | + def enable_reloader(cls): |
| 42 | + """Enables the code reload on the current folder. |
| 43 | +
|
| 44 | + The file must have been saved already in order for this to work.""" |
| 45 | + cls._manage_reloader(enable=True) |
| 46 | + |
| 47 | + @classmethod |
| 48 | + def disable_reloader(cls): |
| 49 | + """Disables the code reload on the current folder. |
| 50 | +
|
| 51 | + The file must have been saved already in order for this to work.""" |
| 52 | + cls._manage_reloader(enable=False) |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def _manage_reloader(cls, enable): |
| 56 | + import scriptcontext |
| 57 | + |
| 58 | + doc_id = scriptcontext.doc.Component.OnPingDocument().DocumentID.ToString() |
| 59 | + key = "__compas_devtools_{}__".format(doc_id) |
| 60 | + if key in scriptcontext.sticky: |
| 61 | + reloader = scriptcontext.sticky[key] |
| 62 | + reloader.stop_watcher() |
| 63 | + reloader = None |
| 64 | + del reloader |
| 65 | + |
| 66 | + if enable: |
| 67 | + reloader = DevTools() |
| 68 | + reloader.start_watcher() |
| 69 | + scriptcontext.sticky[key] = reloader |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def ensure_path(): |
| 73 | + """Ensures the current folder is in the system path.""" |
| 74 | + # Not sure why we need to import sys inside this method but GH complains otherwise |
| 75 | + import scriptcontext |
| 76 | + |
| 77 | + # First ensure the current folder is in the system path |
| 78 | + filepath = scriptcontext.doc.Component.OnPingDocument().FilePath |
| 79 | + |
| 80 | + if not filepath: |
| 81 | + raise Exception("It seems this file is not saved, cannot reload files without knowning where to search for them!") |
| 82 | + |
| 83 | + dirname = os.path.dirname(filepath) |
| 84 | + if dirname not in sys.path: |
| 85 | + sys.path.append(dirname) |
| 86 | + |
| 87 | + return dirname |
| 88 | + |
| 89 | + def start_watcher(self): |
| 90 | + try: |
| 91 | + from System.IO import FileSystemWatcher # noqa : F401 |
| 92 | + from System.IO import NotifyFilters # noqa : F401 |
| 93 | + except ImportError: |
| 94 | + raise Exception("This component requires the System.IO.FileSystemWatcher class to work") |
| 95 | + |
| 96 | + dirname = self.ensure_path() |
| 97 | + |
| 98 | + # Disable previous watchers if any |
| 99 | + if self.watcher: |
| 100 | + self.disable() |
| 101 | + |
| 102 | + # Setup file system watcher on python files |
| 103 | + self.watcher = FileSystemWatcher() |
| 104 | + self.watcher.Path = dirname |
| 105 | + self.watcher.NotifyFilter = NotifyFilters.LastWrite |
| 106 | + self.watcher.IncludeSubdirectories = False |
| 107 | + self.watcher.Filter = "*.py" |
| 108 | + self.watcher.Changed += self.on_changed |
| 109 | + self.watcher.EnableRaisingEvents = True |
| 110 | + |
| 111 | + def on_changed(self, sender, args): |
| 112 | + try: |
| 113 | + # Get module name from full path |
| 114 | + filename = os.path.basename(args.FullPath) |
| 115 | + if filename.lower().endswith(".py"): |
| 116 | + module_name = filename.split(".")[0] |
| 117 | + |
| 118 | + # Unload the modified module |
| 119 | + self.unload_modules(module_name) |
| 120 | + except Exception: |
| 121 | + print("Something failed during unload, this message will not be printed anywhere thou, deal with it") |
| 122 | + |
| 123 | + def stop_watcher(self): |
| 124 | + try: |
| 125 | + if self.watcher: |
| 126 | + self.watcher.Changed |
| 127 | + self.watcher.Dispose() |
| 128 | + del self.watcher |
| 129 | + except: # noqa : E722 |
| 130 | + pass |
| 131 | + self.watcher = None |
| 132 | + |
| 133 | + |
| 134 | +unload_modules = DevTools.unload_modules |
0 commit comments