Skip to content

Commit

Permalink
refactor: tidy codes
Browse files Browse the repository at this point in the history
Signed-off-by: Jack Cherng <[email protected]>
  • Loading branch information
jfcherng committed May 4, 2024
1 parent afbbde4 commit 9b9fb6f
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 44 deletions.
18 changes: 10 additions & 8 deletions plugin/constant.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,22 @@

import sublime

assert __package__

PLUGIN_NAME = __package__.partition(".")[0]
"""Like `"AutoSetSyntax"`."""
"""E.g., `"AutoSetSyntax"`."""

ST_ARCH = sublime.arch()
"""Like `"x64"`."""
"""E.g., `"x64"`."""
ST_CHANNEL = sublime.channel()
"""Like `"dev"`."""
"""E.g., `"dev"`."""
ST_PLATFORM = sublime.platform()
"""Like `"windows"`."""
"""E.g., `"windows"`."""
ST_PLATFORM_ARCH = f"{ST_PLATFORM}_{ST_ARCH}"
"""Like `"windows_x64"`."""
"""E.g., `"windows_x64"`."""
ST_VERSION = int(sublime.version())
"""Like `4113`."""
"""E.g., `4113`."""
PY_VERSION_FULL = sys.version
"""Like `"3.8.8 (default, Mar 10 2021, 13:30:47) [MSC v.1915 64 bit (AMD64)]"`."""
"""E.g., `"3.8.8 (default, Mar 10 2021, 13:30:47) [MSC v.1915 64 bit (AMD64)]"`."""
PY_VERSION = PY_VERSION_FULL.partition(" ")[0]
"""Like `"3.8.8"`."""
"""E.g., `"3.8.8"`."""
40 changes: 18 additions & 22 deletions plugin/fanhuaji.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import annotations

from enum import Enum
from typing import Any

import sublime

from ..vendor import dacite, requests
from ..vendor.requests.exceptions import ConnectionError, RequestException
from .constant import ST_PLATFORM_ARCH, ST_VERSION
from .log import print_msg
from .settings import get_setting
Expand All @@ -15,18 +17,12 @@
}


class FanhuajiApiUrl:
@classmethod
def base_url(cls) -> str:
return get_setting("api_server").rstrip("/")
class FanhuajiEndpoint(str, Enum):
CONVERT = "convert"
SERVICE_INFO = "service-info"

@classmethod
def convert(cls) -> str:
return f"{cls.base_url()}/convert"

@classmethod
def service_info(cls) -> str:
return f"{cls.base_url()}/service-info"
def __str__(self) -> str:
return self.value


