From 73b0399cb91bff203f99f22b04ada3494a2694ee Mon Sep 17 00:00:00 2001 From: ywmoyue Date: Mon, 27 Jan 2025 19:34:19 +0800 Subject: [PATCH] =?UTF-8?q?#1008=20=E6=8E=A8=E9=80=81chocolaty=E8=84=9A?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/choco.yml | 40 +++++ .../chocolaty-templates/BiliLite-uwp.nuspec | 19 +++ .../tools/chocolateyInstall.ps1 | 98 ++++++++++++ .../tools/chocolateyUninstall.ps1 | 18 +++ scripts/packChoco.py | 144 ++++++++++++++++++ 5 files changed, 319 insertions(+) create mode 100644 .github/workflows/choco.yml create mode 100644 scripts/chocolaty-templates/BiliLite-uwp.nuspec create mode 100644 scripts/chocolaty-templates/tools/chocolateyInstall.ps1 create mode 100644 scripts/chocolaty-templates/tools/chocolateyUninstall.ps1 create mode 100644 scripts/packChoco.py diff --git a/.github/workflows/choco.yml b/.github/workflows/choco.yml new file mode 100644 index 000000000..8c8c1e9df --- /dev/null +++ b/.github/workflows/choco.yml @@ -0,0 +1,40 @@ +name: Pack and Push Chocolatey Package + +on: + workflow_dispatch: + inputs: + version: + description: "The version of the package" + required: true + type: string + +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CHOCO_TOKEN: ${{ secrets.CHOCO_TOKEN }} + +jobs: + pack-and-push: + runs-on: windows-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: "3.9" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install requests + + - name: Check choco + run: | + choco -v + + - name: Run packChoco.py script + run: | + $env:PYTHONUNBUFFERED = "1" + python scripts/packChoco.py --version ${{ github.event.inputs.version }} --githubtoken ${{ env.GITHUB_TOKEN }} --chocotoken ${{ env.CHOCO_TOKEN }} diff --git a/scripts/chocolaty-templates/BiliLite-uwp.nuspec b/scripts/chocolaty-templates/BiliLite-uwp.nuspec new file mode 100644 index 000000000..405de7347 --- /dev/null +++ b/scripts/chocolaty-templates/BiliLite-uwp.nuspec @@ -0,0 +1,19 @@ + + + + BiliLite-uwp-{arch} + {version}-beta + BiliLite-uwp + ruamuyan + ruamuyan + https://github.com/ywmoyue/biliuwp-lite + https://github.com/ywmoyue/biliuwp-lite/discussions + https://github.com/ywmoyue/biliuwp-lite/discussions + https://github.com/ywmoyue/biliuwp-lite + https://github.com/ywmoyue/biliuwp-lite + Bilibili third-party UWP client third-party release version. Fork from https://github.com/xiaoyaocz/biliuwp-lite. + Bilibili third-party UWP client third-party release version. + https://raw.githubusercontent.com/ywmoyue/biliuwp-lite/refs/heads/master/src/BiliLite.Packages/Images/StoreLogo.scale-400.png + UWP BiliBili + + \ No newline at end of file diff --git a/scripts/chocolaty-templates/tools/chocolateyInstall.ps1 b/scripts/chocolaty-templates/tools/chocolateyInstall.ps1 new file mode 100644 index 000000000..6ebce107a --- /dev/null +++ b/scripts/chocolaty-templates/tools/chocolateyInstall.ps1 @@ -0,0 +1,98 @@ +# Due to Powershell limitations, this script can only be opened with GBK encoding +$AppName = "BiliLite.Packages" +$Version = "{version}" +$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path +Write-Output "scriptDir: $scriptDir" + +# 获取系统架构 +$arch = $env:PROCESSOR_ARCHITECTURE +# 判断架构并赋值 +if ($arch -eq "AMD64") { + $systemArch = "x64" +} elseif ($arch -eq "x86") { + $systemArch = "x86" +} elseif ($arch -eq "ARM64") { + $systemArch = "ARM64" +} else { + $systemArch = "Unknown" +} + +$Package = "{0}_{1}_{2}" -f $AppName, $Version, $systemArch +Write-Output "Package: $Package" + +# 找到对应的安装包并解压到unpack路径 +$PackageZipRelativePath = "..\resources\{0}.zip" -f $Package +$PackageZipPath = Join-Path $scriptDir $PackageZipRelativePath +$UnpackPath = Join-Path $scriptDir "..\unpack" + +# 检查文件是否存在并解压 +if (Test-Path $PackageZipPath) { + # 确保解压路径存在 + if (-not (Test-Path $UnpackPath)) { + New-Item -ItemType Directory -Path $UnpackPath | Out-Null + } + + # 解压文件 + Expand-Archive -Path $PackageZipPath -DestinationPath $UnpackPath -Force + Write-Host "文件已解压到 $UnpackPath" +} else { + Write-Host "文件 $PackageZipPath 不存在,即将从 GitHub 下载当前平台适配的安装包" + + # 从 GitHub 下载软件包并解压 + $downloadUrl = "https://github.com/ywmoyue/biliuwp-lite/releases/download/v{0}/{1}.zip" -f $Version, $Package + Write-Host "下载地址: $downloadUrl" + + try { + # 下载文件 + Invoke-WebRequest -Uri $downloadUrl -OutFile $PackageZipPath + Write-Host "文件下载完成: $PackageZipPath" + + # 确保解压路径存在 + if (-not (Test-Path $UnpackPath)) { + New-Item -ItemType Directory -Path $UnpackPath | Out-Null + } + + # 解压文件 + Expand-Archive -Path $PackageZipPath -DestinationPath $UnpackPath -Force + Write-Host "文件已解压到 $UnpackPath" + } catch { + Write-Host "下载或解压失败: $_" + exit 1 + } +} + +# 设置开发者模式允许安装未知来源包 +Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" -Name "AllowDevelopmentWithoutDevLicense" -Value 1 +Write-Host "已允许安装未知来源包" + +# 证书路径 +$certRelativePath = "..\unpack\{0}_Test\{0}.cer" -f $Package +$certPath = Resolve-Path (Join-Path $scriptDir $certRelativePath) + +# 安装脚本路径 +$installScriptPath = "$scriptDir\..\unpack\{0}_Test\install.ps1" -f $Package +Write-Host "安装路径 $installScriptPath" + +# 安装证书 +try { + $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 + $cert.Import($certPath.Path) + + $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("Root", "LocalMachine") + $store.Open("ReadWrite") + $store.Add($cert) + $store.Close() + Write-Host "证书安装完成" +} catch { + Write-Host "证书安装失败: $_" + exit 1 +} + +# 执行安装脚本 +try { + . "$installScriptPath" + Write-Host "安装脚本执行成功" +} catch { + Write-Host "安装脚本执行失败: $_" + exit 1 +} \ No newline at end of file diff --git a/scripts/chocolaty-templates/tools/chocolateyUninstall.ps1 b/scripts/chocolaty-templates/tools/chocolateyUninstall.ps1 new file mode 100644 index 000000000..798fcaf6d --- /dev/null +++ b/scripts/chocolaty-templates/tools/chocolateyUninstall.ps1 @@ -0,0 +1,18 @@ +# Due to Powershell limitations, this script can only be opened with GBK encoding +$PackageId = "5422.502643927C6AD" + +$PackageNamePrefix = "{0}_" -f $PackageId +Write-Host "PackageNamePrefix: $PackageNamePrefix" + +# 获取UWP包完整名称 +$PackageFullName = (Get-AppxPackage | Where-Object { $_.PackageFullName -like "$PackageNamePrefix*" }).PackageFullName +Write-Host "PackageFullName: $PackageFullName" + +if ($PackageFullName) { + Write-Host "找到 UWP 包: $PackageFullName" + # 卸载 UWP 包 + Remove-AppxPackage -Package $PackageFullName + Write-Host "UWP 包已卸载" +} else { + Write-Host "未找到匹配的 UWP 包" +} \ No newline at end of file diff --git a/scripts/packChoco.py b/scripts/packChoco.py new file mode 100644 index 000000000..33a997be3 --- /dev/null +++ b/scripts/packChoco.py @@ -0,0 +1,144 @@ +import os +import requests +import shutil +import subprocess + +# python choco_pack.py --version 4.7.13.1403 --githubtoken YOUR_GITHUB_TOKEN --chocotoken YOUR_CHOCO_TOKEN + +def replace_string_in_file(file_path, target_string, replacement_string): + try: + # 鏍规嵁鏂囦欢鎵╁睍鍚嶉夋嫨缂栫爜 + if file_path.endswith('.ps1'): + encoding = 'gbk' # 瀵逛簬 .ps1 鏂囦欢锛屼娇鐢 GBK 缂栫爜 + else: + encoding = 'utf-8' # 瀵逛簬鍏朵粬鏂囦欢锛屼娇鐢 UTF-8 缂栫爜 + + # 璇诲彇鏂囦欢鍐呭 + with open(file_path, 'r', encoding=encoding) as file: + file_contents = file.read() + + # 鏇挎崲鏂囦欢鍐呭涓殑鐩爣瀛楃涓 + updated_contents = file_contents.replace(target_string, replacement_string) + + # 灏嗘洿鏂板悗鐨勫唴瀹瑰啓鍥炴枃浠 + with open(file_path, 'w', encoding=encoding) as file: + file.write(updated_contents) + + print(f"Successfully replaced '{target_string}' with '{replacement_string}' in {file_path}") + except FileNotFoundError: + print(f"The file at {file_path} was not found.") + except IOError as e: + print(f"An IOError occurred: {e.strerror}.") + except UnicodeDecodeError: + print(f"Failed to decode the file {file_path} with {encoding} encoding.") + except UnicodeEncodeError: + print(f"Failed to encode the file {file_path} with {encoding} encoding.") + +def download_github_release_asset(tag, github_token, arch, output_dir): + url = f"https://api.github.com/repos/ywmoyue/biliuwp-lite/releases/tags/{tag}" + headers = { + "Authorization": f"token {github_token}", + "Accept": "application/vnd.github.v3+json" + } + + response = requests.get(url, headers=headers) + if response.status_code != 200: + print(f"Failed to fetch release info for tag {tag}. Status code: {response.status_code}") + return False + + assets = response.json().get("assets", []) + zip_filename = f"BiliLite.Packages_{tag[1:]}_{arch}.zip" + asset_url = None + + for asset in assets: + if asset["name"] == zip_filename: + asset_url = asset["url"] + break + + if not asset_url: + print(f"Asset {zip_filename} not found in release {tag}.") + return False + + headers["Accept"] = "application/octet-stream" + response = requests.get(asset_url, headers=headers, stream=True) + if response.status_code != 200: + print(f"Failed to download asset {zip_filename}. Status code: {response.status_code}") + return False + + os.makedirs(output_dir, exist_ok=True) + zip_path = os.path.join(output_dir, zip_filename) + with open(zip_path, 'wb') as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) + + print(f"Downloaded {zip_filename} to {output_dir}") + return True + +def process_architecture(arch, version, github_token, chocotoken): + # 瀹氫箟璺緞 + template_dir = "scripts/chocolaty-templates" + pack_parent_dir = "C:/choco/pack" + pack_dir = f"{pack_parent_dir}/{arch}" + nuspec_file = f"{pack_dir}/BiliLite-uwp.nuspec" + install_script = f"{pack_dir}/tools/chocolateyInstall.ps1" + resources_dir = f"{pack_dir}/resources" + + # 澶嶅埗妯℃澘鏂囦欢澶瑰埌鐩爣鐩綍 + if not os.path.exists(template_dir): + print(f"Template directory {template_dir} not found.") + return + + os.makedirs(pack_parent_dir, exist_ok=True) + shutil.copytree(template_dir, pack_dir, dirs_exist_ok=True) + + # 鏇挎崲 nuspec 鏂囦欢涓殑 {version} 鍜 {arch} + replace_string_in_file(nuspec_file, "{version}", version) + replace_string_in_file(nuspec_file, "{arch}", arch) + + # 鏇挎崲 chocolateyInstall.ps1 鏂囦欢涓殑 {version} + replace_string_in_file(install_script, "{version}", version) + + # 鍒涘缓 resources 鏂囦欢澶 + os.makedirs(resources_dir, exist_ok=True) + + # 涓嬭浇 GitHub Release 鐨 zip 鍖 + tag = f"v{version}" + if not download_github_release_asset(tag, github_token, arch, resources_dir): + print(f"Skipping architecture {arch} due to missing asset.") + return + + # 鍦ㄧ洰鏍囩洰褰曚笅鎵ц choco pack 鍛戒护 + try: + subprocess.run(["choco", "pack"], cwd=pack_dir, check=True) + except subprocess.CalledProcessError as e: + print(f"Failed to pack for architecture {arch}. Error: {e}") + return + + # 鎷兼帴鍖呭悕 + package_name = f"BiliLite-uwp-{arch}.{version}-beta.nupkg" + package_path = os.path.join(pack_dir, package_name) + + # 鎵ц choco push 鍛戒护 + try: + subprocess.run(["choco", "push", package_path, "--source", "https://push.chocolatey.org/", "--api-key", chocotoken], check=True) + except subprocess.CalledProcessError as e: + print(f"Failed to push package for architecture {arch}. Error: {e}") + +def main(version, github_token, chocotoken): + architectures = ["x64", "x86", "ARM64"] + + for arch in architectures: + print(f"Processing architecture: {arch}") + process_architecture(arch, version, github_token, chocotoken) + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Process Chocolatey packages for different architectures.") + parser.add_argument("--version", required=True, help="The version of the package.") + parser.add_argument("--githubtoken", required=True, help="GitHub token for accessing the release assets.") + parser.add_argument("--chocotoken", required=True, help="Chocolatey API key for pushing the package.") + + args = parser.parse_args() + + main(args.version, args.githubtoken, args.chocotoken) \ No newline at end of file