Skip to content

Commit

Permalink
[python] Make the method fields of requests, responses and notificati…
Browse files Browse the repository at this point in the history
…ons literals

This makes it possible for cattrs to build a disambiguation function
based on this unique field, which allows one to do things like:

```python
>>> from lsprotocol import types, converters
>>>
>>> converter = converters.get_converter()
>>> d = {"jsonrpc":"2.0","method":"window/logMessage","params":{"type":3,"message":"Server starting"}}
>>> converter.structure(d, types.NOTIFICATIONS | types.REQUESTS)
WindowLogMessageNotification(params=LogMessageParams(type=<MessageType.Info: 3>, message='Server starting'), method='window/logMessage', jsonrpc='2.0')
```
  • Loading branch information
svenberkvens committed May 24, 2024
1 parent 5e00406 commit 5c5dadb
Show file tree
Hide file tree
Showing 2 changed files with 111 additions and 99 deletions.
6 changes: 3 additions & 3 deletions generator/plugins/python/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def _reset(self):
self._imports: List[str] = [
"import enum",
"import functools",
"from typing import Any, Dict, Optional, Sequence, Tuple, Union",
"from typing import Any, Dict, Literal, Optional, Sequence, Tuple, Union",
"import attrs",
"from . import validators",
]
Expand Down Expand Up @@ -863,7 +863,7 @@ def _add_requests(self, lsp_mode: model.LSPModel) -> None:
f"{indent}id:Union[int, str] = attrs.field()",
f'{indent}"""The request id."""',
f"{indent}params: {params_type} ={params_field}",
f'{indent}method: str = "{request.method}"',
f'{indent}method: Literal["{request.method}"] = "{request.method}"',
f'{indent}"""The method to be invoked."""',
f'{indent}jsonrpc: str = attrs.field(default="2.0")',
],
Expand Down Expand Up @@ -908,7 +908,7 @@ def _add_notifications(self, lsp_mode: model.LSPModel) -> None:
f"class {class_name}Notification:",
f'{indent}"""{doc}"""' if notification.documentation else "",
f"{indent}params: {params_type} = {params_field}",
f"{indent}method:str = attrs.field(",
f'{indent}method: Literal["{notification.method}"] = attrs.field(',
f'validator=attrs.validators.in_(["{notification.method}"]),',
f'default="{notification.method}",',
")",
Expand Down
Loading

0 comments on commit 5c5dadb

Please sign in to comment.