feat: 支持基于语义化版本的自动更新

This commit is contained in:
Rock Chin 2023-03-05 11:56:40 +08:00
parent 79e970c4c3
commit 792366e221
4 changed files with 93 additions and 26 deletions

1
.gitignore vendored
View File

@ -11,3 +11,4 @@ prompts/
logs/ logs/
sensitive.json sensitive.json
temp/ temp/
current_tag

View File

@ -314,10 +314,14 @@ if __name__ == '__main__':
if not os.path.exists('banlist.py'): if not os.path.exists('banlist.py'):
shutil.copy('banlist-template.py', 'banlist.py') shutil.copy('banlist-template.py', 'banlist.py')
# 检查是否有sensitive.json, # 检查是否有sensitive.json
if not os.path.exists("sensitive.json"): if not os.path.exists("sensitive.json"):
shutil.copy("sensitive-template.json", "sensitive.json") shutil.copy("sensitive-template.json", "sensitive.json")
# 检查temp目录
if not os.path.exists("temp/"):
os.mkdir("temp/")
if len(sys.argv) > 1 and sys.argv[1] == 'init_db': if len(sys.argv) > 1 and sys.argv[1] == 'init_db':
init_db() init_db()
sys.exit(0) sys.exit(0)

View File

@ -1,4 +1,9 @@
import datetime import datetime
import logging
import os.path
import requests
import json
import pkg.utils.context import pkg.utils.context
@ -29,33 +34,85 @@ def pull_latest(repo_path: str) -> bool:
def update_all() -> bool: def update_all() -> bool:
"""使用dulwich更新源码""" """检查更新并下载源码"""
check_dulwich_closure() current_tag = "v0.1.0"
import dulwich if os.path.exists("current_tag"):
try: with open("current_tag", "r") as f:
before_commit_id = get_current_commit_id() current_tag = f.read()
from dulwich import porcelain
repo = porcelain.open_repo('.')
porcelain.pull(repo)
change_log = "" rls_list_resp = requests.get(
url="https://api.github.com/repos/RockChinQ/QChatGPT/releases"
)
for entry in repo.get_walker(): rls_list = rls_list_resp.json()
if str(entry.commit.id)[2:-1] == before_commit_id:
latest_rls = {}
rls_notes = []
for rls in rls_list:
rls_notes.append(rls['name']) # 使用发行名称作为note
if rls['tag_name'] == current_tag:
break break
tz = datetime.timezone(datetime.timedelta(hours=entry.commit.commit_timezone // 3600))
dt = datetime.datetime.fromtimestamp(entry.commit.commit_time, tz)
change_log += dt.strftime('%Y-%m-%d %H:%M:%S') + " [" + str(entry.commit.message, encoding="utf-8").strip()+"]\n"
if change_log != "": if latest_rls == {}:
pkg.utils.context.get_qqbot_manager().notify_admin("代码拉取完成,更新内容如下:\n"+change_log) latest_rls = rls
return True print(rls_notes)
else: if latest_rls == {}: # 没有新版本
return False return False
except ModuleNotFoundError:
raise Exception("dulwich模块未安装,请查看 https://github.com/RockChinQ/QChatGPT/issues/77") # 下载最新版本的zip到temp目录
except dulwich.porcelain.DivergedBranches: logging.info("开始下载最新版本: {}".format(latest_rls['zipball_url']))
raise Exception("分支不一致,自动更新仅支持master分支,请手动更新(https://github.com/RockChinQ/QChatGPT/issues/76)") zip_url = latest_rls['zipball_url']
zip_resp = requests.get(url=zip_url)
zip_data = zip_resp.content
# 检查temp/updater目录
if not os.path.exists("temp"):
os.mkdir("temp")
if not os.path.exists("temp/updater"):
os.mkdir("temp/updater")
with open("temp/updater/{}.zip".format(latest_rls['tag_name']), "wb") as f:
f.write(zip_data)
logging.info("下载最新版本完成: {}".format("temp/updater/{}.zip".format(latest_rls['tag_name'])))
# 解压zip到temp/updater/<tag_name>/
import zipfile
# 检查目标文件夹
if os.path.exists("temp/updater/{}".format(latest_rls['tag_name'])):
import shutil
shutil.rmtree("temp/updater/{}".format(latest_rls['tag_name']))
os.mkdir("temp/updater/{}".format(latest_rls['tag_name']))
with zipfile.ZipFile("temp/updater/{}.zip".format(latest_rls['tag_name']), 'r') as zip_ref:
zip_ref.extractall("temp/updater/{}".format(latest_rls['tag_name']))
# 覆盖源码
source_root = ""
# 找到temp/updater/<tag_name>/中的第一个子目录路径
for root, dirs, files in os.walk("temp/updater/{}".format(latest_rls['tag_name'])):
if root != "temp/updater/{}".format(latest_rls['tag_name']):
source_root = root
break
# 覆盖源码
import shutil
for root, dirs, files in os.walk(source_root):
# 覆盖所有子文件子目录
for file in files:
src = os.path.join(root, file)
dst = src.replace(source_root, ".")
if os.path.exists(dst):
os.remove(dst)
shutil.copy(src, dst)
# 把current_tag写入文件
current_tag = latest_rls['tag_name']
with open("current_tag", "w") as f:
f.write(current_tag)
# 通知管理员
import pkg.utils.context
pkg.utils.context.get_qqbot_manager().notify_admin("已更新到最新版本: {}\n更新日志:\n{}".format(current_tag, "\n".join(rls_notes)))
return True
def is_repo(path: str) -> bool: def is_repo(path: str) -> bool:
@ -144,3 +201,7 @@ def is_new_version_available() -> bool:
latest_commit_id = str(fetch_res[b'HEAD'])[2:-1] latest_commit_id = str(fetch_res[b'HEAD'])[2:-1]
return current_commit_id != latest_commit_id return current_commit_id != latest_commit_id
if __name__ == "__main__":
update_all()

View File

@ -1,5 +1,6 @@
requests~=2.28.1 requests~=2.28.1
openai~=0.27.0 openai~=0.27.0
dulwich~=0.21.3
colorlog~=6.6.0 colorlog~=6.6.0
yiri-mirai~=0.2.6.1 yiri-mirai~=0.2.6.1
websockets~=10.4 websockets~=10.4