-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Jack Cherng <[email protected]>
- Loading branch information
Showing
16 changed files
with
485 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
157 changes: 157 additions & 0 deletions
157
plugin/commands/auto_set_syntax_download_dependencies.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
from __future__ import annotations | ||
|
||
import gzip | ||
import tarfile | ||
import threading | ||
import time | ||
import urllib.request | ||
import zipfile | ||
from collections.abc import Iterable | ||
from pathlib import Path | ||
from typing import Union | ||
|
||
import sublime | ||
import sublime_plugin | ||
|
||
from ..constants import GUESSLANG_SERVER_URL, PLUGIN_NAME | ||
from ..guesslang.server import GuesslangServer | ||
from ..settings import get_merged_plugin_setting | ||
from ..shared import G | ||
from ..utils import first_true, rmtree_ex | ||
|
||
PathLike = Union[Path, str] | ||
|
||
|
||
class AutoSetSyntaxDownloadDependenciesCommand(sublime_plugin.ApplicationCommand): | ||
# Server codes are published on https://github.com/jfcherng-sublime/ST-AutoSetSyntax/tree/dependencies | ||
|
||
def description(self) -> str: | ||
return f"{PLUGIN_NAME}: Download Dependencies" | ||
|
||
def run(self) -> None: | ||
self.t = threading.Thread(target=self._worker) | ||
self.t.start() | ||
|
||
@classmethod | ||
def _worker(cls) -> None: | ||
sublime.status_message("Begin downloading guesslang server...") | ||
|
||
if (server := G.guesslang_server) and server.is_running(): | ||
server.stop() | ||
time.sleep(1) # wait for stopping the server | ||
|
||
rmtree_ex(GuesslangServer.SERVER_DIR, ignore_errors=True) | ||
|
||
try: | ||
cls._prepare_bin() | ||
|
||
if not GuesslangServer.SERVER_FILE.is_file(): | ||
sublime.error_message(f"[{PLUGIN_NAME}] Cannot find the server: {str(GuesslangServer.SERVER_FILE)}") | ||
|
||
if get_merged_plugin_setting("guesslang.enabled"): | ||
sublime.run_command("auto_set_syntax_restart_guesslang") | ||
|
||
sublime.message_dialog(f"[{PLUGIN_NAME}] Finish downloading guesslang server!") | ||
except Exception as e: | ||
sublime.error_message(f"[{PLUGIN_NAME}] {e}") | ||
|
||
@staticmethod | ||
def _prepare_bin() -> None: | ||
zip_path = GuesslangServer.SERVER_DIR / "source.zip" | ||
download_file(GUESSLANG_SERVER_URL, zip_path) | ||
decompress_file(zip_path) | ||
|
||
# get the folder, which is just decompressed | ||
folder = first_true( | ||
sorted( | ||
filter(Path.is_dir, zip_path.parent.iterdir()), | ||
key=lambda p: p.stat().st_mtime, | ||
reverse=True, | ||
), | ||
) | ||
|
||
if not folder: | ||
return | ||
|
||
# move the decompressed folder one level up | ||
guesslang_server_dir = folder.parent | ||
tmp_dir = guesslang_server_dir.parent / ".tmp" | ||
rmtree_ex(tmp_dir, ignore_errors=True) | ||
folder.replace(tmp_dir) | ||
rmtree_ex(guesslang_server_dir, ignore_errors=True) | ||
tmp_dir.replace(guesslang_server_dir) | ||
# cleanup | ||
zip_path.unlink(missing_ok=True) | ||
|
||
|
||
def decompress_file(tarball: PathLike, dst_dir: PathLike | None = None) -> bool: | ||
""" | ||
Decompress the tarball. | ||
:param tarball: The tarball | ||
:param dst_dir: The destination directory | ||
:returns: Successfully decompressed the tarball or not | ||
""" | ||
|
||
def tar_safe_extract( | ||
tar: tarfile.TarFile, | ||
path: PathLike = ".", | ||
members: Iterable[tarfile.TarInfo] | None = None, | ||
*, | ||
numeric_owner: bool = False, | ||
) -> None: | ||
path = Path(path).resolve() | ||
for member in tar.getmembers(): | ||
member_path = (path / member.name).resolve() | ||
if path not in member_path.parents: | ||
raise Exception("Attempted Path Traversal in Tar File") | ||
|
||
tar.extractall(path, members, numeric_owner=numeric_owner) | ||
|
||
tarball = Path(tarball) | ||
dst_dir = Path(dst_dir) if dst_dir else tarball.parent | ||
filename = tarball.name | ||
|
||
try: | ||
if filename.endswith(".tar.gz"): | ||
with tarfile.open(tarball, "r:gz") as f_1: | ||
tar_safe_extract(f_1, dst_dir) | ||
return True | ||
|
||
if filename.endswith(".tar"): | ||
with tarfile.open(tarball, "r:") as f_2: | ||
tar_safe_extract(f_2, dst_dir) | ||
return True | ||
|
||
if filename.endswith(".zip"): | ||
with zipfile.ZipFile(tarball) as f_3: | ||
f_3.extractall(dst_dir) | ||
return True | ||
except Exception: | ||
pass | ||
return False | ||
|
||
|
||
def download_file(url: str, save_path: PathLike) -> None: | ||
""" | ||
Downloads a file. | ||
:param url: The url | ||
:param save_path: The path of the saved file | ||
""" | ||
|
||
save_path = Path(save_path) | ||
save_path.unlink(missing_ok=True) | ||
save_path.parent.mkdir(parents=True, exist_ok=True) | ||
save_path.write_bytes(simple_urlopen(url)) | ||
|
||
|
||
def simple_urlopen(url: str, chunk_size: int = 512 * 1024) -> bytes: | ||
response = urllib.request.urlopen(url) | ||
data = b"" | ||
while chunk := response.read(chunk_size): | ||
data += chunk | ||
if response.info().get("Content-Encoding") == "gzip": | ||
data = gzip.decompress(data) | ||
return data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
// This is a comment, and is ignored by the compiler. | ||
// You can test this code by clicking the "Run" button over there -> | ||
// or if you prefer to use your keyboard, you can use the "Ctrl + Enter" | ||
// shortcut. | ||
|
||
// This code is editable, feel free to hack it! | ||
// You can always return to the original code by clicking the "Reset" button -> | ||
|
||
// This is the main function. | ||
fn main() { | ||
// Statements here are executed when the compiled binary is called. | ||
|
||
// Print text to the console. | ||
println!("Hello World!"); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
from magika import magika as magika, prediction_mode as prediction_mode | ||
|
||
Magika = magika.Magika | ||
MagikaError = magika.MagikaError | ||
PredictionMode = prediction_mode.PredictionMode |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
from _typeshed import Incomplete | ||
from magika import Magika as Magika, MagikaError as MagikaError, PredictionMode as PredictionMode, colors as colors | ||
from magika.content_types import ContentTypesManager as ContentTypesManager | ||
from magika.logger import get_logger as get_logger | ||
from magika.types import FeedbackReport as FeedbackReport, MagikaResult as MagikaResult | ||
from pathlib import Path | ||
from typing import List, Optional | ||
|
||
VERSION: str | ||
CONTACT_EMAIL: str | ||
CONTEXT_SETTINGS: Incomplete | ||
HELP_EPILOG: Incomplete | ||
|
||
def main(file: List[Path], recursive: bool, json_output: bool, jsonl_output: bool, mime_output: bool, label_output: bool, magic_compatibility_mode: bool, output_score: bool, prediction_mode_str: str, batch_size: int, no_dereference: bool, with_colors: bool, verbose: bool, debug: bool, generate_report_flag: bool, output_version: bool, list_output_content_types: bool, model_dir: Optional[Path]) -> None: ... | ||
def should_read_from_stdin(files_paths: List[Path]) -> bool: ... | ||
def get_magika_result_from_stdin(magika: Magika) -> MagikaResult: ... | ||
def generate_feedback_report(magika: Magika, file_path: Path, magika_result: MagikaResult) -> FeedbackReport: ... | ||
def print_feedback_report(magika: Magika, reports: List[FeedbackReport]) -> None: ... | ||
def print_output_content_types_list() -> None: ... |
Oops, something went wrong.