|
| 1 | +"""Implements a Nvim host for python plugins.""" |
| 2 | +import functools |
| 3 | +import imp |
| 4 | +import inspect |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import os.path |
| 8 | + |
| 9 | +from ..api import DecodeHook |
| 10 | +from ..compat import IS_PYTHON3, find_module |
| 11 | + |
| 12 | + |
| 13 | +__all__ = ('Host') |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | +debug, info, warn = (logger.debug, logger.info, logger.warn,) |
| 17 | + |
| 18 | + |
| 19 | +class Host(object): |
| 20 | + |
| 21 | + """Nvim host for python plugins. |
| 22 | +
|
| 23 | + Takes care of loading/unloading plugins and routing msgpack-rpc |
| 24 | + requests/notifications to the appropriate handlers. |
| 25 | + """ |
| 26 | + |
| 27 | + def __init__(self, nvim): |
| 28 | + """Set handlers for plugin_load/plugin_unload.""" |
| 29 | + self.nvim = nvim |
| 30 | + self._specs = {} |
| 31 | + self._loaded = {} |
| 32 | + self._notification_handlers = {} |
| 33 | + self._request_handlers = { |
| 34 | + 'poll': lambda: 'ok', |
| 35 | + 'specs': lambda path: self._specs[path], |
| 36 | + 'shutdown': self.shutdown |
| 37 | + } |
| 38 | + self._nvim_encoding = nvim.options['encoding'] |
| 39 | + |
| 40 | + def start(self, plugins): |
| 41 | + """Start listening for msgpack-rpc requests and notifications.""" |
| 42 | + self.nvim.session.run(self._on_request, |
| 43 | + self._on_notification, |
| 44 | + lambda: self._load(plugins)) |
| 45 | + |
| 46 | + def shutdown(self): |
| 47 | + """Shutdown the host.""" |
| 48 | + self._unload() |
| 49 | + self.nvim.session.stop() |
| 50 | + |
| 51 | + def _on_request(self, name, args): |
| 52 | + """Handle a msgpack-rpc request.""" |
| 53 | + handler = self._request_handlers.get(name, None) |
| 54 | + if not handler: |
| 55 | + msg = 'no request handler registered for "%s"' % name |
| 56 | + warn(msg) |
| 57 | + raise Exception(msg) |
| 58 | + |
| 59 | + debug('calling request handler for "%s", args: "%s"', name, args) |
| 60 | + rv = handler(*args) |
| 61 | + debug("request handler for '%s %s' returns: %s", name, args, rv) |
| 62 | + return rv |
| 63 | + |
| 64 | + def _on_notification(self, name, args): |
| 65 | + """Handle a msgpack-rpc notification.""" |
| 66 | + handler = self._notification_handlers.get(name, None) |
| 67 | + if not handler: |
| 68 | + warn('no notification handler registered for "%s"', name) |
| 69 | + return |
| 70 | + |
| 71 | + debug('calling notification handler for "%s", args: "%s"', name, args) |
| 72 | + handler(*args) |
| 73 | + |
| 74 | + def _load(self, plugins): |
| 75 | + for path in plugins: |
| 76 | + if path in self._loaded: |
| 77 | + raise Exception('{0} is already loaded'.format(path)) |
| 78 | + directory, name = os.path.split(os.path.splitext(path)[0]) |
| 79 | + file, pathname, description = find_module(name, [directory]) |
| 80 | + module = imp.load_module(name, file, pathname, description) |
| 81 | + handlers = [] |
| 82 | + self._discover_classes(module, handlers, path) |
| 83 | + self._discover_functions(module, handlers, path) |
| 84 | + if not handlers: |
| 85 | + raise Exception('{0} exports no handlers'.format(path)) |
| 86 | + self._loaded[path] = {'handlers': handlers, 'module': module} |
| 87 | + |
| 88 | + def _unload(self): |
| 89 | + for path, plugin in self._loaded.items(): |
| 90 | + handlers = plugin['handlers'] |
| 91 | + for handler in handlers: |
| 92 | + method_name = handler._nvim_rpc_method_name |
| 93 | + if hasattr(handler, '_nvim_shutdown_hook'): |
| 94 | + handler() |
| 95 | + elif handler._nvim_rpc_sync: |
| 96 | + del self._request_handlers[method_name] |
| 97 | + else: |
| 98 | + del self._notification_handlers[method_name] |
| 99 | + self._specs = {} |
| 100 | + self._loaded = {} |
| 101 | + |
| 102 | + def _discover_classes(self, module, handlers, plugin_path): |
| 103 | + for _, cls in inspect.getmembers(module, inspect.isclass): |
| 104 | + if getattr(cls, '_nvim_plugin', False): |
| 105 | + # create an instance of the plugin and pass the nvim object |
| 106 | + plugin = cls(self._configure_nvim_for(cls)) |
| 107 | + # discover handlers in the plugin instance |
| 108 | + self._discover_functions(plugin, handlers, plugin_path) |
| 109 | + |
| 110 | + def _discover_functions(self, obj, handlers, plugin_path): |
| 111 | + predicate = lambda o: hasattr(o, '_nvim_rpc_method_name') |
| 112 | + specs = [] |
| 113 | + for _, fn in inspect.getmembers(obj, predicate): |
| 114 | + if fn._nvim_bind: |
| 115 | + # bind a nvim instance to the handler |
| 116 | + fn2 = functools.partial(fn, self._configure_nvim_for(fn)) |
| 117 | + # copy _nvim_* attributes from the original function |
| 118 | + for attr in dir(fn): |
| 119 | + if attr.startswith('_nvim_'): |
| 120 | + setattr(fn2, attr, getattr(fn, attr)) |
| 121 | + fn = fn2 |
| 122 | + # register in the rpc handler dict |
| 123 | + method = fn._nvim_rpc_method_name |
| 124 | + if fn._nvim_prefix_plugin_path: |
| 125 | + method = '{0}:{1}'.format(plugin_path, method) |
| 126 | + if fn._nvim_rpc_sync: |
| 127 | + if method in self._request_handlers: |
| 128 | + raise Exception('Request handler for "{0}" is ' + |
| 129 | + 'already registered'.format(method)) |
| 130 | + self._request_handlers[method] = fn |
| 131 | + else: |
| 132 | + if method in self._notification_handlers: |
| 133 | + raise Exception('Notification handler for "{0}" is ' + |
| 134 | + 'already registered'.format(method)) |
| 135 | + self._notification_handlers[method] = fn |
| 136 | + if hasattr(fn, 'nvim_rpc_spec'): |
| 137 | + specs.append(fn.nvim_rpc_spec) |
| 138 | + handlers.append(fn) |
| 139 | + if specs: |
| 140 | + self._specs[plugin_path] = specs |
| 141 | + |
| 142 | + def _configure_nvim_for(self, obj): |
| 143 | + # Configure a nvim instance for obj(checks encoding configuration) |
| 144 | + nvim = self.nvim |
| 145 | + encoding = getattr(obj, '_nvim_encoding', None) |
| 146 | + if IS_PYTHON3 and encoding is None: |
| 147 | + encoding = True |
| 148 | + if encoding is True: |
| 149 | + encoding = self._nvim_encoding |
| 150 | + if encoding: |
| 151 | + nvim = nvim.with_hook(DecodeHook(encoding)) |
| 152 | + return nvim |
0 commit comments