11from __future__ import annotations
22
3+ import uuid
4+ from dataclasses import dataclass
35from typing import TYPE_CHECKING , Any , Awaitable , Callable , Dict , List , Optional
46
57from ....jsonrpc2 .protocol import JsonRPCErrorException , rpc_method
2325_FUNC_TYPE = Callable [..., Awaitable [Optional [LSPAny ]]]
2426
2527
28+ @dataclass
29+ class CommandEntry :
30+ name : str
31+ callback : _FUNC_TYPE
32+
33+
2634class CommandsProtocolPart (LanguageServerProtocolPart , HasExtendCapabilities ):
2735
2836 _logger = LoggingDescriptor ()
2937
38+ PREFIX = f"{ uuid .uuid4 ()} "
39+
3040 def __init__ (self , parent : LanguageServerProtocol ) -> None :
3141 super ().__init__ (parent )
32- self .commands : Dict [str , _FUNC_TYPE ] = {}
42+ self .commands : Dict [str , CommandEntry ] = {}
3343
34- def register (self , callback : _FUNC_TYPE , name : Optional [str ] = None ) -> None :
35- command = name or get_command_name (callback )
44+ def register (self , callback : _FUNC_TYPE , name : Optional [str ] = None ) -> CommandEntry :
45+ name = name or get_command_name (callback )
46+
47+ command = f"{ self .PREFIX } .{ name } "
3648
3749 if command in self .commands :
3850 self ._logger .critical (f"command '{ command } ' already registered." )
39- return
51+ else :
52+ self .commands [command ] = CommandEntry (name , callback )
53+
54+ return self .commands [command ]
55+
56+ def get_command_name (self , callback : _FUNC_TYPE , name : Optional [str ] = None ) -> str :
57+ name = name or get_command_name (callback )
4058
41- self .commands [ command ] = callback
59+ return f" { self .PREFIX } . { name } "
4260
4361 def extend_capabilities (self , capabilities : ServerCapabilities ) -> None :
4462
@@ -51,8 +69,8 @@ async def _workspace_execute_command(
5169 ) -> Optional [LSPAny ]:
5270 self ._logger .info (f"execute command { command } " )
5371
54- callback = self .commands .get (command , None )
55- if callback is None :
72+ entry = self .commands .get (command , None )
73+ if entry is None or entry . callback is None :
5674 raise JsonRPCErrorException (ErrorCodes .INVALID_PARAMS , f"Command '{ command } ' unknown." )
5775
58- return await callback (* (arguments or ()))
76+ return await entry . callback (* (arguments or ()))
0 commit comments