|
| 1 | +#!/usr/bin/python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +"""code packer |
| 4 | +env-python: developer |
| 5 | +""" |
| 6 | +import os |
| 7 | +import shutil |
| 8 | +import pathlib |
| 9 | +import stat |
| 10 | +import datetime |
| 11 | + |
| 12 | +import py7zr |
| 13 | + |
| 14 | +from tqdm import tqdm |
| 15 | +from loguru import logger |
| 16 | +from github import Github, Auth |
| 17 | + |
| 18 | +# import github.Requester # REMARK(2024-08-08): modified in package: HTTPSRequestsConnectionClass.session.proxies |
| 19 | + |
| 20 | + |
| 21 | +path = pathlib.Path(__file__).parent |
| 22 | +api_github = "https://api.github.com" |
| 23 | +github_token = "**create token by your github account**" |
| 24 | +proxies = None |
| 25 | +headers = { |
| 26 | + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0", |
| 27 | + "Accept": "*/*", |
| 28 | + "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", |
| 29 | + "Accept-Encoding": "gzip, deflate, br, zstd", |
| 30 | + "Origin": "https://github.com", |
| 31 | + "Connection": "keep-alive", |
| 32 | + "Referer": "https://github.com/", |
| 33 | + "Priority": "u=0", |
| 34 | + "Pragma": "no-cache", |
| 35 | + "Cache-Control": "no-cache", |
| 36 | + "TE": "trailers" |
| 37 | +} |
| 38 | +preset = { |
| 39 | + "python": ["api-ms-win-core", "base_library.zip", ".tcl", "tclIndex", "MSVCP140.dll", "cacert.pem", "cp936.enc", |
| 40 | + "__init__", "python.exe", "pythonw.exe", "VCRUNTIME140_1.dll"], |
| 41 | + "matplotlib": ["matplotlibrc", ".load-order", "matplotlib.svg"], "request": ["msgcat-1.6.1.tm"], |
| 42 | + "plotly": ["plotly.json", "plotly.min.js", "package_data\\templates"], "pyecharts": ["pyecharts"], |
| 43 | + "pyqtwebengine": ["QtWebEngineProcess.exe", "icudtl.dat", "qtwebengine_devtools_resources.pak", |
| 44 | + "qtwebengine_resources", "qt.conf"], "streamlit": ["streamlit\\static"], |
| 45 | + "trame_vtk": ["static_viewer.html"], "python-docx": ["docx\\templates"], "python-pptx": ["pptx\\templates"], |
| 46 | + "scrapy": ["mime.types"]} |
| 47 | +release_desc = """开箱即用 |
| 48 | +--- |
| 49 | +解压双击运行 `comic_viewer.exe` |
| 50 | +
|
| 51 | +下载很慢 ?到压缩包的下载链接右键复制到 https://github.akams.cn/ 上进行下载加速 |
| 52 | +
|
| 53 | +一般情况下,使用包内的更新程序 `comic_viewer-更新.exe` 即可<br> |
| 54 | +特殊情况,如运行环境需要变化时,需要在此页面下绿色安装包 (包更新未必是最新,更新日期参照标题) |
| 55 | +> 绿色包保证 `运行环境` 的更新,更新程序保证 `代码` 的更新,<br> |
| 56 | +> 所以会有包更新没跟上代码更新,优先以内置的`comic_viewer-更新.exe` 为主 |
| 57 | +
|
| 58 | +--- |
| 59 | +其他问题 [回到项目主页](https://github.com/jasoneri/comic_viewer) 下方找群进群询问""" |
| 60 | + |
| 61 | + |
| 62 | +class Proj: |
| 63 | + proj = "comic_viewer" |
| 64 | + name = "comic_viewer" |
| 65 | + |
| 66 | + def __repr__(self): |
| 67 | + return self.proj |
| 68 | + |
| 69 | + |
| 70 | +proj = Proj() |
| 71 | + |
| 72 | + |
| 73 | +class Clean: |
| 74 | + """aim at runtime like site-packages""" |
| 75 | + |
| 76 | + @staticmethod |
| 77 | + def clean_packages(): |
| 78 | + """clean site-packages""" |
| 79 | + package_p = path.joinpath('site-packages') |
| 80 | + for p in tqdm(package_p.glob("[psw][ieh][pte]*")): # pip, set-tools, wheel, not need |
| 81 | + shutil.rmtree(str(p), ignore_errors=True) |
| 82 | + |
| 83 | + @staticmethod |
| 84 | + def end_work(specified: iter = None): |
| 85 | + def delete(func, _path, execinfo): |
| 86 | + os.chmod(_path, stat.S_IWUSR) |
| 87 | + func(_path) |
| 88 | + |
| 89 | + waiting = specified or ("scripts/.git", ) |
| 90 | + for p in tqdm(waiting): |
| 91 | + _p = path.joinpath(p) |
| 92 | + if _p.exists(): |
| 93 | + shutil.rmtree(_p, onerror=delete) if _p.is_dir() else os.remove(_p) |
| 94 | + |
| 95 | + |
| 96 | +class Packer: |
| 97 | + github_author = "jasoneri" |
| 98 | + executor = path.parent.joinpath(r'Bat_To_Exe_Converter\Bat_To_Exe_Converter.exe') |
| 99 | + zip_file = path.joinpath(f'{proj}.7z') |
| 100 | + preset_zip_file = path.joinpath(f'{proj}_preset.7z') |
| 101 | + |
| 102 | + def __init__(self, default_specified: tuple): |
| 103 | + self.default_specified = default_specified |
| 104 | + |
| 105 | + @classmethod |
| 106 | + def bat_to_exe(cls): |
| 107 | + def _do(bat_file, exe_file, icon, *args): |
| 108 | + args_str = " ".join(args) |
| 109 | + command = f"cd {path} && {cls.executor} /bat {bat_file} /exe {exe_file} /icon {icon} /x64 {args_str}" |
| 110 | + error_code = os.system(command) |
| 111 | + if error_code: # Unreliable, need raise error make next step run correctly |
| 112 | + raise OSError(f"[ fail - packup {bat_file}], error_code: {error_code}") |
| 113 | + else: |
| 114 | + logger.info(f"[ success {bat_file} ]") |
| 115 | + |
| 116 | + _do(path.joinpath(rf"scripts/launcher/{proj}.bat"), path.joinpath(rf"{proj}.exe"), |
| 117 | + path.joinpath(rf"scripts/launcher/{proj}.ico"), "/invisible") |
| 118 | + _do(path.joinpath(rf"scripts/launcher/update.bat"), path.joinpath(rf"{proj}-更新.exe"), |
| 119 | + path.joinpath(rf"scripts/launcher/{proj}.ico")) |
| 120 | + |
| 121 | + @staticmethod |
| 122 | + def markdown_to_html(file_path, out_name): |
| 123 | + import markdown |
| 124 | + with open(path.joinpath(file_path), 'r', encoding='utf-8') as f: |
| 125 | + md_content = f.read() |
| 126 | + html = markdown.markdown(md_content) |
| 127 | + html_style = f"""<!DOCTYPE html><html><head><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css"></head><body><article class="markdown-body"> |
| 128 | + {html} |
| 129 | + </article></body></html>""" |
| 130 | + with open(path.joinpath(out_name), 'w', encoding='utf-8') as f: |
| 131 | + f.write(html_style) |
| 132 | + |
| 133 | + def packup(self, runtime_init=False): |
| 134 | + zip_file = self.zip_file |
| 135 | + specified = self.default_specified |
| 136 | + mode = "a" |
| 137 | + if runtime_init: |
| 138 | + # {proj}_preset.7z: only include runtime and site-packages. If env changed, re-packup it |
| 139 | + if self.preset_zip_file.exists(): |
| 140 | + logger.debug(f"[ preset_zip_file exists ] run normal packup") |
| 141 | + logger.debug(f"[ if need init ] delete '{self.preset_zip_file}' manually later") |
| 142 | + return self.packup() |
| 143 | + zip_file = self.preset_zip_file |
| 144 | + specified = ('runtime', 'site-packages') |
| 145 | + mode = "w" |
| 146 | + else: |
| 147 | + shutil.copy(self.preset_zip_file, self.zip_file) |
| 148 | + with py7zr.SevenZipFile(zip_file, mode, filters=[{"id": py7zr.FILTER_LZMA2}]) as zip_f: |
| 149 | + for file in tqdm(tuple(specified)): |
| 150 | + if path.joinpath(file).exists(): |
| 151 | + zip_f.writeall(file) |
| 152 | + if not self.zip_file.exists(): |
| 153 | + self.packup() |
| 154 | + |
| 155 | + @staticmethod |
| 156 | + def upload(zip_file): |
| 157 | + date_now = datetime.datetime.now().strftime("%Y%m%d") |
| 158 | + repo = proj.name |
| 159 | + if github_token.startswith("**create"): |
| 160 | + raise ValueError("[ you forget to replace your github token ] ") |
| 161 | + auth = Auth.Token(github_token) |
| 162 | + g = Github(auth=auth) |
| 163 | + user = g.get_user() |
| 164 | + release = user.get_repo(repo).get_latest_release() |
| 165 | + # delete asset |
| 166 | + """github note: |
| 167 | + If you upload an asset with the same filename as another uploaded asset, |
| 168 | + you'll receive an error and must delete the old file before you can re-upload the new asset.""" |
| 169 | + _asset = list(filter(lambda x: x.name == zip_file, release.assets)) |
| 170 | + if _asset: |
| 171 | + _asset[0].delete_asset() |
| 172 | + # upload asset |
| 173 | + release.upload_asset(str(path.joinpath(zip_file)), name=zip_file) |
| 174 | + # update release |
| 175 | + text = release_desc |
| 176 | + release.update_release(name=f"{date_now} - v1.0.0", message=text) |
| 177 | + |
| 178 | + |
| 179 | +def clean(): |
| 180 | + """almost run few times in upfront""" |
| 181 | + Clean.clean_packages() |
| 182 | + Clean.end_work() |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == '__main__': |
| 186 | + # clean() # step 0 |
| 187 | + Packer.bat_to_exe() # step 1 |
| 188 | + Packer.markdown_to_html('scripts/doc/deploy.md', '部署指南.html') # step 2 |
| 189 | + packer = Packer(('scripts', f'{proj}.exe', f'{proj}-更新.exe')) |
| 190 | + packer.packup(runtime_init=True) # step 3 |
| 191 | + packer.upload('comic_viewer.7z') # step 4 |
| 192 | + Clean.end_work((f'{proj}.exe', f'{proj}-更新.exe', 'comic_viewer.7z')) # step 5 |
| 193 | + # If error occur, exegesis previous step and run again |
0 commit comments