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

types: use enum class for enums #92

Merged
merged 1 commit into from
Jan 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ and this project adheres to [Semantic Versioning][semver].
### Added

- Add comparisons and repr support to Range and Location types ([#90])
- Use python enums in types module ([#92])

[#90]: https://github.com/openlawlibrary/pygls/pull/90
[#92]: https://github.com/openlawlibrary/pygls/pull/92

## [0.8.1] - 09/05/2019

Expand Down
10 changes: 9 additions & 1 deletion pygls/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# limitations under the License. #
############################################################################
import asyncio
import enum
import functools
import json
import logging
Expand Down Expand Up @@ -69,6 +70,13 @@ def decorator(self, *args, **kwargs):
return decorator


def default_serializer(o):
"""JSON serializer for complex objects."""
if isinstance(o, enum.Enum):
return o.value
return o.__dict__


def deserialize_message(data):
"""Function used to deserialize data received from client."""
if 'jsonrpc' in data:
Expand Down Expand Up @@ -370,7 +378,7 @@ def _send_data(self, data):
return

try:
body = json.dumps(data, default=lambda o: o.__dict__)
body = json.dumps(data, default=default_serializer)
content_length = len(body.encode(self.CHARSET)) if body else 0

response = (
Expand Down
107 changes: 60 additions & 47 deletions pygls/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
"""


import enum
import sys
from typing import Any, Callable, Dict, List, Optional, Union

from .features import (CODE_ACTION, CODE_LENS, CODE_LENS_RESOLVE, COMPLETION,
Expand Down Expand Up @@ -97,7 +99,7 @@ def __init__(self, diagnostics: List['Diagnostic'],
self.only = only


class CodeActionKind:
class CodeActionKind(str, enum.Enum):
QuickFix = 'quickfix'
Refactor = 'refactor'
RefactorExtract = 'refactor.extract'
Expand Down Expand Up @@ -220,7 +222,7 @@ def __init__(self,
class CompletionItem:
def __init__(self,
label: str,
kind: int = None,
kind: 'CompletionItemKind' = None,
detail: str = None,
documentation: Union[str, 'MarkupContent'] = None,
deprecated: bool = False,
Expand Down Expand Up @@ -265,7 +267,7 @@ def __init__(self,
self.preselectedSupport = preselected_support


class CompletionItemKind:
class CompletionItemKind(enum.IntEnum):
Text = 1
Method = 2
Function = 3
Expand Down Expand Up @@ -321,7 +323,7 @@ def __init__(self,
self.triggerCharacters = trigger_characters


class CompletionTriggerKind:
class CompletionTriggerKind(enum.IntEnum):
Invoked = 1
TriggerCharacter = 2
TriggerForIncompleteCompletions = 3
Expand Down Expand Up @@ -370,11 +372,18 @@ def __init__(self,
self.ignore_if_exists = ignore_if_exists


class DiagnosticSeverity(enum.IntEnum):
Error = 1
Warning = 2
Information = 3
Hint = 4


class Diagnostic:
def __init__(self,
range: 'Range',
message: str,
severity: 'DiagnosticSeverity' = 1,
severity: DiagnosticSeverity = DiagnosticSeverity.Error,
code: str = None,
source: str = None,
related_information: 'DiagnosticRelatedInformation' = None):
Expand All @@ -392,13 +401,6 @@ def __init__(self, location: 'Location', message: str):
self.message = message


class DiagnosticSeverity:
Error = 1
Warning = 2
Information = 3
Hint = 4


class DidChangeConfigurationParams:
def __init__(self, settings: Any):
self.settings = settings
Expand Down Expand Up @@ -466,18 +468,18 @@ def __init__(self,
self.options = options


class DocumentHighlight:
def __init__(self, range: 'Range', kind: int = 1):
self.range = range
self.kind = kind


class DocumentHighlightKind:
class DocumentHighlightKind(enum.IntEnum):
Text = 1
Read = 2
Write = 3


class DocumentHighlight:
def __init__(self, range: 'Range', kind: DocumentHighlightKind = DocumentHighlightKind.Text):
self.range = range
self.kind = kind


class DocumentLink:
def __init__(self, range: 'Range', target: str = None, data: Any = None):
self.range = range
Expand Down Expand Up @@ -528,7 +530,7 @@ def __init__(self,
class DocumentSymbol:
def __init__(self,
name: str,
kind: int,
kind: 'SymbolKind',
range: 'Range',
selection_range: 'Range',
detail: str = None,
Expand Down Expand Up @@ -569,14 +571,14 @@ def __init__(self, commands: List[str]):
self.commands = commands


class FailureHandlingKind:
class FailureHandlingKind(str, enum.Enum):
Abort = 'abort'
Transactional = 'transactional'
TextOnlyTransactional = 'textOnlyTransactional'
FailureHandlingKind = 'undo'


class FileChangeType:
class FileChangeType(enum.IntEnum):
Created = 1
Changed = 2
Deleted = 3
Expand All @@ -588,8 +590,25 @@ def __init__(self, uri: str, type: FileChangeType):
self.type = type


if sys.version_info >= (3, 6):
class WatchKind(enum.IntFlag):
Create = 1
Change = 2
Delete = 4
_WatchKindType = WatchKind
else:
# BBB python 3.5 does not have enum.IntFlag
class WatchKind:
Create = 1
Change = 2
Delete = 4
_WatchKindType = int


class FileSystemWatcher:
def __init__(self, glob_pattern: str, kind: int = 7):
def __init__(self,
glob_pattern: str,
kind: _WatchKindType = WatchKind.Create | WatchKind.Change | WatchKind.Delete):
self.globPattern = glob_pattern
self.kind = kind

Expand All @@ -600,7 +619,7 @@ def __init__(self,
start_character: int,
end_line: int,
end_character: int,
kind: str = None):
kind: 'FoldingRangeKind' = None):
self.startLine = start_line
self.startCharacter = start_character
self.endLine = end_line
Expand All @@ -618,7 +637,7 @@ def __init(self,
self.lineFoldingOnly = line_folding_only


class FoldingRangeKind:
class FoldingRangeKind(str, enum.Enum):
Comment = 'comment'
Imports = 'imports'
Region = 'region'
Expand Down Expand Up @@ -653,15 +672,21 @@ def __init__(self, dynamic_registration,
self.contentFormat = content_format


class Trace(str, enum.Enum):
Off = 'off'
Messages = 'messages'
Verbose = 'verbose'


class InitializeParams:
def __init__(self,
process_id: int,
capabilities: ClientCapabilities,
root_uri: str = None,
root_path: Optional[str] = None,
initialization_options: Optional[Any] = None,
trace: Optional['Trace'] = 'off',
workspace_folders: Optional[List['WorkspaceFolder']] = None):
trace: Optional[Trace] = Trace.Off,
workspace_folders: Optional[List['WorkspaceFolder']] = None) -> None:
self.processId = process_id
self.rootPath = root_path
self.rootUri = root_uri
Expand All @@ -676,7 +701,7 @@ def __init__(self, capabilities: 'ServerCapabilities'):
self.capabilities = capabilities


class InsertTextFormat:
class InsertTextFormat(enum.IntEnum):
PlainText = 1
Snippet = 2

Expand Down Expand Up @@ -720,7 +745,7 @@ def __init__(self, kind: 'MarkupKind', value: str):
self.value = value


class MarkupKind:
class MarkupKind(str, enum.Enum):
PlainText = 'plaintext'
Markdown = 'markdown'

Expand All @@ -730,7 +755,7 @@ def __init__(self, title: str):
self.title = title


class MessageType:
class MessageType(enum.IntEnum):
Error = 1
Warning = 2
Info = 3
Expand Down Expand Up @@ -896,7 +921,7 @@ def __init__(self,
self.newName = new_name


class ResourceOperationKind:
class ResourceOperationKind(str, enum.Enum):
Create = 'create'
Rename = 'rename'
Delete = 'delete'
Expand Down Expand Up @@ -1062,7 +1087,7 @@ def __init__(self,
self.deprecated = deprecated


class SymbolKind:
class SymbolKind(enum.IntEnum):
File = 1
Module = 2
Namespace = 3
Expand Down Expand Up @@ -1256,13 +1281,13 @@ def __init__(self,
self.includeText = include_text


class TextDocumentSaveReason:
class TextDocumentSaveReason(enum.IntEnum):
Manual = 1
AfterDelay = 2
FocusOut = 3


class TextDocumentSyncKind:
class TextDocumentSyncKind(enum.IntEnum):
NONE = 0
FULL = 1
INCREMENTAL = 2
Expand All @@ -1271,7 +1296,7 @@ class TextDocumentSyncKind:
class TextDocumentSyncOptions:
def __init__(self,
open_close: bool = False,
change: int = TextDocumentSyncKind.NONE,
change: TextDocumentSyncKind = TextDocumentSyncKind.NONE,
will_save: bool = False,
will_save_wait_until: bool = False,
save: SaveOptions = None):
Expand All @@ -1288,12 +1313,6 @@ def __init__(self, range: Range, new_text: str):
self.newText = new_text


class Trace:
Off = 'off'
Messages = 'messages'
Verbose = 'verbose'


class Unregistration:
def __init__(self, id: str, method: str):
self.id = id
Expand All @@ -1311,12 +1330,6 @@ def __init__(self, uri: str, version: NumType):
self.version = version


class WatchKind:
Create = 1
Change = 2
Delete = 4


class WillSaveTextDocumentParams:
def __init__(self, text_document: TextDocumentIdentifier, reason: int):
self.textDocument = text_document
Expand Down