Skip to content

Commit

Permalink
使用pyinstaller打包exe时生成hook以存储版本信息,改进检查更新时的文案提示
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuukiy committed Mar 13, 2021
1 parent 06645e8 commit 537e1e5
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 36 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,6 @@ dmypy.json

# Pyre type checker
.pyre/

# hook script generated for pyinstaller
ver_hook.py
3 changes: 1 addition & 2 deletions JavSP.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,7 @@ def error_exit(msg):
colorama.init(autoreset=True)
logger = logging.getLogger('main')
# 检查更新
if cfg.Other.check_update:
check_update(print=tqdm.write)
check_update(allow_check=cfg.Other.check_update, print=tqdm.write)
# 如果未配置有效代理,则显示相应提示
if not cfg.Network.proxy:
logger.warning('未配置有效代理,程序会努力继续运行,但是部分功能可能受限:\n'
Expand Down
102 changes: 69 additions & 33 deletions core/func.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,47 +54,83 @@ def get_actual_width(mix_str: str) -> int:
return width


def align_to_width(mix_str: str, width: int) -> str:
"""给定一个中英混合的字符串,将其实际显示宽度对齐到指定的值"""
def align_center(mix_str: str, total_width: int) -> str:
"""给定一个中英混合的字符串,根据其实际显示宽度中心对齐"""
actual_width = get_actual_width(mix_str)
aligned_str = mix_str + ' ' * (width-actual_width)
add_space = int((total_width - actual_width) / 2)
aligned_str = ' ' * add_space + mix_str
return aligned_str


def check_update(local_version='v0.0', print=print):
"""检查是否有新版本"""
api_url = 'https://api.github.com/repos/Yuukiy/JavSP/releases/latest'
release_url = 'https://github.com/Yuukiy/JavSP/releases/latest'
print('正在检查更新...', end='')
try:
data = request_get(api_url, timeout=3).json()
print(CLEAR_LINE, end='')
except:
print(CLEAR_LINE + '检查更新失败,请前往以下地址查看是否有新版本: ')
print(' ' + release_url + '\n')
return
latest_version = data['tag_name']
if version.parse(local_version) < version.parse(latest_version):
# 提取changelog消息
lines = data['body'].split('\r\n')
changelog = []
for line in lines:
if line.startswith('## '):
changelog.append(Style.BRIGHT + line[3:] + Style.RESET_ALL)
elif line.startswith('- '):
changelog.append(line)
display_width = max([get_actual_width(i) for i in lines]) + 5
display_width = max(display_width, len(release_url))
# 输出更新信息
def check_update(allow_check=True, print=print):
"""检查版本更新"""

def print_header(title, info=[]):
title_width = max([get_actual_width(i) for i in title])
if info:
info_width = max([get_actual_width(i) for i in info])
else:
info_width = 0
display_width = max(title_width, info_width) + 6
print('=' * display_width)
title = '↓ Jav Scraper Package 新版本: ' + latest_version + ' ↓'
print(Fore.LIGHTCYAN_EX + title.center(display_width) + Style.RESET_ALL)
print(release_url.center(display_width))
print('-' * display_width)
print('\n'.join(changelog))
for line in title:
print(align_center(line, display_width))
if info:
print('-' * display_width)
for line in info:
print(line)
print('=' * display_width)
print('')

# 使用pyinstaller打包exe时生成hook,运行时由该hook将版本信息注入到sys中
local_version = getattr(sys, 'javsp_version', None)
if not local_version:
return
# 检查更新
if allow_check:
api_url = 'https://api.github.com/repos/Yuukiy/JavSP/releases/latest'
release_url = 'https://github.com/Yuukiy/JavSP/releases/latest'
print('正在检查更新...', end='')
try:
data = request_get(api_url, timeout=3).json()
latest_version = data['tag_name']
if version.parse(local_version) < version.parse(latest_version):
update_status = 'new_version'
else:
update_status = 'already_latest'
except:
update_status = 'fail_to_check'
else:
update_status = 'disallow'
# 根据检查更新的情况输出软件版本信息和更新信息
print(CLEAR_LINE, end='')
if update_status == 'disallow':
title = f'Jav Scraper Package: {local_version}'
print_header([title])
elif update_status == 'already_latest':
title = f'Jav Scraper Package: {local_version} (已是最新版)'
print_header([title])
elif update_status == 'fail_to_check':
titles = [f'Jav Scraper Package: {local_version}']
info = ['检查更新失败,请前往以下地址查看是否有新版本:', ' '+release_url]
print_header(titles, info)
elif update_status == 'new_version':
titles = [f'Jav Scraper Package: {local_version}']
titles.append(f'↓ 有新版本可下载: {latest_version} ↓')
titles.append(release_url)
# 提取changelog消息
try:
lines = data['body'].split('\r\n')
changelog = []
for line in lines:
if line.startswith('## '):
changelog.append(Style.BRIGHT + line[3:] + Style.RESET_ALL)
elif line.startswith('- '):
changelog.append(line)
print_header(titles, changelog)
except:
print_header(titles)


if __name__ == "__main__":
check_update()
2 changes: 2 additions & 0 deletions make.bat
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ IF EXIST %activate% (
call %activate%
)

python make\gen_ver_hook.py ver_hook.py
pyinstaller --clean --noconfirm make\windows.spec
del ver_hook.py
del dist\config.ini 2>nul
rmdir /s /q build
20 changes: 20 additions & 0 deletions make/gen_ver_hook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import sys
import subprocess

run = subprocess.run(['git', 'describe', '--tags'], capture_output=True, encoding='utf-8')
if run.returncode == 0:
desc = run.stdout.strip()
if '-' in desc:
major, minor, _ = desc.split('-')
auto_ver = major + '.' + minor
else: # means current commit exactly matches the tag
auto_ver = desc
else:
auto_ver = "v0.unknown"

print('JavSP version: ' + auto_ver)

hook_file = sys.argv[1]
with open(hook_file, 'wt') as f:
f.write('import sys\n')
f.write("setattr(sys, 'javsp_version', '" + auto_ver + "')\n")
2 changes: 1 addition & 1 deletion make/windows.spec
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ a = Analysis(['../JavSP.py'],
'core/config.py'
],
hookspath=[],
runtime_hooks=[],
runtime_hooks=['ver_hook.py'],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
Expand Down

0 comments on commit 537e1e5

Please sign in to comment.