chore: coding style upgrade (#10157)

chore: code style upgrade
This commit is contained in:
CY-Zhu
2024-08-10 00:05:40 +08:00
committed by GitHub
parent f7c591239d
commit 3bbcb7c087
3 changed files with 45 additions and 19 deletions

View File

@@ -5,14 +5,16 @@ import urllib.request
import urllib.error
import json
import time
import platform
from pathlib import Path
import shutil
import http.client
TARGET_TAG = "2024-05-30"
basedir = Path(__file__).parent
def detect_host_triplet():
import platform
machine = platform.machine().lower()
system = platform.system().lower()
if machine in {"amd64", "x86_64"}:
@@ -35,6 +37,7 @@ def detect_host_triplet():
raise Exception("unsupported system: " + system)
return f"{machine}-{system}"
def format_size(num, suffix="B"):
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
@@ -47,23 +50,29 @@ class ProgressHook:
def __init__(self):
self.downloaded = 0
self.last_print = 0
def __call__(self, block, chunk, total):
self.downloaded += chunk
t = time.monotonic()
if t - self.last_print >= 0.5 or self.downloaded == total:
self.last_print = t
if total > 0:
print(f"\r [{self.downloaded / total * 100.0:3.1f}%] {format_size(self.downloaded)} / {format_size(total)} \r", end='')
print(
f"\r [{self.downloaded / total * 100.0:3.1f}%] ",
f"{format_size(self.downloaded)} / {format_size(total)}",
" \r",
end=''
)
if self.downloaded == total:
print("")
def sanitize_filename(filename: str):
import platform
system = platform.system()
if system == "Windows":
filename = filename.translate(str.maketrans("/\\:\"?*|\0", "________")).rstrip('.')
filename = filename.translate(
str.maketrans("/\\:\"?*|\0", "________")
).rstrip('.')
elif system == "Darwin":
filename = filename.translate(str.maketrans("/:\0", "___"))
else:
@@ -72,14 +81,14 @@ def sanitize_filename(filename: str):
def retry_urlopen(*args, **kwargs):
import time
import http.client
for _ in range(5):
try:
resp: http.client.HTTPResponse = urllib.request.urlopen(*args, **kwargs)
resp: http.client.HTTPResponse = urllib.request.urlopen(*args,
**kwargs)
return resp
except urllib.error.HTTPError as e:
if e.status == 403 and e.headers.get("x-ratelimit-remaining") == "0":
if (e.status == 403 and
e.headers.get("x-ratelimit-remaining") == "0"):
# rate limit
t0 = time.time()
reset_time = t0 + 10
@@ -88,7 +97,10 @@ def retry_urlopen(*args, **kwargs):
except ValueError:
pass
reset_time = max(reset_time, t0 + 10)
print(f"rate limit exceeded, retrying after {reset_time - t0:.1f} seconds")
print(
"rate limit exceeded, retrying after ",
f"{reset_time - t0:.1f} seconds"
)
time.sleep(reset_time - t0)
continue
raise
@@ -104,16 +116,28 @@ def main():
target_tag = sys.argv[2]
else:
target_tag = TARGET_TAG
print(f"about to download prebuilt dependency libraries for {target_triplet} of {target_tag}")
print(
"about to download prebuilt dependency libraries for ",
f"{target_triplet} of {target_tag}"
)
if len(sys.argv) == 1:
print(f"to specify another triplet [and tag], run `{sys.argv[0]} <target triplet> [tag]`")
print(f"e.g. `{sys.argv[0]} arm64-windows` or `{sys.argv[0]} arm64-windows 2023-04-24-3`")
req = urllib.request.Request("https://api.github.com/repos/MaaAssistantArknights/MaaDeps/releases")
print(
"to specify another triplet [and tag], ",
f"run `{sys.argv[0]} <target triplet> [tag]`"
)
print(
f"e.g. `{sys.argv[0]} arm64-windows` ",
f"or `{sys.argv[0]} arm64-windows 2023-04-24-3`"
)
req = urllib.request.Request(
"https://api.github.com/repos/MaaAssistantArknights/MaaDeps/releases"
)
token = os.environ.get("GH_TOKEN", os.environ.get("GITHUB_TOKEN", None))
if token:
req.add_header("Authorization", f"Bearer {token}")
resp = retry_urlopen(req).read()
releases = json.loads(resp)
def split_asset_name(name: str):
*remainder, component_suffix = name.rsplit('-', 1)
component = component_suffix.split(".", 1)[0]
@@ -147,11 +171,13 @@ def main():
url = asset['browser_download_url']
print("downloading from", url)
local_file = download_dir / sanitize_filename(asset["name"])
urllib.request.urlretrieve(url, local_file, reporthook=ProgressHook())
urllib.request.urlretrieve(url, local_file,
reporthook=ProgressHook())
print("extracting", asset["name"])
shutil.unpack_archive(local_file, maadeps_dir)
else:
raise Exception(f"no binary release found for {target_triplet}")
if __name__ == "__main__":
main()

View File

@@ -415,7 +415,7 @@ namespace MaaWpfGui.ViewModels.UI
Id = id,
Name = ItemListHelper.GetItemName(id),
Image = ItemListHelper.GetItemImage(id),
Count = (int)item["have"]
Count = (int)item["have"],
};
DepotResult.Add(result);
}

View File

@@ -235,6 +235,7 @@ namespace MaaWpfGui.ViewModels.UI
{
File.Delete("MAA_win7.exe");
}
if (File.Exists("启动旧版.cmd"))
{
File.Delete("启动旧版.cmd");
@@ -537,8 +538,7 @@ namespace MaaWpfGui.ViewModels.UI
{
Process.Start(new ProcessStartInfo(UpdateUrl) { UseShellExecute = true });
}
}
);
});
_ = Execute.OnUIThreadAsync(() =>
{
using var toast = new ToastNotification((otaFound ? LocalizationHelper.GetString("NewVersionFoundTitle") : LocalizationHelper.GetString("NewVersionFoundButNoPackageTitle")) + " : " + UpdateTag);