Skip to content

Commit

Permalink
refactor: tidy codes
Browse files Browse the repository at this point in the history
Signed-off-by: Jack Cherng <jfcherng@gmail.com>
  • Loading branch information
jfcherng committed May 4, 2024
1 parent a39b0f8 commit 0fbd8e5
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2,919 deletions.
4 changes: 2 additions & 2 deletions plugin/commands/select_emoji.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import sublime
import sublime_plugin

from ..constants import DB_GENERATOR_REVISION
from ..constants import DB_REVISION
from ..emoji import EmojiDatabase, get_emoji_db


Expand All @@ -31,5 +31,5 @@ def callback(selected: int) -> None:
if selected >= 0:
self.view.run_command("insert", {"characters": db[selected].char})

db = get_emoji_db(DB_GENERATOR_REVISION)
db = get_emoji_db(DB_REVISION)
window.show_quick_panel(emoji_db_to_quick_panel_items(db), callback)
6 changes: 4 additions & 2 deletions plugin/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

import sublime

assert __package__

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

DB_FILE_IN_PACKAGE = f"Packages/{PACKAGE_NAME}/data/emoji-test.txt"
DB_FILE_CACHED = Path(sublime.cache_path()) / f"{PACKAGE_NAME}/db.json"
DB_GENERATOR_REVISION = 1
DB_FILE_CACHED = Path(sublime.cache_path()) / f"{PACKAGE_NAME}/db.bin"
DB_REVISION = 2
41 changes: 18 additions & 23 deletions plugin/emoji.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

import json
import pickle
import re
from collections.abc import Iterable, Iterator, Sequence
from dataclasses import asdict, dataclass, field
Expand All @@ -10,25 +10,25 @@

import sublime

from .constants import DB_FILE_CACHED, DB_FILE_IN_PACKAGE, DB_GENERATOR_REVISION
from .constants import DB_FILE_CACHED, DB_FILE_IN_PACKAGE, DB_REVISION
from .utils import pp_error, pp_info, pp_warning


@lru_cache
def get_emoji_db(generator_revision: int) -> EmojiDatabase:
def get_emoji_db(db_revision: int) -> EmojiDatabase:
def _create_db_cache() -> EmojiDatabase:
pp_info(f"Create database cache: {DB_FILE_CACHED}")
db_content = sublime.load_resource(DB_FILE_IN_PACKAGE)
db = EmojiDatabase.from_content(db_content)
DB_FILE_CACHED.parent.mkdir(parents=True, exist_ok=True)
DB_FILE_CACHED.write_text(db.to_json(), encoding="utf-8")
DB_FILE_CACHED.write_bytes(db.to_pickle())
return db

def _load_db_cache() -> EmojiDatabase | None:
try:
db_dict: dict[str, Any] = json.loads(DB_FILE_CACHED.read_bytes())
db_dict: dict[str, Any] = pickle.loads(DB_FILE_CACHED.read_bytes())
db = EmojiDatabase.from_dict(db_dict)
if db.generator_revision == generator_revision:
if db.db_revision == db_revision:
pp_info(f"Load database cache: {DB_FILE_CACHED}")
return db
pp_warning("Mismatched database cache revision...")
Expand Down Expand Up @@ -118,10 +118,10 @@ def str_to_code_points(s: str) -> list[str]:

@dataclass
class EmojiDatabase:
db_revision: int = 0
date: str = ""
version: str = ""
emojis: list = field(default_factory=list)
generator_revision: int = 0

_re_version = re.compile(r"^#\s*Version:\s*(?P<version>.*)$")
"""Matches `# Version: 15.1`."""
Expand All @@ -132,7 +132,7 @@ def __getitem__(self, index: int) -> Emoji:
return self.emojis[index]

def __hash__(self) -> int:
return hash((self.date, self.version, self.generator_revision))
return hash((self.db_revision, self.date, self.version))

def __iter__(self) -> Iterator[Emoji]:
return iter(self.emojis)
Expand All @@ -144,9 +144,9 @@ def __str__(self) -> str:
"""Returns a string like "emoji-test.txt"."""
data = "\n".join(map(str, self.emojis))
return f"""
# DB Revision: {self.db_revision}
# Date: {self.date}
# Version: {self.version}
# Generator Version: {self.generator_revision}
{data}
# EOF
"""
Expand All @@ -158,18 +158,18 @@ def from_content(cls, content: str) -> EmojiDatabase:
@classmethod
def from_dict(cls, db: dict[str, Any]) -> EmojiDatabase:
return cls(
db_revision=db.get("db_revision", DB_REVISION),
date=db.get("date", ""),
version=db.get("version", ""),
emojis=list(map(Emoji.from_dict, db.get("emojis", []))),
generator_revision=db.get("generator_revision", 0),
)

@classmethod
def from_lines(cls, lines: Iterable[str]) -> EmojiDatabase:
collection = cls()
collection = cls(db_revision=DB_REVISION)
for line in lines:
if e := Emoji.from_line(line):
collection.emojis.append(e)
if emoji := Emoji.from_line(line):
collection.emojis.append(emoji)
continue
if m := cls._re_version.fullmatch(line):
collection.version = m.group("version").strip()
Expand All @@ -179,13 +179,8 @@ def from_lines(cls, lines: Iterable[str]) -> EmojiDatabase:
continue
return collection

def to_json(self, *, pretty: bool = False) -> str:
if pretty:
kwargs: dict[str, Any] = {"indent": "\t"}
else:
kwargs = {"separators": (",", ":")}
return json.dumps(
dict(asdict(self), generator_revision=DB_GENERATOR_REVISION),
ensure_ascii=False,
**kwargs,
)
def to_dict(self) -> dict[str, Any]:
return asdict(self)

def to_pickle(self) -> bytes:
return pickle.dumps(self.to_dict())
Loading

0 comments on commit 0fbd8e5

Please sign in to comment.