Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add decorators for api handlers #38

Merged
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
6f9caf4
feat: add decorators for event handler registration
jfcherng Nov 15, 2020
05489e9
fix: naming + coding style
jfcherng Nov 18, 2020
b9f8122
refactor: factor out register_decorated_handlers() to decorator.py
jfcherng Nov 18, 2020
35e57d5
chore: no need to expose HANDLER_MARKS
jfcherng Nov 18, 2020
a9966e5
chore: cleanup unused import
jfcherng Nov 18, 2020
509cf2a
chore: revise wording
jfcherng Nov 18, 2020
179920b
refactor: early break for register_decorated_handlers()
jfcherng Nov 18, 2020
668833b
refactor: avoid try...except
jfcherng Nov 18, 2020
f90b898
perf: optimize internal working flow for register_decorated_handlers()
jfcherng Nov 18, 2020
b0838e8
chore: revise wording
jfcherng Nov 18, 2020
1bc23d5
refactor: Iterable -> List
jfcherng Nov 18, 2020
96e31b9
chore: revise term namings
jfcherng Nov 18, 2020
226a293
chore: use more LSP spec terms
jfcherng Nov 18, 2020
4d55387
chore: remove unnecessary casting
jfcherng Nov 18, 2020
43c8b44
chore: revise comment wording with LSP spec terms
jfcherng Nov 18, 2020
60465de
refactor: no need for variable "is_registered" in register_decorated_…
jfcherng Nov 18, 2020
c559ef5
style: follow Python's naming convention
jfcherng Nov 18, 2020
f8d656f
style: fixup, real CamelCase
jfcherng Nov 18, 2020
9950965
chore: use more LSP spec terms
jfcherng Nov 18, 2020
e1a2347
Type fixes for request_handler decorator
rchl Nov 18, 2020
295eedd
Add documentation
rchl Nov 18, 2020
ed3064a
More docs
rchl Nov 18, 2020
121517f
Typo
rchl Nov 18, 2020
ca7e9fe
rename decorator => api_decorator
rchl Nov 21, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions st3/lsp_utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from ._client_handler import ClientHandler
from ._client_handler import notification_handler
from ._client_handler import request_handler
from .api_wrapper_interface import ApiWrapperInterface
from .generic_client_handler import GenericClientHandler
from .npm_client_handler import NpmClientHandler
Expand All @@ -14,4 +16,7 @@
'ServerResourceInterface',
'ServerStatus'
'ServerNpmResource',
# decorator-related
'notification_handler',
'request_handler',
]
5 changes: 5 additions & 0 deletions st3/lsp_utils/_client_handler/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from .decorator import notification_handler
from .decorator import request_handler
from LSP.plugin import __version__ as lsp_version


Expand All @@ -8,4 +10,7 @@

__all__ = [
'ClientHandler',
# decorator-related
'notification_handler',
'request_handler',
]
5 changes: 4 additions & 1 deletion st3/lsp_utils/_client_handler/abstract_plugin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from ..api_wrapper_interface import ApiWrapperInterface
from ..server_resource_interface import ServerStatus
from .decorator import register_decorated_handlers
from .interface import ClientHandlerInterface
from LSP.plugin import AbstractPlugin
from LSP.plugin import ClientConfig
Expand Down Expand Up @@ -158,4 +159,6 @@ def _upgrade_languages_list(cls, languages):

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.on_ready(ApiWrapper(self))
api = ApiWrapper(self)
register_decorated_handlers(self, api)
self.on_ready(api)
71 changes: 71 additions & 0 deletions st3/lsp_utils/_client_handler/decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
from ..api_wrapper_interface import ApiWrapperInterface
from .interface import ClientHandlerInterface
from LSP.plugin.core.typing import Any, Callable, List, Optional, Union
import inspect

__all__ = [
"notification_handler",
"request_handler",
"register_decorated_handlers",
]

# the first argument is always "self"
jfcherng marked this conversation as resolved.
Show resolved Hide resolved
T_HANDLER = Callable[[Any, Any], None]
T_MESSAGE_METHODS = Union[str, List[str]]
jfcherng marked this conversation as resolved.
Show resolved Hide resolved

_HANDLER_MARKS = {
"notification": "__handle_notification_events",
"request": "__handle_request_events",
}


def notification_handler(notification_methods: T_MESSAGE_METHODS) -> Callable[[T_HANDLER], T_HANDLER]:
""" Marks the decorated function as a "notification" message handler. """

return _create_handler("notification", notification_methods)


def request_handler(request_methods: T_MESSAGE_METHODS) -> Callable[[T_HANDLER], T_HANDLER]:
""" Marks the decorated function as a "request" message handler. """

return _create_handler("request", request_methods)


def _create_handler(client_event: str, message_methods: T_MESSAGE_METHODS) -> Callable[[T_HANDLER], T_HANDLER]:
""" Marks the decorated function as a message handler. """

message_methods = [message_methods] if isinstance(message_methods, str) else message_methods

def decorator(func: T_HANDLER) -> T_HANDLER:
setattr(func, _HANDLER_MARKS[client_event], message_methods)
return func

return decorator


def register_decorated_handlers(client_handler: ClientHandlerInterface, api: ApiWrapperInterface) -> None:
"""
Register decorator-style custom message handlers.

This method works as following steps:

1. Scan through all methods of `client_handler`.
2. If a method is decorated, it will has a "handler mark" attribute which is set by the decorator.
3. Register the method with wanted message methods, which are stored in the "handler mark" attribute.

:param api: The API instance for interacting with the server.
"""
for _, func in inspect.getmembers(client_handler, predicate=inspect.isroutine):
for client_event, handler_mark in _HANDLER_MARKS.items():
message_methods = getattr(func, handler_mark, None) # type: Optional[List[str]]
if message_methods is None:
continue

event_registrator = getattr(api, "on_" + client_event, None)
if callable(event_registrator):
for message_method in message_methods:
event_registrator(message_method, func)

# it makes no sense that a handler handlers both "notification" and "request"
# so we do early break once we've registered a handler
break
5 changes: 4 additions & 1 deletion st3/lsp_utils/_client_handler/language_handler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from ..api_wrapper_interface import ApiWrapperInterface
from ..helpers import log_and_show_message
from ..server_resource_interface import ServerStatus
from .decorator import register_decorated_handlers
from .interface import ClientHandlerInterface
from LSP.plugin import ClientConfig
from LSP.plugin import LanguageHandler
Expand Down Expand Up @@ -82,7 +83,9 @@ def on_start(cls, window: sublime.Window) -> bool:
return True

def on_initialized(self, client) -> None:
self.on_ready(ApiWrapper(client))
api = ApiWrapper(client)
register_decorated_handlers(self, api)
self.on_ready(api)

# --- ClientHandlerInterface --------------------------------------------------------------------------------------

Expand Down