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 Mar 2, 2024
1 parent 497a53a commit 0f4ace9
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 15 deletions.
15 changes: 6 additions & 9 deletions plugin/commands/auto_set_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,21 +260,18 @@ def _assign_syntax_with_heuristics(view: sublime.View, event: ListenerEvent | No
):
return False

def is_large_file(view: sublime.View) -> bool:
return view.size() >= 10 * 1024 # 10KB

def is_json(view: sublime.View) -> bool:
view_snapshot = G.view_snapshot_collection.get_by_view(view)
assert view_snapshot
def is_large_file(view_snapshot: ViewSnapshot) -> bool:
return view_snapshot.char_count >= 10 * 1024 # 10KB

def is_json(view_snapshot: ViewSnapshot) -> bool:
text_begin = re.sub(r"^\s+", "", view_snapshot.content[:10])
text_end = re.sub(r"\s+$", "", view_snapshot.content[-10:])

# XSSI protection prefix (https://security.stackexchange.com/q/110539)
if text_begin.startswith((")]}'\n", ")]}',\n")):
return True

return is_large_file(view) and bool(
return is_large_file(view_snapshot) and bool(
# map
(re.search(r'^\{"', text_begin) and re.search(r'(?:[\d"\]}]|true|false|null)\}$', text_end))
# array
Expand All @@ -283,7 +280,7 @@ def is_json(view: sublime.View) -> bool:
or (text_begin.startswith("[{") and text_end.endswith("}]"))
)

if is_json(view) and (syntax := find_syntax_by_syntax_like("scope:source.json")):
if is_json(view_snapshot) and (syntax := find_syntax_by_syntax_like("scope:source.json")):
return assign_syntax_to_view(view, syntax, details={"event": event, "reason": "heuristics"})

return False
Expand Down Expand Up @@ -314,7 +311,7 @@ def _assign_syntax_with_magika(view: sublime.View, event: ListenerEvent | None =

classifier = Magika()
output = classifier.identify_bytes(view_snapshot.content.encode()).output
Logger.log(f"🐛 Magika's prediction: {output}", window=window)
# Logger.log(f"🐛 Magika's prediction: {output}", window=window)

threadshold: float = settings.get("magika.min_confidence", 0.0)
if output.score < threadshold or output.ct_label in {"directory", "empty", "txt", "unknown"}:
Expand Down
2 changes: 1 addition & 1 deletion plugin/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def names_as_str(items: Iterable[Any], *, sep: str = ", ") -> str:
def _configured_debounce(func: _T_Callable) -> _T_Callable:
"""Debounce a function so that it's called once in seconds."""

def debounced(*args: Any, **kwargs: Any) -> None:
def debounced(*args: Any, **kwargs: Any) -> Any:
if (time_s := get_merged_plugin_setting("debounce", 0)) > 0:
return debounce(time_s)(func)(*args, **kwargs)
return func(*args, **kwargs)
Expand Down
25 changes: 21 additions & 4 deletions plugin/rules/constraints/selector_matches.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,28 @@

@final
class SelectorMatchesConstraint(AbstractConstraint):
# Quick tips:
# - sublime.score_selector('a.b', 'b') == 0
# - sublime.score_selector('a.b', '') == 1
# - sublime.score_selector('a.b', 'a') == 8
SCORE_THRESHOLD = 1
"""
Quick tips (ST >= 4173):
```python
sublime.score_selector("a.b", "b") == 0
sublime.score_selector("a.b", "") == 1
sublime.score_selector("a.b", " ") == 1
sublime.score_selector("a.b", "a") == 1
sublime.score_selector("a.b", "a.b") == 2
```
Quick tips (ST < 4173):
```python
sublime.score_selector("a.b", "b") == 0
sublime.score_selector("a.b", "") == 1
sublime.score_selector("a.b", " ") == 1
sublime.score_selector("a.b", "a") == 8
sublime.score_selector("a.b", "a.b") == 16
```
"""

def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
Expand Down
6 changes: 5 additions & 1 deletion plugin/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,11 @@ def list_all_views(*, include_transient: bool = False) -> Generator[sublime.View


def get_view_by_id(id: int) -> sublime.View | None:
return first_true(list_all_views(include_transient=True), pred=lambda view: view.id() == id)
return view if (view := sublime.View(id)).is_valid() else None


def get_window_by_id(id: int) -> sublime.Window | None:
return window if (window := sublime.Window(id)).is_valid() else None


def head_tail_content(content: str, partial: int) -> str:
Expand Down

0 comments on commit 0f4ace9

Please sign in to comment.