class Fanhuaji:
Expand All @@ -36,63 +32,55 @@ class Fanhuaji:
name_eng="Simplified Chinese",
name_chi="简体化",
details="将文字转换为简体。",
annotation="",
st_kind=(sublime.KIND_ID_COLOR_ORANGISH, "简", ""),
),
ConverterInfo(
name_api="Traditional",
name_eng="Traditional Chinese",
name_chi="繁體化",
details="將文字轉換為繁體。",
annotation="",
st_kind=(sublime.KIND_ID_COLOR_ORANGISH, "繁", ""),
),
ConverterInfo(
name_api="China",
name_eng="China Localization",
name_chi="中国化",
details="将文字转换为简体,并使用中国地区的词语修正。",
annotation="",
st_kind=(sublime.KIND_ID_COLOR_CYANISH, "中", ""),
),
ConverterInfo(
name_api="Hongkong",
name_eng="Hongkong Localization",
name_chi="香港化",
details="將文字轉換為繁體,並使用香港地區的詞語修正。",
annotation="",
st_kind=(sublime.KIND_ID_COLOR_CYANISH, "港", ""),
),
ConverterInfo(
name_api="Taiwan",
name_eng="Taiwan Localization",
name_chi="台灣化",
details="將文字轉換為繁體,並使用台灣地區的詞語修正。",
annotation="",
st_kind=(sublime.KIND_ID_COLOR_CYANISH, "台", ""),
),
ConverterInfo(
name_api="Pinyin",
name_eng="Pinyin",
name_chi="拼音化",
details="將文字轉為拼音。",
annotation="",
st_kind=(sublime.KIND_ID_COLOR_GREENISH, "拼", ""),
),
ConverterInfo(
name_api="Bopomofo",
name_eng="Bopomofo",
name_chi="注音化",
details="將文字轉為注音。",
annotation="",
st_kind=(sublime.KIND_ID_COLOR_GREENISH, "注", ""),
),
ConverterInfo(
name_api="Mars",
name_eng="Mars",
name_chi="火星化",
details="將文字轉換為繁體火星文。",
annotation="",
st_kind=(sublime.KIND_ID_COLOR_GREENISH, "火", ""),
),
ConverterInfo(
Expand Down Expand Up @@ -120,21 +108,29 @@ class Fanhuaji:
This delimiter should be a extremely rarely used string.
"""

@staticmethod
def base_url() -> str:
return get_setting("api_server").rstrip("/")

@classmethod
def url(cls, endpoint: FanhuajiEndpoint) -> str:
return f"{cls.base_url()}/{endpoint}"

@classmethod
def convert(cls, args: dict[str, Any]) -> ApiConvertResponse:
if get_setting("debug"):
print_msg(f"Request {args = }")

try:
response: requests.Response = requests.post(
url=FanhuajiApiUrl.convert(),
url=cls.url(FanhuajiEndpoint.CONVERT),
data=args,
headers=HTTP_HEADERS,
verify=bool(get_setting("ssl_cert_verification")),
)
except requests.exceptions.ConnectionError as e:
except ConnectionError as e:
raise RuntimeError(f"Failed to reach the server: {e}") from e
except requests.exceptions.RequestException as e:
except RequestException as e:
raise RuntimeError(f"Request exception: {e}") from e

return dacite.from_dict(ApiConvertResponse, sublime.decode_value(response.text))
2 changes: 0 additions & 2 deletions plugin/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ def msg(message: str) -> str:
:returns: The plugin message.
"""

return f"[{PLUGIN_NAME}] {message}"


Expand All @@ -22,6 +21,5 @@ def print_msg(message: str, show_message: bool = True) -> None:
:param message: The message
:param show_message: Whether to print the message
"""

if show_message:
print(msg(message))
20 changes: 12 additions & 8 deletions plugin/types.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
from __future__ import annotations

from dataclasses import dataclass

# ruff: noqa: UP006,UP007
# Cannot use something like `list[str]` in dacite. Typing is reqired for py38.
# @see https://github.com/konradhalas/dacite/issues/102
from typing import Dict, List, Optional, Tuple


@dataclass
class ConverterInfo:
st_kind: Tuple[int, str, str]
"""E.g., `(sublime.KIND_ID_AMBIGUOUS, "繁", "")`."""
name_api: str
"""Like `"WikiTraditional"`."""
"""E.g., `"WikiTraditional"`."""
name_eng: str
"""Like `"Traditional (Wikipeida)"`."""
"""E.g., `"Traditional (Wikipeida)"`."""
name_chi: str
"""Like `"維基繁體化"`."""
"""E.g., `"維基繁體化"`."""
details: str
"""Like `"只使用維基百科的詞庫將文字轉換為繁體。"`."""
annotation: str
"""Like `"(少用)"`."""
st_kind: Tuple[int, str, str]
"""Like `(sublime.KIND_ID_AMBIGUOUS, "繁", "")`."""
"""E.g., `"只使用維基百科的詞庫將文字轉換為繁體。"`."""
annotation: str = ""
"""E.g., `"(少用)"`."""


@dataclass
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ exclude = [
]

[tool.ruff.lint]
select = ["E", "F", "W", "I", "UP"]
select = ["E", "F", "W", "I", "UP", "FURB"]
ignore = ["E203"]

[tool.ruff.lint.per-file-ignores]
Expand Down
2 changes: 1 addition & 1 deletion requirements.in
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
mypy
ruff>=0.3
ruff>=0.4
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# This file was autogenerated by uv via the following command:
# uv pip compile requirements.in -o requirements.txt
mypy==1.9.0
mypy==1.10.0
mypy-extensions==1.0.0
# via mypy
ruff==0.3.7
ruff==0.4.3
typing-extensions==4.11.0
# via mypy

0 comments on commit 9b9fb6f

Please sign in to comment.