Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
Signed-off-by: Jack Cherng <[email protected]>
  • Loading branch information
jfcherng committed Apr 19, 2024
1 parent e419d3e commit 4f2e937
Show file tree
Hide file tree
Showing 15 changed files with 234 additions and 289 deletions.
7 changes: 5 additions & 2 deletions boot.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
from __future__ import annotations


def reload_plugin() -> None:
import sys

# remove all previously loaded plugin modules
prefix = "{}.".format(__package__)
prefix = f"{__package__}."
for module_name in tuple(filter(lambda m: m.startswith(prefix) and m != __name__, sys.modules)):
del sys.modules[module_name]


reload_plugin()

from .plugin import * # noqa: F401, F403
from .plugin import * # noqa: E402, F403
2 changes: 2 additions & 0 deletions plugin/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from .commands import (
CopilotAcceptCompletionCommand,
CopilotAcceptPanelCompletionCommand,
Expand Down
14 changes: 8 additions & 6 deletions plugin/commands.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import annotations

from abc import ABCMeta
from functools import partial, wraps
from typing import Any, Callable, cast

import sublime
from LSP.plugin import Request, Session
from LSP.plugin.core.registry import LspTextCommand, LspWindowCommand
from LSP.plugin.core.typing import Any, Callable, Optional, Union, cast

from .constants import (
PACKAGE_NAME,
Expand Down Expand Up @@ -92,15 +94,15 @@ def _record_telemetry(
self,
session: Session,
request: str,
payload: Union[CopilotPayloadNotifyAccepted, CopilotPayloadNotifyRejected],
payload: CopilotPayloadNotifyAccepted | CopilotPayloadNotifyRejected,
) -> None:
if not get_session_setting(session, "telemetry"):
return

session.send_request(Request(request, payload), lambda _: None)

@_provide_plugin_session(failed_return=False)
def is_enabled(self, plugin: CopilotPlugin, session: Session) -> bool: # type: ignore
def is_enabled(self, plugin: CopilotPlugin, session: Session) -> bool:
return self._can_meet_requirement(session)


Expand Down Expand Up @@ -153,7 +155,7 @@ def run(self, edit: sublime.Edit, completion_index: int) -> None:


class CopilotClosePanelCompletionCommand(CopilotWindowCommand):
def run(self, view_id: Optional[int] = None) -> None:
def run(self, view_id: int | None = None) -> None:
if view_id is None:
view = self.window.active_view()
else:
Expand Down Expand Up @@ -248,7 +250,7 @@ def run(self, plugin: CopilotPlugin, session: Session, _: sublime.Edit) -> None:
local_checks = get_session_setting(session, "local_checks")
session.send_request(Request(REQ_CHECK_STATUS, {"localChecksOnly": local_checks}), self._on_result_check_status)

def _on_result_check_status(self, payload: Union[CopilotPayloadSignInConfirm, CopilotPayloadSignOut]) -> None:
def _on_result_check_status(self, payload: CopilotPayloadSignInConfirm | CopilotPayloadSignOut) -> None:
if payload["status"] == "OK":
CopilotPlugin.set_account_status(signed_in=True, authorized=True)
message_dialog('Signed in and authorized with user "{}".', payload["user"])
Expand Down Expand Up @@ -276,7 +278,7 @@ def run(self, plugin: CopilotPlugin, session: Session, _: sublime.Edit) -> None:
def _on_result_sign_in_initiate(
self,
session: Session,
payload: Union[CopilotPayloadSignInConfirm, CopilotPayloadSignInInitiate],
payload: CopilotPayloadSignInConfirm | CopilotPayloadSignInInitiate,
) -> None:
if payload["status"] == "AlreadySignedIn":
return
Expand Down
4 changes: 4 additions & 0 deletions plugin/constants.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from __future__ import annotations

assert __package__

PACKAGE_NAME = __package__.partition(".")[0]

COPILOT_VIEW_SETTINGS_PREFIX = "copilot.completion"
Expand Down
14 changes: 8 additions & 6 deletions plugin/listeners.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import annotations

import re
from functools import wraps
from typing import Any, Callable, cast

import sublime
import sublime_plugin
from LSP.plugin.core.typing import Any, Callable, Dict, Optional, Tuple, cast

from .plugin import CopilotPlugin
from .types import T_Callable
Expand Down Expand Up @@ -72,8 +74,8 @@ def on_pre_close(self) -> None:
def on_close(self) -> None:
ViewCompletionManager(self.view).handle_close()

def on_query_context(self, key: str, operator: int, operand: Any, match_all: bool) -> Optional[bool]:
def test(value: Any) -> Optional[bool]:
def on_query_context(self, key: str, operator: int, operand: Any, match_all: bool) -> bool | None:
def test(value: Any) -> bool | None:
if operator == sublime.OP_EQUAL:
return value == operand
if operator == sublime.OP_NOT_EQUAL:
Expand Down Expand Up @@ -108,7 +110,7 @@ def test(value: Any) -> Optional[bool]:

return None

def on_post_text_command(self, command_name: str, args: Optional[Dict[str, Any]]) -> None:
def on_post_text_command(self, command_name: str, args: dict[str, Any] | None) -> None:
if command_name == "lsp_save":
self._is_saving = True

Expand All @@ -134,8 +136,8 @@ def on_window_command(
self,
window: sublime.Window,
command_name: str,
args: Optional[Dict[str, Any]],
) -> Optional[Tuple[str, Optional[Dict[str, Any]]]]:
args: dict[str, Any] | None,
) -> tuple[str, dict[str, Any] | None] | None:
sheet = window.active_sheet()

# if the user tries to close panel completion via Ctrl+W
Expand Down
29 changes: 14 additions & 15 deletions plugin/plugin.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from __future__ import annotations

import functools
import json
import os
import weakref
from functools import wraps
from typing import Any, Callable, cast
from urllib.parse import urlparse

import sublime
from LSP.plugin import Request, Session
from LSP.plugin.core.collections import DottedDict
from LSP.plugin.core.typing import Any, Callable, Dict, Optional, Tuple, Union, cast
from lsp_utils import ApiWrapperInterface, NpmClientHandler, notification_handler

from .constants import (
Expand Down Expand Up @@ -92,13 +94,13 @@ class CopilotPlugin(NpmClientHandler):
"agent.js",
)

plugin_mapping = weakref.WeakValueDictionary() # type: weakref.WeakValueDictionary[int, CopilotPlugin]
plugin_mapping: weakref.WeakValueDictionary[int, CopilotPlugin] = weakref.WeakValueDictionary()

# account status
_has_signed_in = False
_is_authorized = False

def __init__(self, session: "weakref.ref[Session]") -> None:
def __init__(self, session: weakref.ref[Session]) -> None:
super().__init__(session)
sess = session()
if sess:
Expand All @@ -125,7 +127,7 @@ def on_set_editor_info(result: str, failed: bool) -> None:
api.send_request(REQ_SET_EDITOR_INFO, self.editor_info(), on_set_editor_info)

def on_settings_changed(self, settings: DottedDict) -> None:
def parse_proxy(proxy: str) -> Optional[NetworkProxy]:
def parse_proxy(proxy: str) -> NetworkProxy | None:
# in the form of "username:password@host:port" or "host:port"
if not proxy:
return None
Expand Down Expand Up @@ -154,14 +156,12 @@ def parse_proxy(proxy: str) -> Optional[NetworkProxy]:
def version() -> str:
"""Return this plugin's version. If it's not installed by Package Control, return `"unknown"`."""
try:
return json.loads(sublime.load_resource("Packages/{}/package-metadata.json".format(PACKAGE_NAME)))[
"version"
]
return json.loads(sublime.load_resource(f"Packages/{PACKAGE_NAME}/package-metadata.json"))["version"]
except Exception:
return "unknown"

@classmethod
def editor_info(cls) -> Dict[str, Any]:
def editor_info(cls) -> dict[str, Any]:
return {
"editorInfo": {
"name": "Sublime Text",
Expand Down Expand Up @@ -190,10 +190,9 @@ def get_account_status(cls) -> AccountStatus:
def set_account_status(
cls,
*,
signed_in: Optional[bool] = None,
authorized: Optional[bool] = None,
quiet: bool = False
# format delimiter
signed_in: bool | None = None,
authorized: bool | None = None,
quiet: bool = False,
) -> None:
if signed_in is not None:
cls._has_signed_in = signed_in
Expand All @@ -210,7 +209,7 @@ def set_account_status(
status_message(msg, icon_=icon, console_=True)

@classmethod
def from_view(cls, view: sublime.View) -> Optional["CopilotPlugin"]:
def from_view(cls, view: sublime.View) -> CopilotPlugin | None:
window = view.window()
if not window:
return None
Expand All @@ -220,7 +219,7 @@ def from_view(cls, view: sublime.View) -> Optional["CopilotPlugin"]:
return self

@classmethod
def plugin_session(cls, view: sublime.View) -> Union[Tuple[None, None], Tuple["CopilotPlugin", Optional[Session]]]:
def plugin_session(cls, view: sublime.View) -> tuple[None, None] | tuple[CopilotPlugin, Session | None]:
plugin = cls.from_view(view)
return (plugin, plugin.weaksession()) if plugin else (None, None)

Expand Down Expand Up @@ -294,7 +293,7 @@ def _on_get_completions(
self,
view: sublime.View,
payload: CopilotPayloadCompletions,
region: Tuple[int, int],
region: tuple[int, int],
) -> None:
completion_manager = ViewCompletionManager(view)
completion_manager.is_waiting = False
Expand Down
Loading

0 comments on commit 4f2e937

Please sign in to comment.