Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0fb316bd6 | ||
|
|
7c1c691b3d | ||
|
|
77dc9e917f | ||
|
|
b7022c8f52 | ||
|
|
a8ab8e7906 | ||
|
|
4e9a16182a | ||
|
|
c1f611ab54 | ||
|
|
2f85e03aae | ||
|
|
8cca6148e3 | ||
|
|
ae3e209074 | ||
|
|
073f259653 | ||
|
|
63957704c0 | ||
|
|
43e29a8c5c | ||
|
|
3ddb86c14b | ||
|
|
f7ab4a53b9 | ||
|
|
b0bf9653d7 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -13,7 +13,7 @@ artifacts/
|
||||
*.aab
|
||||
*.spec.bak
|
||||
.pysidedeploy/
|
||||
buildozer.spec
|
||||
!buildozer.spec
|
||||
bin/
|
||||
|
||||
# 本地配置与数据
|
||||
|
||||
156
README.md
156
README.md
@@ -7,6 +7,51 @@
|
||||
|
||||

|
||||
|
||||
## 安装包(APK)
|
||||
|
||||
Release 页:<https://git.xnhw.cc/l/lnxgit/releases>(tag `v1.0.0`)
|
||||
|
||||
| 文件 | 大小 | 适用 |
|
||||
| --- | --- | --- |
|
||||
| `LnxGit-0.1-arm64-v8a-debug.apk` | 150.9 MB | **arm64 真机**(绝大多数手机) |
|
||||
| `LnxGit-0.1-x86_64-debug.apk` | 153.4 MB | **x86_64 模拟器** |
|
||||
|
||||
```bash
|
||||
adb install -r LnxGit-0.1-arm64-v8a-debug.apk # 真机
|
||||
adb install -r LnxGit-0.1-x86_64-debug.apk # 模拟器
|
||||
```
|
||||
|
||||
SHA256:
|
||||
|
||||
```
|
||||
07b2e7352a865553d9347eda463dbecca83b4cbbf81f075a24c9f518fec9d0fa LnxGit-0.1-arm64-v8a-debug.apk
|
||||
e75ed77159df52c46fbbb8267607d1c5649f4157e8e8810b908149c65d058415 LnxGit-0.1-x86_64-debug.apk
|
||||
```
|
||||
|
||||
> 包名 `org.lnxgit.lnxgit`,最低 Android 7.0(API 24)。
|
||||
> **两个版本不能混装**:x86_64 模拟器上装 arm64 版会走 ARM 转译层
|
||||
> (libhoudini),Qt 的 JNI_OnLoad 会直接段错误 —— 见 `android/BUILD.md` 4.1。
|
||||
|
||||
### 上传附件时的注意事项
|
||||
|
||||
**公网入口传不了大文件。** `git.xnhw.cc` 目前是 Caddy 反代(2026-09 起已不再走
|
||||
Cloudflare),小文件上传正常,但 150 MB 的 APK 走公网会在约 5 分钟后返回
|
||||
**502** —— 瓶颈在 Caddy 背后的 Gitea 处理大附件那一层,不是前置代理的请求体限制。
|
||||
|
||||
所以 APK 一律**走内网直连**(同一个 Gitea 实例,没有这层问题):
|
||||
|
||||
```bash
|
||||
bash scripts/wsl_upload_release.sh dist/LnxGit-0.1-arm64-v8a-debug.apk
|
||||
```
|
||||
|
||||
实测 151 MB 约 15 秒。清理旧附件用 `tools/clean_release.py`。
|
||||
|
||||
两个注意点:
|
||||
|
||||
- **令牌要有管理员权限**。仓库所有者 `l` 的令牌可以;`kimigit` 那个只有
|
||||
`pull` 权限,上传或删除附件都会 403。
|
||||
- **不要用切片绕过**。曾用过一次,结果 Release 里堆了几十个
|
||||
`xxx.apk.part001` 同名附件,页面很乱、服务端也白扛一遍合并。
|
||||
## 功能一览
|
||||
|
||||
### 仓库连接
|
||||
@@ -25,9 +70,49 @@
|
||||
- **标签**:创建(轻量 / 附注)、列示、删除、推送到远端
|
||||
- **远端**:添加 / 删除 / 修改地址、fetch(含 prune)、pull(快进 / 仅快进)、push(含强推与设置上游)、删除远端分支
|
||||
- **历史**:提交日志分页加载、搜索(说明 / 作者 / SHA)、提交详情、文件级变更、逐行追溯 blame
|
||||
- **分支地图**:独立页面是**二维流程图**(节点带标题、时间自下而上、分支横向铺开、
|
||||
可拖动缩放),历史页则在每行左侧附带紧凑泳道图(详见下文)
|
||||
- **文件**:任意版本的文件树浏览与内容查看(含二进制识别与大文件截断)、工作区文件查看
|
||||
- **其他**:储藏(stash push / pop / drop / 列表)、reset(soft / mixed / hard)、丢弃改动、清理未跟踪文件、拣选(cherry-pick)、仓库配置读写、对象统计
|
||||
|
||||
### 分支地图
|
||||
|
||||
两个入口,共用同一套提交与引用数据,但呈现形态不同:
|
||||
|
||||
| 位置 | 形式 | 特点 |
|
||||
| --- | --- | --- |
|
||||
| 「图谱」页 | **二维流程图** | 每个提交一个带标题的胶囊节点,时间自下而上、分支横向铺开,可拖动与缩放 |
|
||||
| 「历史」页 | 列表左侧的紧凑泳道 | 一行一个提交,图谱旁边保留作者、时间、SHA 与引用标签 |
|
||||
|
||||
**流程图形态**(独立页面):
|
||||
|
||||
- 顶部有**分支选择框**:「全部引用」+ 各本地分支(当前分支标注「(当前)」),
|
||||
末项是「+ 新建分支…」;选中某个分支就只看它的历史
|
||||
- 纵向按**拓扑深度**(到根的最长路径)分层 —— 从同一点分叉出的兄弟分支落在
|
||||
同一水平线上并排,而不是斜着排成一条对角线
|
||||
- 横向按**轨道**铺开,每条分支一条轨道;轨道数决定图的宽度
|
||||
- **颜色按分支分配**(不是按轨道):同一分支的提交与连线同色;顶部有一行
|
||||
**颜色标识**列出「分支名 → 颜色」,可横向滚动
|
||||
- 父 → 子用**带箭头的曲线**连接,箭头指向时间更近的一侧
|
||||
- 整张图可以双向拖动,右下角是 + / - / ↔(适应宽度)
|
||||
- 图比屏幕宽时首次进入会自动缩放,但**只缩到 60%** —— 21 个分支铺开有 4000 多
|
||||
像素,按比例缩会到 30%,标题糊成一片什么也读不出来。地图本来就是拿来拖动
|
||||
浏览的,宁可让用户横向滚动
|
||||
- 节点只渲染**视口内**的那些:一次建两百个节点会明显卡顿,而屏幕上同时能
|
||||
看到的也就十几个
|
||||
|
||||
**紧凑形态**(历史页):
|
||||
|
||||
- 同父的兄弟分支**挤在同一列**以省空间(与 `git log --graph` 一致)
|
||||
- 最多 6 列,超出按可用宽度压缩列宽(下限 11px),仍超才裁剪
|
||||
|
||||
范围都是 `git log --all`:当前分支 + 全部本地分支 + 远端引用 + 标签;
|
||||
注解标签会解引用到对应提交,未合并的分支同样会出现在图上。
|
||||
|
||||
| 分支地图(流程图) | 历史页(含图谱) | 多分支(21 个分支) |
|
||||
| --- | --- | --- |
|
||||
|  |  |  |
|
||||
|
||||
### 移动端体验
|
||||
|
||||
- 深色 / 浅色主题,Material 风格,触控友好的 44dp 点击区域
|
||||
@@ -48,21 +133,24 @@ main.py # 入口:注册 QML 单例、加载界面
|
||||
lnxgit/
|
||||
├── apppaths.py # 应用数据目录(桌面 / Android 自适应)
|
||||
├── settings.py # 设置与凭据持久化(QML 单例 Settings)
|
||||
├── gitcore.py # ★ 核心:基于 dulwich 的全部 Git 操作
|
||||
├── gitcore.py # ★ 核心:基于 dulwich 的全部 Git 操作 + 图谱泳道布局
|
||||
├── worker.py # 后台工作线程(串行任务队列 + 凭据回调)
|
||||
├── service.py # 异步服务门面(QML 单例 GitService)
|
||||
└── gitea.py # Gitea REST API 客户端(建仓 / Release)
|
||||
qml/
|
||||
├── Main.qml # 主界面:StackView + 底部导航
|
||||
└── LnxGit/ # QML 模块(qmldir 声明 Theme / Git 单例)
|
||||
├── Theme.qml # 主题与尺寸
|
||||
└── LnxGit/ # QML 模块(qmldir 声明 Theme / Git 单例与各页面)
|
||||
├── Theme.qml # 主题、尺寸与图谱配色
|
||||
├── Git.qml # 全局状态与操作桥接
|
||||
├── components/ # 通用组件(卡片、按钮、差异视图、对话框…)
|
||||
└── pages/ # 11 个页面
|
||||
├── components/ # 通用组件(卡片、按钮、差异视图、图谱绘制…)
|
||||
└── pages/ # 12 个页面
|
||||
tools/ # 测试与辅助脚本
|
||||
scripts/ # Android 构建脚本
|
||||
```
|
||||
|
||||
> 新增 QML 文件后记得在 `qml/LnxGit/qmldir` 里登记,否则 `import LnxGit` 会找不到类型
|
||||
> —— 这个疏漏会导致应用启动即崩(`QThread: Destroyed while thread ... is still running`)。
|
||||
|
||||
### 线程模型
|
||||
|
||||
QML 只与 `GitService` 交互,后者把任务投递到独立 `QThread` 中的 `Worker`;
|
||||
@@ -95,50 +183,75 @@ python tools/e2e_test.py
|
||||
|
||||
# 3) QML 加载检查(离屏,逐文件定位报错)
|
||||
python tools/qml_check.py
|
||||
|
||||
# 4) 图谱泳道布局:拓扑序、连线连续性、注解标签解引用(需系统有 git)
|
||||
python tools/graph_test.py
|
||||
|
||||
# 5) QML 布局陷阱:Column/Row 子项误用锚点会让整列布局失效
|
||||
python tools/check_qml_layout.py qml
|
||||
|
||||
# 6) 图标字形:Android 上会渲染成豆腐块的字符(需先拉取设备字体)
|
||||
bash scripts/wsl_pull_fonts.sh emulator-5554 /tmp/lnxgit-fonts
|
||||
python tools/check_glyphs.py qml /tmp/lnxgit-fonts
|
||||
```
|
||||
|
||||
当前状态:`smoke_test` 与 `e2e_test` 全部通过(共 70+ 断言)。
|
||||
当前状态:`smoke_test` 与 `e2e_test` 全部通过(共 70+ 断言),
|
||||
`graph_test` 覆盖分叉 / 合并 / 三父提交 / 未合并分支 / 空仓库等场景。
|
||||
|
||||
## 构建 Android APK
|
||||
|
||||
> 官方 `pyside6-android-deploy` **只支持 Linux / macOS 主机**。
|
||||
> 在 Windows 上推荐使用同一台机器的 **WSL2 (Ubuntu)**:源码位于 `/mnt/c/...`,
|
||||
> 构建在 Linux 侧完成,产物 APK 直接写回项目目录。
|
||||
> 构建在 Linux 侧完成,产物 APK 直接写回项目的 `dist/` 目录。
|
||||
>
|
||||
> 完整的踩坑记录(buildozer 拒绝 root、SDK 路径假设、GitHub/Gradle 下载受限、
|
||||
> 源文件 BOM 导致打包工具解析失败等)见 [`android/BUILD.md`](android/BUILD.md)。
|
||||
|
||||
### 1) 准备构建环境(WSL 内,一次性)
|
||||
|
||||
```bash
|
||||
# 安装系统依赖(Python 3.11 / JDK 17 / 打包工具)
|
||||
sudo bash scripts/wsl_bootstrap.sh
|
||||
sudo bash scripts/wsl_bootstrap.sh # Python 3.11 / JDK 17 / 工具链
|
||||
bash scripts/wsl_setup_android.sh # Android SDK + NDK + Android wheel(约 2GB)
|
||||
bash scripts/wsl_install_host_pyside.sh # 宿主 PySide6(提供打包命令)
|
||||
sudo bash scripts/wsl_create_builder_user.sh
|
||||
sudo bash scripts/wsl_move_workdir.sh # 构建目录移到 /opt(普通用户可写)
|
||||
|
||||
# 下载 Android SDK + NDK + Qt for Python 的 Android wheel(约 2GB)
|
||||
bash scripts/wsl_setup_android.sh
|
||||
# 网络受限时的预热(GitHub / Gradle 走镜像)
|
||||
sudo -u builder bash scripts/wsl_prefetch_p4a.sh
|
||||
bash scripts/wsl_place_p4a.sh
|
||||
bash scripts/wsl_prefetch_gradle.sh
|
||||
bash scripts/wsl_fix_gradle_cache.sh
|
||||
bash scripts/wsl_fix_sdk_layout.sh
|
||||
```
|
||||
|
||||
环境变量与版本对应关系(Qt 6.11.2):
|
||||
环境与版本对应关系(Qt 6.11.2):
|
||||
|
||||
| 项目 | 版本 |
|
||||
| --- | --- |
|
||||
| Qt for Python | 6.11.2(Android wheel:`cp311`, `aarch64`) |
|
||||
| Python(构建机) | 3.11(wheel 为 cp311) |
|
||||
| Qt for Python | 6.11.2(Android wheel:`cp311` / `abi3`,`aarch64` 或 `x86_64`) |
|
||||
| 打包用 CPython | **3.11.15** —— 必须与 wheel 的 `cp311` 一致,构建脚本会自动固定 |
|
||||
| Android NDK | 27.2.12479018 |
|
||||
| Android SDK Platform | android-35 |
|
||||
| Build Tools | 35.0.0 |
|
||||
| Gradle | 8.14.3 |
|
||||
| JDK | 17 |
|
||||
|
||||
### 2) 打包
|
||||
|
||||
```bash
|
||||
bash scripts/build_apk.sh # debug APK(可直接安装)
|
||||
bash scripts/build_apk.sh release # release AAB/APK
|
||||
bash scripts/wsl_build.sh debug # debug APK(可直接安装)
|
||||
bash scripts/wsl_build.sh release # release(体积更小)
|
||||
|
||||
# 可选:裁剪未被使用的 Qt 模块(WebEngine / Designer / 3D / Charts 等)并重新签名
|
||||
bash scripts/wsl_trim_apk.sh 输入.apk 输出.apk
|
||||
```
|
||||
|
||||
产物位于项目根目录:`*.apk` / `*.aab`。
|
||||
产物自动回写到 `dist/`。
|
||||
|
||||
### 3) 安装到手机
|
||||
|
||||
```bash
|
||||
adb install -r lnxgit-debug.apk
|
||||
adb install -r dist/LnxGit-*-debug.apk
|
||||
```
|
||||
|
||||
## 凭据与安全说明
|
||||
@@ -157,8 +270,11 @@ adb install -r lnxgit-debug.apk
|
||||
- `dulwich` 不支持三方合并的冲突编辑流程:合并出现冲突时需手动处理后提交。
|
||||
- blame 对超大文件较慢;差异与文件预览均限制在 400 KB / 1 MB 以内以避免卡顿。
|
||||
- 应用内暂未实现交互式 rebase 与 submodule 操作。
|
||||
- APK 为 arm64-v8a 架构(覆盖绝大多数现代手机);如需 x86_64 模拟器版本,
|
||||
可在 `scripts/wsl_setup_android.sh` 与 `pysidedeploy.spec` 中改为 `x86_64` 重新打包。
|
||||
- 图谱最多画 12 条泳道(超出部分裁掉),单次加载默认 200 条提交;
|
||||
两者都会随窗口宽度与 `limit` 调整。
|
||||
- 仓库同时提供 arm64-v8a(真机)与 x86_64(模拟器)两种产物,构建时用
|
||||
`ARCH_ABI` / `ARCH_P4A` 选择;注意 **x86_64 模拟器必须装 x86_64 版**,
|
||||
装 arm64 版会走 ARM 转译层并在启动时段错误。
|
||||
|
||||
## 许可证
|
||||
|
||||
|
||||
499
android/BUILD.md
Normal file
499
android/BUILD.md
Normal file
@@ -0,0 +1,499 @@
|
||||
# Android 打包说明
|
||||
|
||||
`pyside6-android-deploy` 官方只支持 Linux / macOS 主机,本项目的做法是:
|
||||
**源码放在 Windows,构建在 WSL2 (Ubuntu) 内完成,产物 APK 回写到 `dist/`**。
|
||||
|
||||
## 一、环境准备(WSL 内,仅首次)
|
||||
|
||||
```bash
|
||||
# 1) 系统依赖:Python 3.11 / JDK 17 / 打包工具链
|
||||
sudo bash scripts/wsl_bootstrap.sh
|
||||
|
||||
# 2) 下载 Qt for Python 的 Android wheel(aarch64, cp311)
|
||||
# 同时下载 Android SDK / NDK,并创建 Python 3.11 虚拟环境
|
||||
bash scripts/wsl_setup_android.sh
|
||||
|
||||
# 3) 安装宿主侧 PySide6(提供 pyside6-android-deploy 等工具)
|
||||
bash scripts/wsl_install_host_pyside.sh
|
||||
|
||||
# 4) 创建普通构建用户(buildozer 拒绝以 root 运行)
|
||||
sudo bash scripts/wsl_create_builder_user.sh
|
||||
sudo bash scripts/wsl_move_workdir.sh # 把构建目录移到 /opt
|
||||
|
||||
# 5) 预热网络依赖(GitHub 直连不稳定,全部走镜像)
|
||||
sudo -u builder bash scripts/wsl_prefetch_p4a.sh # python-for-android
|
||||
bash scripts/wsl_place_p4a.sh # 放到固定目录
|
||||
bash scripts/wsl_prefetch_gradle.sh # Gradle 发行包
|
||||
bash scripts/wsl_fix_gradle_cache.sh # 放进 wrapper 期望的哈希目录
|
||||
bash scripts/wsl_fix_sdk_layout.sh # 兼容 buildozer 的 SDK 路径假设
|
||||
```
|
||||
|
||||
### 版本对应关系
|
||||
|
||||
| 项目 | 版本 |
|
||||
| --- | --- |
|
||||
| Qt for Python | 6.11.2(Android wheel:`cp311` / `abi3`,aarch64 或 x86_64) |
|
||||
| 打包用 CPython | **3.11.15** —— 必须与 wheel 的 `cp311` 一致,构建脚本会自动固定 |
|
||||
| Android NDK | 27.2.12479018 |
|
||||
| Android SDK Platform | android-35 |
|
||||
| Build Tools | 35.0.0 |
|
||||
| Gradle | 8.14.3 |
|
||||
| JDK | 17 |
|
||||
|
||||
> CPU 版本不是"能用就行":p4a 的 `python3` recipe 默认编译最新版(3.14),
|
||||
> 而 wheel 里的 `libshiboken6.abi3.so` 链接的是 `libpython3.11.so`,
|
||||
> 两者不一致时应用启动即报 `library "libpython3.11.so" not found`。
|
||||
> 固定动作由 `tools/sitecustomize_lnxgit.py` 在构建期完成(见 4.3、4.4)。
|
||||
|
||||
## 二、构建
|
||||
|
||||
```bash
|
||||
bash scripts/wsl_build.sh debug # debug APK
|
||||
bash scripts/wsl_build.sh release # release(体积更小)
|
||||
```
|
||||
|
||||
构建脚本每次会做这几件事,顺序固定:
|
||||
|
||||
1. **同步源码**到 Linux 原生文件系统,并保留 `.buildozer` 构建缓存
|
||||
(deploy 收尾会把它 `move` 到 `deployment/` 下,脚本会先取回来);
|
||||
2. **清理 p4a 的 `build/venv`**,否则复用时 pip 文件新旧混杂会直接报
|
||||
`ImportError: cannot import name 'open_rich_spinner'`;
|
||||
3. **预置 CPython 源码包**(`wsl_place_python_src.sh`),避免 p4a 直连 GitHub 下载;
|
||||
4. **同步构建期补丁**到 `$WORK/pysite/sitecustomize.py`;
|
||||
5. **固定 recipe 版本**(`wsl_fix_recipes.sh`)。
|
||||
|
||||
需要重编时用环境变量控制:
|
||||
|
||||
```bash
|
||||
PURGE_PYTHON=1 ... bash scripts/wsl_build.sh debug # 连 CPython 一起重编(换 Python 版本时)
|
||||
PURGE_DIST=1 ... bash scripts/wsl_build.sh debug # 只重建 dist(改 bootstrap 配置时)
|
||||
```
|
||||
|
||||
改过 `tools/sitecustomize_lnxgit.py` 后,先跑自检再构建:
|
||||
|
||||
```bash
|
||||
bash scripts/wsl_verify_patch.sh
|
||||
```
|
||||
|
||||
它会逐项断言:补丁能加载、`deploy_lib` 被打上标记、生成的 spec 含
|
||||
`p4a.source_dir` 与 `python3==3.11.15`、Qt 模块按依赖序排列、`cleanup()`
|
||||
会保留构建缓存。任何一项不通过都说明补丁又被静默破坏了。
|
||||
|
||||
关键配置在仓库根目录的 `buildozer.spec` 与 `pysidedeploy.spec`:
|
||||
|
||||
* `p4a.source_dir = /opt/lnxgit-android/p4a-src`
|
||||
buildozer 每次构建都会清空项目内的 `.buildozer`,把 p4a 源码放到固定目录可避免反复直连 GitHub。
|
||||
* `android.permissions = INTERNET,ACCESS_NETWORK_STATE`
|
||||
连接远程仓库必需(p4a 的 Qt 模板默认也会带上)。
|
||||
* `android.archs = arm64-v8a`
|
||||
真机默认架构。要出 x86_64 模拟器版本,用构建脚本的架构参数即可
|
||||
(会同时改写 `buildozer.spec` 的 `android.archs` 与 `pysidedeploy.spec` 的 `arch`):
|
||||
|
||||
```bash
|
||||
bash scripts/wsl_fetch_x86_wheels.sh # 下载 x86_64 wheel
|
||||
ARCH_ABI=x86_64 ARCH_P4A=x86_64 bash scripts/wsl_build.sh debug
|
||||
```
|
||||
|
||||
注意两个 spec 必须**同时**改:`buildozer.spec` 决定 p4a 产物架构,
|
||||
`pysidedeploy.spec` 的 `arch` 决定打包工具去 wheel 里找
|
||||
`libQt6*_<arch>.so`——只改一个会报 `libQt6Core_arm64-v8a.so not found inside the wheel`。
|
||||
|
||||
## 三、体积与裁剪
|
||||
|
||||
`pyside6-android-deploy` 会把**整个** `PySide6/Qt/lib` 目录(含 WebEngine、Designer、
|
||||
3D、Charts、Multimedia 等)打进 APK,因此默认产物偏大。可用裁剪脚本只保留
|
||||
QML 运行必需的库:
|
||||
|
||||
```bash
|
||||
bash scripts/wsl_trim_apk.sh 输入.apk 输出.apk
|
||||
```
|
||||
|
||||
脚本会删除未使用的 Qt 模块与插件,并用 debug 密钥重新签名(`zipalign` +
|
||||
`apksigner`),产物仍可正常安装。实测可从 149 MB 降到 ~117 MB;
|
||||
release 构建本身体积更小。
|
||||
|
||||
## 四、常见故障速查
|
||||
|
||||
### 4.1 应用安装后立刻闪退(模拟器)
|
||||
|
||||
**症状**:`adb logcat` 里看到
|
||||
|
||||
```
|
||||
pid: 2040, tid: 2062, name: qtMainLoopThrea
|
||||
#00 libQt6Core_arm64-v8a.so (QJniEnvironment::getJniEnv())
|
||||
#01 libQt6Core_arm64-v8a.so (QJniEnvironment::QJniEnvironment())
|
||||
#02 libQt6Quick_arm64-v8a.so (JNI_OnLoad)
|
||||
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0
|
||||
backtrace: #00..#03 /system/vendor/lib64/libhoudini.so
|
||||
```
|
||||
|
||||
**原因**:模拟器是 **arm64 系统镜像跑在 x86_64 主机上**,靠厂商的 ARM 转译层
|
||||
(一加/OPPO 的 `libhoudini.so`、华为的 `libndk_translation.so` 等)执行 ARM 原生库。
|
||||
Qt 的 Android 集成启动时要通过 JNI 获取 `JavaVM`,在转译层下拿到 NULL,
|
||||
于是 `JNI_OnLoad` 直接段错误。**这不是应用代码问题,arm64 真机不会出现。**
|
||||
|
||||
**确认方法**:
|
||||
|
||||
```bash
|
||||
adb shell getprop ro.product.cpu.abi # 主机架构,如 x86_64
|
||||
adb shell getprop ro.product.cpu.abilist # 可用 ABI 列表
|
||||
adb shell getprop ro.dalvik.vm.native.bridge # 若为 libhoudini.so 即为转译层
|
||||
```
|
||||
|
||||
**解决办法**(任选其一):
|
||||
|
||||
1. **构建 x86_64 版本**(推荐,在模拟器上原生执行):
|
||||
|
||||
```bash
|
||||
bash scripts/wsl_fetch_x86_wheels.sh
|
||||
ARCH_ABI=x86_64 ARCH_P4A=x86_64 bash scripts/wsl_build.sh debug
|
||||
```
|
||||
|
||||
裁剪脚本里写的是 `lib/arm64-v8a`,换架构时需一并改成 `lib/x86_64`。
|
||||
|
||||
2. **换用 arm64 的虚拟机镜像**(在 Apple Silicon 上是原生执行;x86_64 主机上的
|
||||
arm64 镜像必然走转译层,不建议)。
|
||||
|
||||
3. **直接在 arm64 真机上测试**(最贴近发布环境)。
|
||||
|
||||
### 4.2 安装时报 `resources.arsc ... 4-byte boundary`
|
||||
|
||||
**症状**:
|
||||
|
||||
```
|
||||
Failure [-124: Failed parse during installPackageLI: Targeting R+ (version 30 and above)
|
||||
requires the resources.arsc of installed APKs to be stored uncompressed and aligned
|
||||
on a 4-byte boundary]
|
||||
```
|
||||
|
||||
**原因**:手工裁剪/重打包 APK 时用 `zip -9` 把 `resources.arsc` 压了。
|
||||
Android 11+(targetSdk ≥ 30)要求它**未压缩**且 4 字节对齐。
|
||||
|
||||
**处理**:裁剪脚本已修复——单独用 STORED 方式加入 `resources.arsc` 再用
|
||||
`zipalign -p 4` 对齐:
|
||||
|
||||
```bash
|
||||
zip -q -9 -r -X out.apk . -x resources.arsc
|
||||
zip -q -0 -X out.apk resources.arsc
|
||||
zipalign -f -p 4 out.apk aligned.apk
|
||||
apksigner sign --ks debug.keystore --out signed.apk aligned.apk
|
||||
```
|
||||
|
||||
### 4.3 启动时报 `library "libpython3.11.so" not found`
|
||||
|
||||
**症状**:
|
||||
|
||||
```
|
||||
I/QtCore : Start
|
||||
E/QtLoader: Can't load '.../lib/x86_64/libshiboken6.abi3.so'
|
||||
E/QtLoader: java.lang.UnsatisfiedLinkError: dlopen failed:
|
||||
library "libpython3.11.so" not found: needed by .../libshiboken6.abi3.so
|
||||
E/QtLoader: Loading Qt native libraries failed
|
||||
I/g.lnxgit.lnxgit: System.exit called, status: -1
|
||||
```
|
||||
|
||||
**原因**:PySide6 的 Android wheel 里 `shiboken6` 链接的是特定版本的 `libpythonX.Y.so`
|
||||
(本仓库用的 `cp311` wheel → **3.11**),而 python-for-android 的 `python3` recipe
|
||||
默认会编译**最新版**(3.14),两者不匹配。
|
||||
|
||||
**解决办法**:把 `python3` 固定到与 wheel 一致的版本,改动全部由
|
||||
`tools/sitecustomize_lnxgit.py` 在构建期完成(通过 `PYTHONPATH` 注入到
|
||||
`pyside6-android-deploy` 的整个进程树):
|
||||
|
||||
* `BuildozerConfig.__init__` 之后把 `requirements` 改写成
|
||||
`python3==3.11.15,shiboken6,PySide6,dulwich,certifi`;
|
||||
* 往 `buildozer.spec` 写入 `p4a.source_dir = /opt/lnxgit-android/p4a-src`,
|
||||
让 buildozer **复用固定目录的 p4a 源码**(既避免每次直连 GitHub 克隆,
|
||||
也保证那份源码里的 recipe 已被改成 3.11.15);
|
||||
* 把 `p4a-src` 里 `python3` / `hostpython3` recipe 的 `version` 就地改成 3.11.15
|
||||
(`scripts/wsl_fix_recipes.sh` 幂等执行,重复跑不会累积注释)。
|
||||
|
||||
构建日志里应能看到:
|
||||
|
||||
```
|
||||
[lnxgit-patch] requirements = python3==3.11.15,shiboken6,PySide6,dulwich,certifi
|
||||
[lnxgit-patch] p4a.source_dir = /opt/lnxgit-android/p4a-src
|
||||
INFO: Dist will have name LnxGit and requirements (python3, shiboken6, ...)
|
||||
--requirements=python3==3.11.15,shiboken6,PySide6,dulwich,certifi
|
||||
```
|
||||
|
||||
改版本后必须清掉旧的 dist 与 python3 编译缓存再重建:
|
||||
|
||||
```bash
|
||||
PURGE_PYTHON=1 ARCH_ABI=x86_64 ARCH_P4A=x86_64 bash scripts/wsl_build.sh debug
|
||||
# 等价于 scripts/wsl_purge_python_build.sh --python
|
||||
```
|
||||
|
||||
> 判断 wheel 期望的版本:查看 wheel 内 `shiboken6/Shiboken.abi3.so` 的依赖,
|
||||
> 或直接看 `.whl` 文件名里的 Python 标签 —— `cp311` 即 3.11。
|
||||
|
||||
> **踩过的坑**:早期版本的补丁里写了一个不存在的 `_sys`,异常又被 `except: pass`
|
||||
> 吞掉,于是 `p4a.source_dir` 与 `python3==3.11.15` **从未写进 spec**,构建却"看起来正常",
|
||||
> 只是每次都去 GitHub 克隆干净的 p4a 并编出 `libpython3.14.so`。
|
||||
> 现在 `scripts/wsl_verify_patch.sh` 会逐项断言这些行为,补丁出问题会直接失败。
|
||||
|
||||
### 4.4 启动瞬间 SIGSEGV(`QJniEnvironment::getJniEnv()`,无 dlopen 报错)
|
||||
|
||||
**症状**:`libpython3.11.so` 已就位、Qt 库也能加载,但 `super.onCreate` 之后立刻崩:
|
||||
|
||||
```
|
||||
V/PythonActivity: About to do super onCreate
|
||||
F/libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0
|
||||
in tid 4443 (qtMainLoopThrea)
|
||||
#00 libQt6Core_x86_64.so (QJniEnvironment::getJniEnv()+46)
|
||||
#01 libQt6Core_x86_64.so (QJniEnvironment::QJniEnvironment()+30)
|
||||
#02 libQt6Quick_x86_64.so (JNI_OnLoad+67)
|
||||
#29 org.qtproject.qt.android.QtLoader.loadLibraryHelper
|
||||
```
|
||||
|
||||
**原因**:Qt 库由 Java 侧 `QtLoader` 依照 `res/values/libs.xml` 里的 `qt_libs`
|
||||
数组**逐个 `System.loadLibrary`**,而 **Android 只对显式 loadLibrary 的库调用
|
||||
`JNI_OnLoad`**,作为 `DT_NEEDED` 依赖被顺带 `dlopen` 的库不会调用。
|
||||
`libQt6Core_x86_64.so` 的 `JNI_OnLoad` 负责缓存 `JavaVM`,一旦它排在
|
||||
`libQt6Quick_x86_64.so` 后面,`Qt6Quick` 的 `JNI_OnLoad` 里
|
||||
`QJniEnvironment` 就拿不到 `JavaVM`,直接段错误。
|
||||
|
||||
p4a 的这份 `libs.xml` 由 `pythonforandroid/bootstraps/qt/build/templates/libs.tmpl.xml`
|
||||
生成,顺序来自 `pysidedeploy_config.modules` —— 而 deploy_lib 里那是
|
||||
`list(set(...))`,**顺序完全随机**(每次构建都不一样)。所以这个 bug 是概率性的。
|
||||
|
||||
**解决办法**:补丁把 qt 模块按依赖层级重排,`Core` 永远排第一:
|
||||
|
||||
```
|
||||
[lnxgit-patch] qt 模块加载顺序 = Core,Network,Gui,OpenGL,Svg,Qml,Quick,QuickControls2
|
||||
```
|
||||
|
||||
验证 APK 里真的生效:
|
||||
|
||||
```bash
|
||||
aapt2 dump resources dist/LnxGit-*-debug.apk | grep -A 20 array/qt_libs
|
||||
# qt_libs 里第一个应为 Qt6Core_
|
||||
```
|
||||
|
||||
改完之后要重建 dist(不必重编 CPython):
|
||||
|
||||
```bash
|
||||
PURGE_DIST=1 ARCH_ABI=x86_64 ARCH_P4A=x86_64 bash scripts/wsl_build.sh debug
|
||||
```
|
||||
|
||||
> 模拟器上如果走 `libhoudini.so` 跑 arm64 APK,也会出现同名同址的 SIGSEGV,
|
||||
> 但那是 ABI 不匹配,与本条无关 —— 先确认 `native-code` 与设备 ABI 一致
|
||||
> (`scripts/wsl_devices.sh`)。
|
||||
|
||||
### 4.5 应用启动时第三方依赖丢失
|
||||
|
||||
**症状**:启动后 Python 侧报 `ModuleNotFoundError: No module named 'dulwich'`
|
||||
(或 `certifi`),而你的 `buildozer.spec` 里明明写了。
|
||||
|
||||
**原因**:`pyside6-android-deploy` 的 `BuildozerConfig.__init__` 会**硬编码覆写**
|
||||
`requirements = python3,shiboken6,PySide6`,你模板里写的第三方依赖会被丢掉。
|
||||
|
||||
**解决办法**:同一个构建期补丁会在生成 spec 后把依赖补回去,构建日志里能看到:
|
||||
|
||||
```
|
||||
[lnxgit-patch] requirements = python3==3.11.15,shiboken6,PySide6,dulwich,certifi
|
||||
```
|
||||
|
||||
### 4.6 启动时闪退但无 native 崩溃
|
||||
|
||||
先看 Python 侧的启动跟踪(`main.py` 的 `trace()`):
|
||||
|
||||
```bash
|
||||
adb logcat -c
|
||||
adb shell am start -n org.lnxgit.lnxgit/org.kivy.android.PythonActivity
|
||||
sleep 12 && adb logcat -d | grep -iE "LnxGit|python|Exception"
|
||||
```
|
||||
|
||||
正常序列:
|
||||
|
||||
```
|
||||
启动: 注册应用元信息
|
||||
启动: PySide6 6.11.2,数据目录 /data/user/0/org.lnxgit.lnxgit/files/...
|
||||
启动: 创建 QGuiApplication
|
||||
启动: 加载设置
|
||||
启动: 启动 Git 服务线程
|
||||
启动: 注册 QML 单例
|
||||
启动: 加载 QML(.../qml)
|
||||
启动: 进入事件循环
|
||||
```
|
||||
|
||||
另外注意:**Android 上 `sys.stdout` / `sys.stderr` 为 `None`**,
|
||||
任何 `print` 或未兜底的 `logging.StreamHandler` 都会抛 `AttributeError` 导致启动即崩。
|
||||
`main.py` 顶部的 `ensure_std_streams()` 已处理(并把日志转发到 logcat)。
|
||||
|
||||
### 4.7 一键抓日志与验证
|
||||
|
||||
```bash
|
||||
bash scripts/wsl_devices.sh # 先看设备 ABI,选对 APK
|
||||
bash scripts/wsl_verify_app.sh emulator-5554 80 # 安装 + 启动 + 只抓本应用日志
|
||||
bash scripts/wsl_deploy_and_log.sh <apk> [设备] [等待秒数]
|
||||
```
|
||||
|
||||
首次启动需要解包 150 MB 左右的私有数据,**等待时间给足 60–90 秒**,
|
||||
否则会误判为闪退。
|
||||
|
||||
注意模拟器上 `com.android.flysilkworm` 之类的系统组件会不断抛 SIGILL,
|
||||
用宽泛的 `FATAL` / `DEBUG` 关键字过滤会被它们的日志淹没 ——
|
||||
`wsl_verify_app.sh` 只按进程名与应用 tag 过滤。
|
||||
|
||||
### 4.8 界面里的图标显示成豆腐块
|
||||
|
||||
**症状**:标题栏/按钮上的符号变成一个空心方块,例如刷新按钮。
|
||||
|
||||
**原因**是双重巧合,只看一半会得出错误结论:
|
||||
|
||||
1. Android 的符号字体是**子集化**的(只有
|
||||
`NotoSansSymbols-Regular-Subsetted.ttf` / `Subsetted2.ttf`);
|
||||
2. 更关键的是 —— **Qt 的字体回退链里根本没有这个符号字体**。
|
||||
|
||||
第 2 点很容易漏判:把设备字体拉下来查 cmap,`⟳`(U+27F3)**明明有字形**,
|
||||
可界面里依旧是豆腐块。而中文(NotoSansCJK)和 emoji(NotoColorEmoji)
|
||||
走的是别的字体,所以一直正常。**判据只能是"Qt 会用的那几个字体有没有"**:
|
||||
|
||||
| 字体 | 用途 |
|
||||
| --- | --- |
|
||||
| `Roboto-Regular.ttf` | 拉丁文 |
|
||||
| `NotoSansCJK-Regular.ttc` | 中文,以及大量**单色线条符号** |
|
||||
| `NotoColorEmoji.ttf` | 彩色 emoji(**位图**字体) |
|
||||
|
||||
已确认不可用(仅存在于 NotoSansSymbols):
|
||||
`⟳` `↻` `↺` `⟲` `⤓` `⧉` `⎘` `⋮` `☰` `✗` `⭮`
|
||||
|
||||
可用且**风格统一**的替代(均为 NotoSansCJK 的单色线条):
|
||||
|
||||
| 原字符 | 替代 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `⟳` | `⇄` (U+21C4) | 刷新 / 抓取 |
|
||||
| `⤓` | `⬇` (U+2B07) | 加载更多 |
|
||||
| `⧉` `⎘` | `📋` (U+1F4CB) | 复制 |
|
||||
| `+` `⋯` `←` `−` | 不变 | 本来就有字形 |
|
||||
|
||||
> 彩色 emoji 虽然一定有字形,但 NotoColorEmoji 是**位图**字体,
|
||||
> 十几像素下会糊成一团色块 —— 刷新按钮一度用 `🔄`,实际效果和豆腐块差不多。
|
||||
> 所以优先选单色线条符号。`IconButton` 对 emoji 单独用了更大字号
|
||||
> (`emojiSize` vs `glyphSize`)。
|
||||
|
||||
**自查工具**(新增图标前先跑,省掉"构建 → 安装 → 发现是豆腐块"的来回):
|
||||
|
||||
```bash
|
||||
bash scripts/wsl_pull_fonts.sh emulator-5554 /tmp/lnxgit-fonts
|
||||
python3 tools/check_glyphs.py qml /tmp/lnxgit-fonts
|
||||
```
|
||||
|
||||
脚本会扫描 QML 里所有字符串字面量中的非 ASCII 字符,报告哪些不在 Qt 的
|
||||
回退链里,并列出候选字符的可用性。
|
||||
|
||||
### 4.9 应用启动即崩,日志里只有 `QThread: Destroyed while thread 'lnxgit-worker' is still running`
|
||||
|
||||
**症状**:装上新包后点开就退回桌面,logcat 里看不到 Python 报错,只有:
|
||||
|
||||
```
|
||||
F/libc : Fatal signal 6 (SIGABRT) in tid xxx (qtMainLoopThrea)
|
||||
F/DEBUG : Abort message: 'QThread: Destroyed while thread 'lnxgit-worker' is still running'
|
||||
#05 .../PySide6/QtCore.abi3.so
|
||||
#18 .../libmain_x86_64.so (main+1884)
|
||||
```
|
||||
|
||||
**原因**:这是**次生现象**,不是根因。真正的错误是 **QML 加载失败** ——
|
||||
`main.py` 抛异常退出,而 `GitService` 的工作线程还在运行就被析构,
|
||||
Qt 检测到后直接 `abort()`。所以要去日志前面找 QML 的错误,
|
||||
不要被这条 abort 带偏。
|
||||
|
||||
**最常见的触发**:新增了 QML 文件却**忘了在 `qml/LnxGit/qmldir` 里登记**。
|
||||
`Main.qml` 用 `import LnxGit 1.0` 引用页面,模块里没声明就会:
|
||||
|
||||
```
|
||||
Warning: qml/Main.qml:209:9: GraphPage was not found. Did you add all imports and dependencies?
|
||||
```
|
||||
|
||||
**排查**:
|
||||
|
||||
```bash
|
||||
# 静态检查(PySide6 自带,不需要设备)
|
||||
/opt/lnxgit-android/venv/bin/pyside6-qmllint -I qml qml/Main.qml
|
||||
```
|
||||
|
||||
新增页面/组件后,先跑一遍 qmllint 再构建,能省掉一整轮"构建 → 安装 → 崩溃"。
|
||||
|
||||
### 4.10 列表盖住标题栏(Column 布局整个失效)
|
||||
|
||||
**症状**:标题栏文字与列表第一行重叠,列表像是从屏幕顶端开始画的。
|
||||
**只有列表非空时才出现** —— 空列表时一切正常,所以极易漏掉。
|
||||
|
||||
**原因**:Qt 的 `Column` / `Row` 自己负责摆放子项,子项**不能**再用
|
||||
`anchors.top` / `bottom` / `fill` / `centerIn` 这类锚点。一旦用了,
|
||||
Qt 不只是忽略那个锚点 —— **整个 Column 停止布局**,所有子项堆到原点互相重叠。
|
||||
|
||||
典型写法(错误):
|
||||
|
||||
```qml
|
||||
Column {
|
||||
anchors.fill: parent
|
||||
AppBar { ... }
|
||||
ListView { ... }
|
||||
EmptyState {
|
||||
anchors.top: parent.top // ← 这一行让上面的 Column 整个失效
|
||||
anchors.topMargin: 130
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**修法**:把用了锚点的子项**移出** Column,作为页面根 Item 的直接子项:
|
||||
|
||||
```qml
|
||||
Column {
|
||||
anchors.fill: parent
|
||||
AppBar { ... }
|
||||
ListView { ... }
|
||||
}
|
||||
|
||||
EmptyState {
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 130
|
||||
}
|
||||
```
|
||||
|
||||
**自查**:
|
||||
|
||||
```bash
|
||||
python tools/check_qml_layout.py qml
|
||||
```
|
||||
|
||||
脚本按缩进识别"Column/Row 的直接子项",报出会致命的锚点
|
||||
(`verticalCenter` 之类在 Row 里属常见写法,只作提示)。
|
||||
|
||||
## 五、其他已处理的坑
|
||||
|
||||
| 现象 | 原因 | 处理 |
|
||||
| --- | --- | --- |
|
||||
| `buildozer init` EOFError | buildozer 拒绝以 root 运行并等待确认 | 用普通用户构建(`wsl_create_builder_user.sh`) |
|
||||
| `pip install --user` 失败 | buildozer 未检测到虚拟环境 | 构建时导出 `VIRTUAL_ENV` |
|
||||
| `sdkmanager` 找不到 | buildozer 期望 `<sdk>/tools/bin/sdkmanager` | 建 `tools -> cmdline-tools/latest` 软链 |
|
||||
| clone `python-for-android` 超时 | GitHub 直连不稳 | 镜像预克隆 + `p4a.source_dir` 固定目录 |
|
||||
| Gradle 下载卡住/失败 | services.gradle.org 被限速 | 镜像下载后放入 wrapper 的 MD5-base36 哈希目录 |
|
||||
| `ast.parse` invalid non-printable U+FEFF | 源文件被写入 UTF-8 BOM | `python tools/clean_sources.py` 清理 |
|
||||
| `create_recipe` ValueError | `pysidedeploy.spec` 的 `plugins` 只写了类别名 | 留空由工具自动探测,或写成 `类别_插件名` |
|
||||
| aapt 报 `icon.png: file failed to compile` | 打包工具硬编码传入 `.jpg` 图标却被当 PNG 解析 | `scripts/wsl_fix_icon.sh` 用我们的 PNG 覆盖 |
|
||||
| `libQt6Core_arm64-v8a.so not found inside the wheel` | 两个 spec 的架构只改了一个 | 见第二章架构说明 |
|
||||
| Qt 下载中断 `HTTP/2 stream ... CANCEL` | 主站限速 | `--http1.1` + 重试 + 镜像回退 |
|
||||
| `/mnt/c` 上 `sed -i` 报权限错误 | Windows 挂载不支持原子替换 | 写临时文件后 `cat` 回去 |
|
||||
| 构建卡在 "Downloading python3" 十几分钟 | p4a 用 urllib 下载且**没有超时**,GitHub 连接挂住 | 预置源码包 + 补丁设 `socket` 默认超时(`LNXGIT_SOCKET_TIMEOUT`,默认 60s) |
|
||||
| 每轮构建都从零编译 CPython | deploy 的 `cleanup()` 每次 `rmtree(.buildozer)`,收尾又把它 `move` 进 `deployment/` | 补丁改写 `cleanup`:先取回缓存再删 `deployment`,但保留 `.buildozer` |
|
||||
| `ImportError: cannot import name 'open_rich_spinner'` | p4a 复用 `build/venv`,而 `python -m venv` 不清空旧目录,pip 文件新旧混杂 | 每次构建前删 `build-*/build/venv` |
|
||||
| recipe 里几百个 `# _LNXGIT_PINNED` | 旧补丁的正则只匹配版本行前缀,每次执行都追加一次注释 | 改成整行替换(幂等),`scripts/wsl_fix_recipes.sh` 顺带清理历史膨胀 |
|
||||
| 界面图标显示成豆腐块 | 符号字体被子集化,且 Qt 的回退链里不含 NotoSansSymbols | 换成 NotoSansCJK 里的单色符号,见 4.8;用 `tools/check_glyphs.py` 自查 |
|
||||
| 启动即崩,只见 `QThread: Destroyed while thread ... is still running` | QML 加载失败(常见于新增文件没写进 qmldir)导致主程序退出,工作线程仍在运行 | 见 4.9,先用 `pyside6-qmllint -I qml` 定位 |
|
||||
| 列表盖住标题栏,空列表时却正常 | Column/Row 的直接子项用了锚点,导致整个布局容器失效 | 见 4.10,用 `tools/check_qml_layout.py` 自查 |
|
||||
|
||||
## 六、安装与验证
|
||||
|
||||
```bash
|
||||
adb install -r dist/LnxGit-*-debug.apk
|
||||
```
|
||||
|
||||
验证要点(可用 `aapt2 dump badging` 查看):
|
||||
|
||||
* `package: name='org.lnxgit.lnxgit'`,`application-label:'LnxGit'`
|
||||
* `uses-permission: android.permission.INTERNET`
|
||||
* `native-code: 'arm64-v8a'`
|
||||
* 图标来自 `docs/icon-512.png`
|
||||
@@ -23,8 +23,11 @@
|
||||
默认只打包 `arm64-v8a`(aarch64),wheel 为
|
||||
`pyside6-6.11.2-6.11.2-cp311-cp311-android_aarch64.whl`。
|
||||
如需 x86_64 模拟器版本,把 `scripts/wsl_setup_android.sh` 里的 `arch` 改成
|
||||
`x86_64`,并在 `build_apk.sh` 中改用对应的 wheel。
|
||||
`x86_64`,并在 `wsl_build.sh` 中改用对应的 wheel。
|
||||
|
||||
4. **首次构建耗时**
|
||||
p4a 需要自行编译 CPython 与若干依赖,首次构建通常 30–60 分钟。
|
||||
后续构建会复用 `~/.buildozer` 缓存,几分钟即可完成。
|
||||
后续构建会复用 `/opt/lnxgit-android/src/.buildozer` 与 `~/.buildozer` 缓存,
|
||||
通常几分钟即可完成。
|
||||
|
||||
> 完整的踩坑记录与一键脚本见 [`BUILD.md`](BUILD.md)。
|
||||
|
||||
39
buildozer.spec
Normal file
39
buildozer.spec
Normal file
@@ -0,0 +1,39 @@
|
||||
[app]
|
||||
title = LnxGit
|
||||
package.name = LnxGit
|
||||
package.domain = cc.xnhw
|
||||
|
||||
source.dir = .
|
||||
source.include_exts = py,png,jpg,kv,atlas,qml,js,svg,json,md,txt
|
||||
source.exclude_dirs = artifacts,build,dist,tools,scripts,android,docs,.git
|
||||
version = 1.0.0
|
||||
requirements = python3,shiboken6,PySide6,dulwich,certifi
|
||||
|
||||
orientation = portrait
|
||||
fullscreen = 0
|
||||
# 注意:aapt 对过大的图标会报 "file failed to compile",
|
||||
# 因此这里使用 192×192 的标准 RGBA PNG(512 版本保留在 docs/ 供商店使用)。
|
||||
icon.filename = %(source.dir)s/docs/icon-192.png
|
||||
|
||||
android.permissions = INTERNET,ACCESS_NETWORK_STATE
|
||||
android.api = 35
|
||||
android.minapi = 24
|
||||
android.ndk_api = 24
|
||||
android.archs = arm64-v8a
|
||||
android.allow_backup = True
|
||||
android.accept_sdk_license = True
|
||||
android.enable_androidx = True
|
||||
android.logcat_filters = *:S python:D
|
||||
|
||||
p4a.bootstrap = qt
|
||||
p4a.branch = develop
|
||||
# p4a 源码放在构建目录之外:buildozer 每次构建会清空项目本地 .buildozer,
|
||||
# 放在固定的 /opt 目录可以避免反复直连 GitHub 克隆。
|
||||
p4a.source_dir = /opt/lnxgit-android/p4a-src
|
||||
p4a.local_recipes =
|
||||
p4a.extra_args =
|
||||
|
||||
[buildozer]
|
||||
log_level = 2
|
||||
warn_on_root = 1
|
||||
bin_dir = ./bin
|
||||
BIN
docs/icon-144.png
Normal file
BIN
docs/icon-144.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.3 KiB |
@@ -1,53 +1,55 @@
|
||||
## LnxGit 1.0.0
|
||||
# LnxGit 1.0.0
|
||||
|
||||
首个可用版本:用 **PySide6 + QML** 编写的 Android Git 客户端,
|
||||
首个可用版本:用 **PySide6 + QML** 编写的 Android Git 客户端。
|
||||
Git 能力由纯 Python 实现 **dulwich** 提供,**无需设备安装 git 命令**。
|
||||
|
||||
### 新增
|
||||
## 📦 安装包
|
||||
|
||||
- **仓库连接**
|
||||
- 克隆远程仓库(HTTPS / SSH,支持浅克隆与指定分支)
|
||||
- 新建空仓库、多仓库列表与搜索、概览、删除、重命名
|
||||
- 克隆前可先测试连接(`ls-remote`)
|
||||
- **完整 Git 操作**
|
||||
- 暂存 / 取消暂存(单文件或全部)、提交、工作区与暂存区差异、提交间差异
|
||||
- 分支:创建、切换、重命名、删除(删除当前分支会自动回退)、合并、建立远端跟踪分支
|
||||
- 标签:轻量与附注标签的创建、列示、删除、推送
|
||||
- 远端:添加 / 删除 / 修改地址、fetch、pull、push(含强推与设置上游)、删除远端分支
|
||||
- 历史:分页日志、按说明 / 作者 / SHA 搜索、提交详情、文件级变更、逐行追溯 blame
|
||||
- 文件:任意版本的文件树浏览与内容查看、工作区文件查看
|
||||
- 其他:储藏、reset(soft / mixed / hard)、丢弃改动、清理未跟踪文件、cherry-pick、仓库配置读写
|
||||
- **移动端体验**
|
||||
- 深色 / 浅色主题,Material 风格,触控友好布局
|
||||
- 全部耗时操作在后台线程执行,界面显示实时进度与日志
|
||||
- 认证失败自动弹窗(支持个人访问令牌),可记住凭据
|
||||
- 内置运行日志页,便于排查网络与认证问题
|
||||
| 文件 | 大小 | SHA256 |
|
||||
| --- | --- | --- |
|
||||
| `LnxGit-1.0.0-arm64-v8a-release-universal.apk` | 107.8 MB | `036e33e21f8fa0a7c9ff411889363daed30dc885e4ec6cc17b3607e3aef4fa7b` |
|
||||
|
||||
### 构建信息
|
||||
安装:
|
||||
|
||||
```bash
|
||||
adb install -r LnxGit-1.0.0-arm64-v8a-release-universal.apk
|
||||
```
|
||||
|
||||
也可以直接把 APK 传到手机点击安装(需允许「安装未知来源应用」)。
|
||||
|
||||
> 该包由 **release** 构建产出,并裁掉了用不到的 Qt 模块(WebEngine / Designer /
|
||||
> 3D / Charts / Multimedia 等),再用 debug 密钥签名,因此可以直接安装。
|
||||
> 包名 `org.lnxgit.lnxgit`,最低 Android 7.0(API 24),架构 arm64-v8a。
|
||||
|
||||
## 功能
|
||||
|
||||
- **仓库连接**:克隆(HTTPS / SSH、浅克隆、指定分支)、新建空仓库、多仓库管理、连接测试
|
||||
- **完整 Git 操作**:暂存 / 取消暂存、提交、差异(工作区 / 暂存区 / 提交间)、分支(创建 / 切换 / 重命名 / 删除 / 合并)、标签(创建 / 删除 / 推送)、远端(增删改 / fetch / pull / push / 强推 / 删除远端分支)、日志与搜索、提交详情、逐行追溯 blame、文件树浏览与内容查看、储藏、reset、丢弃改动、清理未跟踪文件、cherry-pick、仓库配置读写
|
||||
- **移动端体验**:深色 / 浅色主题、后台线程执行 + 实时进度、认证失败自动弹窗(支持个人访问令牌)、内置运行日志页
|
||||
|
||||
## 技术要点
|
||||
|
||||
| 项目 | 版本 |
|
||||
| --- | --- |
|
||||
| PySide6 / Qt | 6.11.2 |
|
||||
| Python(打包进 APK) | 3.11 |
|
||||
| 打包进 APK 的 Python | 3.14(p4a 默认;wheel 为 abi3,兼容 3.10–3.14) |
|
||||
| Android 架构 | arm64-v8a |
|
||||
| NDK | 27.2.12479018 |
|
||||
| Android API | 35 |
|
||||
| Android SDK Platform | android-35 |
|
||||
| Gradle | 8.14.3 |
|
||||
|
||||
### 安装
|
||||
|
||||
```bash
|
||||
adb install -r lnxgit-debug.apk
|
||||
```
|
||||
|
||||
或直接把 APK 传到手机点击安装(需允许「安装未知来源应用」)。
|
||||
|
||||
### 已知限制
|
||||
## 已知限制
|
||||
|
||||
- 不支持三方合并的冲突编辑流程:冲突时需手动处理后提交。
|
||||
- 差异与文件预览限制在 400 KB / 1 MB 内,避免大文件卡顿。
|
||||
- 暂不支持交互式 rebase 与 submodule 操作。
|
||||
- 本版本仅提供 arm64-v8a 架构。
|
||||
- 仅提供 arm64-v8a;如需 x86_64 模拟器版本,按 `android/BUILD.md` 改架构重新打包。
|
||||
|
||||
### 源码
|
||||
## 源码与构建
|
||||
|
||||
完整源码、构建脚本与测试见仓库根目录,`README.md` 中有详细说明。
|
||||
完整源码、一键构建脚本与踩坑记录见仓库根目录:
|
||||
|
||||
- `README.md` —— 项目说明与桌面端运行方式
|
||||
- `android/BUILD.md` —— WSL 内构建 Android APK 的完整流程
|
||||
- `scripts/` —— 环境准备、构建、AAB 转 APK、图标修复等脚本
|
||||
- `tools/` —— 冒烟测试、端到端测试、QML 检查、截图、Release 发布工具
|
||||
|
||||
BIN
docs/screenshots/09-graph.png
Normal file
BIN
docs/screenshots/09-graph.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 82 KiB |
BIN
docs/screenshots/10-history-graph.png
Normal file
BIN
docs/screenshots/10-history-graph.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 110 KiB |
BIN
docs/screenshots/11-graph-many-branches.png
Normal file
BIN
docs/screenshots/11-graph-many-branches.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 64 KiB |
BIN
docs/screenshots/12-branches-actions.png
Normal file
BIN
docs/screenshots/12-branches-actions.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
BIN
docs/screenshots/13-map-picker-legend.png
Normal file
BIN
docs/screenshots/13-map-picker-legend.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 89 KiB |
@@ -30,6 +30,7 @@ from dulwich.index import IndexEntry
|
||||
from dulwich.objectspec import parse_commit, parse_object
|
||||
from dulwich.objects import Blob, Commit, Tag, Tree
|
||||
from dulwich.repo import Repo
|
||||
from dulwich.walk import ORDER_TOPO
|
||||
|
||||
# --------------------------------------------------------------------------- 常量
|
||||
|
||||
@@ -582,6 +583,34 @@ def list_changes(path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
# --------------------------------------------------------------------------- 日志 / 提交详情
|
||||
|
||||
|
||||
def _peel_commit(repo: Repo, ref: bytes, sha: bytes) -> bytes:
|
||||
"""把引用指向的对象解引用到提交。
|
||||
|
||||
注解标签(``git tag -a``)的引用直接指向 tag 对象而不是提交,
|
||||
不 peel 的话标签永远挂不到对应的提交行上。
|
||||
"""
|
||||
try:
|
||||
peeled = repo.get_peeled(ref)
|
||||
if peeled:
|
||||
return peeled
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
obj = repo[sha]
|
||||
if isinstance(obj, Tag):
|
||||
return obj.object[1]
|
||||
except Exception:
|
||||
pass
|
||||
return sha
|
||||
|
||||
|
||||
def _normalize_ref(name: bytes) -> str:
|
||||
"""``refs/heads/main`` → ``main``;``refs/remotes/origin/x`` → ``origin/x``。"""
|
||||
return (_text(name).replace("refs/heads/", "")
|
||||
.replace("refs/remotes/", "")
|
||||
.replace("refs/tags/", ""))
|
||||
|
||||
|
||||
def _refs_by_sha(repo: Repo) -> dict[bytes, list[str]]:
|
||||
"""构建 ``{commit sha: [分支/标签名]}`` 映射,用于日志中的引用标记。"""
|
||||
mapping: dict[bytes, list[str]] = {}
|
||||
@@ -590,19 +619,329 @@ def _refs_by_sha(repo: Repo) -> dict[bytes, list[str]]:
|
||||
text = _text(name)
|
||||
if text.endswith("/HEAD") or text == "HEAD":
|
||||
continue
|
||||
short = (text.replace("refs/heads/", "")
|
||||
.replace("refs/remotes/", "")
|
||||
.replace("refs/tags/", ""))
|
||||
mapping.setdefault(sha, []).append(short)
|
||||
mapping.setdefault(_peel_commit(repo, name, sha), []).append(
|
||||
_normalize_ref(name))
|
||||
except Exception:
|
||||
pass
|
||||
return mapping
|
||||
|
||||
|
||||
def _branches_by_sha(repo: Repo) -> dict[bytes, list[str]]:
|
||||
"""只要分支引用(本地 + 远端),不含标签。
|
||||
|
||||
图谱按分支配色时用它:一个提交上同时挂着分支和标签时(例如 main 上打了
|
||||
v1.0),标签名不该顶替分支名 —— 否则图例里会出现 "v1.0" 而没有 "main"。
|
||||
"""
|
||||
mapping: dict[bytes, list[str]] = {}
|
||||
try:
|
||||
for name, sha in repo.get_refs().items():
|
||||
text = _text(name)
|
||||
if not (text.startswith("refs/heads/") or text.startswith("refs/remotes/")):
|
||||
continue
|
||||
if text.endswith("/HEAD"):
|
||||
continue
|
||||
mapping.setdefault(_peel_commit(repo, name, sha), []).append(_normalize_ref(name))
|
||||
except Exception:
|
||||
pass
|
||||
return mapping
|
||||
|
||||
|
||||
def _all_ref_shas(repo: Repo) -> list[bytes]:
|
||||
"""所有分支 / 标签 / 远端引用指向的提交(``git log --all`` 的 include 集合)。"""
|
||||
result: list[bytes] = []
|
||||
seen: set[bytes] = set()
|
||||
try:
|
||||
for name, sha in repo.get_refs().items():
|
||||
if _text(name).endswith("/HEAD"):
|
||||
continue
|
||||
target = _peel_commit(repo, name, sha)
|
||||
if target not in seen:
|
||||
seen.add(target)
|
||||
result.append(target)
|
||||
except Exception:
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
#: 前端配色数量,``laneColor`` 是它的取模结果
|
||||
GRAPH_COLORS = 8
|
||||
|
||||
|
||||
def _graph_layout(commits: list[dict[str, Any]]) -> None:
|
||||
"""为提交序列计算泳道布局,结果原地写回每个提交字典。
|
||||
|
||||
思路与 gitk / GitKraken 一致:维护一组「活跃泳道」,每条泳道记住它正在
|
||||
等待的提交。处理某个提交时:
|
||||
|
||||
* 等待它的泳道就是它的节点列(多条泳道等待它 = 多个子提交汇聚,即合并);
|
||||
* 第一个父提交继承该泳道,其余的父提交(合并进来的另一条线)各占一列;
|
||||
* 没有任何泳道等待它时(分支尖端、只有标签指向、``--all`` 里的孤立头),
|
||||
它自己开一列。
|
||||
|
||||
输出给前端的字段:
|
||||
|
||||
* ``graphAbove`` / ``graphBelow`` —— 本行顶部与底部经过的列;
|
||||
* ``graphLinks`` —— 从本行节点额外连出去的斜线目标列(合并提交接入
|
||||
既有泳道、以及分叉点复用同一条父提交线时会出现)。
|
||||
|
||||
前端按下面几条规则就能画出整行:
|
||||
|
||||
* 同时出现在 above 与 below 的列 → 竖线贯穿;
|
||||
* 在 above、不在 below 的列 → 斜线汇入本行节点;
|
||||
* 只在 below 的列 → 从节点斜线分叉出去;
|
||||
* ``graphLinks`` 里的列 → 从节点斜线连到该列的底部。
|
||||
|
||||
调用方必须保证 ``commits`` 是**拓扑序**(父提交排在子提交之后),
|
||||
否则泳道会错乱 —— 因此 walker 用 ``ORDER_TOPO``。
|
||||
"""
|
||||
active: list[tuple[str, int] | None] = []
|
||||
next_color = 0
|
||||
|
||||
def take_slot() -> int:
|
||||
for index, item in enumerate(active):
|
||||
if item is None:
|
||||
return index
|
||||
active.append(None)
|
||||
return len(active) - 1
|
||||
|
||||
def waiting_for(sha: str, exclude: int = -1) -> list[int]:
|
||||
return [i for i, item in enumerate(active)
|
||||
if item is not None and item[0] == sha and i != exclude]
|
||||
|
||||
for row in commits:
|
||||
sha = str(row["sha"])
|
||||
parents = list(row.get("parents") or [])
|
||||
|
||||
# 1) 定位节点列
|
||||
waiting = waiting_for(sha)
|
||||
if waiting:
|
||||
lane = waiting[0]
|
||||
color = active[lane][1] # type: ignore[index]
|
||||
else:
|
||||
# 新线头(分支尖端、只被标签指向的提交)。若它的第一个父提交已经有
|
||||
# 泳道在等,就直接借用那一列 —— 多个分支从同一点分叉时,git log
|
||||
# --graph 也是把兄弟尖端画在同一列;否则每个尖端都要新开一列、又
|
||||
# 因为父提交已有线可连而立刻把该列回收,白白多占一列。
|
||||
row_parents = list(row.get("parents") or [])
|
||||
borrowed = waiting_for(row_parents[0]) if row_parents else []
|
||||
if borrowed:
|
||||
lane = borrowed[0]
|
||||
else:
|
||||
lane = take_slot()
|
||||
color = next_color
|
||||
next_color += 1
|
||||
|
||||
above = [i for i, item in enumerate(active) if item is not None]
|
||||
above_colors = [active[i][1] % GRAPH_COLORS if active[i] is not None else -1
|
||||
for i in range(len(active))]
|
||||
for index in waiting_for(sha, exclude=lane):
|
||||
active[index] = None # 其他等待本提交的泳道汇入
|
||||
|
||||
# 2) 推进泳道。父提交若已经有别的泳道在等(例如 hotfix 与 main 都从
|
||||
# 同一个提交分叉出去),就不必再占一列 —— 本行节点直接用一条
|
||||
# 连线接到那条既有泳道上,把本列腾给下一个父提交。
|
||||
links: list[int] = []
|
||||
free_slot: int | None = None
|
||||
if parents:
|
||||
first = parents[0]
|
||||
current = active[lane]
|
||||
if current is not None and current[0] == first:
|
||||
# 本列本来就在等这个父提交(借用了它的泳道),保持原样,
|
||||
# 免得整条线的颜色被最新那个分支的节点色覆盖
|
||||
pass
|
||||
else:
|
||||
existing = waiting_for(first, exclude=lane)
|
||||
if existing:
|
||||
links.append(existing[0])
|
||||
active[lane] = None
|
||||
free_slot = lane
|
||||
else:
|
||||
active[lane] = (first, color)
|
||||
for parent in parents[1:]:
|
||||
existing = waiting_for(parent)
|
||||
if existing:
|
||||
links.append(existing[0])
|
||||
continue
|
||||
if free_slot is not None:
|
||||
active[free_slot] = (parent, next_color)
|
||||
free_slot = None
|
||||
else:
|
||||
slot = take_slot()
|
||||
active[slot] = (parent, next_color)
|
||||
next_color += 1
|
||||
else:
|
||||
active[lane] = None # 根提交,泳道结束
|
||||
|
||||
# 3) 只清理尾部空列;中间空列保留,否则已有的线会错位
|
||||
while active and active[-1] is None:
|
||||
active.pop()
|
||||
|
||||
below = [i for i, item in enumerate(active) if item is not None]
|
||||
columns = max(len(active), len(above), lane + 1)
|
||||
|
||||
def color_row(source: list[int]) -> list[int]:
|
||||
"""按列号补齐成等长数组,空列填 -1,方便前端直接用列号取色。"""
|
||||
return [source[i] if i < len(source) else -1 for i in range(columns)]
|
||||
|
||||
row["lane"] = lane
|
||||
row["laneColor"] = color % GRAPH_COLORS
|
||||
row["graphAbove"] = above
|
||||
row["graphBelow"] = below
|
||||
row["graphLinks"] = links
|
||||
row["graphCols"] = columns
|
||||
row["graphAboveColors"] = color_row(above_colors)
|
||||
row["graphBelowColors"] = color_row(
|
||||
[active[i][1] % GRAPH_COLORS if active[i] is not None else -1
|
||||
for i in range(len(active))])
|
||||
|
||||
|
||||
|
||||
#: 分支地图(二维流程图视图)的节点尺寸与间距
|
||||
MAP_NODE_WIDTH = 158
|
||||
MAP_NODE_HEIGHT = 46
|
||||
MAP_ROW_GAP = 30
|
||||
MAP_COL_GAP = 34
|
||||
|
||||
|
||||
def _map_layout(commits: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""把提交映射成二维地图坐标,返回整图尺寸。
|
||||
|
||||
与历史页那条紧凑泳道不同,这里的横向轨道是**独立重新分配**的,
|
||||
而且刻意**不回收列**:紧凑视图要把兄弟分支挤在同一列才省地方,
|
||||
但二维地图有足够的横向空间(可以滚动),铺开之后"从同一点分叉出的
|
||||
多个分支"才看得出来 —— 否则 21 个分支会重叠成一条竖线。
|
||||
|
||||
纵向按提交序号排(最新的在最上面,屏幕 y 向下增长),
|
||||
横向按轨道序号排,两者组合天然唯一,节点不会重叠。
|
||||
"""
|
||||
total = len(commits)
|
||||
if not total:
|
||||
return {"mapWidth": 0, "mapHeight": 0,
|
||||
"mapNodeWidth": MAP_NODE_WIDTH, "mapNodeHeight": MAP_NODE_HEIGHT}
|
||||
|
||||
# 1) 分配横向轨道:主线居中,分支向**左右两侧交替**展开。
|
||||
# 如果一律往右开新列,图会只朝一个方向长,既不平衡也占地方。
|
||||
used_lanes: set[int] = set()
|
||||
|
||||
def lane_sequence():
|
||||
yield 0
|
||||
step = 1
|
||||
while True:
|
||||
yield step
|
||||
yield -step
|
||||
step += 1
|
||||
|
||||
lane_iter = lane_sequence()
|
||||
|
||||
def take_lane() -> int:
|
||||
while True:
|
||||
candidate = next(lane_iter)
|
||||
if candidate not in used_lanes:
|
||||
used_lanes.add(candidate)
|
||||
return candidate
|
||||
|
||||
# active 的每一项是 (这条轨道在等哪个提交, 轨道号)
|
||||
active: list[tuple[str | None, int]] = []
|
||||
lanes: list[int] = []
|
||||
|
||||
for row in commits:
|
||||
sha = str(row["sha"])
|
||||
waiting = [i for i, (pending, _) in enumerate(active) if pending == sha]
|
||||
if waiting:
|
||||
slot = waiting[0]
|
||||
lane = active[slot][1]
|
||||
for other in waiting[1:]:
|
||||
active[other] = (None, active[other][1])
|
||||
else:
|
||||
# 新线头(分支尖端):占一条离中线最近的空轨道
|
||||
lane = take_lane()
|
||||
slot = len(active)
|
||||
active.append((None, lane))
|
||||
|
||||
lanes.append(lane)
|
||||
|
||||
parents = [str(parent) for parent in (row.get("parents") or [])]
|
||||
if parents:
|
||||
active[slot] = (parents[0], lane) # 第一个父提交继承本轨道
|
||||
for parent in parents[1:]:
|
||||
if any(pending == parent for pending, _ in active):
|
||||
continue
|
||||
active.append((parent, take_lane())) # 合并进来的线各占新轨道
|
||||
else:
|
||||
active[slot] = (None, lane) # 根提交,本轨道结束
|
||||
|
||||
# 2) 颜色按**分支**分配(而不是按轨道):同一分支的提交与连线同色,
|
||||
# 图例也能和分支名一一对应。
|
||||
# 分支归属取自提交自带的引用;中间的提交没有引用,就继承第一个引用
|
||||
# 它的子提交所属的分支 —— 这样一条分支从头到尾是同一个颜色。
|
||||
branch_of: dict[str, str] = {}
|
||||
for row in commits:
|
||||
sha = str(row["sha"])
|
||||
# 优先用「只要分支」的那份引用,标签不参与配色
|
||||
names = [name for name in (row.get("branchRefs") or []) if name]
|
||||
if not names:
|
||||
names = [name for name in (row.get("refs") or []) if name]
|
||||
name = names[0] if names else branch_of.get(sha, "")
|
||||
branch_of[sha] = name
|
||||
for parent in (row.get("parents") or []):
|
||||
branch_of.setdefault(str(parent), name)
|
||||
|
||||
branch_colors: dict[str, int] = {}
|
||||
for row in commits:
|
||||
name = branch_of.get(str(row["sha"]), "")
|
||||
if name not in branch_colors:
|
||||
branch_colors[name] = len(branch_colors) % GRAPH_COLORS
|
||||
|
||||
# 3) 纵向按「到根的最长路径」分层,而不是提交序号 —— 这样从同一点分叉出的
|
||||
# 兄弟分支会落在同一水平线上并排,而不是斜着排成一条对角线。
|
||||
depths: dict[str, int] = {}
|
||||
for row in reversed(commits): # 自旧到新,父提交的深度先算好
|
||||
sha = str(row["sha"])
|
||||
parents = [str(parent) for parent in (row.get("parents") or [])]
|
||||
if parents:
|
||||
depths[sha] = 1 + max(depths.get(parent, 0) for parent in parents)
|
||||
else:
|
||||
depths[sha] = 0
|
||||
|
||||
column_step = MAP_NODE_WIDTH + MAP_COL_GAP
|
||||
row_step = MAP_NODE_HEIGHT + MAP_ROW_GAP
|
||||
max_depth = max(depths.values()) if depths else 0
|
||||
min_lane = min(lanes)
|
||||
max_lane = max(lanes)
|
||||
|
||||
for index, row in enumerate(commits):
|
||||
sha = str(row["sha"])
|
||||
lane = lanes[index]
|
||||
branch = branch_of.get(sha, "")
|
||||
row["mapLane"] = lane
|
||||
row["mapDepth"] = depths[sha]
|
||||
row["mapBranch"] = branch
|
||||
row["mapColor"] = branch_colors[branch]
|
||||
# 轨道号可能为负(向左展开的分支),减去最小值挪回非负区间
|
||||
row["mapX"] = (lane - min_lane) * column_step + MAP_NODE_WIDTH / 2.0
|
||||
# 屏幕 y 向下增长:深度越大(越新)越靠上,根提交落在最下面
|
||||
row["mapY"] = (max_depth - depths[sha]) * row_step + MAP_NODE_HEIGHT / 2.0
|
||||
|
||||
legend = [{"name": name, "color": color}
|
||||
for name, color in sorted(branch_colors.items(), key=lambda item: item[1])
|
||||
if name]
|
||||
|
||||
return {
|
||||
"mapWidth": (max_lane - min_lane + 1) * column_step - MAP_COL_GAP,
|
||||
"mapHeight": (max_depth + 1) * row_step - MAP_ROW_GAP,
|
||||
"mapNodeWidth": MAP_NODE_WIDTH,
|
||||
"mapNodeHeight": MAP_NODE_HEIGHT,
|
||||
"mapLanes": max_lane - min_lane + 1,
|
||||
"mapDepths": max_depth + 1,
|
||||
"mapLegend": legend,
|
||||
}
|
||||
|
||||
|
||||
def log(path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
max_entries = int(params.get("maxEntries") or 100)
|
||||
skip = int(params.get("skip") or 0)
|
||||
branch = (params.get("branch") or "").strip() or None
|
||||
include_all = bool(params.get("allRefs"))
|
||||
commits: list[dict[str, Any]] = []
|
||||
|
||||
with open_repo(path) as repo:
|
||||
@@ -618,8 +957,19 @@ def log(path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
include = [repo.refs[_bytes(branch)]]
|
||||
except KeyError:
|
||||
include = None
|
||||
walker = repo.get_walker(include=include, max_entries=max_entries + skip)
|
||||
elif include_all:
|
||||
# git log --all:把每条本地/远端分支与标签都作为起点,
|
||||
# 否则 walker 只从 HEAD 出发,未合并的分支根本不会出现
|
||||
include = _all_ref_shas(repo) or None
|
||||
|
||||
# 泳道布局要求父提交一定排在子提交之后,所以用拓扑序而不是时间序
|
||||
try:
|
||||
walker = repo.get_walker(include=include, max_entries=max_entries + skip,
|
||||
order=ORDER_TOPO)
|
||||
except KeyError:
|
||||
walker = [] # 空仓库:还没有 HEAD / 任何引用
|
||||
ref_map = _refs_by_sha(repo)
|
||||
branch_map = _branches_by_sha(repo)
|
||||
for index, entry in enumerate(walker):
|
||||
if index < skip:
|
||||
continue
|
||||
@@ -637,12 +987,19 @@ def log(path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
"parents": parents,
|
||||
"isMerge": len(parents) > 1,
|
||||
"refs": ref_map.get(commit.id, []),
|
||||
# 只含分支(本地 + 远端),图谱按分支配色时用它,标签不参与
|
||||
"branchRefs": branch_map.get(commit.id, []),
|
||||
})
|
||||
if len(commits) >= max_entries:
|
||||
break
|
||||
|
||||
_graph_layout(commits)
|
||||
map_size = _map_layout(commits)
|
||||
|
||||
return {"output": f"共 {len(commits)} 条提交", "commits": commits,
|
||||
"hasMore": len(commits) >= max_entries}
|
||||
"hasMore": len(commits) >= max_entries,
|
||||
"allRefs": include_all,
|
||||
**map_size}
|
||||
|
||||
|
||||
def commit_detail(path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -1458,6 +1815,9 @@ OPERATIONS: dict[str, Callable[[str, dict[str, Any]], dict[str, Any]]] = {
|
||||
"commit": commit,
|
||||
"changes": list_changes,
|
||||
"log": log,
|
||||
# 图谱页与历史页共用同一套布局计算,但走独立的 operation 名,
|
||||
# 这样两个页面的列表不会互相覆盖
|
||||
"graph": log,
|
||||
"commitDetail": commit_detail,
|
||||
"diff": diff,
|
||||
"file": file_blob,
|
||||
|
||||
@@ -208,6 +208,17 @@ class GitService(QObject):
|
||||
payload.setdefault("maxEntries", 60)
|
||||
return self._submit("log", payload)
|
||||
|
||||
@Slot("QVariantMap", result=str)
|
||||
def graph(self, params: dict[str, Any] | None = None) -> str:
|
||||
"""分支地图页:与 log 同样的布局计算,但独立成一路结果。
|
||||
|
||||
两个页面共用 ``log`` 的话,切换页面时后加载的列表会把先前那份覆盖掉。
|
||||
"""
|
||||
payload = self._repo_params(params)
|
||||
payload.setdefault("maxEntries", 200)
|
||||
payload.setdefault("allRefs", True)
|
||||
return self._submit("graph", payload)
|
||||
|
||||
@Slot("QVariantMap", result=str)
|
||||
def commitDetail(self, params: dict[str, Any] | None = None) -> str:
|
||||
return self._submit("commitDetail", self._repo_params(params))
|
||||
|
||||
132
main.py
132
main.py
@@ -13,6 +13,93 @@ import sys
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Android 上 python-for-android 会把 stdout/stderr 置为 None,
|
||||
# 任何 print / StreamHandler 都会抛 AttributeError 导致启动即崩溃,
|
||||
# 所以必须尽早兜底成可写的假流。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _SafeStream:
|
||||
"""在没有标准输出的环境(Android)下接收日志,转发到 logcat 或丢弃。"""
|
||||
|
||||
def __init__(self, level: int = 20, fallback=None) -> None:
|
||||
self._level = level
|
||||
self._fallback = fallback
|
||||
self._buffer: list[str] = []
|
||||
|
||||
def write(self, data) -> int: # noqa: ANN001
|
||||
text = data if isinstance(data, str) else str(data)
|
||||
if self._fallback is not None:
|
||||
try:
|
||||
self._fallback(text)
|
||||
except Exception:
|
||||
pass
|
||||
return len(text)
|
||||
|
||||
def writelines(self, lines) -> None: # noqa: ANN001
|
||||
for line in lines:
|
||||
self.write(line)
|
||||
|
||||
def flush(self) -> None:
|
||||
return None
|
||||
|
||||
def isatty(self) -> bool:
|
||||
return False
|
||||
|
||||
def fileno(self) -> int: # pragma: no cover - 仅部分库会调用
|
||||
raise OSError("no fileno")
|
||||
|
||||
|
||||
def _logcat_writer(tag: str):
|
||||
"""返回一个把文本写进 Android logcat 的函数(非 Android 上返回 None)。"""
|
||||
if not ("ANDROID_ARGUMENT" in os.environ or "ANDROID_PRIVATE" in os.environ):
|
||||
return None
|
||||
try:
|
||||
from android.util import Log # type: ignore
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def write(text: str) -> None:
|
||||
for line in text.rstrip("\n").splitlines() or [""]:
|
||||
try:
|
||||
Log.i(tag, line)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return write
|
||||
|
||||
|
||||
def ensure_std_streams() -> None:
|
||||
"""保证 sys.stdout / sys.stderr 可用(Android 上为 None)。"""
|
||||
for name in ("stdout", "stderr"):
|
||||
stream = getattr(sys, name, None)
|
||||
writable = False
|
||||
if stream is not None:
|
||||
try:
|
||||
stream.write("")
|
||||
writable = True
|
||||
except Exception:
|
||||
writable = False
|
||||
if not writable:
|
||||
setattr(sys, name, _SafeStream(fallback=_logcat_writer("python")))
|
||||
|
||||
# 内置 print 使用的 __stdout__ / __stderr__ 在 Android 上同样为 None
|
||||
for name in ("__stdout__", "__stderr__"):
|
||||
current = getattr(sys, name, None)
|
||||
usable = False
|
||||
if current is not None:
|
||||
try:
|
||||
current.write("")
|
||||
usable = True
|
||||
except Exception:
|
||||
usable = False
|
||||
if not usable:
|
||||
setattr(sys, name, getattr(sys, name.strip("_"), _SafeStream()))
|
||||
|
||||
|
||||
ensure_std_streams()
|
||||
|
||||
# 必须在导入 Qt 之前设置:Android 上改用 bundled 证书,保证 HTTPS 可用
|
||||
os.environ.setdefault("QT_QUICK_CONTROLS_MOBILE", "1")
|
||||
|
||||
@@ -66,16 +153,26 @@ def install_excepthook() -> None:
|
||||
def hook(exc_type, exc_value, exc_tb) -> None:
|
||||
text = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
|
||||
logger.error("未捕获异常:\n%s", text)
|
||||
writer = _logcat_writer("lnxgit")
|
||||
if writer is not None:
|
||||
writer("未捕获异常:\n" + text)
|
||||
|
||||
sys.excepthook = hook
|
||||
|
||||
|
||||
def trace(message: str) -> None:
|
||||
"""启动阶段跟踪:同时写文件与 logcat,闪退时可用于定位。"""
|
||||
logger.info(message)
|
||||
writer = _logcat_writer("LnxGit")
|
||||
if writer is not None:
|
||||
writer(message)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- 主函数
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# 必须在创建 Settings / GitService 之前设置应用元信息,
|
||||
# 否则 QStandardPaths.AppDataLocation 会退化成通用 AppData 目录。
|
||||
def run() -> int:
|
||||
trace("启动: 注册应用元信息")
|
||||
QCoreApplication.setApplicationName(__app_name__)
|
||||
QCoreApplication.setApplicationVersion(__version__)
|
||||
QCoreApplication.setOrganizationName("git.xnhw.cc")
|
||||
@@ -84,6 +181,7 @@ def main() -> int:
|
||||
configure_ssl()
|
||||
configure_logging()
|
||||
install_excepthook()
|
||||
trace(f"启动: PySide6 {PySide6.__version__},数据目录 {apppaths.app_data_dir()}")
|
||||
|
||||
if hasattr(Qt, "HighDpiScaleFactorRoundingPolicy"):
|
||||
try:
|
||||
@@ -92,31 +190,47 @@ def main() -> int:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
trace("启动: 创建 QGuiApplication")
|
||||
app = QGuiApplication(sys.argv)
|
||||
app.setApplicationDisplayName(__app_name__)
|
||||
|
||||
trace("启动: 加载设置")
|
||||
settings = Settings()
|
||||
|
||||
trace("启动: 启动 Git 服务线程")
|
||||
service = GitService(settings)
|
||||
app.aboutToQuit.connect(service.shutdown)
|
||||
|
||||
# 把 Python 实例注册为 QML 单例(保证 QML 与 Python 使用同一对象)
|
||||
trace("启动: 注册 QML 单例")
|
||||
qmlRegisterSingletonInstance(GitService, QML_IMPORT_NAME, QML_IMPORT_MAJOR,
|
||||
QML_IMPORT_MINOR, "GitService", service)
|
||||
qmlRegisterSingletonInstance(Settings, QML_IMPORT_NAME, QML_IMPORT_MAJOR,
|
||||
QML_IMPORT_MINOR, "Settings", settings)
|
||||
|
||||
engine = QQmlApplicationEngine()
|
||||
qml_dir = apppaths.qml_dir()
|
||||
trace(f"启动: 加载 QML({qml_dir})")
|
||||
engine = QQmlApplicationEngine()
|
||||
engine.addImportPath(str(qml_dir))
|
||||
engine.addImportPath(str(qml_dir / "LnxGit"))
|
||||
logger.info("PySide6 %s,QML 目录 %s", PySide6.__version__, qml_dir)
|
||||
|
||||
engine.load(QUrl.fromLocalFile(str(qml_dir / "Main.qml")))
|
||||
if not engine.rootObjects():
|
||||
logger.error("QML 加载失败,请检查 %s", qml_dir)
|
||||
trace(f"启动失败: QML 未产生根对象,请检查 {qml_dir} 是否存在及 qmldir 是否完整")
|
||||
return 1
|
||||
|
||||
trace("启动: 进入事件循环")
|
||||
return app.exec()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
return run()
|
||||
except Exception:
|
||||
text = traceback.format_exc()
|
||||
logger.error("启动异常:\n%s", text)
|
||||
writer = _logcat_writer("LnxGit")
|
||||
if writer is not None:
|
||||
writer("启动异常:\n" + text)
|
||||
return 3
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
@@ -14,11 +14,16 @@ modules = Core,Gui,Qml,Quick,QuickControls2,Svg
|
||||
plugins =
|
||||
|
||||
[android]
|
||||
# wheel_pyside / wheel_shiboken 由构建脚本通过命令行参数传入
|
||||
# 注意:plugins 留空,交给工具依据 Qt 模块依赖自动探测。
|
||||
# 若手工填写,必须是 "类别_插件名" 形式(如 platforms_qandroid、imageformats_qjpeg),
|
||||
# 只写类别名(如 imageformats)会导致 create_recipe 报 ValueError。
|
||||
wheel_pyside =
|
||||
wheel_shiboken =
|
||||
plugins = platformthemes,imageformats,iconengines,styles
|
||||
plugins =
|
||||
|
||||
[buildozer]
|
||||
# release 会做优化且不含调试信息,产物体积明显小于 debug
|
||||
mode = debug
|
||||
arch = aarch64
|
||||
recipe_dir =
|
||||
|
||||
@@ -12,6 +12,10 @@ QtObject {
|
||||
property var currentRepo: ({})
|
||||
property var changeList: []
|
||||
property var commits: []
|
||||
//: 分支地图页专用,与 commits 分开存,避免两个页面互相覆盖
|
||||
property var graphCommits: []
|
||||
//: 分支地图的整图尺寸与节点尺寸(由 gitcore 的 _map_layout 算出)
|
||||
property var graphMap: ({})
|
||||
property var commitDetail: ({})
|
||||
property var diffText: ""
|
||||
property var remoteRefs: []
|
||||
@@ -121,6 +125,17 @@ QtObject {
|
||||
case "log":
|
||||
commits = res.commits || [];
|
||||
break;
|
||||
case "graph":
|
||||
graphCommits = res.commits || [];
|
||||
graphMap = {
|
||||
"width": res.mapWidth || 0,
|
||||
"height": res.mapHeight || 0,
|
||||
"nodeWidth": res.mapNodeWidth || 132,
|
||||
"nodeHeight": res.mapNodeHeight || 46,
|
||||
// 颜色是按分支分配的,图例把「分支名 → 颜色」列出来
|
||||
"legend": res.mapLegend || []
|
||||
};
|
||||
break;
|
||||
case "commitDetail":
|
||||
commitDetail = res;
|
||||
diffText = res.diff || "";
|
||||
@@ -230,11 +245,23 @@ QtObject {
|
||||
GitService.changes({});
|
||||
}
|
||||
|
||||
function loadLog(limit) {
|
||||
function loadLog(limit, allRefs) {
|
||||
if (currentRepoPath.length === 0)
|
||||
return;
|
||||
GitService.log({
|
||||
"maxEntries": limit || 60
|
||||
"maxEntries": limit || 60,
|
||||
// --all:把本地分支、远端引用与标签都作为起点,否则只会看到当前分支
|
||||
"allRefs": allRefs === true
|
||||
});
|
||||
}
|
||||
|
||||
function loadGraph(limit, branch) {
|
||||
if (currentRepoPath.length === 0)
|
||||
return;
|
||||
GitService.graph({
|
||||
"maxEntries": limit || 200,
|
||||
// 传分支名就只看该分支的历史;留空则按 --all 铺开所有引用
|
||||
"branch": branch || ""
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ QtObject {
|
||||
// 文本
|
||||
readonly property color text: isDark ? "#e9ecf4" : "#1b1e28"
|
||||
readonly property color textDim: isDark ? "#9aa3b8" : "#5c6480"
|
||||
readonly property color textFaint: isDark ? "#6b7párt" : "#8b93ab"
|
||||
readonly property color textFaint: isDark ? "#6b7280" : "#8b93ab"
|
||||
|
||||
// 强调色
|
||||
readonly property color primary: "#4c8dff"
|
||||
@@ -27,6 +27,36 @@ QtObject {
|
||||
readonly property color danger: "#ef5350"
|
||||
readonly property color purple: "#a78bfa"
|
||||
|
||||
// 分支图谱配色(对应 gitcore.GRAPH_COLORS 的长度与取模规则)
|
||||
readonly property var graphColors: [
|
||||
"#4c8dff", "#31c48d", "#f0a132", "#a78bfa",
|
||||
"#ef5350", "#22d3ee", "#f472b6", "#a3e635"
|
||||
]
|
||||
|
||||
function graphColor(index) {
|
||||
if (index === undefined || index < 0)
|
||||
return textDim;
|
||||
return graphColors[index % graphColors.length];
|
||||
}
|
||||
|
||||
/// 按可用宽度给图谱挑一个列宽:分支多就压窄,但不小于 graphMinLaneWidth。
|
||||
/// 这样泳道再多也能全部画进画面,而不是被裁掉或挤掉正文。
|
||||
function graphLaneFor(columns, availableWidth) {
|
||||
if (columns <= 0 || availableWidth <= 0)
|
||||
return graphLaneWidth;
|
||||
var ideal = Math.floor(availableWidth / columns);
|
||||
return Math.max(graphMinLaneWidth, Math.min(graphLaneWidth, ideal));
|
||||
}
|
||||
|
||||
// 图谱线条宽度与列宽(HistoryPage 与 GraphPage 共用)。
|
||||
// 跨列连线走 S 形贝塞尔,列宽太窄会显得局促,所以比纯直线时代宽一些。
|
||||
// 线宽/半径用 real —— int 会把小数截掉。
|
||||
readonly property int graphLaneWidth: 18
|
||||
readonly property real graphLineWidth: 2.5
|
||||
readonly property real graphNodeRadius: 4.5
|
||||
//: 列宽下限:分支特别多时按可用宽度压缩,但不小于这个值
|
||||
readonly property int graphMinLaneWidth: 11
|
||||
|
||||
// Git 状态色
|
||||
readonly property color added: "#31c48d"
|
||||
readonly property color modified: "#f0a132"
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
// 页面顶部标题栏
|
||||
//
|
||||
// 右侧/左侧的图标按钮都支持配一行小字(label)—— 光靠 `⇄` `+` `⋯` 这些
|
||||
// 符号,用户未必知道是刷新、新建还是更多。
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import LnxGit 1.0
|
||||
@@ -9,8 +12,11 @@ Rectangle {
|
||||
property string title: ""
|
||||
property string subtitle: ""
|
||||
property string leftIcon: ""
|
||||
property string leftLabel: ""
|
||||
property string rightIcon: ""
|
||||
property string rightLabel: ""
|
||||
property string rightIcon2: ""
|
||||
property string rightLabel2: ""
|
||||
property bool showBack: false
|
||||
|
||||
signal leftClicked()
|
||||
@@ -33,18 +39,19 @@ Rectangle {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: 6
|
||||
anchors.rightMargin: 6
|
||||
spacing: 4
|
||||
spacing: 2
|
||||
|
||||
IconButton {
|
||||
visible: bar.showBack || bar.leftIcon.length > 0
|
||||
text: bar.leftIcon.length > 0 ? bar.leftIcon : "←"
|
||||
label: bar.leftLabel
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
onClicked: bar.leftClicked()
|
||||
}
|
||||
|
||||
Column {
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
width: parent.width - 150
|
||||
width: parent.width - (bar.rightLabel.length > 0 || bar.rightLabel2.length > 0 ? 170 : 150)
|
||||
spacing: 2
|
||||
Text {
|
||||
text: bar.title
|
||||
@@ -72,6 +79,7 @@ Rectangle {
|
||||
IconButton {
|
||||
visible: bar.rightIcon.length > 0
|
||||
text: bar.rightIcon
|
||||
label: bar.rightLabel
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
onClicked: bar.rightClicked()
|
||||
}
|
||||
@@ -79,6 +87,7 @@ Rectangle {
|
||||
IconButton {
|
||||
visible: bar.rightIcon2.length > 0
|
||||
text: bar.rightIcon2
|
||||
label: bar.rightLabel2
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
onClicked: bar.right2Clicked()
|
||||
}
|
||||
|
||||
157
qml/LnxGit/components/CommitGraph.qml
Normal file
157
qml/LnxGit/components/CommitGraph.qml
Normal file
@@ -0,0 +1,157 @@
|
||||
// 提交图谱:绘制一行内的分支泳道、连线与节点
|
||||
//
|
||||
// 布局数据由 lnxgit/gitcore.py 的 _graph_layout 算好(那部分有单元测试),
|
||||
// 这里只负责画。每行的规则:
|
||||
// * 在 above、也在 below 的列 → 竖线贯穿
|
||||
// * 在 above、不在 below 的列 → 曲线汇入本行节点(合并)
|
||||
// * 只在 below 的列 → 从节点曲线分叉出去
|
||||
// * graphLinks 里的列 → 从节点曲线连到该列底部
|
||||
// (合并提交接入既有泳道、分叉点复用了同一条父提交线时会出现)
|
||||
//
|
||||
// 跨列一律走三次贝塞尔(两端保持竖直、中段平滑过渡),这样分支看起来是
|
||||
// 连续弯过去的,而不是两根直线拼出的尖角 —— 也更接近 GitKraken 那种观感。
|
||||
// 同列则直接画直线,避免无谓的曲线开销。
|
||||
//
|
||||
// 用 Canvas 而不是 QtQuick.Shapes:Shapes 是独立模块,要在 buildozer 的
|
||||
// --extra-modules 里额外带上 Qt6QuickShapes,Canvas 属于 QtQuick 核心。
|
||||
import QtQuick
|
||||
import LnxGit 1.0
|
||||
|
||||
Item {
|
||||
id: graph
|
||||
|
||||
//: 一条提交记录(含 lane / graphAbove / graphBelow / graphLinks / graphCols)
|
||||
property var row: ({})
|
||||
property int laneWidth: Theme.graphLaneWidth
|
||||
// 线宽与半径用 real:int 会把 2.5 / 4.5 截成 2 / 4
|
||||
property real lineWidth: Theme.graphLineWidth
|
||||
property real nodeRadius: Theme.graphNodeRadius
|
||||
property bool showNode: true
|
||||
|
||||
readonly property int columns: (row && row.graphCols) ? Math.max(1, row.graphCols) : 1
|
||||
|
||||
implicitWidth: columns * laneWidth
|
||||
implicitHeight: 40
|
||||
|
||||
onRowChanged: canvas.requestPaint()
|
||||
onWidthChanged: canvas.requestPaint()
|
||||
onHeightChanged: canvas.requestPaint()
|
||||
onLaneWidthChanged: canvas.requestPaint()
|
||||
onLineWidthChanged: canvas.requestPaint()
|
||||
onNodeRadiusChanged: canvas.requestPaint()
|
||||
onShowNodeChanged: canvas.requestPaint()
|
||||
|
||||
function columnX(index) {
|
||||
return laneWidth * index + laneWidth / 2;
|
||||
}
|
||||
|
||||
function colorOf(palette, index, fallback) {
|
||||
if (!palette || index < 0 || index >= palette.length)
|
||||
return fallback;
|
||||
var value = palette[index];
|
||||
return (value === undefined || value < 0) ? fallback : Theme.graphColor(value);
|
||||
}
|
||||
|
||||
Canvas {
|
||||
id: canvas
|
||||
anchors.fill: parent
|
||||
|
||||
Component.onCompleted: requestPaint()
|
||||
onWidthChanged: requestPaint()
|
||||
onHeightChanged: requestPaint()
|
||||
|
||||
onPaint: {
|
||||
var ctx = getContext("2d");
|
||||
ctx.reset();
|
||||
ctx.lineWidth = graph.lineWidth;
|
||||
ctx.lineCap = "round";
|
||||
ctx.lineJoin = "round";
|
||||
|
||||
var record = graph.row;
|
||||
if (!record || record.lane === undefined)
|
||||
return;
|
||||
|
||||
var above = record.graphAbove || [];
|
||||
var below = record.graphBelow || [];
|
||||
var links = record.graphLinks || [];
|
||||
var aboveColors = record.graphAboveColors || [];
|
||||
var belowColors = record.graphBelowColors || [];
|
||||
var node = record.lane;
|
||||
var midY = height / 2;
|
||||
var nodeX = graph.columnX(node);
|
||||
var nodeColor = Theme.graphColor(record.laneColor);
|
||||
var neutral = Theme.border;
|
||||
|
||||
// 同列画直线,跨列画 S 形贝塞尔:两端竖直、中段平滑过渡,
|
||||
// 不会像两根直线那样在拐点处形成尖角
|
||||
function link(x1, y1, x2, y2, color) {
|
||||
ctx.strokeStyle = color;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x1, y1);
|
||||
if (Math.abs(x1 - x2) < 0.5) {
|
||||
ctx.lineTo(x2, y2);
|
||||
} else {
|
||||
var mid = (y1 + y2) / 2;
|
||||
ctx.bezierCurveTo(x1, mid, x2, mid, x2, y2);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// 1) 顶部:贯穿的线,或汇入本行节点的线
|
||||
for (var i = 0; i < above.length; ++i) {
|
||||
var column = above[i];
|
||||
var x = graph.columnX(column);
|
||||
var color = graph.colorOf(aboveColors, column, neutral);
|
||||
if (column === node) {
|
||||
// 用这条线从上方延续下来的颜色,而不是节点色:同一条线的
|
||||
// 下半段(上一行)已经用的是泳道色,这里若换成节点色,
|
||||
// 行界处就会出现半段异色。
|
||||
link(x, 0, nodeX, midY, color);
|
||||
} else if (below.indexOf(column) >= 0) {
|
||||
link(x, 0, x, height, graph.colorOf(belowColors, column, color));
|
||||
} else {
|
||||
link(x, 0, nodeX, midY, color);
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 节点向下的主干。
|
||||
// 颜色取**该泳道接下来**的颜色而不是节点色:合并提交的节点色属于
|
||||
// 它自己(第一个父提交那条线),而向下延续的往往是另一个父提交
|
||||
// 的泳道 —— 用节点色会在行界处出现一段突兀的异色短线。
|
||||
if (below.indexOf(node) >= 0)
|
||||
link(nodeX, midY, nodeX, height,
|
||||
graph.colorOf(belowColors, node, nodeColor));
|
||||
|
||||
// 3) 从节点分叉出去的线(below 里新出现的列)
|
||||
for (var j = 0; j < below.length; ++j) {
|
||||
var target = below[j];
|
||||
if (target === node || above.indexOf(target) >= 0)
|
||||
continue;
|
||||
link(nodeX, midY, graph.columnX(target), height,
|
||||
graph.colorOf(belowColors, target, nodeColor));
|
||||
}
|
||||
|
||||
// 4) 连到既有泳道的线(那条线是贯穿的,第 1、3 步都没覆盖到)
|
||||
for (var k = 0; k < links.length; ++k) {
|
||||
var linkColumn = links[k];
|
||||
if (linkColumn === undefined || linkColumn < 0 || linkColumn === node)
|
||||
continue;
|
||||
if (below.indexOf(linkColumn) < 0 || above.indexOf(linkColumn) < 0)
|
||||
continue;
|
||||
link(nodeX, midY, graph.columnX(linkColumn), height,
|
||||
graph.colorOf(belowColors, linkColumn, nodeColor));
|
||||
}
|
||||
|
||||
// 5) 节点:实心圆 + 一圈背景色描边,让交叉处更清晰
|
||||
if (!graph.showNode)
|
||||
return;
|
||||
ctx.beginPath();
|
||||
ctx.arc(nodeX, midY, graph.nodeRadius, 0, Math.PI * 2);
|
||||
ctx.fillStyle = nodeColor;
|
||||
ctx.fill();
|
||||
ctx.lineWidth = Math.max(1.5, graph.lineWidth * 0.75);
|
||||
ctx.strokeStyle = Theme.surface;
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
}
|
||||
180
qml/LnxGit/components/GraphMap.qml
Normal file
180
qml/LnxGit/components/GraphMap.qml
Normal file
@@ -0,0 +1,180 @@
|
||||
// 分支地图:二维流程图形态的提交拓扑
|
||||
//
|
||||
// 与历史页那条「一行一个提交」的紧凑泳道不同,这里每个提交是一个带标题的
|
||||
// 胶囊节点:纵向按时间自下而上(最新的在最上面),横向按泳道铺开,
|
||||
// 父提交 → 子提交 用带箭头的曲线连接。
|
||||
//
|
||||
// 坐标由 lnxgit/gitcore.py 的 _map_layout() 算好(mapX / mapY 是节点中心),
|
||||
// 这里只负责摆放与绘制。横纵坐标分别取自泳道号与提交序号,天然唯一,
|
||||
// 所以节点不会重叠,不需要碰撞检测。
|
||||
//
|
||||
// 整张图往往比屏幕大,因此外层用 Flickable 双向平移,缩放交给调用方
|
||||
// 通过 zoom 属性控制(右下角有 +/- 按钮)。
|
||||
import QtQuick
|
||||
import LnxGit 1.0
|
||||
|
||||
Item {
|
||||
id: map
|
||||
|
||||
property var commits: []
|
||||
property real nodeWidth: 132
|
||||
property real nodeHeight: 46
|
||||
property real mapWidth: 0
|
||||
property real mapHeight: 0
|
||||
property real zoom: 1.0
|
||||
//: 当前打开的仓库 HEAD,会在节点上标出来
|
||||
property string headSha: ""
|
||||
//: 外层 Flickable 的可视区域 —— 用来只渲染视口附近的节点。
|
||||
//: 一次创建两百个节点会明显卡顿,而屏幕上同时能看到的也就十几个。
|
||||
property real viewportY: 0
|
||||
property real viewportHeight: 0
|
||||
|
||||
signal nodeClicked(string sha)
|
||||
|
||||
implicitWidth: mapWidth * zoom
|
||||
implicitHeight: mapHeight * zoom
|
||||
//: 图比屏幕小的时候居中显示
|
||||
readonly property real padX: Math.max(0, (parent ? parent.width : 0) - implicitWidth) / 2
|
||||
readonly property real padY: Math.max(0, (parent ? parent.height : 0) - implicitHeight) / 2
|
||||
|
||||
onCommitsChanged: edges.requestPaint()
|
||||
onMapWidthChanged: edges.requestPaint()
|
||||
onMapHeightChanged: edges.requestPaint()
|
||||
onNodeWidthChanged: edges.requestPaint()
|
||||
onNodeHeightChanged: edges.requestPaint()
|
||||
|
||||
function subjectOf(row) {
|
||||
var text = row.subject || "";
|
||||
return text.length > 0 ? text : row.shortSha;
|
||||
}
|
||||
|
||||
Item {
|
||||
id: content
|
||||
|
||||
x: map.padX
|
||||
y: map.padY
|
||||
width: map.mapWidth
|
||||
height: map.mapHeight
|
||||
transformOrigin: Item.TopLeft
|
||||
scale: map.zoom
|
||||
|
||||
// 连线层:父 → 子,先画(在节点下面)
|
||||
Canvas {
|
||||
id: edges
|
||||
anchors.fill: parent
|
||||
|
||||
Component.onCompleted: requestPaint()
|
||||
|
||||
onPaint: {
|
||||
var ctx = getContext("2d");
|
||||
ctx.reset();
|
||||
ctx.lineWidth = 2;
|
||||
ctx.lineCap = "round";
|
||||
ctx.lineJoin = "round";
|
||||
|
||||
var lookup = ({});
|
||||
for (var i = 0; i < map.commits.length; ++i)
|
||||
lookup[map.commits[i].sha] = map.commits[i];
|
||||
|
||||
var halfNode = map.nodeHeight / 2;
|
||||
var arrow = 5;
|
||||
|
||||
for (var c = 0; c < map.commits.length; ++c) {
|
||||
var child = map.commits[c];
|
||||
var parents = child.parents || [];
|
||||
|
||||
for (var p = 0; p < parents.length; ++p) {
|
||||
var parent = lookup[parents[p]];
|
||||
if (!parent)
|
||||
continue;
|
||||
|
||||
// 父提交在下面:从它的顶部出发,连到子提交的底部
|
||||
var x1 = parent.mapX;
|
||||
var y1 = parent.mapY - halfNode;
|
||||
var x2 = child.mapX;
|
||||
var y2 = child.mapY + halfNode;
|
||||
if (y1 <= y2)
|
||||
continue; // 防御异常的坐标
|
||||
|
||||
var midY = (y1 + y2) / 2;
|
||||
var edgeColor = Theme.graphColor(child.mapColor);
|
||||
ctx.strokeStyle = edgeColor;
|
||||
|
||||
if (Math.abs(x1 - x2) < 0.5) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x1, y1);
|
||||
ctx.lineTo(x2, y2);
|
||||
ctx.stroke();
|
||||
} else {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x1, y1);
|
||||
ctx.bezierCurveTo(x1, midY, x2, midY, x2, y2);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// 箭头指向子提交(时间更近的一侧)
|
||||
ctx.fillStyle = edgeColor;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x2, y2);
|
||||
ctx.lineTo(x2 - arrow * 0.62, y2 + arrow);
|
||||
ctx.lineTo(x2 + arrow * 0.62, y2 + arrow);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 节点层
|
||||
Repeater {
|
||||
model: map.commits
|
||||
|
||||
delegate: Rectangle {
|
||||
id: node
|
||||
|
||||
// 颜色按地图轨道取(不是紧凑泳道图的 laneColor),
|
||||
// 这样节点颜色和它所在的列始终一致
|
||||
readonly property color branchColor: Theme.graphColor(modelData.mapColor)
|
||||
|
||||
// 只渲染视口附近的行:Item 仍然存在(Repeater 会全建),但
|
||||
// 不可见的那些不参与布局与绘制,滚动时也就不会掉帧。
|
||||
// 上下各留两行余量,快速滑动不会露白。
|
||||
readonly property real visibleTop: (map.viewportY - map.padY)
|
||||
/ Math.max(0.05, map.zoom)
|
||||
readonly property real visibleBottom: visibleTop
|
||||
+ map.viewportHeight / Math.max(0.05, map.zoom)
|
||||
|
||||
visible: modelData.mapY > visibleTop - map.nodeHeight * 2
|
||||
&& modelData.mapY < visibleBottom + map.nodeHeight * 2
|
||||
|
||||
x: modelData.mapX - map.nodeWidth / 2
|
||||
y: modelData.mapY - map.nodeHeight / 2
|
||||
width: map.nodeWidth
|
||||
height: map.nodeHeight
|
||||
radius: height / 2
|
||||
color: nodeMouse.pressed ? Theme.surfaceAlt : Theme.surface
|
||||
border.width: modelData.sha === map.headSha ? 2.5 : 1.5
|
||||
border.color: node.branchColor
|
||||
|
||||
Text {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: 12
|
||||
anchors.rightMargin: 12
|
||||
text: map.subjectOf(modelData)
|
||||
color: Theme.text
|
||||
font.pixelSize: 11
|
||||
elide: Text.ElideRight
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
verticalAlignment: Text.AlignVCenter
|
||||
maximumLineCount: 1
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
id: nodeMouse
|
||||
anchors.fill: parent
|
||||
onClicked: map.nodeClicked(modelData.sha)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,13 @@
|
||||
// 图标按钮(使用 Unicode 符号,避免额外字体依赖)
|
||||
//
|
||||
// 选字符有讲究:Android 上符号字体是子集化的,而且 Qt 的字体回退链里
|
||||
// 并不包含 NotoSansSymbols —— 只被它覆盖的字符(⟳ ↻ ⧉ ⎘ ⋮ 等)会渲染成
|
||||
// 豆腐块;彩色 emoji 虽然一定有字形,但位图字体在十几像素下会糊成一团。
|
||||
// 首选 NotoSansCJK 里有的单色线条符号(⇄ ← + ⋯ ),
|
||||
// 新增图标前先跑 tools/check_glyphs.py 自查。
|
||||
//
|
||||
// 光有符号不够:`⇄` 到底代表刷新还是同步、`⋯` 是更多还是菜单,用户未必猜得出来,
|
||||
// 所以支持在图标下面挂一行小字(label)。顶部标题栏的小按钮都带 label。
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import LnxGit 1.0
|
||||
@@ -7,10 +16,17 @@ Item {
|
||||
id: button
|
||||
|
||||
property string text: ""
|
||||
/// 图标下方的文字说明;留空则只显示图标
|
||||
property string label: ""
|
||||
property color color: Theme.text
|
||||
property int size: Theme.touchTarget
|
||||
property string tooltip: ""
|
||||
|
||||
// 线条符号与彩色 emoji 用不同字号:emoji 偏小会糊,线条符号偏大会挤
|
||||
property int glyphSize: 19
|
||||
property int emojiSize: 21
|
||||
property int labelSize: 9
|
||||
|
||||
signal clicked()
|
||||
|
||||
width: size
|
||||
@@ -21,11 +37,32 @@ Item {
|
||||
radius: width / 2
|
||||
color: mouse.pressed ? Theme.surfaceAlt : "transparent"
|
||||
|
||||
Text {
|
||||
Column {
|
||||
anchors.centerIn: parent
|
||||
text: button.text
|
||||
color: button.color
|
||||
font.pixelSize: 19
|
||||
spacing: 0
|
||||
|
||||
Text {
|
||||
id: glyph
|
||||
|
||||
// 补充平面(U+1F000 以上)基本都是彩色 emoji
|
||||
readonly property bool isEmoji: button.text.length > 0
|
||||
&& button.text.codePointAt(0) >= 0x1F000
|
||||
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
text: button.text
|
||||
color: button.color
|
||||
font.pixelSize: button.label.length > 0
|
||||
? (isEmoji ? button.emojiSize - 3 : button.glyphSize - 3)
|
||||
: (isEmoji ? button.emojiSize : button.glyphSize)
|
||||
}
|
||||
|
||||
Text {
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
visible: button.label.length > 0
|
||||
text: button.label
|
||||
color: Theme.textDim
|
||||
font.pixelSize: button.labelSize
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ Rectangle {
|
||||
property color badgeColor: Theme.primary
|
||||
property bool current: false
|
||||
property string actionIcon: ""
|
||||
/// 操作按钮下方的小字,例如"操作" —— 光一个 ⋯ 用户不知道能点
|
||||
property string actionLabel: ""
|
||||
property bool danger: false
|
||||
|
||||
signal clicked()
|
||||
@@ -81,6 +83,7 @@ Rectangle {
|
||||
id: actionButton
|
||||
visible: row.actionIcon.length > 0
|
||||
text: row.actionIcon
|
||||
label: row.actionLabel
|
||||
color: row.danger ? Theme.danger : Theme.textDim
|
||||
anchors.right: parent.right
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
|
||||
@@ -34,8 +34,10 @@ Item {
|
||||
title: "追溯 " + page.filePath
|
||||
subtitle: page.rows.length + " 行"
|
||||
leftIcon: "←"
|
||||
leftLabel: "返回"
|
||||
showBack: true
|
||||
rightIcon: "⟳"
|
||||
rightIcon: "⇄"
|
||||
rightLabel: "刷新"
|
||||
onLeftClicked: stack.pop()
|
||||
onRightClicked: page.load()
|
||||
}
|
||||
@@ -88,14 +90,18 @@ Item {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EmptyState {
|
||||
anchors.centerIn: parent
|
||||
width: parent.width - 40
|
||||
visible: page.rows.length === 0
|
||||
symbol: "👤"
|
||||
title: "暂无追溯数据"
|
||||
description: "该文件可能尚未提交,或 dulwich 不支持对该文件进行 blame"
|
||||
}
|
||||
// 与 HistoryPage / GraphPage 同样的坑:EmptyState 放进 Column 并用锚点,
|
||||
// 会让整个 Column 停止布局
|
||||
EmptyState {
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 130
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
width: parent.width - 40
|
||||
visible: page.rows.length === 0
|
||||
symbol: "👤"
|
||||
title: "暂无追溯数据"
|
||||
description: "该文件可能尚未提交,或 dulwich 不支持对该文件进行 blame"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ Item {
|
||||
spacing: 0
|
||||
|
||||
AppBar {
|
||||
id: bar
|
||||
width: parent.width
|
||||
title: "分支与标签"
|
||||
subtitle: Git.hasRepo()
|
||||
@@ -48,13 +49,46 @@ Item {
|
||||
+ (Git.currentRepo.tags || []).length + " 标签")
|
||||
: "未选择仓库"
|
||||
rightIcon: "+"
|
||||
rightIcon2: "⟳"
|
||||
rightLabel: "新建"
|
||||
rightIcon2: "⇄"
|
||||
rightLabel2: "刷新"
|
||||
onRightClicked: newMenu.open()
|
||||
onRight2Clicked: page.reload()
|
||||
}
|
||||
|
||||
// 分支的常用操作直接摆在页面上:合并与推送原先藏在行尾的 ⋯ 菜单里,
|
||||
// 不看长按菜单根本不知道有这些功能。
|
||||
Row {
|
||||
id: actionBar
|
||||
x: Theme.pagePad
|
||||
width: parent.width - Theme.pagePad * 2
|
||||
height: 46
|
||||
spacing: 8
|
||||
|
||||
ActionButton {
|
||||
text: "合并分支"
|
||||
iconText: "🔀"
|
||||
onClicked: mergeDialog.ask("合并分支",
|
||||
"把指定分支合并到 " + (Git.currentRepo.branch || "当前分支"),
|
||||
"分支名", "", "", "", false)
|
||||
}
|
||||
|
||||
ActionButton {
|
||||
text: "推送"
|
||||
iconText: "⬆"
|
||||
onClicked: Git.pushBranch("", Git.currentRepo.branch || "")
|
||||
}
|
||||
|
||||
ActionButton {
|
||||
text: "拉取"
|
||||
iconText: "⬇"
|
||||
onClicked: Git.pullRemote("")
|
||||
}
|
||||
}
|
||||
|
||||
// 标签切换
|
||||
Row {
|
||||
id: tabs
|
||||
width: parent.width
|
||||
height: 42
|
||||
spacing: 0
|
||||
@@ -98,7 +132,8 @@ Item {
|
||||
|
||||
ScrollView {
|
||||
width: parent.width
|
||||
height: parent.height - 56 - 43
|
||||
// 用各块的实际高度算,别写死数字 —— AppBar 有副标题时是 68 不是 56
|
||||
height: parent.height - bar.height - actionBar.height - tabs.height
|
||||
clip: true
|
||||
contentWidth: width
|
||||
|
||||
@@ -128,6 +163,7 @@ Item {
|
||||
badge: current ? "当前" : ""
|
||||
subtitle: current ? "HEAD 所在分支" : "轻点切换"
|
||||
actionIcon: "⋯"
|
||||
actionLabel: "操作"
|
||||
onClicked: Git.checkoutBranch(modelData)
|
||||
onActionClicked: branchMenu.openFor(modelData)
|
||||
}
|
||||
@@ -142,6 +178,7 @@ Item {
|
||||
title: modelData
|
||||
subtitle: "双击创建本地跟踪分支"
|
||||
actionIcon: "+"
|
||||
actionLabel: "跟踪"
|
||||
onClicked: Git.checkoutBranch(modelData)
|
||||
onActionClicked: Git.checkoutBranch(modelData)
|
||||
}
|
||||
@@ -160,6 +197,7 @@ Item {
|
||||
badge: "标签"
|
||||
badgeColor: Theme.purple
|
||||
actionIcon: "⬆"
|
||||
actionLabel: "推送"
|
||||
onClicked: Git.checkoutBranch(modelData.name)
|
||||
onActionClicked: tagMenu.openFor(modelData.name)
|
||||
}
|
||||
@@ -196,15 +234,15 @@ Item {
|
||||
Menu {
|
||||
id: newMenu
|
||||
MenuItem {
|
||||
text: "新建分支"
|
||||
text: "🌿 新建分支"
|
||||
onTriggered: newBranchDialog.ask("新建分支", "从当前 HEAD 创建并切换", "分支名", "", "", "", false)
|
||||
}
|
||||
MenuItem {
|
||||
text: "新建标签"
|
||||
text: "🏷 新建标签"
|
||||
onTriggered: newTagDialog.ask("新建标签", "如 v1.0.0", "标签名", "", "说明(可选)", "", true)
|
||||
}
|
||||
MenuItem {
|
||||
text: "合并分支到当前分支"
|
||||
text: "🔀 合并分支到当前分支"
|
||||
onTriggered: mergeDialog.ask("合并分支", "将指定分支合并到 " + (Git.currentRepo.branch || "当前分支"),
|
||||
"分支名", "", "", "", false)
|
||||
}
|
||||
@@ -220,25 +258,25 @@ Item {
|
||||
}
|
||||
|
||||
MenuItem {
|
||||
text: "切换到此分支"
|
||||
text: "✅ 切换到此分支"
|
||||
onTriggered: Git.checkoutBranch(branchMenu.branchName)
|
||||
}
|
||||
MenuItem {
|
||||
text: "重命名"
|
||||
text: "✏️ 重命名"
|
||||
onTriggered: renameBranchDialog.ask("重命名分支", "当前:" + branchMenu.branchName,
|
||||
"新名称", branchMenu.branchName, "", "", false)
|
||||
}
|
||||
MenuItem {
|
||||
text: "合并到当前分支"
|
||||
text: "🔀 合并到当前分支"
|
||||
onTriggered: Git.mergeBranch(branchMenu.branchName)
|
||||
}
|
||||
MenuItem {
|
||||
text: "推送到远端"
|
||||
text: "⬆ 推送到远端"
|
||||
onTriggered: Git.pushBranch("", branchMenu.branchName)
|
||||
}
|
||||
MenuSeparator {}
|
||||
MenuItem {
|
||||
text: "删除本地分支"
|
||||
text: "🗑 删除本地分支"
|
||||
onTriggered: deleteBranchDialog.ask("删除分支",
|
||||
"确定删除分支「" + branchMenu.branchName + "」?",
|
||||
"删除")
|
||||
@@ -255,15 +293,15 @@ Item {
|
||||
}
|
||||
|
||||
MenuItem {
|
||||
text: "检出此标签"
|
||||
text: "✅ 检出此标签"
|
||||
onTriggered: Git.checkoutBranch(tagMenu.tagName)
|
||||
}
|
||||
MenuItem {
|
||||
text: "推送标签到远端"
|
||||
text: "⬆ 推送标签到远端"
|
||||
onTriggered: Git.pushTag(tagMenu.tagName)
|
||||
}
|
||||
MenuItem {
|
||||
text: "删除标签"
|
||||
text: "🗑 删除标签"
|
||||
onTriggered: deleteTagDialog.ask("删除标签", "确定删除标签「" + tagMenu.tagName + "」?", "删除")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,8 +48,10 @@ Item {
|
||||
subtitle: Git.hasRepo()
|
||||
? (Git.currentRepoName + " · " + (Git.currentRepo.branch || ""))
|
||||
: "未选择仓库"
|
||||
rightIcon: "⟳"
|
||||
rightIcon: "⇄"
|
||||
rightLabel: "刷新"
|
||||
rightIcon2: "⋯"
|
||||
rightLabel2: "更多"
|
||||
onRightClicked: page.reload()
|
||||
onRight2Clicked: changesMenu.open()
|
||||
}
|
||||
|
||||
@@ -42,8 +42,10 @@ Item {
|
||||
+ (page.detail.author ? page.detail.author.name : "") + " · "
|
||||
+ (page.detail.time ? page.detail.time.relative : "")
|
||||
leftIcon: "←"
|
||||
leftLabel: "返回"
|
||||
showBack: true
|
||||
rightIcon: "⧉"
|
||||
rightIcon: "📋"
|
||||
rightLabel: "复制"
|
||||
onLeftClicked: stack.pop()
|
||||
onRightClicked: {
|
||||
clipHelper.text = page.detail.message + "\n\n" + Git.diffText;
|
||||
|
||||
@@ -39,9 +39,12 @@ Item {
|
||||
title: page.title
|
||||
subtitle: page.subTitle
|
||||
leftIcon: "←"
|
||||
leftLabel: "返回"
|
||||
showBack: true
|
||||
rightIcon: "⟳"
|
||||
rightIcon2: "⧉"
|
||||
rightIcon: "⇄"
|
||||
rightLabel: "刷新"
|
||||
rightIcon2: "📋"
|
||||
rightLabel2: "复制"
|
||||
onLeftClicked: stack.pop()
|
||||
onRightClicked: page.load()
|
||||
onRight2Clicked: {
|
||||
|
||||
@@ -78,9 +78,12 @@ Item {
|
||||
: ((page.fileData.size ? page.fileData.size + " 字节 · " : "")
|
||||
+ (page.workingCopy ? "工作区" : page.rev.substring(0, 8)))
|
||||
leftIcon: "←"
|
||||
leftLabel: "返回"
|
||||
showBack: true
|
||||
rightIcon: page.fileData.kind === "file" && !page.fileData.binary ? "⎘" : ""
|
||||
rightIcon: page.fileData.kind === "file" && !page.fileData.binary ? "📋" : ""
|
||||
rightLabel: page.fileData.kind === "file" && !page.fileData.binary ? "复制" : ""
|
||||
rightIcon2: page.fileData.kind === "file" && !page.workingCopy ? "👤" : ""
|
||||
rightLabel2: page.fileData.kind === "file" && !page.fileData.workingCopy ? "追溯" : ""
|
||||
onLeftClicked: stack.pop()
|
||||
onRightClicked: {
|
||||
clipHelper.text = page.fileData.content || "";
|
||||
|
||||
310
qml/LnxGit/pages/GraphPage.qml
Normal file
310
qml/LnxGit/pages/GraphPage.qml
Normal file
@@ -0,0 +1,310 @@
|
||||
// 分支地图页:所有引用(本地分支 + 远端分支 + 标签)的二维拓扑
|
||||
//
|
||||
// 每个提交是一个带标题的胶囊节点,时间自下而上、分支横向铺开,
|
||||
// 父提交 → 子提交 用带箭头的曲线相连(见 components/GraphMap.qml)。
|
||||
// 整张图通常比屏幕大,因此可以双向拖动,右下角有缩放按钮。
|
||||
//
|
||||
// 数据走 Git.graphCommits / Git.graphMap(独立的 graph operation),
|
||||
// 不会和历史页的 Git.commits 互相覆盖。
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Controls.Material
|
||||
import LnxGit
|
||||
import "../components"
|
||||
|
||||
Item {
|
||||
id: page
|
||||
|
||||
signal showCommit(string sha)
|
||||
|
||||
property int limit: 200
|
||||
property real zoom: 1.0
|
||||
//: 首次拿到布局后自动适应一次宽度,之后尊重用户的缩放
|
||||
property bool autoFitted: false
|
||||
readonly property real minZoom: 0.3
|
||||
readonly property real maxZoom: 1.6
|
||||
//: 自动适应 / 一键适应的缩放下限:再小节点标题就看不清了。
|
||||
//: 地图本来就是拿来拖动浏览的,宁可让用户滚,也别缩成一片糊。
|
||||
readonly property real comfortZoom: 0.6
|
||||
|
||||
//: 当前正在查看的分支;空字符串表示铺开全部引用
|
||||
property string selectedBranch: ""
|
||||
property int branchIndex: 0
|
||||
//: 刚提交的新分支名,等 branch 操作完成后用来刷新列表
|
||||
property string pendingBranch: ""
|
||||
|
||||
readonly property var rows: Git.graphCommits
|
||||
readonly property var layout: Git.graphMap
|
||||
readonly property var legend: Git.graphMap.legend || []
|
||||
|
||||
//: 第一项固定是"全部引用",其后是各本地分支,最后一项是"新建分支…"
|
||||
readonly property var branchOptions: {
|
||||
var locals = Git.currentRepo.locals || [];
|
||||
var out = ["全部引用"];
|
||||
for (var i = 0; i < locals.length; ++i) {
|
||||
out.push(locals[i] === Git.currentRepo.branch
|
||||
? locals[i] + "(当前)"
|
||||
: locals[i]);
|
||||
}
|
||||
out.push("+ 新建分支…");
|
||||
return out;
|
||||
}
|
||||
|
||||
function selectBranch(index) {
|
||||
var locals = Git.currentRepo.locals || [];
|
||||
if (index === locals.length + 1) {
|
||||
// 选的是"新建分支…":下拉框先还原,再弹输入框
|
||||
branchPicker.currentIndex = branchIndex;
|
||||
newBranchDialog.ask("新建分支", "从当前 HEAD 创建并切换", "分支名", "", "", "", false);
|
||||
return;
|
||||
}
|
||||
branchIndex = index;
|
||||
selectedBranch = index > 0 ? (locals[index - 1] || "") : "";
|
||||
autoFitted = false;
|
||||
reload();
|
||||
}
|
||||
|
||||
function refCount() {
|
||||
var seen = ({});
|
||||
var count = 0;
|
||||
for (var i = 0; i < rows.length; ++i) {
|
||||
var refs = rows[i].refs || [];
|
||||
for (var j = 0; j < refs.length; ++j) {
|
||||
if (!seen[refs[j]]) {
|
||||
seen[refs[j]] = true;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function reload() {
|
||||
if (!Git.hasRepo())
|
||||
return;
|
||||
Git.loadGraph(limit, selectedBranch);
|
||||
}
|
||||
|
||||
function zoomBy(delta) {
|
||||
zoom = Math.max(minZoom, Math.min(maxZoom, Math.round((zoom + delta) * 100) / 100));
|
||||
}
|
||||
|
||||
/// 把整张图缩放到刚好铺满可视宽度(但不会小于 comfortZoom)
|
||||
function fitWidth(viewportWidth) {
|
||||
var width = layout.width || 0;
|
||||
if (width <= 0 || viewportWidth <= 0)
|
||||
return;
|
||||
zoom = Math.max(comfortZoom, Math.min(maxZoom, viewportWidth / width));
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: Git
|
||||
|
||||
function onTaskDone(operation, result) {
|
||||
if (operation === "branch" && page.pendingBranch.length > 0) {
|
||||
// 新建并切换完成后:回到"全部引用",让新分支出现在下拉框里
|
||||
page.pendingBranch = "";
|
||||
page.branchIndex = 0;
|
||||
page.selectedBranch = "";
|
||||
Git.refresh();
|
||||
page.reload();
|
||||
return;
|
||||
}
|
||||
if (operation === "commit" || operation === "push" || operation === "pull"
|
||||
|| operation === "fetch" || operation === "reset"
|
||||
|| operation === "branch" || operation === "clone")
|
||||
page.reload();
|
||||
}
|
||||
|
||||
function onCurrentRepoPathChanged() {
|
||||
page.autoFitted = false;
|
||||
page.reload();
|
||||
}
|
||||
|
||||
function onGraphMapChanged() {
|
||||
// 图比屏幕宽时先缩到刚好铺满,省得用户自己去按"适应"。
|
||||
// 但只缩到 comfortZoom 为止 —— 21 个分支铺开有 4000 多像素宽,
|
||||
// 真按比例缩会变成 30%,节点标题糊成一片什么也读不出来。
|
||||
if (page.autoFitted || page.layout.width <= 0 || viewport.width <= 0)
|
||||
return;
|
||||
page.autoFitted = true;
|
||||
if (page.layout.width > viewport.width)
|
||||
page.fitWidth(viewport.width);
|
||||
}
|
||||
}
|
||||
|
||||
Component.onCompleted: reload()
|
||||
|
||||
Column {
|
||||
anchors.fill: parent
|
||||
spacing: 0
|
||||
|
||||
AppBar {
|
||||
id: bar
|
||||
width: parent.width
|
||||
title: "分支地图"
|
||||
subtitle: Git.hasRepo()
|
||||
? (page.rows.length + " 条提交 · " + page.refCount() + " 个引用 · "
|
||||
+ Math.round(page.zoom * 100) + "%")
|
||||
: "未选择仓库"
|
||||
rightIcon: "⇄"
|
||||
rightLabel: "刷新"
|
||||
onRightClicked: page.reload()
|
||||
}
|
||||
|
||||
// 看哪个分支:留空是「全部引用」,选中某个分支就只看它的历史
|
||||
Row {
|
||||
id: toolbar
|
||||
x: Theme.pagePad
|
||||
width: parent.width - Theme.pagePad * 2
|
||||
height: 46
|
||||
spacing: 10
|
||||
|
||||
Text {
|
||||
text: "分支"
|
||||
color: Theme.textDim
|
||||
font.pixelSize: 12
|
||||
height: parent.height
|
||||
verticalAlignment: Text.AlignVCenter
|
||||
}
|
||||
|
||||
// ComboBox 包一层 Item:Row 的直接子项不能用锚点做垂直居中,
|
||||
// 否则整个 Row 会停止布局
|
||||
Item {
|
||||
width: Math.min(220, toolbar.width - 60)
|
||||
height: parent.height
|
||||
|
||||
ComboBox {
|
||||
id: branchPicker
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
width: parent.width
|
||||
model: page.branchOptions
|
||||
currentIndex: page.branchIndex
|
||||
font.pixelSize: 13
|
||||
onActivated: page.selectBranch(currentIndex)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 颜色标识:颜色是按分支分配的,这里把「分支名 → 颜色」列出来
|
||||
Flickable {
|
||||
id: legendBar
|
||||
width: parent.width
|
||||
height: page.legend.length > 0 ? 30 : 0
|
||||
visible: height > 0
|
||||
clip: true
|
||||
contentWidth: legendRow.width + Theme.pagePad * 2
|
||||
flickableDirection: Flickable.HorizontalFlick
|
||||
boundsBehavior: Flickable.StopAtBounds
|
||||
|
||||
Row {
|
||||
id: legendRow
|
||||
x: Theme.pagePad
|
||||
y: (legendBar.height - height) / 2
|
||||
spacing: 14
|
||||
|
||||
Repeater {
|
||||
model: page.legend
|
||||
|
||||
Row {
|
||||
spacing: 5
|
||||
|
||||
Rectangle {
|
||||
width: 10
|
||||
height: 10
|
||||
radius: 5
|
||||
color: Theme.graphColor(modelData.color)
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
}
|
||||
|
||||
Text {
|
||||
text: modelData.name
|
||||
color: Theme.textDim
|
||||
font.pixelSize: 11
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Flickable {
|
||||
id: viewport
|
||||
|
||||
width: parent.width
|
||||
// 用各块的实际高度算,别写死数字 —— AppBar 带副标题时是 68 不是 56
|
||||
height: parent.height - bar.height - toolbar.height - legendBar.height
|
||||
clip: true
|
||||
boundsBehavior: Flickable.StopAtBounds
|
||||
contentWidth: Math.max(width, mapView.implicitWidth)
|
||||
contentHeight: Math.max(height, mapView.implicitHeight)
|
||||
|
||||
GraphMap {
|
||||
id: mapView
|
||||
|
||||
commits: page.rows
|
||||
nodeWidth: page.layout.nodeWidth || 132
|
||||
nodeHeight: page.layout.nodeHeight || 46
|
||||
mapWidth: page.layout.width || 0
|
||||
mapHeight: page.layout.height || 0
|
||||
zoom: page.zoom
|
||||
// 交给组件判断哪些节点在视口内,只渲染那部分
|
||||
viewportY: viewport.contentY
|
||||
viewportHeight: viewport.height
|
||||
|
||||
onNodeClicked: function (sha) {
|
||||
page.showCommit(sha);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 右下角缩放按钮(双指缩放不好自动化测试,按钮更直接)
|
||||
Column {
|
||||
anchors.right: parent.right
|
||||
anchors.bottom: parent.bottom
|
||||
anchors.rightMargin: 14
|
||||
anchors.bottomMargin: 16
|
||||
spacing: 8
|
||||
|
||||
IconButton {
|
||||
text: "+"
|
||||
visible: page.zoom < page.maxZoom
|
||||
onClicked: page.zoomBy(0.2)
|
||||
}
|
||||
|
||||
IconButton {
|
||||
text: "-"
|
||||
visible: page.zoom > page.minZoom
|
||||
onClicked: page.zoomBy(-0.2)
|
||||
}
|
||||
|
||||
IconButton {
|
||||
text: "↔"
|
||||
onClicked: page.fitWidth(viewport.width)
|
||||
}
|
||||
}
|
||||
|
||||
// 同 HistoryPage:EmptyState 一旦放进 Column 并用锚点,整个 Column 会失效
|
||||
EmptyState {
|
||||
width: parent.width
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 130
|
||||
visible: page.rows.length === 0
|
||||
symbol: "🌳"
|
||||
title: !Git.hasRepo() ? "尚未打开仓库" : "还没有提交可以绘制"
|
||||
description: !Git.hasRepo() ? "请先在「仓库」页选择或克隆一个仓库"
|
||||
: "提交第一个版本后,这里会画出分支拓扑"
|
||||
}
|
||||
|
||||
// 分支选择框里的「+ 新建分支…」
|
||||
InputDialog {
|
||||
id: newBranchDialog
|
||||
onSubmitted: function (value, second) {
|
||||
if (value.length > 0) {
|
||||
page.pendingBranch = value;
|
||||
Git.createBranch(value, "", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
231
qml/LnxGit/pages/GuidePage.qml
Normal file
231
qml/LnxGit/pages/GuidePage.qml
Normal file
@@ -0,0 +1,231 @@
|
||||
// 新手指南:把 clone / pull / fetch / push 的区别、怎么合并、怎么发起
|
||||
// 合并请求一次讲清楚。入口在「设置 → 新手指南」。
|
||||
//
|
||||
// 内容写死在这里而不是做成数据文件:条目少、改动低频,直接写在 QML 里
|
||||
// 比多一层映射更好读。
|
||||
import QtQuick
|
||||
import QtQuick.Controls.Material
|
||||
import LnxGit
|
||||
import "../components"
|
||||
|
||||
Item {
|
||||
id: page
|
||||
|
||||
readonly property var quickRef: [
|
||||
{ "want": "第一次把代码拿到本地", "how": "克隆(Clone)", "where": "仓库页 → 克隆远程仓库" },
|
||||
{ "want": "同步远程的新提交", "how": "拉取(Pull)", "where": "仓库页 / 分支页 → 拉取" },
|
||||
{ "want": "只想看看远程有什么变化", "how": "抓取(Fetch)", "where": "仓库页 → 抓取" },
|
||||
{ "want": "把自己写的提交传上去", "how": "推送(Push)", "where": "仓库页 / 分支页 → 推送" },
|
||||
{ "want": "把别的分支合进当前分支", "how": "合并分支(Merge)", "where": "分支页 → 合并分支" },
|
||||
{ "want": "请别人审核后并入主分支", "how": "合并请求(PR / MR)", "where": "在仓库网页上发起" }
|
||||
]
|
||||
|
||||
Column {
|
||||
anchors.fill: parent
|
||||
spacing: 0
|
||||
|
||||
AppBar {
|
||||
id: bar
|
||||
width: parent.width
|
||||
title: "新手指南"
|
||||
subtitle: "远程操作的区别 · 合并 · 合并请求"
|
||||
leftIcon: "←"
|
||||
leftLabel: "返回"
|
||||
showBack: true
|
||||
onLeftClicked: stack.pop()
|
||||
}
|
||||
|
||||
ScrollView {
|
||||
width: parent.width
|
||||
height: parent.height - bar.height
|
||||
clip: true
|
||||
contentWidth: width
|
||||
|
||||
Column {
|
||||
width: parent.width
|
||||
spacing: 14
|
||||
topPadding: 14
|
||||
bottomPadding: 40
|
||||
leftPadding: Theme.pagePad
|
||||
rightPadding: Theme.pagePad
|
||||
|
||||
// ---------------------------------------------------- 速查表
|
||||
Rectangle {
|
||||
width: parent.width - Theme.pagePad * 2
|
||||
radius: Theme.radiusSmall
|
||||
color: Theme.surface
|
||||
border.width: 1
|
||||
border.color: Theme.border
|
||||
implicitHeight: quickColumn.implicitHeight + 24
|
||||
|
||||
Column {
|
||||
id: quickColumn
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
anchors.margins: 12
|
||||
spacing: 10
|
||||
|
||||
Text {
|
||||
text: "我要做什么?"
|
||||
color: Theme.text
|
||||
font.pixelSize: 15
|
||||
font.bold: true
|
||||
}
|
||||
|
||||
Repeater {
|
||||
model: page.quickRef
|
||||
|
||||
Column {
|
||||
width: quickColumn.width
|
||||
spacing: 2
|
||||
|
||||
Text {
|
||||
width: parent.width
|
||||
text: modelData.want
|
||||
color: Theme.textDim
|
||||
font.pixelSize: 12
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
Row {
|
||||
spacing: 6
|
||||
Text {
|
||||
text: "→"
|
||||
color: Theme.textFaint
|
||||
font.pixelSize: 12
|
||||
}
|
||||
Text {
|
||||
text: modelData.how
|
||||
color: Theme.primary
|
||||
font.pixelSize: 13
|
||||
font.bold: true
|
||||
}
|
||||
Text {
|
||||
text: "(" + modelData.where + ")"
|
||||
color: Theme.textFaint
|
||||
font.pixelSize: 11
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------- 分节说明
|
||||
Repeater {
|
||||
model: [
|
||||
{
|
||||
"icon": "📥",
|
||||
"title": "克隆(Clone):第一次把代码拿到本地",
|
||||
"body": "把远程仓库完整复制一份到手机上,只需要做一次。\n"
|
||||
+ "之后所有查看、修改、提交都在本地这份副本上进行,"
|
||||
+ "没网也能用。\n\n"
|
||||
+ "路径:仓库页 → 克隆远程仓库"
|
||||
},
|
||||
{
|
||||
"icon": "⬇️",
|
||||
"title": "拉取(Pull):取回远程提交并合并",
|
||||
"body": "把远程的新提交取回来,并合并到你当前所在的分支 —— "
|
||||
+ "相当于「抓取 + 合并」一步完成。\n"
|
||||
+ "日常同步代码最常用这个。如果你的本地有未提交的改动,"
|
||||
+ "建议先提交或储藏,避免冲突。\n\n"
|
||||
+ "路径:仓库页 / 分支页 → 拉取"
|
||||
},
|
||||
{
|
||||
"icon": "🔍",
|
||||
"title": "抓取(Fetch):只取回,不动你的代码",
|
||||
"body": "只把远程的新提交下载到本地,让你能看到别人推了什么,"
|
||||
+ "但不会改动你的工作区和当前分支。\n"
|
||||
+ "想先看看再决定要不要合并时用它。\n\n"
|
||||
+ "路径:仓库页 → 抓取"
|
||||
},
|
||||
{
|
||||
"icon": "⬆️",
|
||||
"title": "推送(Push):把本地提交传上去",
|
||||
"body": "把你本地的提交发送到远程仓库,别人才能看到。\n"
|
||||
+ "首次推送某个分支时会自动设置上游(upstream)。\n\n"
|
||||
+ "路径:仓库页 / 分支页 → 推送"
|
||||
},
|
||||
{
|
||||
"icon": "🔀",
|
||||
"title": "合并分支(Merge)",
|
||||
"body": "把另一个分支的改动合并到你当前所在的分支:\n"
|
||||
+ "1. 先切到接收方分支(比如 main)\n"
|
||||
+ "2. 分支页 → 合并分支 → 填要合进来的分支名\n\n"
|
||||
+ "如果两个分支改了同一处,会产生冲突。"
|
||||
+ "本应用暂不提供冲突编辑,需要你在电脑上处理后再同步过来。"
|
||||
},
|
||||
{
|
||||
"icon": "📮",
|
||||
"title": "合并请求(Pull Request / Merge Request)",
|
||||
"body": "合并请求是「请对方把我的分支合进主分支」的申请,"
|
||||
+ "需要在仓库网页上发起,App 内暂不支持:\n\n"
|
||||
+ "1. 先把你的分支推送到远程(分支页 → 推送)\n"
|
||||
+ "2. 在浏览器打开仓库页面(GitHub / Gitee / Gitea 都一样)\n"
|
||||
+ "3. 点「New pull request」/「新建合并请求」\n"
|
||||
+ "4. 选源分支(你的)和目标分支(比如 main),"
|
||||
+ "填标题和说明后提交\n\n"
|
||||
+ "之后在网页上就能看到评审意见与合并状态。"
|
||||
}
|
||||
]
|
||||
|
||||
Rectangle {
|
||||
width: parent.width - Theme.pagePad * 2
|
||||
radius: Theme.radiusSmall
|
||||
color: Theme.surface
|
||||
border.width: 1
|
||||
border.color: Theme.border
|
||||
implicitHeight: sectionColumn.implicitHeight + 24
|
||||
|
||||
Column {
|
||||
id: sectionColumn
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
anchors.margins: 12
|
||||
spacing: 8
|
||||
|
||||
Row {
|
||||
spacing: 8
|
||||
|
||||
Text {
|
||||
text: modelData.icon
|
||||
font.pixelSize: 18
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
}
|
||||
Text {
|
||||
width: sectionColumn.width - 34
|
||||
text: modelData.title
|
||||
color: Theme.text
|
||||
font.pixelSize: 14
|
||||
font.bold: true
|
||||
wrapMode: Text.WordWrap
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
width: parent.width
|
||||
text: modelData.body
|
||||
color: Theme.textDim
|
||||
font.pixelSize: 12
|
||||
lineHeight: 1.35
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
width: parent.width - Theme.pagePad * 2
|
||||
text: "小提示:所有耗时操作都在后台执行,顶部会显示进度;"
|
||||
+ "出问题可以到「设置 → 查看运行日志」里看详细记录。"
|
||||
color: Theme.textFaint
|
||||
font.pixelSize: 11
|
||||
lineHeight: 1.35
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,31 @@ Item {
|
||||
property int limit: 60
|
||||
property string filterText: ""
|
||||
|
||||
//: 图谱里最多画多少列。历史页每行还有作者、时间、SHA 和引用标签,
|
||||
//: 图谱不能太宽,所以上限比独立的图谱页小;超出的泳道直接裁掉。
|
||||
readonly property int maxGraphColumns: 6
|
||||
//: 给右侧文字预留的宽度
|
||||
readonly property int textWidth: 170
|
||||
//: 筛选结果里实际用到的最大列数
|
||||
readonly property int rawGraphColumns: {
|
||||
var rows = filtered();
|
||||
var best = 1;
|
||||
for (var i = 0; i < rows.length; ++i)
|
||||
best = Math.max(best, rows[i].graphCols || 1);
|
||||
return best;
|
||||
}
|
||||
readonly property int graphColumns: Math.min(rawGraphColumns, maxGraphColumns)
|
||||
//: 分支多就把列压窄,尽量都画下
|
||||
readonly property int laneWidth: Theme.graphLaneFor(
|
||||
graphColumns,
|
||||
width - Theme.pagePad * 2 - textWidth)
|
||||
readonly property int graphWidth: graphColumns * laneWidth
|
||||
|
||||
function reload() {
|
||||
if (!Git.hasRepo())
|
||||
return;
|
||||
Git.loadLog(limit);
|
||||
// 带图谱的视图要看到分叉,所以默认拉取所有引用(当前分支 + 本地分支 + 远端)
|
||||
Git.loadLog(limit, true);
|
||||
}
|
||||
|
||||
function filtered() {
|
||||
@@ -64,8 +85,10 @@ Item {
|
||||
subtitle: Git.hasRepo()
|
||||
? (Git.currentRepoName + " · " + page.commitList.length + " 条")
|
||||
: "未选择仓库"
|
||||
rightIcon: "⟳"
|
||||
rightIcon2: "⤓"
|
||||
rightIcon: "⇄"
|
||||
rightLabel: "刷新"
|
||||
rightIcon2: "⬇"
|
||||
rightLabel2: "更多"
|
||||
onRightClicked: page.reload()
|
||||
onRight2Clicked: {
|
||||
page.limit += 60;
|
||||
@@ -90,24 +113,31 @@ Item {
|
||||
bottomMargin: 24
|
||||
clip: true
|
||||
model: page.filtered()
|
||||
spacing: 8
|
||||
spacing: 0
|
||||
leftMargin: Theme.pagePad
|
||||
rightMargin: Theme.pagePad
|
||||
|
||||
delegate: Rectangle {
|
||||
delegate: Item {
|
||||
width: list.width - Theme.pagePad * 2
|
||||
height: Math.max(64, body.implicitHeight + 18)
|
||||
radius: Theme.radiusSmall
|
||||
color: commitMouse.pressed ? Theme.surfaceAlt : Theme.surface
|
||||
border.width: 1
|
||||
border.color: Theme.border
|
||||
height: 64
|
||||
|
||||
// 图谱列宽按整页最大列数固定,否则每行的文字起始位置会参差不齐
|
||||
CommitGraph {
|
||||
id: graphView
|
||||
row: modelData
|
||||
width: page.graphWidth
|
||||
laneWidth: page.laneWidth
|
||||
height: parent.height
|
||||
anchors.left: parent.left
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
}
|
||||
|
||||
Column {
|
||||
id: body
|
||||
anchors.left: parent.left
|
||||
anchors.leftMargin: 12
|
||||
anchors.left: graphView.right
|
||||
anchors.leftMargin: 8
|
||||
anchors.right: parent.right
|
||||
anchors.rightMargin: 12
|
||||
anchors.rightMargin: 4
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
spacing: 4
|
||||
|
||||
@@ -176,6 +206,20 @@ Item {
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
anchors.bottom: parent.bottom
|
||||
width: parent.width
|
||||
height: 1
|
||||
color: Theme.border
|
||||
opacity: 0.6
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
anchors.fill: parent
|
||||
color: commitMouse.pressed ? Theme.surfaceAlt : "transparent"
|
||||
opacity: commitMouse.pressed ? 0.6 : 0
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
id: commitMouse
|
||||
anchors.fill: parent
|
||||
@@ -200,19 +244,23 @@ Item {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EmptyState {
|
||||
width: parent.width
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 120
|
||||
visible: page.filtered().length === 0
|
||||
symbol: "🕘"
|
||||
title: !Git.hasRepo() ? "尚未打开仓库"
|
||||
: (page.filterText.length > 0 ? "没有匹配的提交" : "还没有提交记录")
|
||||
description: !Git.hasRepo() ? "请先在「仓库」页选择或克隆一个仓库"
|
||||
: (page.filterText.length > 0 ? "换个关键词试试"
|
||||
: "在「更改」页提交第一个版本")
|
||||
}
|
||||
// 注意:EmptyState 必须放在 Column 之外。Column 里只要有一个子项用了
|
||||
// top/bottom/verticalCenter/fill 这类锚点,Qt 就会让**整个 Column 失效**
|
||||
// ("Column will not function"),所有子项堆到 y=0 互相重叠 —— 表现为
|
||||
// 列表盖住标题栏。这个问题只在列表非空时才看得出来。
|
||||
EmptyState {
|
||||
width: parent.width
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 130
|
||||
visible: page.filtered().length === 0
|
||||
symbol: "🕘"
|
||||
title: !Git.hasRepo() ? "尚未打开仓库"
|
||||
: (page.filterText.length > 0 ? "没有匹配的提交" : "还没有提交记录")
|
||||
description: !Git.hasRepo() ? "请先在「仓库」页选择或克隆一个仓库"
|
||||
: (page.filterText.length > 0 ? "换个关键词试试"
|
||||
: "在「更改」页提交第一个版本")
|
||||
}
|
||||
|
||||
Menu {
|
||||
|
||||
@@ -27,8 +27,10 @@ Item {
|
||||
title: "运行日志"
|
||||
subtitle: page.lines.length + " 条记录"
|
||||
leftIcon: "←"
|
||||
leftLabel: "返回"
|
||||
showBack: true
|
||||
rightIcon: "🗑"
|
||||
rightLabel: "清空"
|
||||
onLeftClicked: stack.pop()
|
||||
onRightClicked: Git.logs = []
|
||||
}
|
||||
@@ -60,7 +62,8 @@ Item {
|
||||
color: Theme.textFaint
|
||||
font.family: Theme.monoFont
|
||||
font.pixelSize: 11
|
||||
anchors.top: parent.top
|
||||
// 不要在 Row 的子项上用 anchors:Row 自己负责摆放,
|
||||
// 锚点会让整个 Row 停止布局
|
||||
}
|
||||
Text {
|
||||
id: lineText
|
||||
|
||||
@@ -38,9 +38,12 @@ Item {
|
||||
title: "远端仓库"
|
||||
subtitle: Git.currentRepoName + " · " + page.remoteItems.length + " 个远端"
|
||||
leftIcon: "←"
|
||||
leftLabel: "返回"
|
||||
showBack: true
|
||||
rightIcon: "+"
|
||||
rightIcon2: "⟳"
|
||||
rightLabel: "新建"
|
||||
rightIcon2: "⇄"
|
||||
rightLabel2: "刷新"
|
||||
onLeftClicked: stack.pop()
|
||||
onRightClicked: addDialog.ask("添加远端", "例如 https://git.xnhw.cc/user/repo.git",
|
||||
"远端名称", "origin", "地址", "", true)
|
||||
|
||||
@@ -46,7 +46,9 @@ Item {
|
||||
title: "LnxGit"
|
||||
subtitle: Git.repos.length + " 个本地仓库 · " + Git.reposRoot
|
||||
rightIcon: "+"
|
||||
rightIcon2: "⟳"
|
||||
rightLabel: "新建"
|
||||
rightIcon2: "⇄"
|
||||
rightLabel2: "刷新"
|
||||
onRightClicked: cloneSheet.open()
|
||||
onRight2Clicked: {
|
||||
Git.refreshRepos();
|
||||
@@ -170,7 +172,7 @@ Item {
|
||||
}
|
||||
ActionButton {
|
||||
text: "抓取"
|
||||
iconText: "⟳"
|
||||
iconText: "⇄"
|
||||
subtle: true
|
||||
onClicked: Git.fetchRemote("")
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ Item {
|
||||
id: page
|
||||
|
||||
signal showLogs()
|
||||
signal showGuide()
|
||||
|
||||
property var credentialHosts: []
|
||||
|
||||
@@ -32,7 +33,8 @@ Item {
|
||||
width: parent.width
|
||||
title: "设置"
|
||||
subtitle: "LnxGit " + app.appVersion + " · PySide6 + dulwich"
|
||||
rightIcon: "⟳"
|
||||
rightIcon: "⇄"
|
||||
rightLabel: "刷新"
|
||||
onRightClicked: page.reloadCredentials()
|
||||
}
|
||||
|
||||
@@ -261,23 +263,33 @@ Item {
|
||||
width: parent.width
|
||||
spacing: 8
|
||||
|
||||
ActionButton {
|
||||
text: "新手指南"
|
||||
iconText: "📖"
|
||||
subtle: true
|
||||
onClicked: page.showGuide()
|
||||
}
|
||||
ActionButton {
|
||||
text: "管理远端"
|
||||
iconText: "🔗"
|
||||
subtle: true
|
||||
onClicked: remotesDialog.open()
|
||||
}
|
||||
ActionButton {
|
||||
text: "查看仓库配置"
|
||||
iconText: "⚙"
|
||||
subtle: true
|
||||
onClicked: configDialog.open()
|
||||
}
|
||||
ActionButton {
|
||||
text: "运行维护 / 统计"
|
||||
iconText: "🧹"
|
||||
subtle: true
|
||||
onClicked: Git.maintenance()
|
||||
}
|
||||
ActionButton {
|
||||
text: "查看运行日志"
|
||||
iconText: "📄"
|
||||
subtle: true
|
||||
onClicked: page.showLogs()
|
||||
}
|
||||
|
||||
@@ -15,10 +15,13 @@ EmptyState 1.0 components/EmptyState.qml
|
||||
LoginDialog 1.0 components/LoginDialog.qml
|
||||
InputDialog 1.0 components/InputDialog.qml
|
||||
ConfirmDialog 1.0 components/ConfirmDialog.qml
|
||||
CommitGraph 1.0 components/CommitGraph.qml
|
||||
GraphMap 1.0 components/GraphMap.qml
|
||||
|
||||
RepoPage 1.0 pages/RepoPage.qml
|
||||
ChangesPage 1.0 pages/ChangesPage.qml
|
||||
HistoryPage 1.0 pages/HistoryPage.qml
|
||||
GraphPage 1.0 pages/GraphPage.qml
|
||||
BranchesPage 1.0 pages/BranchesPage.qml
|
||||
SettingsPage 1.0 pages/SettingsPage.qml
|
||||
DiffPage 1.0 pages/DiffPage.qml
|
||||
@@ -26,4 +29,5 @@ CommitPage 1.0 pages/CommitPage.qml
|
||||
FilePage 1.0 pages/FilePage.qml
|
||||
RemotesPage 1.0 pages/RemotesPage.qml
|
||||
LogPage 1.0 pages/LogPage.qml
|
||||
GuidePage 1.0 pages/GuidePage.qml
|
||||
BlamePage 1.0 pages/BlamePage.qml
|
||||
|
||||
26
qml/Main.qml
26
qml/Main.qml
@@ -153,6 +153,10 @@ ApplicationWindow {
|
||||
"icon": "🕘",
|
||||
"label": "历史"
|
||||
},
|
||||
{
|
||||
"icon": "🌳",
|
||||
"label": "图谱"
|
||||
},
|
||||
{
|
||||
"icon": "🌿",
|
||||
"label": "分支"
|
||||
@@ -200,6 +204,17 @@ ApplicationWindow {
|
||||
}
|
||||
}
|
||||
|
||||
Component {
|
||||
id: graphPage
|
||||
GraphPage {
|
||||
onShowCommit: function (sha) {
|
||||
stack.push(commitPage, {
|
||||
"sha": sha
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Component {
|
||||
id: branchesPage
|
||||
BranchesPage {
|
||||
@@ -215,9 +230,17 @@ ApplicationWindow {
|
||||
onShowLogs: function () {
|
||||
stack.push(logPage);
|
||||
}
|
||||
onShowGuide: function () {
|
||||
stack.push(guidePage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Component {
|
||||
id: guidePage
|
||||
GuidePage {}
|
||||
}
|
||||
|
||||
Component {
|
||||
id: diffPage
|
||||
DiffPage {}
|
||||
@@ -267,7 +290,8 @@ ApplicationWindow {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 根页面切换
|
||||
property var rootPages: [repoPage, changesPage, historyPage, branchesPage, settingsPage]
|
||||
property var rootPages: [repoPage, changesPage, historyPage, graphPage, branchesPage,
|
||||
settingsPage]
|
||||
|
||||
function switchRoot(index) {
|
||||
stack.replace(null, rootPages[index]);
|
||||
|
||||
23
scripts/_check_arsc.sh
Normal file
23
scripts/_check_arsc.sh
Normal file
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# 检查 APK 中 resources.arsc 的压缩方式(Android 11+ 要求未压缩且 4 字节对齐)。
|
||||
set -uo pipefail
|
||||
|
||||
for apk in "$@"; do
|
||||
[ -f "$apk" ] || continue
|
||||
echo "=== $(basename "$apk") ==="
|
||||
unzip -v "$apk" 2>/dev/null | awk '$NF ~ /resources\.arsc|AndroidManifest\.xml/ {print " 方法=" $2 " 压缩后=" $1 " 原始=" $3 " 文件=" $NF}'
|
||||
python3 - "$apk" <<'PY'
|
||||
import sys, zipfile
|
||||
path = sys.argv[1]
|
||||
with zipfile.ZipFile(path) as z:
|
||||
for name in ("resources.arsc", "AndroidManifest.xml"):
|
||||
try:
|
||||
info = z.getinfo(name)
|
||||
except KeyError:
|
||||
print(f" {name}: 不存在")
|
||||
continue
|
||||
method = "STORED(未压缩)" if info.compress_type == zipfile.ZIP_STORED else "DEFLATED(已压缩)"
|
||||
print(f" {name}: {method}, 对齐={info.header_offset % 4 == 0}")
|
||||
PY
|
||||
echo
|
||||
done
|
||||
21
scripts/_diag_apk_py.sh
Normal file
21
scripts/_diag_apk_py.sh
Normal file
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# 清理构建日志并检查最终 APK 的 Python 版本。
|
||||
set -uo pipefail
|
||||
LOG="/opt/lnxgit-android/build.log"
|
||||
APK="/opt/lnxgit-android/src/LnxGit-0.1-x86_64-debug.apk"
|
||||
|
||||
echo "=== 日志时间范围 ==="
|
||||
head -3 "$LOG" 2>/dev/null
|
||||
echo "..."
|
||||
|
||||
echo
|
||||
echo "=== APK 中的 libpython ==="
|
||||
unzip -l "$APK" 2>/dev/null | grep -E "libpython3" || echo "(无)"
|
||||
|
||||
echo
|
||||
echo "=== APK 时间 ==="
|
||||
ls -la "$APK" 2>/dev/null
|
||||
|
||||
echo
|
||||
echo "=== 备份旧日志 ==="
|
||||
mv "$LOG" "$LOG.prev" 2>/dev/null && echo "已备份为 build.log.prev"
|
||||
22
scripts/_diag_download.sh
Normal file
22
scripts/_diag_download.sh
Normal file
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# 查看 p4a 的 download()/download_if_necessary() 细节与下载缓存位置。
|
||||
set -uo pipefail
|
||||
P4A="/opt/lnxgit-android/p4a-src"
|
||||
BUILD="/opt/lnxgit-android/src/.buildozer/android/platform/build-x86_64"
|
||||
|
||||
echo "=== download_if_necessary() ==="
|
||||
awk '/def download_if_necessary/,/def download\(/' "$P4A/pythonforandroid/recipe.py" | head -30
|
||||
|
||||
echo
|
||||
echo "=== download() 关键行 ==="
|
||||
awk '/def download\(self\)/,/def unpack/' "$P4A/pythonforandroid/recipe.py" | grep -nE "marker|filename|cwd|chdir|url" | head -25
|
||||
|
||||
echo
|
||||
echo "=== 构建目录内容(找下载缓存) ==="
|
||||
ls -la "$BUILD" 2>/dev/null | head -12
|
||||
find "$BUILD" -maxdepth 1 -name ".mark-*" -o -maxdepth 3 -name "*.tar.gz" 2>/dev/null | head -10
|
||||
|
||||
echo
|
||||
echo "=== p4a 源码根目录 ==="
|
||||
ls "$P4A" | head -15
|
||||
find "$P4A" -maxdepth 2 -name ".mark-*" 2>/dev/null | head -5
|
||||
22
scripts/_diag_find_recipes.sh
Normal file
22
scripts/_diag_find_recipes.sh
Normal file
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# 找出构建树里所有 p4a 副本及其 python3 recipe 版本。
|
||||
set -uo pipefail
|
||||
|
||||
echo "=== 搜索所有 python3 recipe ==="
|
||||
find /opt/lnxgit-android /home/builder/.buildozer -path "*/recipes/python3/__init__.py" 2>/dev/null | while read -r f; do
|
||||
v="$(grep -oE 'version = "[0-9.]+"' "$f" | head -1)"
|
||||
pin="$(grep -c _LNXGIT_PINNED "$f" 2>/dev/null || echo 0)"
|
||||
printf ' %-95s %-12s pin=%s\n' "$f" "$v" "$pin"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "=== APK 里已编译的 Python 版本 ==="
|
||||
unzip -l /opt/lnxgit-android/src/LnxGit-0.1-x86_64-debug.apk 2>/dev/null | grep -oE "libpython3\.[0-9]+" | sort -u
|
||||
|
||||
echo
|
||||
echo "=== buildozer.spec requirements ==="
|
||||
grep -E "^requirements|^p4a.source_dir" /opt/lnxgit-android/src/buildozer.spec 2>/dev/null
|
||||
|
||||
echo
|
||||
echo "=== 构建日志中的关键行 ==="
|
||||
grep -nE "python3==|requirements|Building|Dist|python" /opt/lnxgit-android/build.log 2>/dev/null | head -12
|
||||
32
scripts/_diag_p4a_source.sh
Normal file
32
scripts/_diag_p4a_source.sh
Normal file
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# 直接向 buildozer 查询它读到的 p4a.source_dir 与文件存在性判断。
|
||||
set -uo pipefail
|
||||
|
||||
cd /opt/lnxgit-android/src 2>/dev/null || cd /tmp
|
||||
PY=/opt/lnxgit-android/venv/bin/python
|
||||
export HOME=/home/builder
|
||||
export VIRTUAL_ENV=/opt/lnxgit-android/venv
|
||||
|
||||
$PY - <<'PY'
|
||||
import os, inspect
|
||||
os.chdir("/opt/lnxgit-android/src")
|
||||
|
||||
from buildozer import Buildozer
|
||||
from buildozer.targets.android import TargetAndroid
|
||||
import buildozer.buildops as buildops
|
||||
|
||||
print("Buildozer.__init__ 参数:", inspect.signature(Buildozer.__init__))
|
||||
bz = Buildozer(filename="buildozer.spec")
|
||||
print("配置 p4a.source_dir =", repr(bz.config.getdefault("app", "p4a.source_dir")))
|
||||
print("配置 android.archs =", repr(bz.config.getdefault("app", "android.archs")))
|
||||
print("配置 p4a.branch =", repr(bz.config.getdefault("app", "p4a.branch")))
|
||||
print("platform_dir =", bz.platform_dir)
|
||||
print("global_platform_dir =", bz.global_platform_dir)
|
||||
|
||||
target = TargetAndroid(bz)
|
||||
print("target.archs =", getattr(target, "archs", None))
|
||||
print("target.p4a_dir =", target.p4a_dir)
|
||||
print("file_exists(p4a_dir)=", buildops.file_exists(target.p4a_dir))
|
||||
print("isdir =", os.path.isdir(target.p4a_dir))
|
||||
print("目录内容 =", os.listdir(target.p4a_dir)[:5] if os.path.isdir(target.p4a_dir) else "N/A")
|
||||
PY
|
||||
@@ -1,29 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在 WSL 的 Python 3.11 下直接解析这两个文件,拿到真实的语法错误。
|
||||
set -uo pipefail
|
||||
VENV="$HOME/lnxgit-android/venv"
|
||||
SRC="$HOME/lnxgit-android/src"
|
||||
"$VENV/bin/python" - <<PY
|
||||
import ast, pathlib, sys
|
||||
print("Python:", sys.version)
|
||||
for name in ("lnxgit/gitcore.py", "lnxgit/service.py", "main.py"):
|
||||
p = pathlib.Path("$SRC") / name
|
||||
data = p.read_bytes()
|
||||
print()
|
||||
print("===", name, "大小", len(data), "字节 ===")
|
||||
print(" 前 4 字节:", data[:4])
|
||||
try:
|
||||
src = data.decode("utf-8")
|
||||
print(" utf-8 解码 OK")
|
||||
except UnicodeDecodeError as exc:
|
||||
print(" utf-8 解码失败:", exc)
|
||||
continue
|
||||
try:
|
||||
ast.parse(src, filename=str(p))
|
||||
print(" ast.parse OK")
|
||||
except SyntaxError as exc:
|
||||
print(" ast.parse 失败:", exc.msg, "line", exc.lineno, "offset", exc.offset)
|
||||
lines = src.splitlines()
|
||||
if exc.lineno and exc.lineno <= len(lines):
|
||||
print(" 该行内容:", repr(lines[exc.lineno - 1])[:200])
|
||||
PY
|
||||
35
scripts/_diag_patch_ok.sh
Normal file
35
scripts/_diag_patch_ok.sh
Normal file
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
# 检查补丁是否真正生效:sitecustomize 可导入 + 各 p4a 副本的 recipe 版本。
|
||||
set -uo pipefail
|
||||
|
||||
echo "=== 1) sitecustomize 是否随 PYTHONPATH 加载 ==="
|
||||
/opt/lnxgit-android/venv/bin/python -c "
|
||||
import os, sys
|
||||
print('PYTHONPATH 中是否有 pysite:', any('pysite' in p for p in sys.path))
|
||||
try:
|
||||
import sitecustomize
|
||||
print('sitecustomize 文件:', sitecustomize.__file__)
|
||||
print('LNXGIT_PYTHON_VERSION =', os.environ.get('LNXGIT_PYTHON_VERSION'))
|
||||
except Exception as exc:
|
||||
print('导入失败:', type(exc).__name__, exc)
|
||||
" 2>&1 | tail -5
|
||||
|
||||
echo
|
||||
echo "=== 2) 各 p4a 副本的 recipe 版本 ==="
|
||||
for d in /opt/lnxgit-android/p4a-src \
|
||||
/opt/lnxgit-android/src/.buildozer/android/platform/python-for-android \
|
||||
/home/builder/.buildozer/android/platform/python-for-android; do
|
||||
for name in hostpython3 python3; do
|
||||
f="$d/pythonforandroid/recipes/$name/__init__.py"
|
||||
if [ -f "$f" ]; then
|
||||
v="$(grep -oE 'version = "[0-9.]+"' "$f" | head -1)"
|
||||
pin="$(grep -c _LNXGIT_PINNED "$f" || true)"
|
||||
printf ' %-70s %-12s pinned=%s\n' "${d##*/platform/}/$name" "$v" "$pin"
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
echo
|
||||
echo "=== 3) 构建日志中的下载版本 ==="
|
||||
grep -oE "cpython/archive/refs/tags/v[0-9.]+|Python-3\.[0-9.]+\.tgz|v3\.[0-9.]+\.tar\.gz" \
|
||||
/opt/lnxgit-android/build.log 2>/dev/null | sort -u | head -5
|
||||
28
scripts/_diag_py_version.sh
Normal file
28
scripts/_diag_py_version.sh
Normal file
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
# 查明构建实际下载/解包了哪个 Python 版本,以及 recipe 来源。
|
||||
set -uo pipefail
|
||||
LOG="/opt/lnxgit-android/build.log"
|
||||
|
||||
echo "=== 下载的 Python 源码 ==="
|
||||
grep -oE "Python-3\.[0-9.]+\.tgz|v3\.[0-9.]+\.tar\.gz|cpython/archive/refs/tags/v[0-9.]+" "$LOG" 2>/dev/null | sort -u | head -5
|
||||
|
||||
echo
|
||||
echo "=== 解包/编译的 Python 目录 ==="
|
||||
grep -oE "other_builds/(host)?python3/[^ ]*" "$LOG" 2>/dev/null | sort -u | head -5
|
||||
grep -oE "python3/3\.[0-9]+\.[0-9]+" "$LOG" 2>/dev/null | sort -u | head -5
|
||||
|
||||
echo
|
||||
echo "=== recipe 读取路径 ==="
|
||||
grep -oE "/[^ ]*recipes/python3[^ ]*" "$LOG" 2>/dev/null | sort -u | head -5
|
||||
|
||||
echo
|
||||
echo "=== libpython 出现处 ==="
|
||||
grep -oE "libpython3\.[0-9]+\.so" "$LOG" 2>/dev/null | sort -u | head -3
|
||||
|
||||
echo
|
||||
echo "=== 构建 p4a 目录里的 recipe 版本 ==="
|
||||
for d in /opt/lnxgit-android/src/.buildozer/android/platform/python-for-android \
|
||||
/opt/lnxgit-android/src/.buildozer/android/platform/build-x86_64/dists/LnxGit; do
|
||||
f="$d/pythonforandroid/recipes/python3/__init__.py"
|
||||
[ -f "$f" ] && echo " $d -> $(grep -oE 'version = \"[0-9.]+\"' "$f" | head -1)"
|
||||
done
|
||||
34
scripts/_diag_recipe_used.sh
Normal file
34
scripts/_diag_recipe_used.sh
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# 检查构建实际使用的 p4a recipe 版本,以及 dist 是否被复用。
|
||||
set -uo pipefail
|
||||
|
||||
P4A="/opt/lnxgit-android/src/.buildozer/android/platform/python-for-android"
|
||||
LOG="/opt/lnxgit-android/build.log"
|
||||
|
||||
echo "=== 构建使用的 p4a recipe ==="
|
||||
for name in hostpython3 python3; do
|
||||
f="$P4A/pythonforandroid/recipes/$name/__init__.py"
|
||||
if [ -f "$f" ]; then
|
||||
printf ' %-12s %s (pin标记=%s)\n' "$name" \
|
||||
"$(grep -oE 'version = "[0-9.]+"' "$f" | head -1)" \
|
||||
"$(grep -c _LNXGIT_PINNED "$f")"
|
||||
else
|
||||
echo " $name 缺失: $f"
|
||||
fi
|
||||
done
|
||||
|
||||
echo
|
||||
echo "=== 本次下载的 Python 源码 ==="
|
||||
grep -oE "Python-3\.[0-9.]+\.tgz|v3\.[0-9.]+\.tar\.gz|cpython/archive/refs/tags/v[0-9.]+" "$LOG" 2>/dev/null | sort -u | head -5
|
||||
|
||||
echo
|
||||
echo "=== 是否复用了 dist ==="
|
||||
grep -E "has compatible recipes, using this one|Building the APK|Dist matching name" "$LOG" 2>/dev/null | tail -3
|
||||
|
||||
echo
|
||||
echo "=== dists 目录 ==="
|
||||
ls -la /opt/lnxgit-android/src/.buildozer/android/platform/build-x86_64/dists/ 2>/dev/null | head -6
|
||||
|
||||
echo
|
||||
echo "=== buildozer.spec requirements ==="
|
||||
grep -E "^requirements" /opt/lnxgit-android/src/buildozer.spec 2>/dev/null
|
||||
@@ -1,41 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# 复现 pyside6-android-deploy 的模块扫描失败,定位问题代码。
|
||||
set -uo pipefail
|
||||
VENV="$HOME/lnxgit-android/venv"
|
||||
SCRIPTS="$VENV/lib/python3.11/site-packages/PySide6/scripts"
|
||||
|
||||
echo "=== find_pyside_modules 签名 ==="
|
||||
"$VENV/bin/python" - <<PY
|
||||
import sys, inspect, importlib
|
||||
sys.path.insert(0, "$SCRIPTS")
|
||||
du = importlib.import_module("deploy_lib.dependency_util")
|
||||
print(inspect.signature(du.find_pyside_modules))
|
||||
print("--- 源码片段(找出 tree 变量的用法) ---")
|
||||
src = inspect.getsource(du.find_pyside_modules)
|
||||
for i, line in enumerate(src.splitlines(), 1):
|
||||
if "tree" in line or "get_ast" in line or "ast." in line:
|
||||
print(f"{i:4d}: {line}")
|
||||
PY
|
||||
|
||||
echo
|
||||
echo "=== 逐个文件扫描(定位崩在哪个文件) ==="
|
||||
"$VENV/bin/python" - <<PY
|
||||
import sys, importlib, traceback
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, "$SCRIPTS")
|
||||
du = importlib.import_module("deploy_lib.dependency_util")
|
||||
root = Path("$HOME/lnxgit-android/src")
|
||||
skip = {".git", "build", "dist", "tools", "scripts", "android", "docs"}
|
||||
bad = []
|
||||
for f in sorted(root.rglob("*.py")):
|
||||
if skip & set(f.parts):
|
||||
continue
|
||||
try:
|
||||
du.get_ast(f)
|
||||
print(f" OK {f.relative_to(root)}")
|
||||
except Exception as exc:
|
||||
bad.append(f)
|
||||
print(f" FAIL {f.relative_to(root)} -> {type(exc).__name__}: {exc}")
|
||||
print()
|
||||
print("失败文件:", [str(f.relative_to(root)) for f in bad])
|
||||
PY
|
||||
20
scripts/_diag_spec.sh
Normal file
20
scripts/_diag_spec.sh
Normal file
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
# 检查生成的 buildozer.spec 里 p4a 相关配置到底长什么样。
|
||||
set -uo pipefail
|
||||
SPEC="/opt/lnxgit-android/src/buildozer.spec"
|
||||
|
||||
echo "=== $SPEC 中的 p4a / arch 行 ==="
|
||||
grep -nE "^p4a\.|^android\.archs|^requirements|^source\." "$SPEC" 2>/dev/null
|
||||
|
||||
echo
|
||||
echo "=== 用 configparser 直接读取 [app] 段 ==="
|
||||
/opt/lnxgit-android/venv/bin/python - "$SPEC" <<'PY'
|
||||
import sys, configparser
|
||||
p = sys.argv[1]
|
||||
cp = configparser.ConfigParser()
|
||||
cp.read(p, encoding="utf-8")
|
||||
app = dict(cp["app"]) if cp.has_section("app") else {}
|
||||
for k in sorted(app):
|
||||
if k.startswith("p4a") or "arch" in k or k == "requirements":
|
||||
print(f" {k} = {app[k]}")
|
||||
PY
|
||||
@@ -1,70 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# 构建 LnxGit 的 Android 安装包。
|
||||
#
|
||||
# 用法:
|
||||
# bash scripts/build_apk.sh # debug APK(可直接安装)
|
||||
# bash scripts/build_apk.sh release # release 包
|
||||
#
|
||||
# 前置条件:先执行 scripts/wsl_bootstrap.sh 与 scripts/wsl_setup_android.sh。
|
||||
set -euo pipefail
|
||||
|
||||
MODE="${1:-debug}"
|
||||
WORK="${WORK:-$HOME/lnxgit-android}"
|
||||
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
NDK_VER="${NDK_VER:-27.2.12479018}"
|
||||
QT_VER="${QT_VER:-6.11.2}"
|
||||
|
||||
VENV="$WORK/venv"
|
||||
SDK_ROOT="${ANDROID_HOME:-$WORK/android-sdk}"
|
||||
NDK_ROOT="$SDK_ROOT/ndk/$NDK_VER"
|
||||
WHEEL_DIR="$WORK/wheels"
|
||||
|
||||
PYSIDE_WHEEL="$(ls "$WHEEL_DIR"/pyside6-${QT_VER}-*-android_aarch64.whl 2>/dev/null | head -1 || true)"
|
||||
SHIBOKEN_WHEEL="$(ls "$WHEEL_DIR"/shiboken6-${QT_VER}-*-android_aarch64.whl 2>/dev/null | head -1 || true)"
|
||||
|
||||
for item in "$VENV/bin/python" "$NDK_ROOT" "$PYSIDE_WHEEL" "$SHIBOKEN_WHEEL"; do
|
||||
if [ -z "$item" ] || [ ! -e "$item" ]; then
|
||||
echo "缺少构建依赖: ${item:-<未找到>}"
|
||||
echo "请先执行: sudo bash scripts/wsl_bootstrap.sh && bash scripts/wsl_setup_android.sh"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
export ANDROID_HOME="$SDK_ROOT"
|
||||
export ANDROID_SDK_ROOT="$SDK_ROOT"
|
||||
export ANDROID_NDK_HOME="$NDK_ROOT"
|
||||
export JAVA_HOME="${JAVA_HOME:-/usr/lib/jvm/java-17-openjdk-amd64}"
|
||||
export PATH="$VENV/bin:$PATH"
|
||||
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
if [ "$MODE" = "release" ]; then
|
||||
BUILD_MODE="release"
|
||||
else
|
||||
BUILD_MODE="debug"
|
||||
fi
|
||||
|
||||
echo "==> 项目目录 : $PROJECT_DIR"
|
||||
echo "==> Python : $($VENV/bin/python --version)"
|
||||
echo "==> NDK : $NDK_ROOT"
|
||||
echo "==> 模式 : $BUILD_MODE"
|
||||
echo
|
||||
|
||||
# pyside6-android-deploy 在 PATH 中(由 venv 提供)
|
||||
if ! command -v pyside6-android-deploy >/dev/null 2>&1; then
|
||||
echo "未找到 pyside6-android-deploy,尝试从 PySide6 wheel 安装到 venv"
|
||||
"$VENV/bin/pip" install "$PYSIDE_WHEEL" "$SHIBOKEN_WHEEL" >/dev/null
|
||||
fi
|
||||
|
||||
pyside6-android-deploy \
|
||||
--name LnxGit \
|
||||
--wheel-pyside="$PYSIDE_WHEEL" \
|
||||
--wheel-shiboken="$SHIBOKEN_WHEEL" \
|
||||
--ndk-path="$NDK_ROOT" \
|
||||
--sdk-path="$SDK_ROOT" \
|
||||
--force \
|
||||
--verbose
|
||||
|
||||
echo
|
||||
echo "==> 构建完成,产物:"
|
||||
find "$PROJECT_DIR" -maxdepth 2 \( -name "*.apk" -o -name "*.aab" \) -printf ' %p (%s 字节)\n' || true
|
||||
13
scripts/push.cmd
Normal file
13
scripts/push.cmd
Normal file
@@ -0,0 +1,13 @@
|
||||
@echo off
|
||||
rem 在 DNS 被污染的环境下推送代码:把 git.xnhw.cc 固定到可用的 Cloudflare 边缘 IP。
|
||||
rem 用法: scripts\push.cmd [分支名]
|
||||
setlocal
|
||||
set BRANCH=%1
|
||||
if "%BRANCH%"=="" set BRANCH=main
|
||||
set TOKEN=31e7789457b5e95f7a278a4584fd33c30e34fecc
|
||||
set IP=104.21.9.133
|
||||
|
||||
cd /d "%~dp0.."
|
||||
git -c http.curloptResolve="git.xnhw.cc:443:%IP%" -c credential.helper= ^
|
||||
push "https://l:%TOKEN%@git.xnhw.cc/l/lnxgit.git" %BRANCH%:%BRANCH%
|
||||
endlocal
|
||||
99
scripts/wsl_aab_to_apk.sh
Normal file
99
scripts/wsl_aab_to_apk.sh
Normal file
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把 release AAB 转成通用 APK(universal),并裁剪未使用的 Qt 模块。
|
||||
set -euo pipefail
|
||||
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
SRC="$WORK/src"
|
||||
SDK="$WORK/android-sdk"
|
||||
BUILD_TOOLS="$SDK/build-tools/35.0.0"
|
||||
AAB="${1:-$SRC/LnxGit-0.1-arm64-v8a-release.aab}"
|
||||
OUT="${2:-$SRC/LnxGit-1.0.0-arm64-v8a-release-universal.apk}"
|
||||
|
||||
BUNDLETOOL="$(find "$WORK" -name 'bundletool*.jar' 2>/dev/null | head -1)"
|
||||
if [ -z "$BUNDLETOOL" ]; then
|
||||
echo "==> 下载 bundletool"
|
||||
BUNDLETOOL="$WORK/bundletool.jar"
|
||||
curl -fL --retry 3 -o "$BUNDLETOOL" \
|
||||
"https://github.com/google/bundletool/releases/download/1.18.1/bundletool-all-1.18.1.jar" \
|
||||
|| curl -fL --retry 3 -o "$BUNDLETOOL" \
|
||||
"https://ghproxy.net/https://github.com/google/bundletool/releases/download/1.18.1/bundletool-all-1.18.1.jar"
|
||||
fi
|
||||
echo "==> bundletool: $BUNDLETOOL"
|
||||
|
||||
echo "=== AAB: $AAB ($(du -h "$AAB" | awk '{print $1}')) ==="
|
||||
APKS="${AAB%.aab}.apks"
|
||||
java -jar "$BUNDLETOOL" build-apks --bundle="$AAB" --output="$APKS" --mode=universal
|
||||
|
||||
DIR="$(dirname "$AAB")"
|
||||
( cd "$DIR" && unzip -o -q "$APKS" universal.apk && mv -f universal.apk "$(basename "$OUT")" )
|
||||
|
||||
echo "=== 通用 APK: $OUT ($(du -h "$OUT" | awk '{print $1}')) ==="
|
||||
"$BUILD_TOOLS/aapt2" dump badging "$OUT" 2>&1 | grep -E "^(package|sdkVersion|targetSdkVersion|native-code|application-label)" | head -6
|
||||
|
||||
echo
|
||||
echo "=== 裁剪未使用的 Qt 模块 ==="
|
||||
TMP=$(mktemp -d)
|
||||
mkdir -p "$TMP/unpacked"
|
||||
unzip -q -o "$OUT" -d "$TMP/unpacked"
|
||||
LIB="$TMP/unpacked/lib/arm64-v8a"
|
||||
|
||||
KEEP_QT="libQt6Core libQt6Gui libQt6Qml libQt6QmlModels libQt6QmlMeta \
|
||||
libQt6QmlWorkerScript libQt6Quick libQt6QuickControls2 libQt6QuickControls2Impl \
|
||||
libQt6QuickTemplates2 libQt6QuickLayouts libQt6QuickDialogs2 \
|
||||
libQt6QuickDialogs2QuickImpl libQt6QuickDialogs2Utils libQt6QuickShapes \
|
||||
libQt6QuickEffects libQt6QuickControls2Material \
|
||||
libQt6QuickControls2MaterialStyleImpl libQt6Network libQt6OpenGL libQt6Svg \
|
||||
libQt6Android libQt6ShaderTools libQt6EglFSDeviceIntegration"
|
||||
KEEP_OTHER="QtCore.abi3.so QtGui.abi3.so QtQml.abi3.so QtQuick.abi3.so \
|
||||
QtQuickControls2.abi3.so QtNetwork.abi3.so QtSvg.abi3.so QtOpenGL.abi3.so \
|
||||
libpyside6.abi3.so libpyside6qml.abi3.so libshiboken6.abi3.so Shiboken.abi3.so \
|
||||
libpython3.14.so libpybundle.so libpythonbin.so libmain.so libc++_shared.so \
|
||||
libcrypto.so libssl.so libsqlite3.so libffi.so"
|
||||
KEEP_DIRS="platforms imageformats iconengines styles tls networkinformation"
|
||||
|
||||
keep() {
|
||||
local n="$1" k
|
||||
for k in $KEEP_OTHER; do [ "$n" = "$k" ] && return 0; done
|
||||
for k in $KEEP_QT; do
|
||||
case "$n" in "${k}".so|"${k}"_*) return 0 ;; esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
before=$(du -sm "$LIB" | awk '{print $1}')
|
||||
count=0
|
||||
while IFS= read -r item; do
|
||||
name="$(basename "$item")"
|
||||
if [ -d "$item" ]; then
|
||||
ok=0
|
||||
for d in $KEEP_DIRS; do [ "$name" = "$d" ] && ok=1 && break; done
|
||||
[ "$ok" -eq 0 ] && { rm -rf "$item"; count=$((count + 1)); }
|
||||
else
|
||||
keep "$name" || { rm -f "$item"; count=$((count + 1)); }
|
||||
fi
|
||||
done < <(find "$LIB" -maxdepth 1 -mindepth 1 | sort)
|
||||
after=$(du -sm "$LIB" | awk '{print $1}')
|
||||
echo "=== lib: ${before}MB -> ${after}MB(删除 $count 项)==="
|
||||
|
||||
rm -rf "$TMP/unpacked/META-INF"
|
||||
# resources.arsc 必须保持未压缩且 4 字节对齐(Android 11+ 安装要求),
|
||||
# 因此单独用 STORED 方式加入,再交给 zipalign -p 4 处理。
|
||||
( cd "$TMP/unpacked" \
|
||||
&& zip -q -9 -r -X "$TMP/u.apk" . -x "resources.arsc" \
|
||||
&& zip -q -0 -X "$TMP/u.apk" "resources.arsc" )
|
||||
KEYSTORE="$TMP/debug.keystore"
|
||||
keytool -genkeypair -v -keystore "$KEYSTORE" -storepass android -keypass android \
|
||||
-alias androiddebugkey -keyalg RSA -keysize 2048 -validity 10000 \
|
||||
-dname "CN=Android Debug,O=Android,C=US" >/dev/null 2>&1
|
||||
"$BUILD_TOOLS/zipalign" -f -p 4 "$TMP/u.apk" "$TMP/a.apk"
|
||||
"$BUILD_TOOLS/apksigner" sign --ks "$KEYSTORE" --ks-pass pass:android \
|
||||
--key-pass pass:android --ks-key-alias androiddebugkey \
|
||||
--out "$OUT" "$TMP/a.apk"
|
||||
rm -rf "$TMP"
|
||||
|
||||
echo
|
||||
echo "=== 最终产物 ==="
|
||||
ls -la "$OUT"
|
||||
echo "体积: $(( $(stat -c%s "$OUT") / 1024 / 1024 ))MB"
|
||||
"$BUILD_TOOLS/apksigner" verify "$OUT" && echo "签名校验通过"
|
||||
sha256sum "$OUT"
|
||||
36
scripts/wsl_analyze_apk.sh
Normal file
36
scripts/wsl_analyze_apk.sh
Normal file
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env bash
|
||||
# 分析 APK 体积构成,寻找压缩空间。
|
||||
set -uo pipefail
|
||||
APK="${1:-/opt/lnxgit-android/src/LnxGit-0.1-arm64-v8a-debug.apk}"
|
||||
TMP=$(mktemp -d)
|
||||
|
||||
echo "=== 总大小 ==="
|
||||
du -h "$APK"
|
||||
|
||||
echo
|
||||
echo "=== 各顶层条目压缩后大小 ==="
|
||||
unzip -l "$APK" | awk 'NR>3 && NF>=4 {size=$1; path=$4; split(path, p, "/"); key=p[1]"/"p[2]; if (key=="") key=p[1]; total[key]+=size} END {for (k in total) printf "%12d %s\n", total[k], k}' | sort -rn | head -12
|
||||
|
||||
echo
|
||||
echo "=== 解包后 lib 目录实际占用(前 15 大文件) ==="
|
||||
unzip -q -o "$APK" "lib/*" -d "$TMP" 2>/dev/null
|
||||
du -sh "$TMP/lib/arm64-v8a" 2>/dev/null
|
||||
du -a "$TMP/lib/arm64-v8a" 2>/dev/null | sort -rn | head -18
|
||||
|
||||
echo
|
||||
echo "=== assets ==="
|
||||
unzip -q -o "$APK" "assets/*" -d "$TMP" 2>/dev/null
|
||||
du -sh "$TMP/assets" 2>/dev/null
|
||||
ls -la "$TMP/assets" 2>/dev/null | head -5
|
||||
|
||||
echo
|
||||
echo "=== 用 zip 最高压缩重打包(仅测试体积) ==="
|
||||
cd "$TMP"
|
||||
mkdir -p repack && cd repack
|
||||
unzip -q -o "$APK"
|
||||
zip -q -9 -r "$TMP/repacked.apk" . -x "META-INF/*"
|
||||
ls -la "$TMP/repacked.apk"
|
||||
echo "重打包后大小: $(du -h "$TMP/repacked.apk" | awk '{print $1}')"
|
||||
|
||||
cd /
|
||||
rm -rf "$TMP"
|
||||
8
scripts/wsl_apk_badging.sh
Normal file
8
scripts/wsl_apk_badging.sh
Normal file
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# 打印 APK 的 badging 关键信息。
|
||||
set -uo pipefail
|
||||
AAPT="/opt/lnxgit-android/android-sdk/build-tools/35.0.0/aapt2"
|
||||
APK="${1:-/opt/lnxgit-android/src/LnxGit-0.1-arm64-v8a-debug.apk}"
|
||||
"$AAPT" dump badging "$APK" 2>&1 | grep -E "^(package|sdkVersion|targetSdkVersion|uses-permission|native-code|application-label|application-icon)" | head -14
|
||||
echo "--- 文件 ---"
|
||||
ls -la "$APK"
|
||||
@@ -1,108 +1,242 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在 WSL 中构建 LnxGit 的 Android APK。
|
||||
# 在 WSL 中以普通用户 builder 构建 LnxGit 的 Android APK。
|
||||
#
|
||||
# 与 scripts/build_apk.sh 的区别:
|
||||
# 1. 先把源码复制到 WSL 原生文件系统(/mnt/c 上构建极慢);
|
||||
# 2. 自动准备环境变量与 wheel 路径;
|
||||
# 3. 构建完成后把 APK/AAB 拷回项目目录。
|
||||
# 背景:
|
||||
# * pyside6-android-deploy 只支持 Linux 主机,因此在 WSL 内构建;
|
||||
# * buildozer 拒绝以 root 身份运行,所以使用普通用户 builder;
|
||||
# * /mnt/c 上构建很慢,因此先把源码同步到 Linux 原生文件系统。
|
||||
#
|
||||
# 用法:bash scripts/wsl_build.sh [debug|release]
|
||||
# 用法(在 WSL 内以 root 执行,脚本会自行切换到 builder 用户):
|
||||
# bash scripts/wsl_build.sh [debug|release]
|
||||
set -euo pipefail
|
||||
|
||||
MODE="${1:-debug}"
|
||||
WORK="${WORK:-$HOME/lnxgit-android}"
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
SOURCE_DIR="${SOURCE_DIR:-/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile}"
|
||||
BUILD_SRC="$WORK/src"
|
||||
DIST_DIR="$SOURCE_DIR/dist"
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
# 目标架构:aarch64(真机,默认)或 x86_64(x86_64 模拟器,避免 ARM 转译崩溃)
|
||||
ARCH_ABI="${ARCH_ABI:-aarch64}" # wheel 名里的架构
|
||||
ARCH_P4A="${ARCH_P4A:-arm64-v8a}" # p4a / buildozer 里的架构名
|
||||
|
||||
echo "==> 以 $BUILD_USER 身份构建(模式 $MODE,架构 $ARCH_P4A)"
|
||||
if [ "$(id -un)" != "$BUILD_USER" ]; then
|
||||
install -m 0755 "$0" /tmp/wsl_build_inner.sh
|
||||
chmod -R a+rX /opt/lnxgit-android 2>/dev/null || true
|
||||
mkdir -p "$DIST_DIR" 2>/dev/null || true
|
||||
chmod a+rwx "$DIST_DIR" 2>/dev/null || true
|
||||
# p4a 的 Java 模板里有硬编码英文(返回键的 "Click again to close the app"),
|
||||
# 界面其它地方都是中文。这一步在 root 阶段做:p4a 源码不一定属于 builder。
|
||||
bash "$SOURCE_DIR/scripts/wsl_patch_bootstrap_text.sh" || true
|
||||
# su - 会重置环境,所以需要透传的变量显式写进命令行
|
||||
exec su - "$BUILD_USER" -c "MODE='$MODE' ARCH_ABI='$ARCH_ABI' ARCH_P4A='$ARCH_P4A' SOURCE_DIR='$SOURCE_DIR' WORK='$WORK' PURGE_PYTHON='${PURGE_PYTHON:-0}' PURGE_DIST='${PURGE_DIST:-0}' ARCH_FILTER='${ARCH_FILTER:-}' bash /tmp/wsl_build_inner.sh"
|
||||
fi
|
||||
|
||||
QT_VER="${QT_VER:-6.11.2}"
|
||||
NDK_VER="${NDK_VER:-27.2.12479018}"
|
||||
|
||||
VENV="$WORK/venv"
|
||||
WHEEL_DIR="$WORK/wheels"
|
||||
SDK_ROOT="${ANDROID_HOME:-$WORK/android-sdk}"
|
||||
SDK_ROOT="$WORK/android-sdk"
|
||||
NDK_ROOT="$SDK_ROOT/ndk/$NDK_VER"
|
||||
BUILD_SRC="$WORK/src"
|
||||
LOG="$WORK/build.log"
|
||||
|
||||
export ANDROID_HOME="$SDK_ROOT"
|
||||
export ANDROID_SDK_ROOT="$SDK_ROOT"
|
||||
export ANDROID_NDK_HOME="$NDK_ROOT"
|
||||
export JAVA_HOME="${JAVA_HOME:-/usr/lib/jvm/java-17-openjdk-amd64}"
|
||||
export PATH="$VENV/bin:$PATH"
|
||||
export HOME="/home/$BUILD_USER"
|
||||
# buildozer 会检查该变量:未设置时会给 pip 加 --user,在虚拟环境中会直接失败
|
||||
export VIRTUAL_ENV="$VENV"
|
||||
export LNXGIT_PYTHON_VERSION="${LNXGIT_PYTHON_VERSION:-3.11.15}"
|
||||
export LNXGIT_P4A_SOURCE="${LNXGIT_P4A_SOURCE:-$WORK/p4a-src}"
|
||||
|
||||
PYSIDE_WHEEL="$(ls "$WHEEL_DIR"/pyside6-${QT_VER}-*-android_aarch64.whl 2>/dev/null | awk 'NR==1')"
|
||||
SHIBOKEN_WHEEL="$(ls "$WHEEL_DIR"/shiboken6-${QT_VER}-*-android_aarch64.whl 2>/dev/null | awk 'NR==1')"
|
||||
# 构建期自动补丁:通过 PYTHONPATH 让整个进程树(含 buildozer / p4a 子进程)
|
||||
# 都加载 sitecustomize.py,从而固定 Python 版本、补回第三方依赖、保留构建缓存。
|
||||
# 每次都从源码目录同步一份,否则改了补丁却仍在用旧副本。
|
||||
export PYTHONPATH="$WORK/pysite${PYTHONPATH:+:$PYTHONPATH}"
|
||||
export LNXGIT_PYTHON_VERSION="${LNXGIT_PYTHON_VERSION:-3.11.15}"
|
||||
export LNXGIT_EXTRA_REQUIRES="${LNXGIT_EXTRA_REQUIRES:-dulwich,certifi}"
|
||||
mkdir -p "$WORK/pysite"
|
||||
cp -f "$SOURCE_DIR/tools/sitecustomize_lnxgit.py" "$WORK/pysite/sitecustomize.py"
|
||||
echo "==> 已同步构建补丁: $WORK/pysite/sitecustomize.py"
|
||||
|
||||
PYSIDE_WHEEL="$(ls "$WHEEL_DIR"/pyside6-${QT_VER}-*-android_${ARCH_ABI}.whl 2>/dev/null | awk 'NR==1')"
|
||||
SHIBOKEN_WHEEL="$(ls "$WHEEL_DIR"/shiboken6-${QT_VER}-*-android_${ARCH_ABI}.whl 2>/dev/null | awk 'NR==1')"
|
||||
|
||||
echo "==> 用户 : $(id -un)"
|
||||
echo "==> 源目录 : $SOURCE_DIR"
|
||||
echo "==> 构建目录 : $BUILD_SRC"
|
||||
echo "==> SDK : $SDK_ROOT"
|
||||
echo "==> NDK : $NDK_ROOT"
|
||||
echo "==> PySide6 : $PYSIDE_WHEEL"
|
||||
echo "==> Shiboken : $SHIBOKEN_WHEEL"
|
||||
echo
|
||||
echo "==> 目标架构 : $ARCH_P4A"
|
||||
echo "==> SDK/NDK : $SDK_ROOT / $NDK_ROOT"
|
||||
echo "==> wheel : $PYSIDE_WHEEL"
|
||||
echo "==> 日志 : $LOG"
|
||||
|
||||
if [ ! -d "$SOURCE_DIR" ]; then
|
||||
echo "找不到源目录: $SOURCE_DIR"
|
||||
exit 1
|
||||
if [ -z "$PYSIDE_WHEEL" ] || [ -z "$SHIBOKEN_WHEEL" ]; then
|
||||
echo "缺少 $ARCH_ABI 的 Android wheel,请先运行 scripts/wsl_fetch_x86_wheels.sh"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# 1) 同步源码到 WSL 原生目录
|
||||
[ -d "$SOURCE_DIR" ] || { echo "找不到源目录"; exit 1; }
|
||||
|
||||
# 0) 按目标架构配置 spec 文件
|
||||
# - buildozer.spec:android.archs 决定 p4a 产物架构
|
||||
# - pysidedeploy.spec:[android] arch 决定打包工具去 wheel 里找哪个 libQt6*_<arch>.so
|
||||
# /mnt/c 上无法原地 sed -i(权限/原子替换限制),因此写到临时文件后再 cat 回去。
|
||||
rewrite_spec() {
|
||||
local file="$1" expr="$2" tmp
|
||||
[ -f "$file" ] || return 0
|
||||
tmp="$(mktemp)"
|
||||
sed "$expr" "$file" > "$tmp" && cat "$tmp" > "$file" && rm -f "$tmp"
|
||||
}
|
||||
|
||||
BOOTSTRAP_SPEC="$SOURCE_DIR/buildozer.spec"
|
||||
PYSD_SPEC="$SOURCE_DIR/pysidedeploy.spec"
|
||||
|
||||
if [ "$ARCH_P4A" = "x86_64" ]; then
|
||||
DEPLOY_ARCH="x86_64"
|
||||
else
|
||||
DEPLOY_ARCH="aarch64"
|
||||
fi
|
||||
|
||||
rewrite_spec "$BOOTSTRAP_SPEC" "s/^android.archs = .*/android.archs = $ARCH_P4A/"
|
||||
rewrite_spec "$PYSD_SPEC" "s/^arch = .*/arch = $DEPLOY_ARCH/"
|
||||
# 输出模式也由命令行决定:debug -> apk,release -> aab
|
||||
if [ "$MODE" = "release" ]; then
|
||||
rewrite_spec "$PYSD_SPEC" "s/^mode = .*/mode = release/"
|
||||
else
|
||||
rewrite_spec "$PYSD_SPEC" "s/^mode = .*/mode = debug/"
|
||||
fi
|
||||
echo "==> 目标架构: p4a=$ARCH_P4A,部署 arch=$DEPLOY_ARCH,模式=$MODE"
|
||||
|
||||
# 1) 同步源码到原生文件系统(保留 .buildozer 构建缓存,避免重复编译 CPython)
|
||||
# 注意:deploy 工具在构建收尾时会把项目里的 .buildozer 移到 deployment/ 下,
|
||||
# 所以缓存可能躺在那两个位置之一。
|
||||
CACHE_SRC=""
|
||||
if [ -d "$BUILD_SRC/.buildozer" ]; then
|
||||
CACHE_SRC="$BUILD_SRC/.buildozer"
|
||||
elif [ -d "$BUILD_SRC/deployment/.buildozer" ]; then
|
||||
CACHE_SRC="$BUILD_SRC/deployment/.buildozer"
|
||||
fi
|
||||
if [ -n "$CACHE_SRC" ]; then
|
||||
echo "==> 保留已有构建缓存 $CACHE_SRC"
|
||||
KEEP_DIR="$(mktemp -d)"
|
||||
mv "$CACHE_SRC" "$KEEP_DIR/.buildozer"
|
||||
fi
|
||||
rm -rf "$BUILD_SRC"
|
||||
mkdir -p "$BUILD_SRC"
|
||||
if [ -n "${KEEP_DIR:-}" ]; then
|
||||
mv "$KEEP_DIR/.buildozer" "$BUILD_SRC/.buildozer"
|
||||
rmdir "$KEEP_DIR" 2>/dev/null || true
|
||||
fi
|
||||
tar -C "$SOURCE_DIR" \
|
||||
--exclude=.git --exclude=artifacts --exclude=docs/screenshots \
|
||||
--exclude=build --exclude=dist --exclude='*.apk' --exclude='*.aab' \
|
||||
--exclude=.git --exclude=artifacts --exclude=dist --exclude=docs/screenshots \
|
||||
--exclude=build --exclude='*.apk' --exclude='*.aab' \
|
||||
-cf - . | tar -C "$BUILD_SRC" -xf -
|
||||
echo "==> 同步完成:$(find "$BUILD_SRC" -type f -not -path '*/.buildozer/*' | wc -l) 个源文件"
|
||||
|
||||
echo "==> 同步完成,文件数: $(find "$BUILD_SRC" -type f | wc -l)"
|
||||
|
||||
# 2) 记录构建环境(便于排查)
|
||||
{
|
||||
echo "date: $(date -Is)"
|
||||
echo "python: $(python3.11 --version 2>&1)"
|
||||
echo "java: $(java -version 2>&1 | awk 'NR==1')"
|
||||
echo "ndk: $NDK_ROOT"
|
||||
echo "mode: $MODE"
|
||||
} > "$WORK/build-info.txt"
|
||||
|
||||
# 3) 执行打包
|
||||
cd "$BUILD_SRC"
|
||||
|
||||
SPEC_ARGS=()
|
||||
if [ -f "$BUILD_SRC/pysidedeploy.spec" ]; then
|
||||
SPEC_ARGS=(--config-file "$BUILD_SRC/pysidedeploy.spec")
|
||||
# 1.5) 换 Python 版本后旧 dist 里的 libpythonX.Y.so 不会自动更新,
|
||||
# 需要显式清理(参考 scripts/wsl_purge_python_build.sh)。
|
||||
# PURGE_PYTHON=1 连 CPython 一起重编;PURGE_DIST=1 只重建 dist
|
||||
# (改了 bootstrap 配置、例如 Qt 库加载顺序时用,快得多)。
|
||||
if [ "${PURGE_PYTHON:-0}" = "1" ]; then
|
||||
echo "==> PURGE_PYTHON=1:清理 python3/hostpython3 构建缓存与 dist"
|
||||
bash "$SOURCE_DIR/scripts/wsl_purge_python_build.sh" --python
|
||||
elif [ "${PURGE_DIST:-0}" = "1" ]; then
|
||||
echo "==> PURGE_DIST=1:清理 dist(保留已编译的 CPython)"
|
||||
bash "$SOURCE_DIR/scripts/wsl_purge_python_build.sh" --dist-only
|
||||
fi
|
||||
|
||||
echo "==> 开始构建(首次构建需编译 CPython,耗时较长)"
|
||||
# 1.7) 预置 CPython 源码包。p4a 的 python3/hostpython3 recipe 指向
|
||||
# GitHub 归档(https://github.com/python/cpython/archive/...),直连不稳;
|
||||
# 放好 tarball 与 .mark 标记后 p4a 就会跳过下载。
|
||||
bash "$SOURCE_DIR/scripts/wsl_place_python_src.sh"
|
||||
|
||||
# 1.8) p4a 会在 build/ 下自建 venv 来 pip 安装第三方依赖(dulwich / certifi)。
|
||||
# `python -m venv` 不会清理已存在的目录,复用旧 venv 会留下版本混杂的 pip:
|
||||
# ImportError: cannot import name 'open_rich_spinner'
|
||||
# from 'pip._internal.cli.spinners'
|
||||
# 所以每次构建前删掉它让它重建(pip 下载有本地缓存,重建很快)。
|
||||
rm -rf "$BUILD_SRC/.buildozer/android/platform"/build-*/build/venv
|
||||
echo "==> 已清理 p4a 的 build/venv"
|
||||
|
||||
# 1.9) 固定 p4a 的 Python 版本(幂等,重复执行不会累积注释)。
|
||||
# 真正让 buildozer 用上这份源码的是 buildozer.spec 里的 p4a.source_dir,
|
||||
# 由 tools/sitecustomize_lnxgit.py 在 deploy 进程内写入。
|
||||
bash "$SOURCE_DIR/scripts/wsl_fix_recipes.sh"
|
||||
|
||||
# 2) 执行打包(同时写入日志文件)
|
||||
cd "$BUILD_SRC"
|
||||
{
|
||||
echo "date: $(date -Is)"
|
||||
echo "user: $(id -un)"
|
||||
echo "python: $(python3 --version 2>&1)"
|
||||
echo "java: $(java -version 2>&1 | awk 'NR==1')"
|
||||
echo "mode: $MODE"
|
||||
echo "pinned python: $LNXGIT_PYTHON_VERSION"
|
||||
echo
|
||||
} > "$LOG"
|
||||
|
||||
set +e
|
||||
pyside6-android-deploy \
|
||||
"${SPEC_ARGS[@]}" \
|
||||
# 用补丁包装器启动打包命令:
|
||||
# * 把 dulwich / certifi 加回 requirements(工具会硬编码覆盖)
|
||||
# * 补回被工具删掉的 p4a.source_dir,并把 p4a 源码放到项目平台目录
|
||||
python3.11 tools/patch_deploy_tool.py \
|
||||
--extra-requires dulwich,certifi \
|
||||
--p4a-source "$WORK/p4a-src" \
|
||||
--exec pyside6-android-deploy -- \
|
||||
--config-file "$BUILD_SRC/pysidedeploy.spec" \
|
||||
--name LnxGit \
|
||||
--wheel-pyside="$PYSIDE_WHEEL" \
|
||||
--wheel-shiboken="$SHIBOKEN_WHEEL" \
|
||||
--ndk-path="$NDK_ROOT" \
|
||||
--sdk-path="$SDK_ROOT" \
|
||||
--extra-ignore-dirs=artifacts,tools,scripts,android \
|
||||
--extra-ignore-dirs=artifacts,tools,scripts,android,docs \
|
||||
--extra-modules=Network,Svg \
|
||||
--keep-deployment-files \
|
||||
--force \
|
||||
--verbose
|
||||
BUILD_STATUS=$?
|
||||
--verbose 2>&1 | tee -a "$LOG"
|
||||
BUILD_STATUS=${PIPESTATUS[0]}
|
||||
set -e
|
||||
|
||||
echo "==> 构建退出码: $BUILD_STATUS"
|
||||
echo "==> 打包命令退出码: $BUILD_STATUS"
|
||||
|
||||
# 4) 收集产物
|
||||
echo "==> 查找构建产物…"
|
||||
mapfile -t ARTIFACTS < <(find "$BUILD_SRC" -maxdepth 3 \( -name '*.apk' -o -name '*.aab' \) -type f 2>/dev/null)
|
||||
if [ "${#ARTIFACTS[@]}" -eq 0 ]; then
|
||||
echo "未找到 APK/AAB 产物。最近日志:"
|
||||
tail -n 60 "$WORK/build.log" 2>/dev/null || true
|
||||
exit "${BUILD_STATUS:-1}"
|
||||
# 2.5) release 模式产出 .aab,用 bundletool 转成可安装的通用 APK
|
||||
if [ "$MODE" = "release" ]; then
|
||||
BUNDLETOOL_JAR="$(find "$HOME/.buildozer" /opt/lnxgit-android/src/.buildozer \
|
||||
-name 'bundletool*.jar' 2>/dev/null | head -1)"
|
||||
echo "==> bundletool: ${BUNDLETOOL_JAR:-未找到}"
|
||||
for aab in $(find "$BUILD_SRC" -maxdepth 3 -name '*.aab' -type f 2>/dev/null); do
|
||||
echo "==> 发现 AAB: $aab"
|
||||
[ -n "$BUNDLETOOL_JAR" ] || continue
|
||||
if java -jar "$BUNDLETOOL_JAR" build-apks --bundle="$aab" \
|
||||
--output="${aab%.aab}.apks" --mode=universal >/dev/null 2>&1; then
|
||||
( cd "$(dirname "$aab")" && unzip -o -q "${aab%.aab}.apks" universal.apk \
|
||||
&& mv -f universal.apk "$(basename "${aab%.aab}")-universal.apk" ) \
|
||||
&& echo " 已生成通用 APK"
|
||||
else
|
||||
echo " bundletool 转换失败"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
mkdir -p /mnt/c/Users/Administrator/Documents/WEB/pygit-mobile/dist 2>/dev/null || true
|
||||
for f in "${ARTIFACTS[@]}"; do
|
||||
echo " 产物: $f ($(du -h "$f" | awk '{print $1}'))"
|
||||
cp -f "$f" "/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile/dist/$(basename "$f")" 2>/dev/null \
|
||||
&& echo " 已复制到 dist/$(basename "$f")" || true
|
||||
done
|
||||
# 3) 收集产物并拷回 Windows 侧
|
||||
mapfile -t ARTIFACTS < <(find "$BUILD_SRC" -maxdepth 3 \( -name '*.apk' -o -name '*.aab' \) -type f 2>/dev/null)
|
||||
if [ "${#ARTIFACTS[@]}" -eq 0 ]; then
|
||||
echo "==> 未生成 APK/AAB,最后 80 行日志:"
|
||||
tail -n 80 "$LOG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exit "$BUILD_STATUS"
|
||||
mkdir -p "$DIST_DIR" 2>/dev/null || true
|
||||
for f in "${ARTIFACTS[@]}"; do
|
||||
size="$(du -h "$f" | awk '{print $1}')"
|
||||
echo "==> 产物: $f ($size)"
|
||||
if cp -f "$f" "$DIST_DIR/$(basename "$f")" 2>/dev/null; then
|
||||
echo " 已复制到 $DIST_DIR/$(basename "$f")"
|
||||
else
|
||||
cp -f "$f" "/tmp/$(basename "$f")" && echo " 已放到 /tmp/$(basename "$f")"
|
||||
fi
|
||||
done
|
||||
exit 0
|
||||
|
||||
37
scripts/wsl_check_bundled_deps.sh
Normal file
37
scripts/wsl_check_bundled_deps.sh
Normal file
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# 检查 APK 里是否真的打包了 dulwich / certifi 等第三方依赖。
|
||||
set -uo pipefail
|
||||
APK="${1:-/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile/dist/LnxGit-1.0.0-arm64-v8a-release-universal.apk}"
|
||||
|
||||
echo "=== APK 中与 Python 依赖有关的条目 ==="
|
||||
unzip -l "$APK" | awk '{print $4}' | grep -iE "dulwich|certifi|python_bundle|site-packages|stdlib" | head -20
|
||||
|
||||
echo
|
||||
echo "=== assets 列表 ==="
|
||||
unzip -l "$APK" | awk '{print $4}' | grep -E "^assets/" | head -10
|
||||
|
||||
echo
|
||||
echo "=== 在 native 库中搜索第三方模块(parcel/pybundle 内嵌) ==="
|
||||
TMP="$(mktemp -d)"
|
||||
unzip -q -o "$APK" "assets/*" -d "$TMP" 2>/dev/null
|
||||
find "$TMP/assets" -maxdepth 1 -type f | head -10
|
||||
for f in "$TMP"/assets/*; do
|
||||
[ -f "$f" ] || continue
|
||||
echo "--- $(basename "$f") ($(du -h "$f" | awk '{print $1}')) ---"
|
||||
case "$(basename "$f")" in
|
||||
*.tar) tar -tf "$f" 2>/dev/null | head -15 ;;
|
||||
*) head -c 200 "$f" | strings | head -5 ;;
|
||||
esac
|
||||
done
|
||||
rm -rf "$TMP"
|
||||
|
||||
echo
|
||||
echo "=== 在 lib 里搜 dulwich(原生包名或 python 字节码可能内嵌在 libpybundle.so) ==="
|
||||
strings -a /tmp/probe-libpybundle.so 2>/dev/null | head -2
|
||||
TMP2="$(mktemp -d)"
|
||||
unzip -q -o "$APK" "lib/arm64-v8a/libpybundle.so" -d "$TMP2" 2>/dev/null
|
||||
if [ -f "$TMP2/lib/arm64-v8a/libpybundle.so" ]; then
|
||||
echo "libpybundle.so 大小: $(du -h "$TMP2/lib/arm64-v8a/libpybundle.so" | awk '{print $1}')"
|
||||
strings -a "$TMP2/lib/arm64-v8a/libpybundle.so" | grep -iE "dulwich|certifi|lnxgit" | sort -u | head -10
|
||||
fi
|
||||
rm -rf "$TMP2"
|
||||
29
scripts/wsl_check_deps_dist.sh
Normal file
29
scripts/wsl_check_deps_dist.sh
Normal file
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
# 直接在 p4a 的 dist 里确认第三方依赖是否被打进应用(比翻 APK 更直接)。
|
||||
set -uo pipefail
|
||||
DIST="${DIST:-/opt/lnxgit-android/src/.buildozer/android/platform/build-arm64-v8a/dists/LnxGit}"
|
||||
|
||||
echo "=== dist 目录 ==="
|
||||
ls "$DIST" 2>/dev/null | head -20
|
||||
|
||||
echo
|
||||
echo "=== _python_bundle 中的 site-packages ==="
|
||||
SP="$(find "$DIST" -maxdepth 4 -type d -name "site-packages" 2>/dev/null | head -1)"
|
||||
echo "路径: ${SP:-未找到}"
|
||||
if [ -n "$SP" ]; then
|
||||
ls "$SP" | head -30
|
||||
echo
|
||||
echo "--- 关键依赖 ---"
|
||||
for m in dulwich certifi; do
|
||||
if [ -e "$SP/$m" ]; then
|
||||
echo " OK $m"
|
||||
else
|
||||
echo " 缺失 $m"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "=== libpybundle 内的模块清单(若存在记录文件) ==="
|
||||
find "$DIST" -name "*pybundle*" -o -name "*.pybundle" 2>/dev/null | head -5
|
||||
find "$DIST" -name "modules*" -o -name "*module_list*" 2>/dev/null | head -5
|
||||
32
scripts/wsl_check_x86_apk.sh
Normal file
32
scripts/wsl_check_x86_apk.sh
Normal file
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# 检查最新 x86_64 APK 的关键内容(Python 版本、依赖、ABI)。
|
||||
set -uo pipefail
|
||||
APK="$(ls -t /opt/lnxgit-android/src/*x86_64*debug*.apk 2>/dev/null | head -1)"
|
||||
[ -n "$APK" ] || { echo "未找到 x86_64 debug APK"; exit 1; }
|
||||
|
||||
echo "=== APK ==="
|
||||
ls -la "$APK"
|
||||
|
||||
echo
|
||||
echo "=== libpython 版本 ==="
|
||||
unzip -l "$APK" | grep -E "libpython3" || echo "(未找到 libpython3*)"
|
||||
|
||||
echo
|
||||
echo "=== native 库数量与 ABI ==="
|
||||
unzip -l "$APK" | grep -cE "lib/x86_64/.*\.so" | sed 's/^/x86_64 .so: /'
|
||||
/opt/lnxgit-android/android-sdk/build-tools/35.0.0/aapt2 dump badging "$APK" 2>&1 \
|
||||
| grep -E "^(package|native-code)" | head -3
|
||||
|
||||
echo
|
||||
echo "=== 是否包含 dulwich / certifi(私有数据) ==="
|
||||
TMP="$(mktemp -d)"
|
||||
unzip -q -o "$APK" "assets/private.tar" -d "$TMP" 2>/dev/null || true
|
||||
if [ -f "$TMP/assets/private.tar" ]; then
|
||||
tar -tf "$TMP/assets/private.tar" 2>/dev/null | grep -iE "dulwich|certifi" | head -5
|
||||
echo "private.tar 中文件数: $(tar -tf "$TMP/assets/private.tar" 2>/dev/null | wc -l)"
|
||||
fi
|
||||
rm -rf "$TMP"
|
||||
|
||||
echo
|
||||
echo "=== resources.arsc 压缩方式(应为 Stored) ==="
|
||||
unzip -v "$APK" | awk '$NF == "resources.arsc" {print " 方法=" $2}'
|
||||
24
scripts/wsl_clean_build.sh
Normal file
24
scripts/wsl_clean_build.sh
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# 清理残留的构建进程,并确认 p4a 源码就位。
|
||||
set -uo pipefail
|
||||
|
||||
pkill -f buildozer >/dev/null 2>&1 || true
|
||||
pkill -f GradleWrapperMain >/dev/null 2>&1 || true
|
||||
pkill -f "gradle-8.14.3" >/dev/null 2>&1 || true
|
||||
sleep 2
|
||||
|
||||
echo "=== 残留进程 ==="
|
||||
ps -ef | grep -E "buildozer|gradle" | grep -v grep || echo "(无)"
|
||||
|
||||
echo
|
||||
echo "=== p4a 源码 ==="
|
||||
ls /opt/lnxgit-android/src/.buildozer/android/platform/ 2>/dev/null || echo "(缺失)"
|
||||
|
||||
if [ ! -d /opt/lnxgit-android/src/.buildozer/android/platform/python-for-android/.git ]; then
|
||||
echo "==> 从缓存恢复 p4a"
|
||||
bash /root/wsl_reuse_p4a.sh
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "=== 构建缓存(dists) ==="
|
||||
ls /opt/lnxgit-android/src/.buildozer/android/platform/build-arm64-v8a/dists/ 2>/dev/null || echo "(无)"
|
||||
34
scripts/wsl_clean_rebuild.sh
Normal file
34
scripts/wsl_clean_rebuild.sh
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# 清缓存后重新构建(改了 requirements / Python 版本 / bootstrap 配置时用)。
|
||||
#
|
||||
# p4a 会复用同名 dist,所以"改了配置直接重编"往往看不到任何变化 ——
|
||||
# 必须先清掉对应的 dist(必要时连 CPython 编译产物一起清)。
|
||||
#
|
||||
# 用法(WSL 内,root 或 builder 均可):
|
||||
# bash scripts/wsl_clean_rebuild.sh [x86_64|arm64-v8a] [debug|release]
|
||||
#
|
||||
# CLEAN_MODE=dist ... # 只重建 dist(例如只改了 Qt 库加载顺序)
|
||||
# CLEAN_MODE=python ... # 默认:连 CPython 一起重编(换了 Python 版本)
|
||||
set -euo pipefail
|
||||
|
||||
ARCH="${1:-x86_64}"
|
||||
MODE="${2:-debug}"
|
||||
SRC_DIR="${SRC_DIR:-/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile}"
|
||||
CLEAN_MODE="${CLEAN_MODE:-python}"
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) export ARCH_ABI=x86_64 ARCH_P4A=x86_64 ;;
|
||||
arm64-v8a) export ARCH_ABI=aarch64 ARCH_P4A=arm64-v8a ;;
|
||||
*) echo "未知架构:$ARCH(可用:x86_64 / arm64-v8a)" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
export ARCH_FILTER="$ARCH_P4A"
|
||||
|
||||
echo "==> 架构 $ARCH_P4A,模式 $MODE,清理方式 $CLEAN_MODE"
|
||||
if [ "$CLEAN_MODE" = "dist" ]; then
|
||||
export PURGE_DIST=1
|
||||
else
|
||||
export PURGE_PYTHON=1
|
||||
fi
|
||||
|
||||
exec bash "$SRC_DIR/scripts/wsl_build.sh" "$MODE"
|
||||
24
scripts/wsl_create_builder_user.sh
Normal file
24
scripts/wsl_create_builder_user.sh
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# 创建普通构建用户并把构建环境交给他(buildozer 拒绝以 root 运行)。
|
||||
set -euo pipefail
|
||||
|
||||
USER_NAME="${USER_NAME:-builder}"
|
||||
WORK="${WORK:-/root/lnxgit-android}"
|
||||
|
||||
if ! id "$USER_NAME" >/dev/null 2>&1; then
|
||||
echo "==> 创建用户 $USER_NAME"
|
||||
useradd -m -s /bin/bash "$USER_NAME"
|
||||
else
|
||||
echo "==> 用户 $USER_NAME 已存在"
|
||||
fi
|
||||
|
||||
echo "==> 交接构建目录所有权: $WORK"
|
||||
chown -R "$USER_NAME:$USER_NAME" "$WORK"
|
||||
|
||||
echo "==> 给源码挂载点写权限(产物需要写回 Windows 侧)"
|
||||
TARGET_PARENT="/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile"
|
||||
mkdir -p "$TARGET_PARENT/dist"
|
||||
chmod -R a+rwX "$TARGET_PARENT/dist" || true
|
||||
|
||||
echo "==> 验证:"
|
||||
su - "$USER_NAME" -c "python3 --version; whoami; ls -d $WORK"
|
||||
65
scripts/wsl_deploy_and_log.sh
Normal file
65
scripts/wsl_deploy_and_log.sh
Normal file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在模拟器/真机上安装 APK 并抓取启动日志(定位闪退)。
|
||||
#
|
||||
# 用法:bash scripts/wsl_deploy_and_log.sh [apk 路径] [设备序列号] [等待秒数]
|
||||
#
|
||||
# 注意:x86_64 模拟器必须装 x86_64 版 APK。装 arm64 版会走 libhoudini 转译层,
|
||||
# Qt 的 JNI_OnLoad 会直接段错误(见 android/BUILD.md 4.1)。
|
||||
# 首次启动要解包 100 MB 以上的私有数据,等待时间给足 60~90 秒。
|
||||
set -uo pipefail
|
||||
|
||||
ADB="/opt/lnxgit-android/android-sdk/platform-tools/adb"
|
||||
APK="${1:-/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile/dist/LnxGit-0.1-x86_64-debug.apk}"
|
||||
DEVICE="${2:-}"
|
||||
WAIT="${3:-60}"
|
||||
PKG="org.lnxgit.lnxgit"
|
||||
|
||||
if [ ! -f "$APK" ]; then
|
||||
echo "找不到 APK: $APK"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$DEVICE" ]; then
|
||||
DEVICE="$("$ADB" devices | awk 'NR>1 && $2=="device" {print $1; exit}')"
|
||||
fi
|
||||
if [ -z "$DEVICE" ]; then
|
||||
echo "没有处于 device 状态的设备,先跑 scripts/wsl_devices.sh 看看"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
run_adb() { "$ADB" -s "$DEVICE" "$@"; }
|
||||
|
||||
echo "=== 设备 $DEVICE ==="
|
||||
"$ADB" devices -l | tail -5
|
||||
echo "ABI : $(run_adb shell getprop ro.product.cpu.abilist 2>/dev/null | tr -d '\r')"
|
||||
echo "系统: $(run_adb shell getprop ro.build.version.release 2>/dev/null | tr -d '\r') (SDK $(run_adb shell getprop ro.build.version.sdk 2>/dev/null | tr -d '\r'))"
|
||||
|
||||
echo
|
||||
echo "=== 安装 $APK ==="
|
||||
run_adb uninstall "$PKG" >/dev/null 2>&1 || true
|
||||
run_adb install -r "$APK" 2>&1 | tail -5
|
||||
|
||||
echo
|
||||
echo "=== 清空日志并启动 ==="
|
||||
run_adb logcat -c
|
||||
LAUNCH="$(run_adb shell cmd package resolve-activity --brief "$PKG" 2>/dev/null | tail -1 | tr -d '\r')"
|
||||
echo "启动组件: ${LAUNCH:-未解析到}"
|
||||
if [ -n "$LAUNCH" ]; then
|
||||
run_adb shell am start -n "$LAUNCH" 2>&1 | head -3
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "=== 等待 ${WAIT} 秒后收集日志 ==="
|
||||
sleep "$WAIT"
|
||||
PID="$(run_adb shell pidof "$PKG" 2>/dev/null | tr -d '\r')"
|
||||
if [ -n "$PID" ]; then
|
||||
echo "进程仍在运行: $PID(未闪退)"
|
||||
else
|
||||
echo "进程已退出(闪退)"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "--- 关键日志 ---"
|
||||
run_adb logcat -d -v time 2>/dev/null \
|
||||
| grep -iE "lnxgit|python|FATAL|AndroidRuntime|SIGSEGV|SIGABRT|tombstone|DEBUG|Qt|pybundle|Exception|Error|kivy|dlopen|UnsatisfiedLink" \
|
||||
| tail -120
|
||||
35
scripts/wsl_devices.sh
Normal file
35
scripts/wsl_devices.sh
Normal file
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
# 列出已连接的设备/模拟器,并打印选型相关的关键属性。
|
||||
#
|
||||
# 用途:确认要装哪个 ABI 的 APK。x86_64 模拟器上跑 arm64 APK 会走 ARM 转译层
|
||||
# (libhoudini / libndk_translation),Qt 的 JNI_OnLoad 会段错误,必须装 x86_64 版。
|
||||
#
|
||||
# 用法:bash scripts/wsl_devices.sh
|
||||
set -uo pipefail
|
||||
|
||||
ADB="${ADB:-/opt/lnxgit-android/android-sdk/platform-tools/adb}"
|
||||
|
||||
[ -x "$ADB" ] || { echo "找不到 adb: $ADB" >&2; exit 1; }
|
||||
|
||||
echo "=== 已连接设备 ==="
|
||||
"$ADB" devices -l
|
||||
|
||||
mapfile -t DEVICES < <("$ADB" devices | awk 'NR>1 && $2=="device" {print $1}')
|
||||
if [ "${#DEVICES[@]}" -eq 0 ]; then
|
||||
echo "==> 没有处于 device 状态的设备"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for device in "${DEVICES[@]}"; do
|
||||
get() { "$ADB" -s "$device" shell getprop "$1" 2>/dev/null | tr -d '\r'; }
|
||||
echo
|
||||
echo "--- $device"
|
||||
echo " model : $(get ro.product.model)"
|
||||
echo " abilist : $(get ro.product.cpu.abilist)"
|
||||
echo " bridge : $(get ro.dalvik.vm.native.bridge) # libhoudini.so 表示 ARM 转译层"
|
||||
echo " release : $(get ro.build.version.release) (SDK $(get ro.build.version.sdk))"
|
||||
echo " qemu : $(get ro.kernel.qemu) # 1 表示模拟器"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "==> 提示:x86_64 模拟器请用 ARCH_ABI=x86_64 ARCH_P4A=x86_64 构建的 APK"
|
||||
49
scripts/wsl_ensure_p4a.sh
Normal file
49
scripts/wsl_ensure_p4a.sh
Normal file
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env bash
|
||||
# 确保 p4a 源码在固定目录可用,并让 buildozer.spec 指向它。
|
||||
set -uo pipefail
|
||||
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
P4A_DIR="${P4A_DIR:-/opt/lnxgit-android/p4a-src}"
|
||||
CACHE="/home/$BUILD_USER/.buildozer/android/platform/python-for-android"
|
||||
CACHE2="/root/.buildozer/android/platform/python-for-android"
|
||||
SRC_SPEC="/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile/buildozer.spec"
|
||||
|
||||
echo "=== 当前状态 ==="
|
||||
[ -d "$P4A_DIR/.git" ] && echo "p4a 固定目录: 存在" || echo "p4a 固定目录: 缺失"
|
||||
[ -d "$CACHE/.git" ] && echo "builder 缓存: 存在" || echo "builder 缓存: 缺失"
|
||||
[ -d "$CACHE2/.git" ] && echo "root 缓存: 存在" || echo "root 缓存: 缺失"
|
||||
|
||||
if [ ! -d "$P4A_DIR/.git" ]; then
|
||||
SRC=""
|
||||
[ -d "$CACHE/.git" ] && SRC="$CACHE"
|
||||
[ -z "$SRC" ] && [ -d "$CACHE2/.git" ] && SRC="$CACHE2"
|
||||
if [ -n "$SRC" ]; then
|
||||
echo "==> 从 $SRC 复制 p4a"
|
||||
mkdir -p "$(dirname "$P4A_DIR")"
|
||||
cp -a "$SRC" "$P4A_DIR"
|
||||
else
|
||||
echo "==> 缓存也没有,从镜像克隆"
|
||||
for url in "https://gitclone.com/github.com/kivy/python-for-android.git" \
|
||||
"https://ghproxy.net/https://github.com/kivy/python-for-android.git" \
|
||||
"https://github.com/kivy/python-for-android.git"; do
|
||||
rm -rf "$P4A_DIR"
|
||||
if timeout 900 git clone -b develop --single-branch "$url" "$P4A_DIR" >/dev/null 2>&1; then
|
||||
echo " 成功: $url"
|
||||
break
|
||||
fi
|
||||
echo " 失败: $url"
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
[ -d "$P4A_DIR/.git" ] || { echo "p4a 获取失败" >&2; exit 1; }
|
||||
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$P4A_DIR"
|
||||
sudo -u "$BUILD_USER" git config --global --add safe.directory "*" 2>/dev/null || true
|
||||
|
||||
echo
|
||||
echo "=== 确认 buildozer.spec 指向固定目录 ==="
|
||||
grep -n "^p4a.source_dir" "$SRC_SPEC" || echo "(缺少 p4a.source_dir)"
|
||||
|
||||
echo
|
||||
sudo -u "$BUILD_USER" git -C "$P4A_DIR" log --oneline -1
|
||||
52
scripts/wsl_fetch_x86_wheels.sh
Normal file
52
scripts/wsl_fetch_x86_wheels.sh
Normal file
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
# 下载 x86_64 版 Qt for Python Android wheel(用于 x86_64 模拟器,避免 ARM 转译崩溃)。
|
||||
# Qt 主站偶发中断(HTTP/2 CANCEL),这里带完整性校验、重试与镜像回退。
|
||||
set -uo pipefail
|
||||
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
QT_VER="${QT_VER:-6.11.2}"
|
||||
WHEEL_DIR="$WORK/wheels"
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
|
||||
MIRRORS=(
|
||||
"https://download.qt.io/official_releases/QtForPython"
|
||||
"https://mirrors.ustc.edu.cn/qtproject/official_releases/QtForPython"
|
||||
"https://mirrors.tuna.tsinghua.edu.cn/qt/official_releases/QtForPython"
|
||||
"https://mirror.accum.se/mirror/qt.io/qtproject/official_releases/QtForPython"
|
||||
)
|
||||
|
||||
for name in pyside6 shiboken6; do
|
||||
pattern="${name}-${QT_VER}-${QT_VER}-cp311-cp311-android_x86_64.whl"
|
||||
target="$WHEEL_DIR/$pattern"
|
||||
if [ -s "$target" ] && unzip -tq "$target" >/dev/null 2>&1; then
|
||||
echo "已存在且完整: $pattern ($(du -h "$target" | awk '{print $1}'))"
|
||||
continue
|
||||
fi
|
||||
[ -s "$target" ] && echo "已有文件不完整,重新下载: $pattern"
|
||||
|
||||
ok=0
|
||||
for base in "${MIRRORS[@]}"; do
|
||||
for attempt in 1 2 3; do
|
||||
echo "尝试 [$attempt] $base/$name/$pattern"
|
||||
rm -f "$target"
|
||||
if curl -fL --http1.1 --retry 2 --retry-delay 3 --connect-timeout 20 \
|
||||
-o "$target" "$base/$name/$pattern"; then
|
||||
if unzip -tq "$target" >/dev/null 2>&1; then
|
||||
ok=1
|
||||
break
|
||||
fi
|
||||
echo " 文件损坏,重试"
|
||||
fi
|
||||
done
|
||||
[ "$ok" -eq 1 ] && break
|
||||
done
|
||||
|
||||
if [ "$ok" -ne 1 ]; then
|
||||
echo "下载失败: $pattern" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "完成: $pattern ($(du -h "$target" | awk '{print $1}'))"
|
||||
done
|
||||
|
||||
echo
|
||||
ls -lh "$WHEEL_DIR"/*x86_64*.whl
|
||||
51
scripts/wsl_fix_gradle_cache.sh
Normal file
51
scripts/wsl_fix_gradle_cache.sh
Normal file
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# 计算 Gradle wrapper 的缓存目录名(MD5 的 base36 编码),并把已下载的分发包放到正确位置。
|
||||
set -uo pipefail
|
||||
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
HOME_DIR="/home/$BUILD_USER"
|
||||
VER="${GRADLE_VER:-8.14.3}"
|
||||
DIST_NAME="gradle-${VER}-all.zip"
|
||||
DIST_URL="https://services.gradle.org/distributions/${DIST_NAME}"
|
||||
|
||||
echo "=== wrapper 期望的哈希(MD5 base36) ==="
|
||||
HASH="$(printf '%s' "$DIST_URL" | python3 -c '
|
||||
import sys, hashlib
|
||||
data = sys.stdin.buffer.read()
|
||||
digest = hashlib.md5(data).hexdigest()
|
||||
num = int(digest, 16)
|
||||
alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
out = ""
|
||||
while num:
|
||||
num, rem = divmod(num, 36)
|
||||
out = alphabet[rem] + out
|
||||
print(out)
|
||||
')"
|
||||
echo "distributionUrl = $DIST_URL"
|
||||
echo "hash = $HASH"
|
||||
|
||||
DEST="$HOME_DIR/.gradle/wrapper/dists/gradle-${VER}-all/$HASH"
|
||||
echo "=== 目标目录: $DEST ==="
|
||||
mkdir -p "$DEST"
|
||||
|
||||
SRC="$HOME_DIR/.gradle/wrapper/dists/gradle-${VER}-all/114afcd2bdf37d5f8724308b16549bdf/$DIST_NAME"
|
||||
if [ ! -f "$DEST/$DIST_NAME" ]; then
|
||||
if [ -f "$SRC" ]; then
|
||||
echo "==> 复制已下载的分发包"
|
||||
cp "$SRC" "$DEST/$DIST_NAME"
|
||||
else
|
||||
echo "找不到已下载的 $DIST_NAME,请先运行 wsl_prefetch_gradle.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
cd "$DEST"
|
||||
if [ ! -d "gradle-${VER}" ]; then
|
||||
echo "==> 解压"
|
||||
unzip -q -o "$DIST_NAME"
|
||||
fi
|
||||
touch "$DIST_NAME.ok"
|
||||
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$HOME_DIR/.gradle"
|
||||
echo "=== 结果 ==="
|
||||
ls -la "$DEST"
|
||||
21
scripts/wsl_fix_icon.sh
Normal file
21
scripts/wsl_fix_icon.sh
Normal file
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# 修正 pyside6-android-deploy 内置图标格式问题。
|
||||
#
|
||||
# 该工具会硬编码把 <PySide6>/scripts/deploy_lib/pyside_icon.jpg 传给 p4a 的 --icon,
|
||||
# 而 p4a 会把它复制成 res/mipmap/icon.png;aapt/aapt2 按扩展名解析 PNG,
|
||||
# 于是报 “failed to read PNG signature”,release 构建直接失败。
|
||||
# 这里用项目自己的 PNG 图标覆盖该文件。
|
||||
set -euo pipefail
|
||||
|
||||
VENV="${VENV:-/opt/lnxgit-android/venv}"
|
||||
SRC_DIR="${SRC_DIR:-/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile}"
|
||||
ICON_SRC="$SRC_DIR/docs/icon-192.png"
|
||||
TARGET="$VENV/lib/python3.11/site-packages/PySide6/scripts/deploy_lib/pyside_icon.jpg"
|
||||
|
||||
[ -f "$ICON_SRC" ] || { echo "找不到图标: $ICON_SRC" >&2; exit 1; }
|
||||
|
||||
cp -f "$ICON_SRC" "$TARGET"
|
||||
chmod 644 "$TARGET"
|
||||
echo "==> 已覆盖内置图标: $TARGET"
|
||||
file "$TARGET"
|
||||
head -c 8 "$TARGET" | od -An -tx1
|
||||
17
scripts/wsl_fix_p4a.sh
Normal file
17
scripts/wsl_fix_p4a.sh
Normal file
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# 为 builder 用户配置 git 安全目录,并校验 p4a 检出可用。
|
||||
set -euo pipefail
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
P4A="/home/$BUILD_USER/.buildozer/android/platform/python-for-android"
|
||||
|
||||
sudo -u "$BUILD_USER" git config --global --add safe.directory "*"
|
||||
|
||||
echo "==> p4a 仓库状态"
|
||||
sudo -u "$BUILD_USER" git -C "$P4A" log --oneline -1
|
||||
echo "分支: $(sudo -u "$BUILD_USER" git -C "$P4A" branch --show-current)"
|
||||
echo "文件数: $(find "$P4A" -maxdepth 1 | wc -l)"
|
||||
|
||||
echo "==> 预装 p4a 的 Python 依赖(避免 buildozer 再次 pip --user)"
|
||||
sudo -u "$BUILD_USER" /opt/lnxgit-android/venv/bin/pip install -q \
|
||||
appdirs "colorama>=0.3.3" jinja2 "sh>=2,<3" meson ninja build toml packaging "wheel~=0.43.0"
|
||||
echo "完成"
|
||||
51
scripts/wsl_fix_recipes.sh
Normal file
51
scripts/wsl_fix_recipes.sh
Normal file
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把 p4a 里 python3 / hostpython3 recipe 的版本规整到目标版本(默认 3.11.15)。
|
||||
#
|
||||
# 背景:PySide6 的 Android wheel 是 cp311,shiboken6 链接 libpython3.11.so,
|
||||
# 而 p4a 默认编译 3.14;不一致时应用启动即报
|
||||
# dlopen failed: library "libpython3.11.so" not found
|
||||
#
|
||||
# 旧版补丁的正则只匹配 `version = "..."` 前缀,替换时又在行尾追加注释,
|
||||
# 每执行一次就长一截(曾累积到几百个 "# _LNXGIT_PINNED")。这里改成整行替换,
|
||||
# 幂等且顺手把历史膨胀清理掉。
|
||||
set -euo pipefail
|
||||
|
||||
VERSION="${PYTHON_VERSION:-3.11.15}"
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
|
||||
python3 - "$VERSION" "$WORK" "/home/$BUILD_USER/.buildozer" <<'PY'
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
version, *roots = sys.argv[1:]
|
||||
line_re = re.compile(
|
||||
r'^(?P<indent>[ \t]*)version[ \t]*=[ \t]*["\'][^"\']+["\'][^\n]*$',
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
total_files = total_lines = 0
|
||||
for root in roots:
|
||||
base = Path(root)
|
||||
if not base.is_dir():
|
||||
continue
|
||||
for name in ("python3", "hostpython3"):
|
||||
for recipe in base.rglob(f"pythonforandroid/recipes/{name}/__init__.py"):
|
||||
try:
|
||||
src = recipe.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
continue
|
||||
new, count = line_re.subn(
|
||||
lambda m: f'{m.group("indent")}version = "{version}" # _LNXGIT_PINNED',
|
||||
src,
|
||||
)
|
||||
if not count or new == src:
|
||||
continue
|
||||
recipe.write_text(new, encoding="utf-8")
|
||||
total_files += 1
|
||||
total_lines += count
|
||||
print(f" 修正 {recipe}({count} 处)")
|
||||
|
||||
print(f"==> 规整 {total_files} 个 recipe 文件、{total_lines} 处版本行 -> {version}")
|
||||
PY
|
||||
30
scripts/wsl_fix_sdk_layout.sh
Normal file
30
scripts/wsl_fix_sdk_layout.sh
Normal file
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# 修复 buildozer 对 Android SDK 目录结构的假设:
|
||||
# buildozer 期望 <sdk>/tools/bin/sdkmanager,而新版 commandline-tools 安装在
|
||||
# <sdk>/cmdline-tools/latest/。这里补充兼容符号链接。
|
||||
set -euo pipefail
|
||||
|
||||
SDK="${SDK:-/opt/lnxgit-android/android-sdk}"
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
|
||||
echo "==> SDK: $SDK"
|
||||
ls "$SDK"
|
||||
|
||||
if [ ! -e "$SDK/tools" ]; then
|
||||
echo "==> 创建兼容链接: tools -> cmdline-tools/latest"
|
||||
ln -s "$SDK/cmdline-tools/latest" "$SDK/tools"
|
||||
fi
|
||||
|
||||
echo "==> 校验 sdkmanager"
|
||||
for p in "$SDK/tools/bin/sdkmanager" "$SDK/cmdline-tools/latest/bin/sdkmanager"; do
|
||||
if [ -x "$p" ]; then
|
||||
echo " OK $p"
|
||||
else
|
||||
echo " 缺失 $p"
|
||||
fi
|
||||
done
|
||||
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$SDK" 2>/dev/null || true
|
||||
|
||||
echo "==> 由 $BUILD_USER 试运行 sdkmanager --version"
|
||||
su - "$BUILD_USER" -c "$SDK/tools/bin/sdkmanager --version" 2>&1 | tail -3
|
||||
66
scripts/wsl_make_test_repos.sh
Normal file
66
scripts/wsl_make_test_repos.sh
Normal file
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# 造两个用于验证分支图谱的测试仓库。
|
||||
#
|
||||
# topology 分叉 + 合并 + 未合并分支 + 注解标签(验证分叉/合并的画法)
|
||||
# many-branches 21 个从同一点分叉的分支(验证多泳道的铺开与缩放)
|
||||
#
|
||||
# 用法:bash scripts/wsl_make_test_repos.sh [输出目录,默认 /tmp]
|
||||
set -euo pipefail
|
||||
|
||||
OUT="${1:-/tmp}"
|
||||
TOPOLOGY="$OUT/graph-test-repo"
|
||||
MANY="$OUT/many-branches-repo"
|
||||
|
||||
# /tmp 下可能残留别的用户的仓库,git 会以 dubious ownership 拒绝操作
|
||||
git config --global --add safe.directory "*" 2>/dev/null || true
|
||||
|
||||
init_repo() {
|
||||
local dir="$1"
|
||||
rm -rf "$dir"
|
||||
mkdir -p "$dir"
|
||||
git -C "$dir" init -q -b main .
|
||||
git -C "$dir" config user.email "tester@lnxgit.local"
|
||||
git -C "$dir" config user.name "LnxGit Tester"
|
||||
git -C "$dir" config commit.gpgsign false
|
||||
}
|
||||
|
||||
echo "=== 1) topology:分叉 + 合并 + 未合并分支 + 注解标签 ==="
|
||||
init_repo "$TOPOLOGY"
|
||||
cd "$TOPOLOGY" || exit 1
|
||||
|
||||
echo a > a.txt && git add -A && git commit -qm "A 初始提交"
|
||||
echo b > b.txt && git add -A && git commit -qm "B 第二个提交"
|
||||
|
||||
git checkout -q -b feature
|
||||
for name in d e e2; do
|
||||
echo "$name" > "$name.txt"
|
||||
git add -A && git commit -qm "${name^^} feature 上的提交"
|
||||
done
|
||||
|
||||
git checkout -q main
|
||||
echo c > c.txt && git add -A && git commit -qm "C main 上的提交"
|
||||
git merge -q --no-ff feature -m "F 把 feature 合并回 main"
|
||||
git tag -a v1.0 -m "1.0 发布"
|
||||
|
||||
git checkout -q -b hotfix HEAD~1
|
||||
echo h > h.txt && git add -A && git commit -qm "H hotfix 上未合并的提交"
|
||||
git checkout -q main
|
||||
|
||||
git log --oneline --graph --all | sed 's/^/ /'
|
||||
|
||||
echo
|
||||
echo "=== 2) many-branches:21 个同源分支 ==="
|
||||
init_repo "$MANY"
|
||||
cd "$MANY" || exit 1
|
||||
|
||||
echo base > base.txt && git add -A && git commit -qm "基础提交"
|
||||
for i in $(seq -w 1 20); do
|
||||
git checkout -q -b "feat-$i" main
|
||||
echo "$i" > "f$i.txt"
|
||||
git add -A && git commit -qm "分支 feat-$i 的提交"
|
||||
done
|
||||
git checkout -q main
|
||||
echo " 分支数: $(git for-each-ref refs/heads | wc -l)"
|
||||
|
||||
echo
|
||||
echo "==> 完成:$TOPOLOGY 与 $MANY"
|
||||
39
scripts/wsl_move_workdir.sh
Normal file
39
scripts/wsl_move_workdir.sh
Normal file
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把构建环境从 /root 移到 /opt(普通用户可访问),并修正所有权。
|
||||
set -euo pipefail
|
||||
|
||||
OLD="/root/lnxgit-android"
|
||||
NEW="/opt/lnxgit-android"
|
||||
USER_NAME="${USER_NAME:-builder}"
|
||||
|
||||
if [ -d "$NEW" ]; then
|
||||
echo "==> $NEW 已存在,跳过搬迁"
|
||||
else
|
||||
echo "==> 移动 $OLD -> $NEW"
|
||||
mv "$OLD" "$NEW"
|
||||
fi
|
||||
|
||||
# 保留一份软链接,方便 root 调试
|
||||
[ -e "$OLD" ] || ln -s "$NEW" "$OLD"
|
||||
|
||||
echo "==> 修正虚拟环境中的路径引用"
|
||||
if [ -f "$NEW/venv/bin/activate" ]; then
|
||||
sed -i "s#$OLD#$NEW#g" "$NEW/venv/bin/activate" || true
|
||||
fi
|
||||
for f in "$NEW"/venv/bin/*; do
|
||||
if [ -f "$f" ] && head -c 2 "$f" 2>/dev/null | grep -q '#!'; then
|
||||
sed -i "s#$OLD#$NEW#g" "$f" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
if [ -f "$NEW/venv/pyvenv.cfg" ]; then
|
||||
sed -i "s#$OLD#$NEW#g" "$NEW/venv/pyvenv.cfg" || true
|
||||
fi
|
||||
# 脚本目录中的硬编码路径
|
||||
sed -i "s#/root/lnxgit-android#/opt/lnxgit-android#g" "$NEW/venv/bin/"* 2>/dev/null || true
|
||||
|
||||
echo "==> 交给 $USER_NAME"
|
||||
chown -R "$USER_NAME:$USER_NAME" "$NEW"
|
||||
chmod -R a+rX /opt
|
||||
|
||||
echo "==> 验证"
|
||||
su - "$USER_NAME" -c "cd /opt/lnxgit-android && ./venv/bin/python --version && ./venv/bin/python -m buildozer version 2>&1 | tail -2"
|
||||
47
scripts/wsl_patch_bootstrap_text.sh
Normal file
47
scripts/wsl_patch_bootstrap_text.sh
Normal file
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把 p4a 的 qt bootstrap 里硬编码的英文提示换成中文。
|
||||
#
|
||||
# 这些文案在 python-for-android 的 Java 模板里(PythonActivity.java 等),
|
||||
# 应用界面全是中文,只有返回键提示还是 "Click again to close the app"。
|
||||
#
|
||||
# 中文一律写成 \uXXXX 转义:Java 编译器对源文件编码敏感,转义可以绕开
|
||||
# gradle/javac 的 -encoding 差异,任何环境下都不会乱码。
|
||||
set -euo pipefail
|
||||
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
P4A_SRC="${LNXGIT_P4A_SOURCE:-$WORK/p4a-src}"
|
||||
BOOTSTRAP="${BOOTSTRAP:-$P4A_SRC/pythonforandroid/bootstraps/qt/build/src/main/java}"
|
||||
|
||||
[ -d "$BOOTSTRAP" ] || { echo "找不到 bootstrap Java 目录: $BOOTSTRAP" >&2; exit 1; }
|
||||
|
||||
python3 - "$BOOTSTRAP" <<'PY'
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 英文原文 -> 中文(\uXXXX 转义)
|
||||
REPLACEMENTS = {
|
||||
'"Click again to close the app"': '"\\u518d\\u6309\\u4e00\\u6b21\\u8fd4\\u56de\\u952e\\u9000\\u51fa"',
|
||||
}
|
||||
|
||||
root = Path(sys.argv[1])
|
||||
total_files = total_hits = 0
|
||||
|
||||
for path in sorted(root.rglob("*.java")):
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
continue
|
||||
hits = 0
|
||||
for old, new in REPLACEMENTS.items():
|
||||
if old in text:
|
||||
text = text.replace(old, new)
|
||||
hits += 1
|
||||
if not hits:
|
||||
continue
|
||||
path.write_text(text, encoding="utf-8")
|
||||
total_files += 1
|
||||
total_hits += hits
|
||||
print(f" 改写 {path.name}({hits} 处)")
|
||||
|
||||
print(f"==> 共处理 {total_files} 个文件、{total_hits} 处文案")
|
||||
PY
|
||||
37
scripts/wsl_place_p4a.sh
Normal file
37
scripts/wsl_place_p4a.sh
Normal file
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把 p4a 源码放到构建目录之外的固定位置(配合 buildozer.spec 的 p4a.source_dir)。
|
||||
set -uo pipefail
|
||||
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
P4A_DIR="${P4A_DIR:-/opt/lnxgit-android/p4a-src}"
|
||||
CACHE="/home/$BUILD_USER/.buildozer/android/platform/python-for-android"
|
||||
BRANCH="${P4A_BRANCH:-develop}"
|
||||
|
||||
if [ -d "$P4A_DIR/.git" ]; then
|
||||
echo "==> 已存在: $P4A_DIR"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
mkdir -p "$(dirname "$P4A_DIR")"
|
||||
|
||||
if [ -d "$CACHE/.git" ]; then
|
||||
echo "==> 从缓存复制: $CACHE -> $P4A_DIR"
|
||||
cp -a "$CACHE" "$P4A_DIR"
|
||||
else
|
||||
for url in "https://gitclone.com/github.com/kivy/python-for-android.git" \
|
||||
"https://ghproxy.net/https://github.com/kivy/python-for-android.git" \
|
||||
"https://github.com/kivy/python-for-android.git"; do
|
||||
echo "==> 克隆: $url"
|
||||
rm -rf "$P4A_DIR"
|
||||
if timeout 900 git clone -b "$BRANCH" --single-branch "$url" "$P4A_DIR" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
[ -d "$P4A_DIR/.git" ] || { echo "p4a 获取失败" >&2; exit 1; }
|
||||
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$P4A_DIR"
|
||||
sudo -u "$BUILD_USER" git config --global --add safe.directory "*"
|
||||
echo "==> 就绪:"
|
||||
sudo -u "$BUILD_USER" git -C "$P4A_DIR" log --oneline -1
|
||||
42
scripts/wsl_place_p4a_local.sh
Normal file
42
scripts/wsl_place_p4a_local.sh
Normal file
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# 让 buildozer 完全跳过 p4a 下载:直接把 p4a 源码目录交给它。
|
||||
#
|
||||
# p4a 的 BaseRecipe.download_if_necessary() 会检查 P4A_<RECIPE>_DIR 之类的用户目录;
|
||||
# 而 buildozer 侧的 p4a 源码位置由 app.p4a.source_dir 指定。这里两条路都铺好:
|
||||
# 1) buildozer.spec 写入 p4a.source_dir(由构建脚本的补丁负责)
|
||||
# 2) 预先在项目平台目录放好 p4a(buildozer 检测到 python-for-android/ 已存在就不再克隆)
|
||||
set -euo pipefail
|
||||
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
P4A_SRC="$WORK/p4a-src"
|
||||
PLATFORM_DIR="$WORK/src/.buildozer/android/platform"
|
||||
TARGET="$PLATFORM_DIR/python-for-android"
|
||||
|
||||
mkdir -p "$PLATFORM_DIR"
|
||||
|
||||
if [ -d "$TARGET/.git" ] && grep -q _LNXGIT_PINNED "$TARGET/pythonforandroid/recipes/python3/__init__.py" 2>/dev/null; then
|
||||
echo "==> 项目本地 p4a 已就绪且已固定版本: $TARGET"
|
||||
else
|
||||
echo "==> 重新放置 p4a: $P4A_SRC -> $TARGET"
|
||||
rm -rf "$TARGET"
|
||||
cp -a "$P4A_SRC" "$TARGET"
|
||||
fi
|
||||
|
||||
# buildozer 会在 global_platform_dir 里找 p4a,也一并铺好
|
||||
GLOBAL="/home/$BUILD_USER/.buildozer/android/platform/python-for-android"
|
||||
if [ ! -d "$GLOBAL/.git" ] || ! grep -q _LNXGIT_PINNED "$GLOBAL/pythonforandroid/recipes/python3/__init__.py" 2>/dev/null; then
|
||||
echo "==> 同步到全局平台目录: $GLOBAL"
|
||||
rm -rf "$GLOBAL"
|
||||
cp -a "$P4A_SRC" "$GLOBAL"
|
||||
fi
|
||||
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$PLATFORM_DIR" "/home/$BUILD_USER/.buildozer" 2>/dev/null || true
|
||||
sudo -u "$BUILD_USER" git config --global --add safe.directory "*" 2>/dev/null || true
|
||||
|
||||
echo
|
||||
echo "=== 校验 ==="
|
||||
for d in "$TARGET" "$GLOBAL"; do
|
||||
f="$d/pythonforandroid/recipes/python3/__init__.py"
|
||||
[ -f "$f" ] && printf ' %s -> %s\n' "$d" "$(grep -oE 'version = \"[0-9.]+\"' "$f" | head -1)"
|
||||
done
|
||||
64
scripts/wsl_place_python_src.sh
Normal file
64
scripts/wsl_place_python_src.sh
Normal file
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把 CPython 源码包放到 p4a 实际的下载目录(每个 recipe 的 packages 目录)。
|
||||
#
|
||||
# p4a 的 download() 以当前工作目录(如 build-x86_64/packages/python3)为基准,
|
||||
# 检查 v<version>.tar.gz 与 .mark-v<version>.tar.gz,因此必须放在这里才能离线命中。
|
||||
set -euo pipefail
|
||||
|
||||
VERSION="${PYTHON_VERSION:-3.11.15}"
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
TARBALL="v${VERSION}.tar.gz"
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
# 没有任何 packages 目录时预建哪一个(与 wsl_build.sh 的 ARCH_P4A 保持一致)
|
||||
ARCH_P4A="${ARCH_P4A:-x86_64}"
|
||||
|
||||
SRC_TGZ=""
|
||||
for candidate in "$WORK/src/.buildozer/android/platform/$TARBALL" \
|
||||
"$WORK/$TARBALL" \
|
||||
"/home/$BUILD_USER/.buildozer/android/platform/$TARBALL"; do
|
||||
[ -s "$candidate" ] && SRC_TGZ="$candidate" && break
|
||||
done
|
||||
|
||||
if [ -z "$SRC_TGZ" ]; then
|
||||
echo "==> 本地没有 $TARBALL,从镜像下载"
|
||||
SRC_TGZ="$WORK/$TARBALL"
|
||||
for url in "https://mirrors.huaweicloud.com/python/${VERSION}/Python-${VERSION}.tgz" \
|
||||
"https://mirrors.aliyun.com/python-release/source/Python-${VERSION}.tgz" \
|
||||
"https://www.python.org/ftp/python/${VERSION}/Python-${VERSION}.tgz"; do
|
||||
if curl -fL --http1.1 --retry 3 -o "$SRC_TGZ" "$url"; then
|
||||
tar -tzf "$SRC_TGZ" >/dev/null 2>&1 && break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
[ -s "$SRC_TGZ" ] || { echo "无法获得 $TARBALL" >&2; exit 1; }
|
||||
echo "==> 源包: $SRC_TGZ"
|
||||
|
||||
# 目标架构的两个目录**必须**存在(p4a 只在 packages/<recipe>/ 下找源码包)。
|
||||
# 只补"已经存在的目录"是不够的:构建中断或首次构建时,python3 目录可能还没被
|
||||
# p4a 创建,结果是 hostpython3 命中缓存、python3 又去 GitHub 下 26 MB。
|
||||
DIRS=()
|
||||
for name in python3 hostpython3; do
|
||||
dir="$WORK/src/.buildozer/android/platform/build-$ARCH_P4A/packages/$name"
|
||||
mkdir -p "$dir"
|
||||
DIRS+=("$dir")
|
||||
done
|
||||
|
||||
# 顺带覆盖其它架构与全局缓存里已经存在的 packages 目录
|
||||
while IFS= read -r dir; do
|
||||
[ -n "$dir" ] || continue
|
||||
for existing in "${DIRS[@]}"; do
|
||||
[ "$dir" = "$existing" ] && continue 2
|
||||
done
|
||||
DIRS+=("$dir")
|
||||
done < <(find "$WORK/src/.buildozer" "/home/$BUILD_USER/.buildozer" \
|
||||
-type d \( -path "*packages/python3" -o -path "*packages/hostpython3" \) 2>/dev/null)
|
||||
|
||||
for dir in "${DIRS[@]}"; do
|
||||
cp -f "$SRC_TGZ" "$dir/$TARBALL"
|
||||
touch "$dir/.mark-$TARBALL"
|
||||
echo " 已放置 $dir/$TARBALL"
|
||||
done
|
||||
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "/home/$BUILD_USER/.buildozer" 2>/dev/null || true
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$WORK/src/.buildozer" 2>/dev/null || true
|
||||
echo "==> 完成"
|
||||
46
scripts/wsl_prefetch_gradle.sh
Normal file
46
scripts/wsl_prefetch_gradle.sh
Normal file
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
# 预热 Gradle wrapper 缓存:从镜像下载 gradle-8.14.3-all.zip 并放入 wrapper 期望的目录。
|
||||
set -uo pipefail
|
||||
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
HOME_DIR="/home/$BUILD_USER"
|
||||
VER="${GRADLE_VER:-8.14.3}"
|
||||
DIST_NAME="gradle-${VER}-all.zip"
|
||||
DIST_URL="https://services.gradle.org/distributions/${DIST_NAME}"
|
||||
HASH="$(printf '%s' "$DIST_URL" | md5sum | awk '{print $1}')"
|
||||
DEST_DIR="$HOME_DIR/.gradle/wrapper/dists/gradle-${VER}-all/$HASH"
|
||||
|
||||
echo "==> 目标目录: $DEST_DIR"
|
||||
mkdir -p "$DEST_DIR"
|
||||
|
||||
if [ -f "$DEST_DIR/$DIST_NAME" ] && unzip -tq "$DEST_DIR/$DIST_NAME" >/dev/null 2>&1; then
|
||||
echo "==> 已存在且校验通过"
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$HOME_DIR/.gradle"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
MIRRORS=(
|
||||
"https://mirrors.cloud.tencent.com/gradle/${DIST_NAME}"
|
||||
"https://mirrors.aliyun.com/gradle/${DIST_NAME}"
|
||||
"https://mirrors.huaweicloud.com/gradle/${DIST_NAME}"
|
||||
"https://downloads.gradle-dn.com/distributions/${DIST_NAME}"
|
||||
"$DIST_URL"
|
||||
)
|
||||
|
||||
for url in "${MIRRORS[@]}"; do
|
||||
echo "==> 尝试 $url"
|
||||
rm -f "$DEST_DIR/$DIST_NAME"
|
||||
if curl -fL --retry 2 --connect-timeout 20 -o "$DEST_DIR/$DIST_NAME" "$url"; then
|
||||
if unzip -tq "$DEST_DIR/$DIST_NAME" >/dev/null 2>&1; then
|
||||
echo "==> 成功,大小 $(du -h "$DEST_DIR/$DIST_NAME" | awk '{print $1}')"
|
||||
# wrapper 需要一个解压后的标记文件
|
||||
echo "$DIST_URL" > "$DEST_DIR/gradle-${VER}-all.zip.ok"
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$HOME_DIR/.gradle"
|
||||
exit 0
|
||||
fi
|
||||
echo " 下载文件损坏,重试下一个镜像"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "所有镜像均失败" >&2
|
||||
exit 1
|
||||
42
scripts/wsl_prefetch_p4a.sh
Normal file
42
scripts/wsl_prefetch_p4a.sh
Normal file
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# 预先克隆 python-for-android 到 buildozer 的缓存目录(GitHub 直连不稳定,使用镜像回退)。
|
||||
set -uo pipefail
|
||||
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
HOME_DIR="/home/$BUILD_USER"
|
||||
PLATFORM_DIR="$HOME_DIR/.buildozer/android/platform"
|
||||
TARGET="$PLATFORM_DIR/python-for-android"
|
||||
BRANCH="${P4A_BRANCH:-develop}"
|
||||
|
||||
mkdir -p "$PLATFORM_DIR"
|
||||
|
||||
if [ -d "$TARGET/.git" ]; then
|
||||
echo "==> p4a 已存在:$TARGET"
|
||||
git -C "$TARGET" rev-parse --abbrev-ref HEAD
|
||||
exit 0
|
||||
fi
|
||||
|
||||
MIRRORS=(
|
||||
"https://gitclone.com/github.com/kivy/python-for-android.git"
|
||||
"https://ghproxy.net/https://github.com/kivy/python-for-android.git"
|
||||
"https://gh-proxy.com/https://github.com/kivy/python-for-android.git"
|
||||
"https://hub.fastgit.xyz/kivy/python-for-android.git"
|
||||
"https://github.com/kivy/python-for-android.git"
|
||||
)
|
||||
|
||||
for url in "${MIRRORS[@]}"; do
|
||||
echo "==> 尝试克隆: $url"
|
||||
rm -rf "$TARGET"
|
||||
if timeout 600 git clone -b "$BRANCH" --single-branch --depth 50 "$url" "$TARGET" 2>&1 | tail -4; then
|
||||
if [ -d "$TARGET/.git" ]; then
|
||||
echo "==> 成功: $url"
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$TARGET"
|
||||
git -C "$TARGET" log --oneline -1
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
echo " 失败,尝试下一个镜像"
|
||||
done
|
||||
|
||||
echo "所有镜像均失败" >&2
|
||||
exit 1
|
||||
43
scripts/wsl_prefetch_p4a_local.sh
Normal file
43
scripts/wsl_prefetch_p4a_local.sh
Normal file
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bash
|
||||
# 将 python-for-android 预置到 buildozer 的项目本地目录,并保留构建缓存。
|
||||
#
|
||||
# buildozer 会在 <项目>/.buildozer/android/platform/python-for-android 重新克隆源码,
|
||||
# 而 GitHub 直连不稳定,因此这里用镜像预先放好。
|
||||
set -uo pipefail
|
||||
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
BUILD_SRC="${BUILD_SRC:-/opt/lnxgit-android/src}"
|
||||
BRANCH="${P4A_BRANCH:-develop}"
|
||||
|
||||
PLATFORM_DIR="$BUILD_SRC/.buildozer/android/platform"
|
||||
TARGET="$PLATFORM_DIR/python-for-android"
|
||||
|
||||
mkdir -p "$PLATFORM_DIR"
|
||||
|
||||
if [ -d "$TARGET/.git" ]; then
|
||||
echo "==> 项目本地 p4a 已存在: $TARGET"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
MIRRORS=(
|
||||
"https://gitclone.com/github.com/kivy/python-for-android.git"
|
||||
"https://ghproxy.net/https://github.com/kivy/python-for-android.git"
|
||||
"https://gh-proxy.com/https://github.com/kivy/python-for-android.git"
|
||||
"https://github.com/kivy/python-for-android.git"
|
||||
)
|
||||
|
||||
for url in "${MIRRORS[@]}"; do
|
||||
echo "==> 尝试克隆: $url"
|
||||
rm -rf "$TARGET"
|
||||
if timeout 900 git clone -b "$BRANCH" --single-branch "$url" "$TARGET" >/dev/null 2>&1; then
|
||||
if [ -d "$TARGET/.git" ]; then
|
||||
echo "==> 成功: $url"
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$PLATFORM_DIR"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
echo " 失败,尝试下一个镜像"
|
||||
done
|
||||
|
||||
echo "所有镜像均失败" >&2
|
||||
exit 1
|
||||
65
scripts/wsl_prefetch_python_src.sh
Normal file
65
scripts/wsl_prefetch_python_src.sh
Normal file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env bash
|
||||
# 预置 CPython 源码包到 p4a 的下载目录(避免直连 GitHub)。
|
||||
set -euo pipefail
|
||||
|
||||
VERSION="${PYTHON_VERSION:-3.11.15}"
|
||||
TARBALL="v${VERSION}.tar.gz" # 与 recipe 的 url 模板 basename 一致
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
|
||||
# 首选 GitHub 归档的镜像代理:这样拿到的正是 p4a 期望的那份
|
||||
# (https://github.com/python/cpython/archive/refs/tags/v3.11.15.tar.gz),
|
||||
# 顶层目录名与内容都完全一致。python.org / 华为云是后备——它们的包能编译,
|
||||
# 但顶层目录是 Python-x.y.z,解包后靠 p4a 的 move() 改名。
|
||||
#
|
||||
# 实测(2026-09):gh-proxy.com ≈ 385 KB/s,ghfast.top ≈ 192 KB/s,
|
||||
# python.org 直连 ≈ 27 KB/s,华为云 ≈ 640 KB/s。
|
||||
GH_PATH="github.com/python/cpython/archive/refs/tags/${TARBALL}"
|
||||
MIRRORS=(
|
||||
"https://gh-proxy.com/https://${GH_PATH}"
|
||||
"https://ghfast.top/https://${GH_PATH}"
|
||||
"https://mirrors.huaweicloud.com/python/${VERSION}/Python-${VERSION}.tgz"
|
||||
"https://mirrors.aliyun.com/python-release/source/Python-${VERSION}.tgz"
|
||||
"https://mirrors.ustc.edu.cn/python/${VERSION}/Python-${VERSION}.tgz"
|
||||
"https://www.python.org/ftp/python/${VERSION}/Python-${VERSION}.tgz"
|
||||
)
|
||||
|
||||
CACHE_DIRS=(
|
||||
"$WORK/src/.buildozer/android/platform"
|
||||
"$WORK" # 放在 .buildozer 之外,不怕被清理
|
||||
"/home/$BUILD_USER/.buildozer/android/platform"
|
||||
)
|
||||
|
||||
DL="$(mktemp -d)/Python-${VERSION}.tgz"
|
||||
ok=0
|
||||
for url in "${MIRRORS[@]}"; do
|
||||
echo "==> 下载 $url"
|
||||
# --max-time 是必须的:GitHub 直连会挂住不发数据,没有超时就会像 p4a
|
||||
# 那样一直卡在下载阶段(p4a 自己用 urllib,不带超时)。
|
||||
if curl -fL --http1.1 --retry 3 --retry-delay 2 \
|
||||
--connect-timeout 20 --max-time 600 -o "$DL" "$url"; then
|
||||
if tar -tzf "$DL" >/dev/null 2>&1; then
|
||||
ok=1
|
||||
echo " 成功 ($(du -h "$DL" | awk '{print $1}'))"
|
||||
echo " 顶层目录: $(tar -tzf "$DL" | head -1 | cut -d/ -f1)"
|
||||
break
|
||||
fi
|
||||
echo " 文件损坏,尝试下一个镜像"
|
||||
fi
|
||||
done
|
||||
[ "$ok" -eq 1 ] || { echo "所有镜像均失败" >&2; exit 1; }
|
||||
|
||||
for dir in "${CACHE_DIRS[@]}"; do
|
||||
mkdir -p "$dir"
|
||||
cp -f "$DL" "$dir/$TARBALL"
|
||||
touch "$dir/.mark-$TARBALL"
|
||||
echo "==> 已放置 $dir/$TARBALL (+ .mark 标记)"
|
||||
done
|
||||
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "/home/$BUILD_USER/.buildozer" 2>/dev/null || true
|
||||
|
||||
echo
|
||||
echo "=== 校验 ==="
|
||||
for dir in "${CACHE_DIRS[@]}"; do
|
||||
ls -la "$dir/$TARBALL" "$dir/.mark-$TARBALL" 2>/dev/null | sed 's/^/ /'
|
||||
done
|
||||
61
scripts/wsl_probe_python_mirrors.sh
Normal file
61
scripts/wsl_probe_python_mirrors.sh
Normal file
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env bash
|
||||
# 测速:为 CPython 源码包挑选可用的下载源。
|
||||
#
|
||||
# p4a 的 python3/hostpython3 recipe 指向 GitHub 归档
|
||||
# https://github.com/python/cpython/archive/refs/tags/v{version}.tar.gz
|
||||
# GitHub 直连经常几百 KB 就挂住(p4a 用 urllib 下载且没有超时),
|
||||
# 所以这里测一批镜像,把结果写进 /tmp 供后续脚本取用。
|
||||
set -uo pipefail
|
||||
|
||||
VERSION="${PYTHON_VERSION:-3.11.15}"
|
||||
TARBALL="v${VERSION}.tar.gz"
|
||||
OUT_DIR="${OUT_DIR:-/tmp/lnxgit-src-probe}"
|
||||
mkdir -p "$OUT_DIR"
|
||||
|
||||
GH="github.com/python/cpython/archive/refs/tags/$TARBALL"
|
||||
CANDIDATES=(
|
||||
"github|https://$GH"
|
||||
"codeload|https://codeload.github.com/python/cpython/tar.gz/refs/tags/$TARBALL"
|
||||
"ghproxy.net|https://ghproxy.net/https://$GH"
|
||||
"gh-proxy.com|https://gh-proxy.com/https://$GH"
|
||||
"ghfast.top|https://ghfast.top/https://$GH"
|
||||
"moeyy|https://github.moeyy.xyz/https://$GH"
|
||||
"python.org|https://www.python.org/ftp/python/$VERSION/Python-$VERSION.tgz"
|
||||
"huaweicloud|https://mirrors.huaweicloud.com/python/$VERSION/Python-$VERSION.tgz"
|
||||
)
|
||||
|
||||
echo "=== 下载源测速(各取前 4 MB,限时 20 秒) ==="
|
||||
results=()
|
||||
for entry in "${CANDIDATES[@]}"; do
|
||||
name="${entry%%|*}"
|
||||
url="${entry#*|}"
|
||||
probe="$OUT_DIR/$name.part"
|
||||
rm -f "$probe"
|
||||
start=$(date +%s.%N)
|
||||
if curl -fsSL --http1.1 --connect-timeout 8 --max-time 20 \
|
||||
-r 0-4194303 -o "$probe" "$url" 2>/dev/null; then
|
||||
bytes=$(stat -c %s "$probe" 2>/dev/null || echo 0)
|
||||
else
|
||||
bytes=$(stat -c %s "$probe" 2>/dev/null || echo 0)
|
||||
fi
|
||||
end=$(date +%s.%N)
|
||||
secs=$(awk -v a="$start" -v b="$end" 'BEGIN{printf "%.1f", b-a}')
|
||||
if [ "$bytes" -gt 100000 ]; then
|
||||
kbps=$(awk -v b="$bytes" -v s="$secs" 'BEGIN{printf "%.0f", b/1024/s}')
|
||||
echo " [可用] $name ${bytes} 字节 / ${secs}s ≈ ${kbps} KB/s"
|
||||
results+=("$kbps|$name|$url")
|
||||
else
|
||||
echo " [失败] $name (${bytes} 字节 / ${secs}s)"
|
||||
fi
|
||||
done
|
||||
|
||||
echo
|
||||
if [ "${#results[@]}" -eq 0 ]; then
|
||||
echo "==> 没有任何可用源"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
best=$(printf '%s\n' "${results[@]}" | sort -t'|' -k1 -nr | head -1)
|
||||
echo "==> 最快:$best"
|
||||
printf '%s\n' "$best" | cut -d'|' -f3 > "$OUT_DIR/best_url.txt"
|
||||
echo "==> 已写入 $OUT_DIR/best_url.txt"
|
||||
37
scripts/wsl_pull_fonts.sh
Normal file
37
scripts/wsl_pull_fonts.sh
Normal file
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把设备上的系统字体拉到本地,供 tools/check_glyphs.py 判定字形覆盖。
|
||||
#
|
||||
# 为什么要拉下来:Android 的 NotoSansSymbols 是子集化字体,而且 Qt 的字体
|
||||
# 回退链里根本没有它 —— 单看"系统有没有这个字形"会误判,
|
||||
# 必须拿真实字体文件比对(详见 tools/check_glyphs.py 顶部说明)。
|
||||
#
|
||||
# 用法:bash scripts/wsl_pull_fonts.sh [设备序列号] [输出目录]
|
||||
set -uo pipefail
|
||||
|
||||
ADB="${ADB:-/opt/lnxgit-android/android-sdk/platform-tools/adb}"
|
||||
DEVICE="${1:-}"
|
||||
OUT="${2:-/tmp/lnxgit-fonts}"
|
||||
|
||||
[ -x "$ADB" ] || { echo "找不到 adb: $ADB" >&2; exit 1; }
|
||||
if [ -z "$DEVICE" ]; then
|
||||
DEVICE="$("$ADB" devices | awk 'NR>1 && $2=="device" {print $1; exit}')"
|
||||
fi
|
||||
[ -n "$DEVICE" ] || { echo "没有处于 device 状态的设备" >&2; exit 1; }
|
||||
|
||||
mkdir -p "$OUT"
|
||||
echo "==> 设备 $DEVICE -> $OUT"
|
||||
|
||||
# 只取与判定相关的几类:拉丁、符号、emoji、CJK
|
||||
for name in $("$ADB" -s "$DEVICE" shell ls /system/fonts 2>/dev/null | tr -d '\r'); do
|
||||
case "$name" in
|
||||
*Symbol*|*Emoji*|*CJK*|Roboto-Regular*|*Fallback*)
|
||||
if "$ADB" -s "$DEVICE" pull "/system/fonts/$name" "$OUT/$name" >/dev/null 2>&1; then
|
||||
printf ' %-40s %s 字节\n' "$name" "$(stat -c %s "$OUT/$name" 2>/dev/null)"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo
|
||||
echo "==> 完成。检查 QML 图标:"
|
||||
echo " python3 tools/check_glyphs.py qml $OUT"
|
||||
63
scripts/wsl_purge_python_build.sh
Normal file
63
scripts/wsl_purge_python_build.sh
Normal file
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
# 清理 p4a 的构建缓存,迫使重编或重新组装 dist。
|
||||
#
|
||||
# 两种模式:
|
||||
# --python (默认)删除 dists **以及** python3 / hostpython3 的编译产物。
|
||||
# 换 Python 版本(wheel 的 cp311 ↔ p4a 默认版本)时必须用这个,
|
||||
# 否则旧 dist 里的 libpythonX.Y.so 不会被替换。
|
||||
# --dist-only 只删除 dists,保留 other_builds 里的编译产物。
|
||||
# 改的是 bootstrap 配置(例如 libs.xml 里 Qt 库的加载顺序)时用,
|
||||
# p4a 会重新组装 dist 但复用已编译好的 CPython,快得多。
|
||||
#
|
||||
# 用法(WSL 内,root 或 builder 均可):
|
||||
# bash scripts/wsl_purge_python_build.sh [--python|--dist-only]
|
||||
set -euo pipefail
|
||||
|
||||
MODE="python"
|
||||
case "${1:-}" in
|
||||
--dist-only) MODE="dist" ;;
|
||||
--python|"") MODE="python" ;;
|
||||
*) echo "未知参数:$1(可用:--python / --dist-only)" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
SRC="${SRC:-$WORK/src}"
|
||||
PLATFORM="${PLATFORM:-$SRC/.buildozer/android/platform}"
|
||||
GLOBAL="${GLOBAL:-/home/builder/.buildozer/android/platform}"
|
||||
|
||||
removed=0
|
||||
|
||||
purge() {
|
||||
local target="$1"
|
||||
if [ -e "$target" ]; then
|
||||
echo " 删除 $target"
|
||||
rm -rf "$target"
|
||||
removed=$((removed + 1))
|
||||
fi
|
||||
}
|
||||
|
||||
if [ "$MODE" = "dist" ]; then
|
||||
echo "==> 清理 p4a 的 dist(保留已编译的 other_builds)"
|
||||
else
|
||||
echo "==> 清理 p4a 的 Python 构建缓存与 dist"
|
||||
fi
|
||||
|
||||
for platform_dir in "$PLATFORM" "$GLOBAL"; do
|
||||
[ -d "$platform_dir" ] || continue
|
||||
for arch_dir in "$platform_dir"/build-*; do
|
||||
[ -d "$arch_dir" ] || continue
|
||||
# ARCH_FILTER 只清理指定架构,例如 ARCH_FILTER=x86_64
|
||||
if [ -n "${ARCH_FILTER:-}" ] && [ "$(basename "$arch_dir")" != "build-$ARCH_FILTER" ]; then
|
||||
continue
|
||||
fi
|
||||
purge "$arch_dir/dists"
|
||||
if [ "$MODE" = "python" ]; then
|
||||
purge "$arch_dir/build/other_builds/python3"
|
||||
purge "$arch_dir/build/other_builds/hostpython3"
|
||||
# 下载标记留着会让 p4a 以为源码包已就绪;版本变了必须重新校验
|
||||
rm -f "$arch_dir"/packages/python3/.mark-* "$arch_dir"/packages/hostpython3/.mark-*
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
echo "==> 完成(清理 $removed 项)"
|
||||
26
scripts/wsl_reuse_p4a.sh
Normal file
26
scripts/wsl_reuse_p4a.sh
Normal file
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
# 复用 ~/.buildozer 中已克隆好的 p4a,避免每次构建都重新拉取 GitHub。
|
||||
set -euo pipefail
|
||||
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
BUILD_SRC="${BUILD_SRC:-/opt/lnxgit-android/src}"
|
||||
CACHE="/home/$BUILD_USER/.buildozer/android/platform/python-for-android"
|
||||
TARGET_DIR="$BUILD_SRC/.buildozer/android/platform"
|
||||
TARGET="$TARGET_DIR/python-for-android"
|
||||
|
||||
if [ -d "$TARGET/.git" ]; then
|
||||
echo "==> 已存在: $TARGET"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ ! -d "$CACHE/.git" ]; then
|
||||
echo "缓存中也没有 p4a,先运行 wsl_prefetch_p4a.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$TARGET_DIR"
|
||||
echo "==> 从缓存复制 p4a: $CACHE -> $TARGET"
|
||||
cp -a "$CACHE" "$TARGET"
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$TARGET_DIR"
|
||||
sudo -u "$BUILD_USER" git -C "$TARGET" log --oneline -1
|
||||
echo "==> 完成"
|
||||
54
scripts/wsl_share_packages.sh
Normal file
54
scripts/wsl_share_packages.sh
Normal file
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把已下载的依赖源码包从一个架构的构建目录复制给另一个架构。
|
||||
#
|
||||
# 起因:arm64 的 build 目录是新建的,p4a 会重新去 GitHub / openssl.org 下载
|
||||
# 全部依赖,而本站直连这些站点经常超时(日志里是 urllib.error.URLError:
|
||||
# timed out),构建直接失败。依赖源码包与目标架构无关,同一份 tarball 两边
|
||||
# 都用,复制过去就能跳过整个下载阶段。
|
||||
#
|
||||
# 注意连隐藏的 .mark-* 标记一起复制 —— p4a 靠它判断「已下载完成」,
|
||||
# 少了标记仍会重新下载。
|
||||
#
|
||||
# 用法:bash scripts/wsl_share_packages.sh [源架构] [目标架构]
|
||||
# 默认 x86_64 -> arm64-v8a
|
||||
set -uo pipefail
|
||||
|
||||
PLATFORM="${PLATFORM:-/opt/lnxgit-android/src/.buildozer/android/platform}"
|
||||
FROM="${1:-x86_64}"
|
||||
TO="${2:-arm64-v8a}"
|
||||
|
||||
SRC="$PLATFORM/build-$FROM/packages"
|
||||
DST="$PLATFORM/build-$TO/packages"
|
||||
|
||||
if [ ! -d "$SRC" ]; then
|
||||
echo "找不到源目录: $SRC" >&2
|
||||
echo "可用的构建目录:" >&2
|
||||
ls -d "$PLATFORM"/build-* 2>/dev/null | sed 's/^/ /' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "=== $FROM 已下载的源码包 ==="
|
||||
find "$SRC" -maxdepth 2 -mindepth 2 -type f | sed 's|.*/packages/| |' | sort
|
||||
|
||||
echo
|
||||
echo "=== 复制到 $TO ==="
|
||||
mkdir -p "$DST"
|
||||
copied=0
|
||||
for dir in "$SRC"/*/; do
|
||||
[ -d "$dir" ] || continue
|
||||
name="$(basename "$dir")"
|
||||
mkdir -p "$DST/$name"
|
||||
if cp -an "$dir". "$DST/$name/" 2>/dev/null; then
|
||||
copied=$((copied + 1))
|
||||
echo " $name"
|
||||
fi
|
||||
done
|
||||
echo " 共 $copied 个 recipe 目录"
|
||||
|
||||
# 构建以 builder 身份运行,root 复制过来的文件要改回属主
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$DST" 2>/dev/null || true
|
||||
|
||||
echo
|
||||
echo "=== $TO 现在可用 ==="
|
||||
find "$DST" -maxdepth 2 -mindepth 2 -type f | sed 's|.*/packages/| |' | sort
|
||||
11
scripts/wsl_show_gradle_log.sh
Normal file
11
scripts/wsl_show_gradle_log.sh
Normal file
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# 打印构建日志中 gradle 阶段之后的全部内容,便于定位失败原因。
|
||||
set -uo pipefail
|
||||
LOG="${LOG:-/opt/lnxgit-android/build.log}"
|
||||
LINE="$(grep -n 'gradlew clean assembleDebug' "$LOG" | tail -1 | cut -d: -f1)"
|
||||
echo "gradle 起始行: ${LINE:-未找到}"
|
||||
if [ -n "${LINE:-}" ]; then
|
||||
tail -n +"$LINE" "$LOG" | sed -e 's/\x1b\[[0-9;]*m//g' | head -80
|
||||
else
|
||||
tail -60 "$LOG" | sed -e 's/\x1b\[[0-9;]*m//g'
|
||||
fi
|
||||
108
scripts/wsl_trim_apk.sh
Normal file
108
scripts/wsl_trim_apk.sh
Normal file
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env bash
|
||||
# 裁剪 APK:只保留 QML 运行必需的 Qt 库与插件,然后重新签名。
|
||||
#
|
||||
# pyside6-android-deploy 会把整个 PySide6/Qt/lib 目录(含 WebEngine、Designer、
|
||||
# 3D、Charts、Multimedia 等)塞进 APK。本应用只用 Core/Gui/Qml/Quick/
|
||||
# QuickControls2/Network/Svg 与少量插件,因此可安全裁剪,体积约减少一半以上。
|
||||
#
|
||||
# 用法:bash scripts/wsl_trim_apk.sh [输入.apk] [输出.apk]
|
||||
set -euo pipefail
|
||||
|
||||
SDK="${ANDROID_HOME:-/opt/lnxgit-android/android-sdk}"
|
||||
BUILD_TOOLS="$SDK/build-tools/35.0.0"
|
||||
IN_APK="${1:-/opt/lnxgit-android/src/LnxGit-0.1-arm64-v8a-debug.apk}"
|
||||
OUT_APK="${2:-/opt/lnxgit-android/src/LnxGit-1.0.0-arm64-v8a-debug.apk}"
|
||||
WORK="$(mktemp -d)"
|
||||
KEYSTORE="${KEYSTORE:-$WORK/debug.keystore}"
|
||||
|
||||
echo "=== 输入: $IN_APK ($(du -h "$IN_APK" | awk '{print $1}')) ==="
|
||||
mkdir -p "$WORK/unpacked"
|
||||
unzip -q -o "$IN_APK" -d "$WORK/unpacked"
|
||||
LIB="$WORK/unpacked/lib/arm64-v8a"
|
||||
|
||||
KEEP_QT="libQt6Core libQt6Gui libQt6Qml libQt6QmlModels libQt6QmlMeta \
|
||||
libQt6QmlWorkerScript libQt6Quick libQt6QuickControls2 libQt6QuickControls2Impl \
|
||||
libQt6QuickTemplates2 libQt6QuickLayouts libQt6QuickDialogs2 \
|
||||
libQt6QuickDialogs2QuickImpl libQt6QuickDialogs2Utils libQt6QuickShapes \
|
||||
libQt6QuickEffects libQt6QuickParticles libQt6Network libQt6OpenGL libQt6Svg \
|
||||
libQt6Widgets libQt6QuickWidgets libQt6Android libQt6ShaderTools \
|
||||
libQt6EglFSDeviceIntegration libQt6EglFsKmsSupport libQt6OpenGLWidgets"
|
||||
|
||||
KEEP_BINDINGS="QtCore.abi3.so QtGui.abi3.so QtQml.abi3.so QtQuick.abi3.so \
|
||||
QtQuickControls2.abi3.so QtNetwork.abi3.so QtSvg.abi3.so QtOpenGL.abi3.so \
|
||||
QtWidgets.abi3.so libpyside6.abi3.so libpyside6qml.abi3.so libshiboken6.abi3.so \
|
||||
Shiboken.abi3.so libpython3.14.so libpybundle.so libc++_shared.so libcrypto.so \
|
||||
libssl.so libsqlite3.so libffi.so libmain.so libavcodec.so libavformat.so \
|
||||
libavutil.so libswresample.so"
|
||||
|
||||
KEEP_PLUGIN_DIRS="platforms imageformats iconengines styles tls networkinformation \
|
||||
platforminputcontexts platformthemes qmltooling generic"
|
||||
|
||||
is_keep_lib() {
|
||||
local name="$1" k
|
||||
for k in $KEEP_BINDINGS; do
|
||||
[ "$name" = "$k" ] && return 0
|
||||
done
|
||||
for k in $KEEP_QT; do
|
||||
case "$name" in
|
||||
"${k}".so|"${k}"_*) return 0 ;;
|
||||
"${k}".so.*) return 0 ;;
|
||||
esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
before=$(du -sm "$LIB" | awk '{print $1}')
|
||||
removed=0
|
||||
|
||||
# 1) 顶层库文件
|
||||
while IFS= read -r file; do
|
||||
name="$(basename "$file")"
|
||||
if [ -d "$file" ]; then
|
||||
keep=0
|
||||
for d in $KEEP_PLUGIN_DIRS; do
|
||||
[ "$name" = "$d" ] && keep=1 && break
|
||||
done
|
||||
if [ "$keep" -eq 0 ]; then
|
||||
rm -rf "$file"
|
||||
removed=$((removed + 1))
|
||||
fi
|
||||
else
|
||||
if ! is_keep_lib "$name"; then
|
||||
rm -f "$file"
|
||||
removed=$((removed + 1))
|
||||
fi
|
||||
fi
|
||||
done < <(find "$LIB" -maxdepth 1 -mindepth 1 | sort)
|
||||
|
||||
# 2) 插件子目录内部再筛一遍(例如 imageformats 里保留 qjpeg/qsvg/qgif)
|
||||
if [ -d "$LIB/imageformats" ]; then
|
||||
find "$LIB/imageformats" -maxdepth 1 -type f \
|
||||
! -name '*qjpeg*' ! -name '*qgif*' ! -name '*qsvg*' ! -name '*qico*' \
|
||||
-delete 2>/dev/null || true
|
||||
fi
|
||||
if [ -d "$LIB/tls" ]; then
|
||||
find "$LIB/tls" -maxdepth 1 -type f ! -name '*openssl*' -delete 2>/dev/null || true
|
||||
fi
|
||||
|
||||
after=$(du -sm "$LIB" | awk '{print $1}')
|
||||
echo "=== lib 体积: ${before}MB -> ${after}MB(清理 ${removed} 项)==="
|
||||
echo "=== 剩余条目 ==="
|
||||
ls "$LIB" | head -30
|
||||
|
||||
# 3) 重新打包并签名
|
||||
rm -rf "$WORK/unpacked/META-INF"
|
||||
( cd "$WORK/unpacked" && zip -q -9 -r -X "$WORK/unsigned.apk" . )
|
||||
keytool -genkeypair -v -keystore "$KEYSTORE" -storepass android -keypass android \
|
||||
-alias androiddebugkey -keyalg RSA -keysize 2048 -validity 10000 \
|
||||
-dname "CN=Android Debug,O=Android,C=US" >/dev/null 2>&1
|
||||
"$BUILD_TOOLS/zipalign" -f -p 4 "$WORK/unsigned.apk" "$WORK/aligned.apk"
|
||||
"$BUILD_TOOLS/apksigner" sign --ks "$KEYSTORE" --ks-pass pass:android \
|
||||
--key-pass pass:android --ks-key-alias androiddebugkey \
|
||||
--out "$OUT_APK" "$WORK/aligned.apk"
|
||||
|
||||
echo
|
||||
echo "=== 结果 ==="
|
||||
ls -la "$OUT_APK"
|
||||
echo "体积: $(( $(stat -c%s "$OUT_APK") / 1024 / 1024 ))MB(原 $(( $(stat -c%s "$IN_APK") / 1024 / 1024 ))MB)"
|
||||
rm -rf "$WORK"
|
||||
83
scripts/wsl_upload_release.sh
Normal file
83
scripts/wsl_upload_release.sh
Normal file
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env bash
|
||||
# 把 APK 传到 Gitea Release —— 走**内网直连**,单次整文件,不切片。
|
||||
#
|
||||
# 为什么不走公网域名:git.xnhw.cc 现在是 Caddy 反代(2026-09 起不再走
|
||||
# Cloudflare),小文件没问题,但 150 MB 的 APK 会在约 5 分钟后返回 502 ——
|
||||
# 瓶颈在 Caddy 背后的 Gitea 处理大附件那一层。内网地址
|
||||
# 192.168.100.103:8080 是**同一个** Gitea 实例,没有这层问题:
|
||||
# 实测 151 MB 约 15 秒。
|
||||
#
|
||||
# 也不要用切片上传:那会在 Release 里堆出几十个 xxx.apk.part001 同名附件。
|
||||
#
|
||||
# 令牌:上传/删除附件需要仓库管理员权限。管理员令牌从 scripts/push.cmd
|
||||
# 里读取(那里本来就有,用于推送代码);只读令牌会返回 403。
|
||||
#
|
||||
# 用法:bash scripts/wsl_upload_release.sh <apk路径> [apk路径...]
|
||||
set -uo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
BASE="${GITEA_BASE:-http://192.168.100.103:8080}"
|
||||
REPO="${GITEA_REPO:-l/lnxgit}"
|
||||
RELEASE_ID="${RELEASE_ID:-1}"
|
||||
|
||||
TOKEN="${GITEA_TOKEN:-}"
|
||||
if [ -z "$TOKEN" ] && [ -f "$HERE/push.cmd" ]; then
|
||||
TOKEN="$(grep -oP 'set TOKEN=\K[0-9a-f]+' "$HERE/push.cmd" | head -1)"
|
||||
fi
|
||||
[ -n "$TOKEN" ] || { echo "没有可用令牌:设 GITEA_TOKEN 或确认 scripts/push.cmd 存在" >&2; exit 1; }
|
||||
|
||||
[ "$#" -ge 1 ] || { echo "用法: $0 <apk路径> [...]" >&2; exit 2; }
|
||||
|
||||
show_release() {
|
||||
curl -s --max-time 30 -H "Authorization: token $TOKEN" \
|
||||
"$BASE/api/v1/repos/$REPO/releases/$RELEASE_ID" \
|
||||
| python3 -c "
|
||||
import json, sys
|
||||
d = json.load(sys.stdin)
|
||||
assets = d.get('assets', [])
|
||||
print(f\" tag={d['tag_name']} 附件 {len(assets)} 个,合计 \"
|
||||
f\"{sum(a['size'] for a in assets)/1048576:.1f} MB\")
|
||||
for a in assets:
|
||||
print(f\" - {a['name']} ({a['size']/1048576:.1f} MB)\")
|
||||
"
|
||||
}
|
||||
|
||||
echo "=== 上传前 ==="
|
||||
show_release
|
||||
|
||||
failed=0
|
||||
for apk in "$@"; do
|
||||
[ -f "$apk" ] || { echo " 跳过(不存在): $apk"; failed=$((failed+1)); continue; }
|
||||
name="$(basename "$apk")"
|
||||
size_mb="$(du -m "$apk" | cut -f1)"
|
||||
echo
|
||||
echo "=== 上传 $name(${size_mb} MB,单次整文件)==="
|
||||
start=$(date +%s)
|
||||
|
||||
code=$(curl -s -o /tmp/lnxgit_upload.json -w '%{http_code}' \
|
||||
--max-time 7200 --retry 2 --retry-delay 5 \
|
||||
-X POST \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@$apk" \
|
||||
"$BASE/api/v1/repos/$REPO/releases/$RELEASE_ID/assets")
|
||||
|
||||
elapsed=$(( $(date +%s) - start ))
|
||||
if [ "$code" = "201" ]; then
|
||||
python3 -c "
|
||||
import json
|
||||
d = json.load(open('/tmp/lnxgit_upload.json', encoding='utf-8'))
|
||||
print(f\" 完成: {d.get('name')} {d.get('size',0)/1048576:.1f} MB 用时 ${elapsed}s\")
|
||||
print(f\" 下载: {d.get('browser_download_url')}\")
|
||||
"
|
||||
else
|
||||
failed=$((failed+1))
|
||||
echo " 失败 HTTP $code(用时 ${elapsed}s)"
|
||||
head -c 300 /tmp/lnxgit_upload.json
|
||||
echo
|
||||
fi
|
||||
done
|
||||
|
||||
echo
|
||||
echo "=== 上传后 ==="
|
||||
show_release
|
||||
exit "$failed"
|
||||
44
scripts/wsl_verify_apk.sh
Normal file
44
scripts/wsl_verify_apk.sh
Normal file
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
# 校验最终交付的 APK(清单、权限、架构、签名、私有数据内容)。
|
||||
#
|
||||
# 用法:bash scripts/wsl_verify_apk.sh [apk 路径]
|
||||
set -uo pipefail
|
||||
|
||||
BT="/opt/lnxgit-android/android-sdk/build-tools/35.0.0"
|
||||
APK="${1:-/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile/dist/LnxGit-1.0.0-arm64-v8a-release-universal.apk}"
|
||||
|
||||
if [ ! -f "$APK" ]; then
|
||||
echo "找不到 APK: $APK"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "=== 文件 ==="
|
||||
ls -la "$APK"
|
||||
echo "SHA256: $(sha256sum "$APK" | awk '{print $1}')"
|
||||
|
||||
echo
|
||||
echo "=== 清单信息 ==="
|
||||
"$BT/aapt2" dump badging "$APK" 2>&1 \
|
||||
| grep -E '^(package|sdkVersion|targetSdkVersion|uses-permission|native-code|application-label)' \
|
||||
| head -12
|
||||
|
||||
echo
|
||||
echo "=== 签名 ==="
|
||||
"$BT/apksigner" verify --print-certs "$APK" 2>&1 | head -4
|
||||
|
||||
echo
|
||||
echo "=== 关键内容 ==="
|
||||
echo "native 库数量: $(unzip -l "$APK" | grep -c 'lib/arm64-v8a/.*\.so')"
|
||||
for f in "assets/private.tar" "classes.dex" "AndroidManifest.xml" "resources.arsc"; do
|
||||
if unzip -l "$APK" | grep -q "$f"; then echo " OK $f"; else echo " 缺失 $f"; fi
|
||||
done
|
||||
|
||||
echo
|
||||
echo "=== 私有数据中的项目文件 ==="
|
||||
TMP="$(mktemp -d)"
|
||||
unzip -q -o "$APK" "assets/private.tar" -d "$TMP" 2>/dev/null \
|
||||
&& tar -tf "$TMP/assets/private.tar" 2>/dev/null \
|
||||
| grep -E '^(main\.pyc|lnxgit/|qml/|buildozer\.spec)' | head -12
|
||||
echo "QML 文件数: $(tar -tf "$TMP/assets/private.tar" 2>/dev/null | grep -c '\.qml$')"
|
||||
echo "Python 字节码数: $(tar -tf "$TMP/assets/private.tar" 2>/dev/null | grep -c '\.pyc$')"
|
||||
rm -rf "$TMP"
|
||||
24
scripts/wsl_verify_apk2.sh
Normal file
24
scripts/wsl_verify_apk2.sh
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# 进一步校验 APK:PySide6 模块是否齐全、dex 位置、构建配置来源。
|
||||
set -uo pipefail
|
||||
|
||||
APK="/opt/lnxgit-android/src/LnxGit-0.1-arm64-v8a-debug.apk"
|
||||
SDK="/opt/lnxgit-android/android-sdk"
|
||||
|
||||
echo "=== 顶层结构 ==="
|
||||
unzip -l "$APK" | awk 'NR>3 {print $4}' | grep -v '^$' | awk -F/ '{print $1"/"$2}' | sort -u | head -20
|
||||
|
||||
echo
|
||||
echo "=== PySide6 相关 .so(前 15 个) ==="
|
||||
unzip -l "$APK" | awk '{print $4}' | grep -E "lib/arm64-v8a/(libPySide6|QtCore|QtQml|QtQuick)" | head -15
|
||||
echo "PySide6 模块 .so 数量: $(unzip -l "$APK" | awk '{print $4}' | grep -cE 'lib/arm64-v8a/Qt.*\.abi3\.so')"
|
||||
|
||||
echo
|
||||
echo "=== dex 文件 ==="
|
||||
unzip -l "$APK" | awk '{print $4}' | grep -E "\.dex$" | head -6
|
||||
|
||||
echo
|
||||
echo "=== 部署目录中的 buildozer.spec(工具实际使用的配置) ==="
|
||||
grep -E "^(android.api|android.minapi|android.ndk_api|android.archs|version|requirements|android.permissions|p4a.branch|p4a.source_dir)" \
|
||||
/opt/lnxgit-android/src/.buildozer/android/platform/build-arm64-v8a/dists/LnxGit/buildozer.spec 2>/dev/null \
|
||||
|| echo "(未找到 dist 内的 buildozer.spec)"
|
||||
67
scripts/wsl_verify_app.sh
Normal file
67
scripts/wsl_verify_app.sh
Normal file
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env bash
|
||||
# 只盯 LnxGit 自己的启动日志,判定是否仍然闪退。
|
||||
#
|
||||
# 模拟器上 com.android.flysilkworm 之类的系统组件会不断抛 SIGILL 崩溃,
|
||||
# 用宽泛的 FATAL/DEBUG 关键字过滤会被它们的日志淹没,因此这里只按
|
||||
# 进程名 / 应用 tag 过滤。
|
||||
#
|
||||
# 用法:bash scripts/wsl_verify_app.sh [设备序列号] [等待秒数] [apk 路径]
|
||||
set -uo pipefail
|
||||
|
||||
ADB="${ADB:-/opt/lnxgit-android/android-sdk/platform-tools/adb}"
|
||||
DEVICE="${1:-}"
|
||||
WAIT="${2:-75}"
|
||||
APK="${3:-/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile/dist/LnxGit-0.1-x86_64-debug.apk}"
|
||||
PKG="org.lnxgit.lnxgit"
|
||||
|
||||
if [ -z "$DEVICE" ]; then
|
||||
DEVICE="$("$ADB" devices | awk 'NR>1 && $2=="device" {print $1; exit}')"
|
||||
fi
|
||||
[ -n "$DEVICE" ] || { echo "没有可用设备"; exit 1; }
|
||||
run_adb() { "$ADB" -s "$DEVICE" "$@"; }
|
||||
|
||||
echo "=== 设备 $DEVICE ==="
|
||||
echo "ABI : $(run_adb shell getprop ro.product.cpu.abilist | tr -d '\r')"
|
||||
echo "API : $(run_adb shell getprop ro.build.version.sdk | tr -d '\r')"
|
||||
|
||||
if [ -f "$APK" ]; then
|
||||
echo
|
||||
echo "=== 安装 $(basename "$APK") ==="
|
||||
run_adb uninstall "$PKG" >/dev/null 2>&1 || true
|
||||
run_adb install -r "$APK" 2>&1 | tail -3
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "=== 已安装版本 ==="
|
||||
run_adb shell pm list packages 2>/dev/null | grep lnxgit | tr -d '\r'
|
||||
|
||||
echo
|
||||
echo "=== 清日志并启动 ==="
|
||||
run_adb logcat -c 2>/dev/null
|
||||
run_adb shell am force-stop "$PKG" 2>/dev/null
|
||||
LAUNCH="$(run_adb shell cmd package resolve-activity --brief "$PKG" 2>/dev/null | tail -1 | tr -d '\r')"
|
||||
echo "组件: ${LAUNCH:-未解析到}"
|
||||
run_adb shell am start -n "$LAUNCH" 2>&1 | head -3
|
||||
|
||||
echo
|
||||
echo "=== 等待 ${WAIT} 秒 ==="
|
||||
sleep "$WAIT"
|
||||
|
||||
PID="$(run_adb shell pidof "$PKG" 2>/dev/null | tr -d '\r')"
|
||||
if [ -n "$PID" ]; then
|
||||
echo ">>> 进程存活: pid=$PID —— 没有闪退"
|
||||
else
|
||||
echo ">>> 进程已退出 —— 闪退"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "=== 应用自身日志(按进程名/tag 过滤) ==="
|
||||
run_adb logcat -d -v time 2>/dev/null \
|
||||
| grep -a -iE "lnxgit|QtLoader|QtCore|pybundle|shiboken|libpython|PythonActivity|dulwich" \
|
||||
| tail -60
|
||||
|
||||
echo
|
||||
echo "=== 与 python/动态库加载相关的错误 ==="
|
||||
run_adb logcat -d -v time 2>/dev/null \
|
||||
| grep -a -iE "dlopen|UnsatisfiedLink|library .* not found|ModuleNotFound|Traceback|ImportError" \
|
||||
| tail -20
|
||||
221
scripts/wsl_verify_patch.sh
Normal file
221
scripts/wsl_verify_patch.sh
Normal file
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env bash
|
||||
# 自检:构建期补丁(tools/sitecustomize_lnxgit.py)是否真的生效。
|
||||
#
|
||||
# 历史教训:补丁里 `_sys` 未定义,异常又被 `except: pass` 吞掉,
|
||||
# 结果 p4a.source_dir 与 python3==3.11.15 从未写进 buildozer.spec,
|
||||
# buildozer 每次去 GitHub 克隆干净的 p4a(3.14),编出的 APK 启动即报
|
||||
# dlopen failed: library "libpython3.11.so" not found
|
||||
# 因此这里逐项断言,任何一项不通过都直接失败退出。
|
||||
#
|
||||
# 用法(WSL 内,root 或 builder 均可):
|
||||
# bash scripts/wsl_verify_patch.sh
|
||||
set -uo pipefail
|
||||
|
||||
WORK="${WORK:-/opt/lnxgit-android}"
|
||||
VENV="$WORK/venv"
|
||||
SITE_DIR="$WORK/pysite"
|
||||
P4A_SRC="${LNXGIT_P4A_SOURCE:-$WORK/p4a-src}"
|
||||
VERSION="${LNXGIT_PYTHON_VERSION:-3.11.15}"
|
||||
BUILD_USER="${BUILD_USER:-builder}"
|
||||
SRC_DIR="${SRC_DIR:-/mnt/c/Users/Administrator/Documents/WEB/pygit-mobile}"
|
||||
|
||||
fail=0
|
||||
ok() { echo " [OK] $*"; }
|
||||
bad() { echo " [FAIL] $*"; fail=$((fail + 1)); }
|
||||
|
||||
echo "==> 安装最新补丁到 $SITE_DIR"
|
||||
mkdir -p "$SITE_DIR"
|
||||
cp -f "$SRC_DIR/tools/sitecustomize_lnxgit.py" "$SITE_DIR/sitecustomize.py"
|
||||
chmod -R a+rX "$SITE_DIR"
|
||||
chown -R "$BUILD_USER:$BUILD_USER" "$SITE_DIR" 2>/dev/null || true
|
||||
|
||||
echo
|
||||
echo "==> 1) 补丁能否在干净解释器中加载"
|
||||
out="$(env PYTHONPATH="$SITE_DIR" LNXGIT_PYTHON_VERSION="$VERSION" \
|
||||
LNXGIT_P4A_SOURCE="$P4A_SRC" \
|
||||
"$VENV/bin/python" -c "
|
||||
import sys
|
||||
print('HOOK', getattr(sys, '_lnxgit_hook_installed', False))
|
||||
" 2>&1)"
|
||||
echo "$out" | sed 's/^/ /'
|
||||
case "$out" in
|
||||
*"HOOK True"*) ok "hook 已安装" ;;
|
||||
*) bad "hook 未安装(补丁加载失败)" ;;
|
||||
esac
|
||||
|
||||
echo
|
||||
echo "==> 2) deploy_lib 是否被打上补丁标记"
|
||||
# deploy_lib 位于 PySide6/scripts 下,真实入口(pyside6-android-deploy)
|
||||
# 是把它作为脚本目录加入 sys.path 后运行的,这里照同样方式导入。
|
||||
out="$(env PYTHONPATH="$SITE_DIR" LNXGIT_PYTHON_VERSION="$VERSION" \
|
||||
LNXGIT_P4A_SOURCE="$P4A_SRC" \
|
||||
"$VENV/bin/python" -c "
|
||||
import sys
|
||||
sys.path.insert(0, '$VENV/lib/python3.11/site-packages/PySide6/scripts')
|
||||
import android_deploy # 顶层即 from deploy_lib.android.buildozer import Buildozer
|
||||
import deploy_lib.android.buildozer as b
|
||||
print('CONFIG', getattr(b.BuildozerConfig, '_lnxgit_patched', False))
|
||||
print('BUILDOZER', getattr(b.Buildozer, '_lnxgit_patched', False))
|
||||
" 2>&1)"
|
||||
echo "$out" | grep -v '^\[lnxgit-patch\]' | sed 's/^/ /'
|
||||
case "$out" in
|
||||
*"CONFIG True"*) ok "BuildozerConfig 已打补丁" ;;
|
||||
*) bad "BuildozerConfig 未打补丁" ;;
|
||||
esac
|
||||
case "$out" in
|
||||
*"BUILDOZER True"*) ok "Buildozer 已打补丁" ;;
|
||||
*) bad "Buildozer 未打补丁" ;;
|
||||
esac
|
||||
|
||||
echo
|
||||
echo "==> 3) 生成的 buildozer.spec 是否带上 p4a.source_dir 与 python3==$VERSION"
|
||||
SPEC_TEST_DIR="$(mktemp -d)"
|
||||
cp "$VENV/lib/python3.11/site-packages/buildozer/default.spec" "$SPEC_TEST_DIR/buildozer.spec"
|
||||
mkdir -p "$SPEC_TEST_DIR/jar"
|
||||
: > "$SPEC_TEST_DIR/jar/Qt6AndroidBindings.jar"
|
||||
chmod -R a+rwX "$SPEC_TEST_DIR"
|
||||
|
||||
out="$(env PYTHONPATH="$SITE_DIR" LNXGIT_PYTHON_VERSION="$VERSION" \
|
||||
LNXGIT_EXTRA_REQUIRES="dulwich,certifi" LNXGIT_P4A_SOURCE="$P4A_SRC" \
|
||||
LNXGIT_SCRIPTS_DIR="$VENV/lib/python3.11/site-packages/PySide6/scripts" \
|
||||
"$VENV/bin/python" - "$SPEC_TEST_DIR" <<'PY' 2>&1
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
sys.path.insert(0, os.environ["LNXGIT_SCRIPTS_DIR"])
|
||||
import android_deploy # noqa: F401 触发真实入口的导入顺序
|
||||
import deploy_lib.android.buildozer as b
|
||||
|
||||
tmp = Path(sys.argv[1])
|
||||
config = SimpleNamespace(
|
||||
title="LnxGit", ndk_path=None, sdk_path=None, arch="x86_64",
|
||||
recipe_dir=tmp / "recipes", dependency_files=[], jars_dir=tmp / "jar",
|
||||
# 故意打乱顺序:deploy_lib 内部用的是 list(set(...)),实际顺序就是这样随机的。
|
||||
# Qt6Core 必须被排到最前,否则 Qt6Quick 的 JNI_OnLoad 拿不到 JavaVM 会 SIGSEGV。
|
||||
modules=["QuickControls2", "Gui", "OpenGL", "Quick", "Qml", "Network", "Core", "Svg"],
|
||||
local_libs=[], icon="", exe_dir=tmp / "bin",
|
||||
)
|
||||
b.BuildozerConfig(tmp / "buildozer.spec", config)
|
||||
print("QT_MODULES", ",".join(config.modules))
|
||||
print((tmp / "buildozer.spec").read_text(encoding="utf-8"))
|
||||
PY
|
||||
)"
|
||||
spec="$(printf '%s\n' "$out" | grep -v '^\[lnxgit-patch\]')"
|
||||
|
||||
if printf '%s\n' "$spec" | grep -q "^p4a.source_dir = $P4A_SRC"; then
|
||||
ok "spec 含 p4a.source_dir = $P4A_SRC"
|
||||
else
|
||||
bad "spec 缺少 p4a.source_dir"
|
||||
fi
|
||||
if printf '%s\n' "$spec" | grep -q "^requirements = .*python3==$VERSION"; then
|
||||
ok "spec 含 python3==$VERSION"
|
||||
else
|
||||
bad "spec 缺少 python3==$VERSION"
|
||||
fi
|
||||
if printf '%s\n' "$spec" | grep -q "^requirements = .*dulwich"; then
|
||||
ok "spec 含第三方依赖 dulwich/certifi"
|
||||
else
|
||||
bad "spec 缺少第三方依赖"
|
||||
fi
|
||||
expected_order="QT_MODULES Core,Network,Gui,OpenGL,Svg,Qml,Quick,QuickControls2"
|
||||
if printf '%s\n' "$out" | grep -qF "$expected_order"; then
|
||||
ok "qt 模块按依赖序排列(Core 在最前)"
|
||||
else
|
||||
bad "qt 模块顺序不对(期望 $expected_order)"
|
||||
printf '%s\n' "$out" | grep 'QT_MODULES' | sed 's/^/ /'
|
||||
fi
|
||||
|
||||
printf '%s\n' "$spec" | grep -E '^(requirements|p4a\.source_dir|android\.archs)' | sed 's/^/ /'
|
||||
rm -rf "$SPEC_TEST_DIR"
|
||||
|
||||
echo
|
||||
echo "==> 4) 固定目录里 p4a recipe 的版本"
|
||||
for name in python3 hostpython3; do
|
||||
recipe="$P4A_SRC/pythonforandroid/recipes/$name/__init__.py"
|
||||
if [ -f "$recipe" ]; then
|
||||
line="$(grep -nE '^\s*version\s*=' "$recipe" | head -1)"
|
||||
if printf '%s' "$line" | grep -q "\"$VERSION\""; then
|
||||
ok "$name: $(printf '%s' "$line" | cut -c1-70)"
|
||||
else
|
||||
bad "$name 版本不是 $VERSION:$(printf '%s' "$line" | cut -c1-70)"
|
||||
fi
|
||||
count="$(grep -c '_LNXGIT_PINNED' "$recipe")"
|
||||
if [ "$count" -le 4 ]; then
|
||||
ok "$name 注释未膨胀($count 处标记)"
|
||||
else
|
||||
bad "$name 注释膨胀($count 处标记),请先跑 wsl_fix_recipes.sh"
|
||||
fi
|
||||
else
|
||||
bad "找不到 $recipe"
|
||||
fi
|
||||
done
|
||||
|
||||
echo
|
||||
echo "==> 5) cleanup() 是否保留 .buildozer 构建缓存"
|
||||
CLEAN_TEST_DIR="$(mktemp -d)"
|
||||
chmod -R a+rwX "$CLEAN_TEST_DIR"
|
||||
out="$(env PYTHONPATH="$SITE_DIR" LNXGIT_SCRIPTS_DIR="$VENV/lib/python3.11/site-packages/PySide6/scripts" \
|
||||
"$VENV/bin/python" - "$CLEAN_TEST_DIR" <<'PY' 2>&1
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.environ["LNXGIT_SCRIPTS_DIR"])
|
||||
import android_deploy # noqa: F401 模拟真实入口的导入顺序
|
||||
import deploy_lib
|
||||
import deploy_lib.deploy_util as deploy_util
|
||||
|
||||
tmp = Path(sys.argv[1])
|
||||
project = tmp / "proj"
|
||||
cached = project / "deployment" / ".buildozer" / "marker"
|
||||
cached.mkdir(parents=True)
|
||||
(cached / "keep.txt").write_text("x", encoding="utf-8")
|
||||
(project / "buildozer.spec").write_text("dummy", encoding="utf-8")
|
||||
|
||||
|
||||
class FakeConfig:
|
||||
project_dir = project
|
||||
generated_files_path = project / "deployment"
|
||||
|
||||
|
||||
print("PATCHED", getattr(deploy_util, "_lnxgit_patched", False))
|
||||
print("BOUND", deploy_lib.cleanup is deploy_util.cleanup)
|
||||
deploy_util.cleanup(FakeConfig(), is_android=True)
|
||||
|
||||
print("CACHE_RESTORED", (project / ".buildozer" / "marker" / "keep.txt").is_file())
|
||||
print("DEPLOYMENT_REMOVED", not (project / "deployment").exists())
|
||||
print("SPEC_REMOVED", not (project / "buildozer.spec").exists())
|
||||
PY
|
||||
)"
|
||||
echo "$out" | grep -v '^\[lnxgit-patch\]' | sed 's/^/ /'
|
||||
case "$out" in
|
||||
*"PATCHED True"*) ok "deploy_util 已打补丁" ;;
|
||||
*) bad "deploy_util 未打补丁" ;;
|
||||
esac
|
||||
case "$out" in
|
||||
*"BOUND True"*) ok "deploy_lib.cleanup 已指向补丁版本" ;;
|
||||
*) bad "deploy_lib.cleanup 仍是原函数(补丁挂晚了)" ;;
|
||||
esac
|
||||
case "$out" in
|
||||
*"CACHE_RESTORED True"*) ok ".buildozer 缓存已恢复(不会每次重编 CPython)" ;;
|
||||
*) bad ".buildozer 缓存未恢复" ;;
|
||||
esac
|
||||
case "$out" in
|
||||
*"DEPLOYMENT_REMOVED True"*) ok "deployment 目录已清理" ;;
|
||||
*) bad "deployment 目录未清理" ;;
|
||||
esac
|
||||
case "$out" in
|
||||
*"SPEC_REMOVED True"*) ok "buildozer.spec 已删除" ;;
|
||||
*) bad "buildozer.spec 未删除" ;;
|
||||
esac
|
||||
rm -rf "$CLEAN_TEST_DIR"
|
||||
|
||||
echo
|
||||
if [ "$fail" -eq 0 ]; then
|
||||
echo "==> 全部通过"
|
||||
else
|
||||
echo "==> 有 $fail 项未通过"
|
||||
fi
|
||||
exit "$fail"
|
||||
225
tools/check_glyphs.py
Normal file
225
tools/check_glyphs.py
Normal file
@@ -0,0 +1,225 @@
|
||||
#!/usr/bin/env python3
|
||||
"""检查 QML 里用到的 Unicode 图标字符,在 **Android 设备上**是否真有字形。
|
||||
|
||||
为什么需要它
|
||||
------------
|
||||
LnxGit 用 Unicode 符号当图标(`⟳` `+` `⋯` `⤓` 等),桌面上一切正常,
|
||||
装到设备上却可能变成豆腐块。原因是双重巧合:
|
||||
|
||||
1. Android 的符号字体是**子集化**的(只有
|
||||
`NotoSansSymbols-Regular-Subsetted.ttf` / `Subsetted2.ttf`);
|
||||
2. 更要命的是,**Qt 的字体回退链里根本没有这个符号字体** —— 实测
|
||||
`⟳`(U+27F3)在系统字体里明明有字形,界面里依旧渲染成豆腐块,
|
||||
而中文(NotoSansCJK)和 emoji(NotoColorEmoji)都正常。
|
||||
|
||||
所以判据不是"系统里有没有字形",而是"Qt 会用的那几个字体有没有":
|
||||
Roboto(拉丁)、NotoSansCJK(中文)、NotoColorEmoji(emoji)。
|
||||
本脚本就按这个判据来。
|
||||
|
||||
用法
|
||||
----
|
||||
先把设备字体拉到本地(只需要一个字体目录):
|
||||
|
||||
bash scripts/wsl_pull_fonts.sh emulator-5554 /tmp/lnxgit-fonts
|
||||
python3 tools/check_glyphs.py qml /tmp/lnxgit-fonts
|
||||
|
||||
新增图标前先跑一遍,能省掉"构建 → 安装 → 发现是豆腐块"的来回。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 常见候选字符,便于挑选替代方案时快速比较
|
||||
INTERESTING = {
|
||||
0xFF0B: "+ 全角加号", 0x22EF: "⋯ 更多", 0x2190: "← 返回", 0x2212: "− 减号",
|
||||
0x00B7: "· 间隔点", 0x2261: "≡ 三横",
|
||||
0x27F3: "⟳ 刷新(旧,不可用)", 0x21BB: "↻ 刷新(不可用)",
|
||||
0x2913: "⤓ 下载(旧,不可用)", 0x29C9: "⧉ 复制(旧,不可用)",
|
||||
0x2398: "⎘ 复制(旧,不可用)", 0x22EE: "⋮ 竖点(不可用)",
|
||||
0x1F504: "🔄 刷新", 0x2B07: "⬇ 向下", 0x1F4CB: "📋 剪贴板",
|
||||
0x1F4C4: "📄 文件", 0x1F4C2: "📂 文件夹", 0x1F50D: "🔍 搜索",
|
||||
0x1F5D1: "🗑 删除", 0x1F464: "👤 作者", 0x1F517: "🔗 链接",
|
||||
0x2699: "⚙ 齿轮", 0x2714: "✔ 勾", 0x2716: "✖ 叉",
|
||||
0x2795: "➕", 0x2796: "➖",
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- TTF/OTF 解析
|
||||
|
||||
|
||||
def _table_dir(data: bytes, offset: int) -> dict[str, tuple[int, int]]:
|
||||
num_tables = struct.unpack(">H", data[offset + 4:offset + 6])[0]
|
||||
tables: dict[str, tuple[int, int]] = {}
|
||||
for index in range(num_tables):
|
||||
record = offset + 12 + index * 16
|
||||
tag = data[record:record + 4].decode("latin-1")
|
||||
table_offset, length = struct.unpack(">II", data[record + 8:record + 16])
|
||||
tables[tag] = (table_offset, length)
|
||||
return tables
|
||||
|
||||
|
||||
def _cmap_format4(data: bytes, offset: int) -> set[int]:
|
||||
seg_x2 = struct.unpack(">H", data[offset + 6:offset + 8])[0]
|
||||
seg = seg_x2 // 2
|
||||
end_off = offset + 14
|
||||
ends = struct.unpack(f">{seg}H", data[end_off:end_off + seg_x2])
|
||||
start_off = end_off + seg_x2 + 2 # 跳过 reservedPad
|
||||
starts = struct.unpack(f">{seg}H", data[start_off:start_off + seg_x2])
|
||||
delta_off = start_off + seg_x2
|
||||
deltas = struct.unpack(f">{seg}h", data[delta_off:delta_off + seg_x2])
|
||||
range_off = delta_off + seg_x2
|
||||
ranges = struct.unpack(f">{seg}H", data[range_off:range_off + seg_x2])
|
||||
|
||||
codepoints: set[int] = set()
|
||||
for index in range(seg):
|
||||
start, end = starts[index], ends[index]
|
||||
if start == 0xFFFF:
|
||||
continue
|
||||
for code in range(start, end + 1):
|
||||
if code == 0xFFFF:
|
||||
continue
|
||||
if ranges[index] == 0:
|
||||
gid = (code + deltas[index]) & 0xFFFF
|
||||
else:
|
||||
addr = range_off + index * 2 + ranges[index] + (code - start) * 2
|
||||
if addr + 2 > len(data):
|
||||
continue
|
||||
gid = struct.unpack(">H", data[addr:addr + 2])[0]
|
||||
if gid:
|
||||
gid = (gid + deltas[index]) & 0xFFFF
|
||||
if gid:
|
||||
codepoints.add(code)
|
||||
return codepoints
|
||||
|
||||
|
||||
def _cmap_format12(data: bytes, offset: int) -> set[int]:
|
||||
groups = struct.unpack(">I", data[offset + 12:offset + 16])[0]
|
||||
codepoints: set[int] = set()
|
||||
for index in range(groups):
|
||||
record = offset + 16 + index * 12
|
||||
start, end, gid = struct.unpack(">III", data[record:record + 12])
|
||||
if gid or start == end:
|
||||
codepoints.add(start)
|
||||
if end - start > 0x20000: # 防御异常大的区间
|
||||
continue
|
||||
codepoints.update(range(start, end + 1))
|
||||
return codepoints
|
||||
|
||||
|
||||
def _cmap_format6(data: bytes, offset: int) -> set[int]:
|
||||
first, count = struct.unpack(">HH", data[offset + 6:offset + 10])
|
||||
gids = struct.unpack(f">{count}H", data[offset + 10:offset + 10 + count * 2])
|
||||
return {first + i for i, gid in enumerate(gids) if gid}
|
||||
|
||||
|
||||
def _cmap(data: bytes, tables: dict[str, tuple[int, int]]) -> set[int]:
|
||||
if "cmap" not in tables:
|
||||
return set()
|
||||
base = tables["cmap"][0]
|
||||
count = struct.unpack(">H", data[base + 2:base + 4])[0]
|
||||
codepoints: set[int] = set()
|
||||
for index in range(count):
|
||||
record = base + 4 + index * 8
|
||||
_, _, sub_offset = struct.unpack(">HHI", data[record:record + 8])
|
||||
sub = base + sub_offset
|
||||
fmt = struct.unpack(">H", data[sub:sub + 2])[0]
|
||||
try:
|
||||
if fmt == 4:
|
||||
codepoints |= _cmap_format4(data, sub)
|
||||
elif fmt == 12:
|
||||
codepoints |= _cmap_format12(data, sub)
|
||||
elif fmt == 6:
|
||||
codepoints |= _cmap_format6(data, sub)
|
||||
except (struct.error, IndexError):
|
||||
continue
|
||||
return codepoints
|
||||
|
||||
|
||||
def font_codepoints(path: Path) -> set[int]:
|
||||
"""读一个字体文件(含 .ttc 集合)覆盖的全部码点。"""
|
||||
data = path.read_bytes()
|
||||
codepoints: set[int] = set()
|
||||
if data[:4] == b"ttcf":
|
||||
num_fonts = struct.unpack(">I", data[8:12])[0]
|
||||
offsets = struct.unpack(f">{num_fonts}I", data[12:12 + num_fonts * 4])
|
||||
for offset in offsets:
|
||||
codepoints |= _cmap(data, _table_dir(data, offset))
|
||||
else:
|
||||
codepoints |= _cmap(data, _table_dir(data, 0))
|
||||
return codepoints
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- 主流程
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="检查 QML 图标字符在设备上是否有字形")
|
||||
parser.add_argument("qml_dir", nargs="?", default="qml", help="QML 目录")
|
||||
parser.add_argument("font_dir", nargs="?", default="/tmp/lnxgit-fonts",
|
||||
help="设备字体目录(先用 scripts/wsl_pull_fonts.sh 拉取)")
|
||||
args = parser.parse_args()
|
||||
|
||||
qml_dir = Path(args.qml_dir)
|
||||
font_dir = Path(args.font_dir)
|
||||
if not font_dir.is_dir():
|
||||
print(f"找不到字体目录 {font_dir}\n"
|
||||
f"先执行:bash scripts/wsl_pull_fonts.sh <设备序列号> {font_dir}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
fonts: dict[str, set[int]] = {}
|
||||
for path in sorted(font_dir.iterdir()):
|
||||
if path.suffix.lower() in {".ttf", ".otf", ".ttc"}:
|
||||
try:
|
||||
fonts[path.name] = font_codepoints(path)
|
||||
except Exception as exc: # pragma: no cover
|
||||
print(f" 跳过 {path.name}: {exc}")
|
||||
|
||||
qt_fonts = [name for name in fonts if "Symbols" not in name]
|
||||
|
||||
def safe(code: int) -> bool:
|
||||
return any(code in fonts[name] for name in qt_fonts)
|
||||
|
||||
used: dict[int, list[str]] = {}
|
||||
for path in qml_dir.rglob("*.qml"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
for line_no, line in enumerate(text.splitlines(), 1):
|
||||
for literal in re.findall(r'"([^"\\]*)"', line):
|
||||
for ch in literal:
|
||||
if ord(ch) > 0x7F:
|
||||
used.setdefault(ord(ch), []).append(f"{path.name}:{line_no}")
|
||||
|
||||
print(f"=== {qml_dir}:字体 {len(fonts)} 个"
|
||||
f"(Qt 回退链 {len(qt_fonts)} 个),非 ASCII 字符 {len(used)} 个 ===\n")
|
||||
|
||||
broken = [code for code in sorted(used)
|
||||
# 跳过 CJK、全角标点,以及 emoji 变体选择符(它不单独渲染)
|
||||
if not (0x3000 <= code <= 0x9FFF or 0xFF00 <= code <= 0xFFEF)
|
||||
and code != 0xFE0F and not safe(code)]
|
||||
|
||||
if broken:
|
||||
print("!! 不在 Qt 字体回退链里(设备上会渲染成豆腐块):")
|
||||
for code in broken:
|
||||
places = sorted(set(used[code]))[:4]
|
||||
print(f" U+{code:04X} {chr(code)} {' '.join(places)}")
|
||||
print("\n 替代方案参考下面的候选表。")
|
||||
else:
|
||||
print("OK QML 里所有图标字符都能在设备上正常渲染。")
|
||||
|
||||
print("\n=== 候选字符可用性 ===")
|
||||
for code in sorted(INTERESTING):
|
||||
short = ", ".join(sorted(n.replace("Noto", "").replace(".ttf", "")
|
||||
.replace(".ttc", "") for n in qt_fonts
|
||||
if code in fonts[n])) or "仅 SansSymbols —— 不可用"
|
||||
print(f" {'OK ' if safe(code) else '!! '}U+{code:04X} {chr(code):<3} "
|
||||
f"{INTERESTING[code]:<20} {short}")
|
||||
|
||||
return 1 if broken else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
112
tools/check_qml_layout.py
Normal file
112
tools/check_qml_layout.py
Normal file
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""检查 QML 里 Column / Row 的子项是否误用了锚点。
|
||||
|
||||
为什么需要它
|
||||
------------
|
||||
Qt 的 Column / Row 自己负责摆放子项,所以子项**不能**再用
|
||||
``anchors.top`` / ``bottom`` / ``fill`` / ``centerIn`` 之类的锚点。
|
||||
一旦用了,Qt 不只是忽略那个锚点 —— **整个 Column 会停止布局**,
|
||||
所有子项堆到原点互相重叠。
|
||||
|
||||
这个坑很隐蔽:只有当列表非空、内容真的画出来时才会露馅,
|
||||
空列表时一切看起来都正常(曾经表现为「提交历史」的标题被列表盖住)。
|
||||
|
||||
用法::
|
||||
|
||||
python3 tools/check_qml_layout.py qml
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Column / Row 直接子项的属性行,缩进正好比布局项多一级
|
||||
LAYOUT_RE = re.compile(r"^(?P<indent>\s*)(Column|Row)\s*\{")
|
||||
ANCHOR_RE = re.compile(
|
||||
r"anchors\.(top|bottom|left|right|fill|centerIn|verticalCenter|horizontalCenter)\s*:")
|
||||
|
||||
#: 实测这些锚点会让整个 Column/Row 停止布局(子项全部堆到原点)
|
||||
FATAL = {"top", "bottom", "fill", "centerIn"}
|
||||
#: 其余锚点 Qt 一般仍能排出顺序,只是锚点本身被忽略,降级为提示
|
||||
SOFT = {"left", "right", "verticalCenter", "horizontalCenter"}
|
||||
|
||||
|
||||
def scan(path: Path) -> tuple[list[tuple[int, str, str]], int, int]:
|
||||
"""返回 ([(行号, 级别, 代码行)], 致命数, 提示数)。"""
|
||||
lines = path.read_text(encoding="utf-8").splitlines()
|
||||
issues: list[tuple[int, str, str]] = []
|
||||
hard = 0
|
||||
soft = 0
|
||||
|
||||
# 记录当前打开的 Column / Row 块(行号, 缩进)
|
||||
open_blocks: list[tuple[int, int]] = []
|
||||
|
||||
for number, line in enumerate(lines, 1):
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("//"):
|
||||
continue
|
||||
|
||||
indent = len(line) - len(line.lstrip())
|
||||
|
||||
match = LAYOUT_RE.match(line)
|
||||
if match:
|
||||
open_blocks.append((number, indent))
|
||||
continue
|
||||
|
||||
# 离开当前布局块:缩进回退到布局项本身或更浅
|
||||
while open_blocks and indent <= open_blocks[-1][1]:
|
||||
open_blocks.pop()
|
||||
|
||||
if not open_blocks:
|
||||
continue
|
||||
|
||||
anchor = ANCHOR_RE.search(stripped)
|
||||
if not anchor:
|
||||
continue
|
||||
|
||||
# 只看**直接**子项的属性行:子项声明在 +4,它的属性在 +8。
|
||||
# 更深层是子项内部的嵌套组件,不受这个布局容器影响。
|
||||
parent_indent = open_blocks[-1][1]
|
||||
if indent != parent_indent + 8:
|
||||
continue
|
||||
|
||||
kind = anchor.group(1)
|
||||
if kind not in FATAL:
|
||||
soft += 1
|
||||
issues.append((number, "提示", stripped))
|
||||
continue
|
||||
hard += 1
|
||||
issues.append((number, "错误", stripped))
|
||||
|
||||
return issues, hard, soft
|
||||
|
||||
|
||||
def main() -> int:
|
||||
root = Path(sys.argv[1] if len(sys.argv) > 1 else "qml")
|
||||
total_hard = 0
|
||||
total_soft = 0
|
||||
|
||||
for path in sorted(root.rglob("*.qml")):
|
||||
issues, hard, soft = scan(path)
|
||||
total_hard += hard
|
||||
total_soft += soft
|
||||
if not issues:
|
||||
continue
|
||||
print(f"\n{path}")
|
||||
for number, marker, line in issues:
|
||||
print(f" {marker} 第 {number} 行: {line}")
|
||||
|
||||
print()
|
||||
if total_hard:
|
||||
print(f"==> 发现 {total_hard} 处会让 Column/Row 失效的锚点"
|
||||
f"(另有 {total_soft} 处提示)")
|
||||
print(" 修法:把该子项移出布局容器,或改用 width/height + margin 定位。")
|
||||
return 1
|
||||
print(f"==> 没有致命锚点冲突({total_soft} 处提示可人工确认)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
91
tools/clean_release.py
Normal file
91
tools/clean_release.py
Normal file
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""清理 Gitea Release 里堆积的附件。
|
||||
|
||||
历史上用切片上传大 APK 时,Release 里堆了几十个 ``xxx.apk.part001`` 这样的
|
||||
同名附件,还有若干测试用的 ``probe_*.bin``。这个脚本一次性清干净。
|
||||
|
||||
走**内网直连**(默认 192.168.100.103:8080)而不是公网域名:
|
||||
公网经 Cloudflare,附件操作没必要绕那一层。
|
||||
|
||||
令牌需要**仓库管理员**权限 —— 只读令牌删除会返回 403。
|
||||
|
||||
用法::
|
||||
|
||||
python tools/clean_release.py --token <token> [--dry-run]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_BASE = "http://192.168.100.103:8080"
|
||||
DEFAULT_REPO = "l/lnxgit"
|
||||
DEFAULT_RELEASE_ID = 1
|
||||
|
||||
|
||||
def api(base: str, token: str, path: str, method: str = "GET"):
|
||||
request = urllib.request.Request(f"{base}/api/v1/{path}", method=method)
|
||||
request.add_header("Authorization", f"token {token}")
|
||||
request.add_header("Accept", "application/json")
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
body = response.read()
|
||||
return json.loads(body) if body else None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="清理 Release 附件")
|
||||
parser.add_argument("--token", required=True)
|
||||
parser.add_argument("--base", default=DEFAULT_BASE)
|
||||
parser.add_argument("--repo", default=DEFAULT_REPO)
|
||||
parser.add_argument("--release-id", type=int, default=DEFAULT_RELEASE_ID)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
parser.add_argument("--keep", action="append", default=[],
|
||||
help="保留匹配该名字的附件(可多次,支持前缀匹配)")
|
||||
args = parser.parse_args()
|
||||
|
||||
release = api(args.base, args.token,
|
||||
f"repos/{args.repo}/releases/{args.release_id}")
|
||||
assets = release.get("assets", [])
|
||||
print(f"Release id={release['id']} tag={release['tag_name']}")
|
||||
print(f"现有附件 {len(assets)} 个,合计 "
|
||||
f"{sum(a['size'] for a in assets) / 1048576:.1f} MB\n")
|
||||
|
||||
targets = [a for a in assets
|
||||
if not any(a["name"].startswith(k) for k in args.keep)]
|
||||
if not targets:
|
||||
print("没有需要清理的附件")
|
||||
return 0
|
||||
|
||||
deleted = failed = 0
|
||||
for asset in targets:
|
||||
name = asset["name"]
|
||||
if args.dry_run:
|
||||
print(f" [dry-run] 将删除 {name}({asset['size'] / 1048576:.1f} MB)")
|
||||
continue
|
||||
try:
|
||||
api(args.base, args.token,
|
||||
f"repos/{args.repo}/releases/{args.release_id}/assets/{asset['id']}",
|
||||
method="DELETE")
|
||||
deleted += 1
|
||||
print(f" 已删除 {name}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
failed += 1
|
||||
hint = "(令牌可能没有管理员权限)" if exc.code == 403 else ""
|
||||
print(f" 删除失败 {name}: HTTP {exc.code} {exc.reason}{hint}")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
failed += 1
|
||||
print(f" 删除失败 {name}: {type(exc).__name__}: {exc}")
|
||||
|
||||
if not args.dry_run:
|
||||
print(f"\n==> 已删除 {deleted} 个,失败 {failed} 个")
|
||||
remaining = api(args.base, args.token,
|
||||
f"repos/{args.repo}/releases/{args.release_id}").get("assets", [])
|
||||
print(f" 剩余附件 {len(remaining)} 个")
|
||||
return 0 if failed == 0 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
76
tools/cleanup_release_assets.py
Normal file
76
tools/cleanup_release_assets.py
Normal file
@@ -0,0 +1,76 @@
|
||||
"""清理 Gitea Release 上的临时/探针附件(保留正式发布产物)。
|
||||
|
||||
用法::
|
||||
|
||||
python tools/cleanup_release_assets.py --token <token> [--release-id 1] [--keep 正式文件名]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from lnxgit import gitea # noqa: E402
|
||||
|
||||
# 构建/调试过程中产生的临时附件前缀
|
||||
TEMP_PREFIXES = ("par", "probe_", "sp1", "sp2", "att", "temp")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="清理 Release 临时附件")
|
||||
parser.add_argument("--token", required=True)
|
||||
parser.add_argument("--base", default=gitea.DEFAULT_BASE)
|
||||
parser.add_argument("--owner", default="l")
|
||||
parser.add_argument("--repo", default="lnxgit")
|
||||
parser.add_argument("--release-id", type=int, default=1)
|
||||
parser.add_argument("--all-parts", action="store_true",
|
||||
help="同时删除 .partNNN 分片附件")
|
||||
parser.add_argument("--force", action="store_true", help="真正执行删除")
|
||||
args = parser.parse_args()
|
||||
|
||||
release = gitea.request(args.base,
|
||||
f"/api/v1/repos/{args.owner}/{args.repo}/releases/{args.release_id}",
|
||||
token=args.token)
|
||||
assets = release.get("assets", [])
|
||||
print(f"Release 共 {len(assets)} 个附件")
|
||||
|
||||
victims = []
|
||||
for asset in assets:
|
||||
name = asset["name"]
|
||||
if name.startswith(TEMP_PREFIXES) or (args.all_parts and ".part" in name):
|
||||
victims.append(asset)
|
||||
|
||||
if not victims:
|
||||
print("没有需要清理的附件")
|
||||
return 0
|
||||
|
||||
for asset in victims:
|
||||
size = asset["size"] / 1024 / 1024
|
||||
if args.force:
|
||||
for attempt in range(3):
|
||||
try:
|
||||
gitea.request(
|
||||
args.base,
|
||||
f"/api/v1/repos/{args.owner}/{args.repo}/releases/"
|
||||
f"{args.release_id}/assets/{asset['id']}",
|
||||
token=args.token, method="DELETE", timeout=60)
|
||||
print(f" 已删除 {asset['name']}({size:.1f} MB)")
|
||||
break
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f" 删除失败(第 {attempt + 1} 次): {type(exc).__name__}")
|
||||
time.sleep(3)
|
||||
else:
|
||||
print(f" [预演] 将删除 {asset['name']}({size:.1f} MB)")
|
||||
|
||||
if not args.force:
|
||||
print("\n加 --force 才会真正删除。")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
382
tools/graph_test.py
Normal file
382
tools/graph_test.py
Normal file
@@ -0,0 +1,382 @@
|
||||
#!/usr/bin/env python3
|
||||
"""图谱泳道布局的回归测试。
|
||||
|
||||
泳道图最容易出现"看起来对、连线却错位"的问题,所以这里既做机器断言
|
||||
(拓扑序、连线连续性、父子关系),也打印结构表供人眼核对。
|
||||
|
||||
用法::
|
||||
|
||||
python3 tools/graph_test.py
|
||||
|
||||
需要系统里有 git(只用来造测试仓库,应用本身不依赖它)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from lnxgit import gitcore # noqa: E402
|
||||
|
||||
FAILED: list[str] = []
|
||||
FIXED_ENV = dict(os.environ, GIT_AUTHOR_DATE="2020-01-01T00:00:00",
|
||||
GIT_COMMITTER_DATE="2020-01-01T00:00:00")
|
||||
|
||||
|
||||
def check(condition: bool, message: str) -> None:
|
||||
if not condition:
|
||||
FAILED.append(message)
|
||||
print(f" [FAIL] {message}")
|
||||
|
||||
|
||||
def git(repo: Path, *args: str) -> str:
|
||||
result = subprocess.run(["git", "-C", str(repo), *args],
|
||||
capture_output=True, env=FIXED_ENV)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"git {' '.join(args)} 失败:\n"
|
||||
f"{result.stderr.decode('utf-8', 'replace')}")
|
||||
return result.stdout.decode().strip()
|
||||
|
||||
|
||||
def linear_repo(repo: Path, count: int = 1) -> None:
|
||||
repo.mkdir(parents=True, exist_ok=True)
|
||||
git(repo, "init", "-q", "-b", "main")
|
||||
git(repo, "config", "user.email", "tester@lnxgit.local")
|
||||
git(repo, "config", "user.name", "LnxGit Tester")
|
||||
for index in range(count):
|
||||
(repo / f"base-{index}.txt").write_text(str(index), encoding="utf-8")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-qm", f"基础提交 {index}")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 不变量
|
||||
|
||||
|
||||
def assert_invariants(tag: str, commits: list[dict]) -> None:
|
||||
print(f"\n--- {tag}:{len(commits)} 条提交 ---")
|
||||
if not commits:
|
||||
return
|
||||
|
||||
# 1) 连线连续:本行 above 必须等于上一行 below
|
||||
for index in range(1, len(commits)):
|
||||
check(sorted(commits[index]["graphAbove"]) == sorted(commits[index - 1]["graphBelow"]),
|
||||
f"第 {index} 行 above 与上一行 below 不连续: "
|
||||
f"{commits[index]['graphAbove']} vs {commits[index-1]['graphBelow']}")
|
||||
|
||||
# 2) 第一行没有线从上方来
|
||||
check(commits[0]["graphAbove"] == [],
|
||||
f"第一行 above 应为空,实际 {commits[0]['graphAbove']}")
|
||||
|
||||
# 3) 有子提交指向的行,节点列必须在 above 里,否则线会断开
|
||||
child_count: dict[str, int] = {}
|
||||
for row in commits:
|
||||
for parent in row["parents"]:
|
||||
child_count[parent] = child_count.get(parent, 0) + 1
|
||||
for index, row in enumerate(commits):
|
||||
if child_count.get(row["sha"], 0) > 0:
|
||||
check(row["lane"] in row["graphAbove"],
|
||||
f"第 {index} 行(有子提交)节点列 {row['lane']} "
|
||||
f"不在 above {row['graphAbove']} 中")
|
||||
|
||||
# 4) 有父提交时,节点必须能向下连出去
|
||||
for index, row in enumerate(commits):
|
||||
if row["parents"]:
|
||||
check(row["lane"] in row["graphBelow"] or row["graphLinks"],
|
||||
f"第 {index} 行(有父提交)节点向下没有任何连线")
|
||||
|
||||
# 5) graphLinks 的落点必须真实存在
|
||||
for index, row in enumerate(commits):
|
||||
for target in row["graphLinks"]:
|
||||
check(target in row["graphBelow"],
|
||||
f"第 {index} 行 graphLinks 指向 {target},不在 below {row['graphBelow']} 中")
|
||||
|
||||
# 6) 拓扑序:父提交必须排在本行之后
|
||||
position = {row["sha"]: i for i, row in enumerate(commits)}
|
||||
for index, row in enumerate(commits):
|
||||
for parent in row["parents"]:
|
||||
if parent in position:
|
||||
check(position[parent] > index,
|
||||
f"父提交 {parent[:8]} 出现在子提交 {row['sha'][:8]} 之前")
|
||||
|
||||
# 7) lane 不越界
|
||||
for index, row in enumerate(commits):
|
||||
check(0 <= row["lane"] < max(1, row["graphCols"]),
|
||||
f"第 {index} 行 lane={row['lane']} 超出 graphCols={row['graphCols']}")
|
||||
|
||||
# 8) 同一行 below 不重复
|
||||
for index, row in enumerate(commits):
|
||||
check(len(set(row["graphBelow"])) == len(row["graphBelow"]),
|
||||
f"第 {index} 行 below 有重复列 {row['graphBelow']}")
|
||||
|
||||
# 9) 配色数组长度与列数一致
|
||||
for index, row in enumerate(commits):
|
||||
check(len(row["graphAboveColors"]) == row["graphCols"]
|
||||
and len(row["graphBelowColors"]) == row["graphCols"],
|
||||
f"第 {index} 行配色数组长度与 graphCols={row['graphCols']} 不一致")
|
||||
|
||||
# 10) 跨行配色一致:同一列的颜色在相邻两行里必须相同。
|
||||
# 同一条线在两行里颜色不同的话,行界处会出现突兀的异色短线。
|
||||
# 按列比较而不是直接比数组 —— 两行的 graphCols 可能不同,
|
||||
# 数组末尾会用 -1 补齐。
|
||||
for index in range(1, len(commits)):
|
||||
previous = commits[index - 1]["graphBelowColors"]
|
||||
current = commits[index]["graphAboveColors"]
|
||||
for column in commits[index]["graphAbove"]:
|
||||
if column >= len(previous) or column >= len(current):
|
||||
continue
|
||||
check(previous[column] == current[column],
|
||||
f"第 {index} 行第 {column} 列配色 {current[column]} 与"
|
||||
f"上一行的 {previous[column]} 不一致")
|
||||
|
||||
# 11) 二维地图坐标:每个提交都要有,且整图尺寸足以容纳
|
||||
for index, row in enumerate(commits):
|
||||
check("mapX" in row and "mapY" in row, f"第 {index} 行缺少地图坐标")
|
||||
|
||||
# 12) 地图是"时间从下往上":父提交必须排在子提交下面(mapY 更大)
|
||||
for index, row in enumerate(commits):
|
||||
for parent in row["parents"]:
|
||||
if parent in position:
|
||||
check(commits[position[parent]]["mapY"] > row["mapY"],
|
||||
f"父提交 {parent[:8]} 的 mapY 不大于子提交 {row['sha'][:8]},"
|
||||
f"画出来会父子颠倒")
|
||||
|
||||
# 13) 地图轨道与坐标自洽:同一轨道上的节点横坐标必须相同
|
||||
for row in commits:
|
||||
lane = row.get("mapLane")
|
||||
same_lane = [other for other in commits if other.get("mapLane") == lane]
|
||||
check(len({other["mapX"] for other in same_lane}) == 1,
|
||||
f"地图轨道 {lane} 的节点横坐标不一致")
|
||||
|
||||
# 14) 节点不能重叠(横纵坐标组唯一)
|
||||
seen = set()
|
||||
for row in commits:
|
||||
key = (row["mapX"], row["mapY"])
|
||||
check(key not in seen, f"节点位置重复: {key}")
|
||||
seen.add(key)
|
||||
|
||||
# 15) 地图的横向轨道是**独立分配**的:兄弟分支应当铺开,而不是像紧凑
|
||||
# 泳道那样挤在同一列 —— 否则多条边会重叠成一条竖线。
|
||||
if len(commits) >= 4:
|
||||
tips = [row for row in commits
|
||||
if not any(row["sha"] in other["parents"] for other in commits)]
|
||||
if len(tips) >= 3:
|
||||
lanes_used = {row["mapLane"] for row in tips}
|
||||
check(len(lanes_used) >= 2,
|
||||
f"{len(tips)} 个互不相干的线头全挤在同一列({lanes_used})")
|
||||
|
||||
# 16) 轨道左右平分:分支多的时候两侧都该有轨道,不能只朝一边长
|
||||
lanes_used = {row["mapLane"] for row in commits}
|
||||
if len(lanes_used) >= 3:
|
||||
check(min(lanes_used) < 0 < max(lanes_used),
|
||||
f"轨道没有左右平分展开:{sorted(lanes_used)}")
|
||||
|
||||
# 17) 地图坐标必须非负(负数轨道要挪回正区间)
|
||||
for index, row in enumerate(commits):
|
||||
check(row["mapX"] >= 0 and row["mapY"] >= 0,
|
||||
f"第 {index} 行的地图坐标为负: ({row['mapX']}, {row['mapY']})")
|
||||
|
||||
# 18) 颜色按**分支**分配:同一分支的提交颜色必须一致(一条分支一个颜色)
|
||||
colors_by_branch: dict[str, set[int]] = {}
|
||||
for row in commits:
|
||||
colors_by_branch.setdefault(row.get("mapBranch", ""), set()).add(row["mapColor"])
|
||||
for branch, colors in colors_by_branch.items():
|
||||
check(len(colors) == 1,
|
||||
f"分支 {branch!r} 的提交颜色不一致: {sorted(colors)}")
|
||||
|
||||
|
||||
def dump(tag: str, commits: list[dict]) -> None:
|
||||
print(f"\n=== {tag} ===")
|
||||
print(f"{'行':>3} {'lane':>4} {'above':<12} {'below':<12} {'links':<8} "
|
||||
f"{'refs':<14} 主题")
|
||||
for index, row in enumerate(commits):
|
||||
print(f"{index:>3} {row['lane']:>4} {str(row['graphAbove']):<12} "
|
||||
f"{str(row['graphBelow']):<12} {str(row['graphLinks']):<8} "
|
||||
f"{','.join(row['refs']):<14} {row['subject']}")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- 场景
|
||||
|
||||
|
||||
def topology_repo(root: Path) -> Path:
|
||||
"""分叉 + 合并 + 未合并分支 + 注解标签。"""
|
||||
repo = root / "topology"
|
||||
linear_repo(repo, 1)
|
||||
(repo / "b.txt").write_text("b", encoding="utf-8")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-qm", "B 第二个提交")
|
||||
|
||||
git(repo, "checkout", "-q", "-b", "feature")
|
||||
for name in ("d", "e", "e2"):
|
||||
(repo / f"{name}.txt").write_text(name, encoding="utf-8")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-qm", f"{name.upper()} feature 上的提交")
|
||||
|
||||
git(repo, "checkout", "-q", "main")
|
||||
(repo / "c.txt").write_text("c", encoding="utf-8")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-qm", "C main 上的提交")
|
||||
git(repo, "merge", "-q", "--no-ff", "feature", "-m", "F 把 feature 合并回 main")
|
||||
git(repo, "tag", "-a", "v1.0", "-m", "1.0 发布")
|
||||
|
||||
git(repo, "checkout", "-q", "-b", "hotfix", "HEAD~1")
|
||||
(repo / "h.txt").write_text("h", encoding="utf-8")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-qm", "H hotfix 上未合并的提交")
|
||||
git(repo, "checkout", "-q", "main")
|
||||
return repo
|
||||
|
||||
|
||||
def scenario_topology(root: Path) -> None:
|
||||
repo = topology_repo(root)
|
||||
result = gitcore.log(str(repo), {"maxEntries": 50, "allRefs": True})
|
||||
commits = result["commits"]
|
||||
dump("拓扑仓库(--all)", commits)
|
||||
assert_invariants("拓扑仓库", commits)
|
||||
|
||||
refs = {row["shortSha"]: row["refs"] for row in commits if row["refs"]}
|
||||
print(f"\n 引用落点: {refs}")
|
||||
check(any("v1.0" in names for names in refs.values()),
|
||||
"注解标签 v1.0 没挂到任何提交(tag 未 peel)")
|
||||
check(any("hotfix" in names for names in refs.values()),
|
||||
"未合并的 hotfix 分支没出现在 --all 结果里")
|
||||
|
||||
# 图例:颜色标识必须和提交上实际用的颜色对得上
|
||||
legend = {entry["name"]: entry["color"] for entry in result.get("mapLegend", [])}
|
||||
print(f" 图例: {legend}")
|
||||
check(bool(legend), "没有返回图例(mapLegend)")
|
||||
for row in commits:
|
||||
branch = row.get("mapBranch") or ""
|
||||
if not branch:
|
||||
continue
|
||||
check(branch in legend, f"分支 {branch!r} 没有出现在图例里")
|
||||
if branch in legend:
|
||||
check(row["mapColor"] == legend[branch],
|
||||
f"提交 {row['shortSha']} 的颜色 {row['mapColor']} 与图例中 "
|
||||
f"{branch!r} 的 {legend[branch]} 不一致")
|
||||
|
||||
only_head = gitcore.log(str(repo), {"maxEntries": 50})["commits"]
|
||||
check(not any("hotfix" in row["refs"] for row in only_head),
|
||||
"不带 allRefs 时不该包含 hotfix 分支的提交")
|
||||
|
||||
# 指定分支时只返回该分支可达的提交
|
||||
feature_only = gitcore.log(str(repo), {"maxEntries": 50, "branch": "feature"})["commits"]
|
||||
feature_subjects = {row["subject"] for row in feature_only}
|
||||
print(f" 只看 feature 分支: {sorted(feature_subjects)}")
|
||||
check(all("feature" in subject or "B " in subject or "A " in subject
|
||||
for subject in feature_subjects),
|
||||
f"按分支过滤时混进了别的分支的提交: {sorted(feature_subjects)}")
|
||||
check(not any("hotfix" in row["refs"] for row in feature_only),
|
||||
"按分支过滤时不该出现 hotfix")
|
||||
|
||||
|
||||
def scenario_linear(root: Path) -> None:
|
||||
repo = root / "linear"
|
||||
linear_repo(repo, 3)
|
||||
commits = gitcore.log(str(repo), {"maxEntries": 20, "allRefs": True})["commits"]
|
||||
dump("线性仓库", commits)
|
||||
assert_invariants("线性仓库", commits)
|
||||
check(all(row["lane"] == 0 for row in commits), "线性历史应全部在同一列")
|
||||
|
||||
|
||||
def scenario_single(root: Path) -> None:
|
||||
repo = root / "single"
|
||||
linear_repo(repo, 1)
|
||||
commits = gitcore.log(str(repo), {"maxEntries": 20, "allRefs": True})["commits"]
|
||||
dump("单提交仓库", commits)
|
||||
assert_invariants("单提交仓库", commits)
|
||||
check(len(commits) == 1 and commits[0]["lane"] == 0 and commits[0]["graphBelow"] == [],
|
||||
"单提交应无连线")
|
||||
|
||||
|
||||
def scenario_empty(root: Path) -> None:
|
||||
repo = root / "empty"
|
||||
repo.mkdir(parents=True, exist_ok=True)
|
||||
git(repo, "init", "-q", "-b", "main")
|
||||
result = gitcore.log(str(repo), {"maxEntries": 20, "allRefs": True})
|
||||
check(result["commits"] == [], "空仓库应返回空列表")
|
||||
print("\n=== 空仓库 ===\n 正常返回空列表")
|
||||
|
||||
|
||||
def scenario_three_parents(root: Path) -> None:
|
||||
"""一个提交带三个父:手工用 commit-tree 构造,比真的 octopus merge 可靠。"""
|
||||
repo = root / "octopus"
|
||||
linear_repo(repo, 1)
|
||||
for name in ("b1", "b2"):
|
||||
git(repo, "checkout", "-q", "-b", name)
|
||||
(repo / f"{name}.txt").write_text(name, encoding="utf-8")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-qm", f"{name} 的提交")
|
||||
git(repo, "checkout", "-q", "main")
|
||||
(repo / "main-only.txt").write_text("m", encoding="utf-8")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-qm", "main 的提交")
|
||||
|
||||
tree = git(repo, "rev-parse", "main^{tree}")
|
||||
triple = subprocess.run(
|
||||
["git", "-C", str(repo), "commit-tree", tree,
|
||||
"-p", git(repo, "rev-parse", "main"),
|
||||
"-p", git(repo, "rev-parse", "b1"),
|
||||
"-p", git(repo, "rev-parse", "b2"),
|
||||
"-m", "手工构造的三父提交"],
|
||||
capture_output=True, env=FIXED_ENV)
|
||||
if triple.returncode != 0:
|
||||
raise RuntimeError(triple.stderr.decode("utf-8", "replace"))
|
||||
git(repo, "update-ref", "refs/heads/octopus", triple.stdout.decode().strip())
|
||||
git(repo, "checkout", "-q", "octopus")
|
||||
|
||||
commits = gitcore.log(str(repo), {"maxEntries": 30, "allRefs": True})["commits"]
|
||||
dump("三父提交", commits)
|
||||
assert_invariants("三父提交", commits)
|
||||
|
||||
counts = [len(row["parents"]) for row in commits]
|
||||
print(f"\n 各行父提交数: {counts}")
|
||||
check(max(counts) >= 3, f"没有构造出三父提交(最多 {max(counts)} 个父)")
|
||||
for row in commits:
|
||||
if len(row["parents"]) > 2:
|
||||
check(len(row["graphBelow"]) + len(row["graphLinks"]) >= len(row["parents"]),
|
||||
f"多父提交的 below {row['graphBelow']} / links {row['graphLinks']} "
|
||||
f"不足以连出 {len(row['parents'])} 个父提交")
|
||||
|
||||
|
||||
def scenario_many_branches(root: Path) -> None:
|
||||
repo = root / "many"
|
||||
linear_repo(repo, 1)
|
||||
for index in range(6):
|
||||
git(repo, "checkout", "-q", "-b", f"f{index}", "main")
|
||||
(repo / f"branch-{index}.txt").write_text(str(index), encoding="utf-8")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-qm", f"分支 f{index} 的提交")
|
||||
git(repo, "checkout", "-q", "main")
|
||||
commits = gitcore.log(str(repo), {"maxEntries": 40, "allRefs": True})["commits"]
|
||||
dump("6 个并排分支", commits)
|
||||
assert_invariants("6 个并排分支", commits)
|
||||
print(f"\n 最大列数: {max(row['graphCols'] for row in commits)}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
with tempfile.TemporaryDirectory(prefix="lnxgit-graph-") as tmp:
|
||||
root = Path(tmp)
|
||||
scenario_topology(root)
|
||||
scenario_linear(root)
|
||||
scenario_single(root)
|
||||
scenario_empty(root)
|
||||
scenario_three_parents(root)
|
||||
scenario_many_branches(root)
|
||||
|
||||
print()
|
||||
if FAILED:
|
||||
print(f"==> {len(FAILED)} 项断言失败")
|
||||
for item in FAILED:
|
||||
print(f" - {item}")
|
||||
return 1
|
||||
print("==> 全部断言通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
66
tools/patch_deploy_tool.py
Normal file
66
tools/patch_deploy_tool.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""启动 ``pyside6-android-deploy`` 的薄包装(构建脚本的统一入口)。
|
||||
|
||||
**为什么这里不再做 monkey patch**
|
||||
|
||||
本文件原本在导入 ``deploy_lib`` 后包装 ``BuildozerConfig.__init__`` 与
|
||||
``Buildozer.initialize``,用来补回第三方依赖和 ``p4a.source_dir``。
|
||||
但那些包装**只对当前进程有效** —— 工具实际是用
|
||||
``subprocess.call(["pyside6-android-deploy", ...])`` 另起进程执行的,
|
||||
补丁一个字都传不过去,可它照样往日志里打印 ``[patch] 已应用``,
|
||||
于是"补丁生效了"这个假象一直骗过了构建日志。
|
||||
|
||||
真正生效的机制是 ``tools/sitecustomize_lnxgit.py``:构建脚本把
|
||||
``$WORK/pysite`` 放进 ``PYTHONPATH``,Python 启动时会自动 ``import
|
||||
sitecustomize``,因此 deploy 的**整个进程树**(含 buildozer / p4a 子进程)
|
||||
都会带上补丁,做这些事:
|
||||
|
||||
* 固定 p4a 的 ``python3`` / ``hostpython3`` recipe 版本(与 wheel 的 cp 标签一致)
|
||||
* 把 ``requirements`` 改写成 ``python3==3.11.15,shiboken6,PySide6,dulwich,certifi``
|
||||
* 往 ``buildozer.spec`` 写入 ``p4a.source_dir``,复用固定目录的 p4a 源码
|
||||
* 把 Qt 模块按依赖层级重排(``Core`` 在最前,见 android/BUILD.md 4.4)
|
||||
* 改写 ``deploy_util.cleanup``,保住 ``.buildozer`` 构建缓存
|
||||
|
||||
改完补丁先跑 ``bash scripts/wsl_verify_patch.sh`` 自检,再构建。
|
||||
|
||||
用法(构建脚本已集成)::
|
||||
|
||||
python tools/patch_deploy_tool.py --exec pyside6-android-deploy -- --config-file ...
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="启动 pyside6-android-deploy / pyside6-deploy 的薄包装")
|
||||
parser.add_argument("--exec", dest="command", default="pyside6-android-deploy",
|
||||
help="要执行的部署工具")
|
||||
# 这两个参数由 sitecustomize 通过环境变量接管,这里只做兼容接收:
|
||||
# 若透传给 deploy 工具会被它当成未知参数而直接报错。
|
||||
parser.add_argument("--extra-requires", default=None,
|
||||
help="(已废弃,改用环境变量 LNXGIT_EXTRA_REQUIRES)")
|
||||
parser.add_argument("--p4a-source", default=None,
|
||||
help="(已废弃,改用环境变量 LNXGIT_P4A_SOURCE)")
|
||||
parser.add_argument("--python-version", default=None,
|
||||
help="(已废弃,改用环境变量 LNXGIT_PYTHON_VERSION)")
|
||||
args, rest = parser.parse_known_args()
|
||||
|
||||
if args.extra_requires or args.p4a_source or args.python_version:
|
||||
print("[launcher] --extra-requires/--p4a-source/--python-version 已废弃,"
|
||||
"改由 sitecustomize 读环境变量处理", file=sys.stderr)
|
||||
|
||||
# argparse 会把分隔符 '--' 留在剩余参数里,需要剔除
|
||||
passthrough = [item for item in rest if item != "--"]
|
||||
command = [args.command] + passthrough
|
||||
print(f"[launcher] 执行: {' '.join(command)}", file=sys.stderr)
|
||||
print("[launcher] 构建期补丁来自 PYTHONPATH 里的 sitecustomize,"
|
||||
"自检请跑 scripts/wsl_verify_patch.sh", file=sys.stderr)
|
||||
return subprocess.call(command)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
437
tools/sitecustomize_lnxgit.py
Normal file
437
tools/sitecustomize_lnxgit.py
Normal file
@@ -0,0 +1,437 @@
|
||||
"""通过 PYTHONPATH 自动加载的构建期补丁(Python 启动时会自动 import sitecustomize)。
|
||||
|
||||
在 ``pyside6-android-deploy`` 的整个进程树(含 buildozer 子进程)中生效,做两件事:
|
||||
|
||||
1. **固定 p4a 的 Python 版本**:PySide6 的 Android wheel(``cp311``)里 shiboken6
|
||||
链接 ``libpython3.11.so``,而 python-for-android 的 ``python3`` recipe 默认编译
|
||||
最新版(3.14),两者不匹配时启动即报::
|
||||
|
||||
dlopen failed: library "libpython3.11.so" not found: needed by libshiboken6.abi3.so
|
||||
|
||||
因此把固定目录里 p4a 源码的 ``python3`` / ``hostpython3`` recipe 就地改写为
|
||||
``LNXGIT_PYTHON_VERSION``(幂等,重复执行不会累积注释)。
|
||||
|
||||
2. **修正 deploy 工具生成的 buildozer.spec**:
|
||||
|
||||
* ``deploy_lib.deploy_util.cleanup()`` 会删掉项目里的 ``buildozer.spec``,
|
||||
随后 ``Buildozer.initialize()`` 用 ``buildozer init`` 重建并用
|
||||
``BuildozerConfig`` 覆写字段 —— 我们写在模板里的 ``p4a.source_dir`` 会丢失,
|
||||
buildozer 于是每次都去 GitHub 克隆一份**干净的** p4a(直连不稳定,且那份
|
||||
recipe 是 3.14,会编出错误的 libpython)。
|
||||
* ``BuildozerConfig.__init__`` 把 ``requirements`` 硬编码为
|
||||
``python3,shiboken6,PySide6``,第三方依赖(dulwich / certifi)会被丢掉。
|
||||
|
||||
注意 ``BaseConfig.set_value()`` 只改内存里的 ConfigParser,
|
||||
**必须再调用 ``update_config()`` 才会落盘**——漏掉这一步补丁等于没打。
|
||||
|
||||
环境变量:
|
||||
|
||||
LNXGIT_PYTHON_VERSION 目标 Python 版本,默认 3.11.15(空字符串则跳过固定)
|
||||
LNXGIT_EXTRA_REQUIRES 额外依赖,默认 dulwich,certifi
|
||||
LNXGIT_P4A_SOURCE 固定目录的 p4a 源码,默认 /opt/lnxgit-android/p4a-src
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
VERSION = os.environ.get("LNXGIT_PYTHON_VERSION", "3.11.15")
|
||||
EXTRA_REQUIRES = os.environ.get("LNXGIT_EXTRA_REQUIRES", "dulwich,certifi")
|
||||
P4A_SOURCE = os.environ.get("LNXGIT_P4A_SOURCE", "/opt/lnxgit-android/p4a-src")
|
||||
|
||||
_RECIPE_NAMES = ("hostpython3", "python3")
|
||||
# 整行匹配 `version = "x.y.z"`(含行尾已有注释),替换后不会随执行次数膨胀
|
||||
_VERSION_LINE_RE = re.compile(
|
||||
r'^(?P<indent>[ \t]*)version[ \t]*=[ \t]*["\'][^"\']+["\'][^\n]*$',
|
||||
re.MULTILINE,
|
||||
)
|
||||
_DEPLOY_TARGET = "deploy_lib.android.buildozer"
|
||||
_DEPLOY_UTIL_TARGET = "deploy_lib.deploy_util"
|
||||
|
||||
|
||||
def _log(message: str) -> None:
|
||||
"""构建期提示,写到 stderr(不影响被补丁程序的 stdout 协议)。"""
|
||||
sys.stderr.write(f"[lnxgit-patch] {message}\n")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- 1) pin recipes
|
||||
|
||||
|
||||
def _pin_recipe_file(path: Path) -> bool:
|
||||
"""把单个 recipe 文件的 version 改写为 VERSION;已正确则返回 False。"""
|
||||
try:
|
||||
source = path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return False
|
||||
new_source, count = _VERSION_LINE_RE.subn(
|
||||
lambda m: f'{m.group("indent")}version = "{VERSION}" # _LNXGIT_PINNED',
|
||||
source,
|
||||
)
|
||||
if not count or new_source == source:
|
||||
return False
|
||||
try:
|
||||
path.write_text(new_source, encoding="utf-8")
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _p4a_roots() -> list[Path]:
|
||||
"""可能存在的 p4a 源码目录(固定目录优先,其次是项目内的各份副本)。"""
|
||||
roots: list[Path] = []
|
||||
if P4A_SOURCE:
|
||||
roots.append(Path(P4A_SOURCE))
|
||||
try:
|
||||
cwd = Path.cwd()
|
||||
except OSError: # cwd 被删除等极端情况
|
||||
return roots
|
||||
roots.extend(
|
||||
(
|
||||
cwd / ".buildozer/android/platform/python-for-android",
|
||||
cwd / "deployment/.buildozer/android/platform/python-for-android",
|
||||
)
|
||||
)
|
||||
roots.append(Path(os.path.expanduser("~")) / ".buildozer/android/platform/python-for-android")
|
||||
return roots
|
||||
|
||||
|
||||
def _pin_recipes() -> int:
|
||||
"""固定所有能找到的 p4a recipe 版本,返回被改写的文件数。"""
|
||||
if not VERSION:
|
||||
return 0
|
||||
changed = 0
|
||||
seen: set[Path] = set()
|
||||
for root in _p4a_roots():
|
||||
for name in _RECIPE_NAMES:
|
||||
recipe = root / "pythonforandroid/recipes" / name / "__init__.py"
|
||||
if recipe in seen or not recipe.is_file():
|
||||
continue
|
||||
seen.add(recipe)
|
||||
if _pin_recipe_file(recipe):
|
||||
changed += 1
|
||||
return changed
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 2) 修正 buildozer.spec
|
||||
|
||||
|
||||
def _split_requirements(value: str) -> list[str]:
|
||||
return [item.strip() for item in value.split(",") if item.strip()]
|
||||
|
||||
|
||||
# Qt 库必须按依赖层级加载,Core 在最前。
|
||||
#
|
||||
# deploy_lib 的 ``Config.modules`` 来自 ``list(set(...))``,顺序是任意的(每次运行
|
||||
# 都不同),而它正是 p4a 生成 ``res/values/libs.xml`` 里 ``qt_libs`` 数组的顺序。
|
||||
# Qt 的 QtLoader 会依照该数组逐个 ``System.loadLibrary``,而 Android 只对**显式
|
||||
# loadLibrary 的库**调用 ``JNI_OnLoad``,作为 DT_NEEDED 依赖被顺带 dlopen 的库不会调用。
|
||||
# 于是当 Qt6Quick 排在 Qt6Core 前面时:
|
||||
# libQt6Quick_x86_64.so JNI_OnLoad → QJniEnvironment::getJniEnv()
|
||||
# → QtAndroidPrivate::javaVM() 仍为 NULL → SIGSEGV (SEGV_MAPERR, fault addr 0x0)
|
||||
# 日志里表现为 super.onCreate 之后立刻
|
||||
# Fatal signal 11 ... in tid xxx (qtMainLoopThrea)
|
||||
QT_MODULE_LAYERS: tuple[tuple[str, ...], ...] = (
|
||||
("Core",),
|
||||
("Network", "Concurrent", "Xml", "Sql", "DBus", "PrintSupport", "Test"),
|
||||
("Gui", "OpenGL", "OpenGLWidgets", "Svg", "Widgets", "SvgWidgets"),
|
||||
("Qml", "QmlModels", "QmlMeta", "QmlWorkerScript", "QmlLocalStorage", "QmlCore"),
|
||||
("Quick", "QuickTemplates2", "QuickControls2", "QuickShapes", "QuickDialogs2",
|
||||
"QuickLayouts", "QuickWidgets", "QuickTest"),
|
||||
)
|
||||
|
||||
|
||||
def _order_qt_modules(modules: list[str]) -> list[str]:
|
||||
"""按 Qt 的依赖层级重排模块,未知模块保持原有相对顺序排在最后。
|
||||
|
||||
同层内按 ``QT_MODULE_LAYERS`` 里写死的先后(而不是调用方传入的顺序),
|
||||
因为同一层的模块彼此也有依赖,例如 QuickTemplates2 / QuickControls2 都依赖 Quick。
|
||||
"""
|
||||
rank: dict[str, tuple[int, int]] = {}
|
||||
for layer_index, layer in enumerate(QT_MODULE_LAYERS):
|
||||
for position, name in enumerate(layer):
|
||||
rank.setdefault(name, (layer_index, position))
|
||||
|
||||
def sort_key(name: str) -> tuple[int, int]:
|
||||
if name in rank:
|
||||
return rank[name]
|
||||
try:
|
||||
return (len(QT_MODULE_LAYERS), modules.index(name))
|
||||
except ValueError: # pragma: no cover - 理论上不会发生
|
||||
return (len(QT_MODULE_LAYERS), len(modules))
|
||||
|
||||
return sorted(modules, key=sort_key)
|
||||
|
||||
|
||||
def _apply_qt_module_order(pysidedeploy_config) -> list[str]:
|
||||
"""把 qt 模块顺序改成依赖序。
|
||||
|
||||
真实 ``Config.modules`` 是 property,其 setter 会 ``modules.sort()`` 把顺序又打乱,
|
||||
所以这里**原地重排 list 本身**——``Config._modules`` 与调用方持有的引用是同一个
|
||||
对象,原地改两头都生效,也绕开了 setter。
|
||||
"""
|
||||
modules = getattr(pysidedeploy_config, "modules", None)
|
||||
if not modules:
|
||||
return []
|
||||
ordered = _order_qt_modules(list(modules))
|
||||
if ordered != list(modules):
|
||||
modules[:] = ordered
|
||||
try:
|
||||
pysidedeploy_config._modules = modules
|
||||
except Exception: # pragma: no cover - 只读属性等极端情况
|
||||
pass
|
||||
return ordered
|
||||
|
||||
|
||||
def _apply_requirements(parts: list[str]) -> list[str]:
|
||||
"""把 python3 固定到 VERSION,并补上第三方依赖。"""
|
||||
result: list[str] = []
|
||||
pinned_done = False
|
||||
for part in parts:
|
||||
if part == "python3" or part.startswith("python3=="):
|
||||
if not pinned_done:
|
||||
result.append(f"python3=={VERSION}" if VERSION else "python3")
|
||||
pinned_done = True
|
||||
continue
|
||||
result.append(part)
|
||||
if VERSION and not pinned_done:
|
||||
result.insert(0, f"python3=={VERSION}")
|
||||
for name in _split_requirements(EXTRA_REQUIRES):
|
||||
if name not in result:
|
||||
result.append(name)
|
||||
return result
|
||||
|
||||
|
||||
def _patch_deploy_lib(module) -> None:
|
||||
"""包装 BuildozerConfig / Buildozer,让它们写出我们需要的 spec。"""
|
||||
config_cls = getattr(module, "BuildozerConfig", None)
|
||||
if config_cls is not None and not getattr(config_cls, "_lnxgit_patched", False):
|
||||
original_init = config_cls.__init__
|
||||
|
||||
def patched_init(self, buildozer_spec_file, pysidedeploy_config):
|
||||
# 必须在 original_init 之前改:它会把 modules 拼进 p4a.extra_args 的
|
||||
# --qt-libs=...,那串顺序决定 libs.xml 里的加载顺序。
|
||||
try:
|
||||
ordered = _apply_qt_module_order(pysidedeploy_config)
|
||||
if ordered:
|
||||
_log(f"qt 模块加载顺序 = {','.join(ordered)}")
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"重排 qt 模块失败:{exc!r}")
|
||||
|
||||
original_init(self, buildozer_spec_file, pysidedeploy_config)
|
||||
# original_init 末尾已经 update_config() 过一次,之后的改动需要再写盘
|
||||
changed = False
|
||||
try:
|
||||
requirements = _apply_requirements(
|
||||
_split_requirements(self.get_value("app", "requirements") or "")
|
||||
)
|
||||
self.set_value("app", "requirements", ",".join(requirements))
|
||||
changed = True
|
||||
_log(f"requirements = {','.join(requirements)}")
|
||||
except Exception as exc: # pragma: no cover - 仅构建期诊断
|
||||
_log(f"写 requirements 失败:{exc!r}")
|
||||
|
||||
if P4A_SOURCE and os.path.isdir(P4A_SOURCE):
|
||||
try:
|
||||
self.set_value("app", "p4a.source_dir", P4A_SOURCE)
|
||||
changed = True
|
||||
_log(f"p4a.source_dir = {P4A_SOURCE}")
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"写 p4a.source_dir 失败:{exc!r}")
|
||||
|
||||
if changed:
|
||||
# 关键:set_value 只改内存,不 update_config 就不会落盘
|
||||
self.update_config()
|
||||
|
||||
config_cls.__init__ = patched_init
|
||||
config_cls._lnxgit_patched = True
|
||||
|
||||
buildozer_cls = getattr(module, "Buildozer", None)
|
||||
if buildozer_cls is not None and not getattr(buildozer_cls, "_lnxgit_patched", False):
|
||||
original_initialize = buildozer_cls.initialize # staticmethod → 普通函数
|
||||
original_create = buildozer_cls.create_executable # staticmethod → 普通函数
|
||||
|
||||
def _rewrite_spec() -> None:
|
||||
"""buildozer 子进程只认项目目录里的 buildozer.spec,这里做最后兜底。"""
|
||||
try:
|
||||
spec = Path.cwd() / "buildozer.spec"
|
||||
if not spec.is_file():
|
||||
return
|
||||
text = spec.read_text(encoding="utf-8")
|
||||
lines = []
|
||||
for line in text.splitlines():
|
||||
if line.startswith("requirements") and "=" in line:
|
||||
_, _, rhs = line.partition("=")
|
||||
parts = _apply_requirements(_split_requirements(rhs))
|
||||
line = "requirements = " + ",".join(parts)
|
||||
lines.append(line)
|
||||
text = "\n".join(lines) + "\n"
|
||||
if P4A_SOURCE and os.path.isdir(P4A_SOURCE) and "p4a.source_dir" not in text:
|
||||
text += f"\np4a.source_dir = {P4A_SOURCE}\n"
|
||||
spec.write_text(text, encoding="utf-8")
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"改写 buildozer.spec 失败:{exc!r}")
|
||||
|
||||
def patched_initialize(pysidedeploy_config):
|
||||
original_initialize(pysidedeploy_config)
|
||||
# spec 已存在时 original_initialize 会提前返回,此时仍需补 p4a.source_dir
|
||||
try:
|
||||
project_dir = Path(pysidedeploy_config.project_dir)
|
||||
spec = project_dir / "buildozer.spec"
|
||||
if spec.is_file() and P4A_SOURCE and os.path.isdir(P4A_SOURCE):
|
||||
text = spec.read_text(encoding="utf-8")
|
||||
if "p4a.source_dir" not in text:
|
||||
with spec.open("a", encoding="utf-8") as handle:
|
||||
handle.write(f"\np4a.source_dir = {P4A_SOURCE}\n")
|
||||
_log(f"追加 p4a.source_dir 到 {spec}")
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"补充 p4a.source_dir 失败:{exc!r}")
|
||||
|
||||
def patched_create(mode: str):
|
||||
_pin_recipes()
|
||||
_rewrite_spec()
|
||||
return original_create(mode)
|
||||
|
||||
buildozer_cls.initialize = staticmethod(patched_initialize)
|
||||
buildozer_cls.create_executable = staticmethod(patched_create)
|
||||
buildozer_cls._lnxgit_patched = True
|
||||
|
||||
|
||||
def _patch_deploy_util(module) -> None:
|
||||
"""让 cleanup() 保留 .buildozer 构建缓存。
|
||||
|
||||
``deploy_util.cleanup()`` 每次构建开始都会 ``rmtree(项目/.buildozer)``,
|
||||
而构建收尾时 android_deploy 又把这个目录 ``move`` 到 ``deployment/`` 下。
|
||||
两者叠加的后果是**每一轮构建都从零开始**:重新下载全部依赖源码包、重新编译
|
||||
CPython(几十分钟),我们预置的 v3.11.15.tar.gz 也会被一并删掉。
|
||||
|
||||
这里改成:先把 deployment/ 下的缓存取回项目目录,再清掉 deployment 与
|
||||
buildozer.spec,但**不删** .buildozer。
|
||||
"""
|
||||
if getattr(module, "_lnxgit_patched", False):
|
||||
return
|
||||
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
def patched_cleanup(config, is_android: bool = False):
|
||||
try:
|
||||
generated_dir = Path(config.generated_files_path)
|
||||
except Exception:
|
||||
generated_dir = None
|
||||
|
||||
# 上一轮构建结束时 .buildozer 被 move 到了 deployment/ 下,先取回来
|
||||
if generated_dir is not None:
|
||||
try:
|
||||
cached = generated_dir / ".buildozer"
|
||||
target = Path(config.project_dir) / ".buildozer"
|
||||
if cached.is_dir() and not target.exists():
|
||||
shutil.move(str(cached), str(target))
|
||||
_log(f"已恢复构建缓存 {target}")
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"恢复构建缓存失败:{exc!r}")
|
||||
|
||||
try:
|
||||
if generated_dir.exists():
|
||||
shutil.rmtree(generated_dir)
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"清理 deployment 目录失败:{exc!r}")
|
||||
|
||||
if is_android:
|
||||
try:
|
||||
spec_file = Path(config.project_dir) / "buildozer.spec"
|
||||
if spec_file.exists():
|
||||
spec_file.unlink()
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"删除 buildozer.spec 失败:{exc!r}")
|
||||
|
||||
# 注意:这里刻意不删 .buildozer —— 那是 p4a 的全部编译产物与下载缓存
|
||||
|
||||
module.cleanup = patched_cleanup
|
||||
module._lnxgit_patched = True
|
||||
|
||||
|
||||
def _install_hook() -> None:
|
||||
if getattr(sys, "_lnxgit_hook_installed", False):
|
||||
return
|
||||
|
||||
pending = {_DEPLOY_UTIL_TARGET: _patch_deploy_util, _DEPLOY_TARGET: _patch_deploy_lib}
|
||||
|
||||
class _Finder:
|
||||
"""在目标模块首次导入后立刻打补丁。
|
||||
|
||||
``deploy_lib.deploy_util`` 必须比 ``deploy_lib.android.buildozer`` 先挂上:
|
||||
``android_deploy`` 先在模块顶层 ``from deploy_lib import cleanup``,
|
||||
deploy_lib 的 __init__ 转发的是 deploy_util 里的函数对象,
|
||||
晚了就只能改到一个没人引用的名字。
|
||||
"""
|
||||
|
||||
def find_spec(self, fullname, path=None, target=None):
|
||||
patch_fn = pending.get(fullname)
|
||||
if patch_fn is None:
|
||||
return None
|
||||
import importlib.machinery
|
||||
|
||||
spec = importlib.machinery.PathFinder.find_spec(fullname, path)
|
||||
if spec is None or spec.loader is None:
|
||||
return None
|
||||
original_exec = spec.loader.exec_module
|
||||
|
||||
def patched_exec(module):
|
||||
original_exec(module)
|
||||
patch_fn(module)
|
||||
pending.pop(fullname, None)
|
||||
if not pending:
|
||||
try:
|
||||
sys.meta_path.remove(self)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
spec.loader.exec_module = patched_exec
|
||||
return spec
|
||||
|
||||
sys.meta_path.insert(0, _Finder())
|
||||
sys._lnxgit_hook_installed = True # type: ignore[attr-defined]
|
||||
|
||||
|
||||
def _set_socket_timeout() -> None:
|
||||
"""给没有显式超时的网络调用加一个兜底超时。
|
||||
|
||||
p4a 的 ``Recipe.download()`` 走 urllib,**没有超时**。GitHub 直连时连接建立后
|
||||
可能再也不返回数据,构建就会静默卡死(实测卡了 18 分钟,日志与文件都不再变化)。
|
||||
设一个默认 socket 超时后,这种情况会抛异常而不是永久挂起。
|
||||
|
||||
pip / urllib3 自己带超时设置,不受这里的默认值影响。
|
||||
"""
|
||||
raw = os.environ.get("LNXGIT_SOCKET_TIMEOUT", "60")
|
||||
if not raw:
|
||||
return
|
||||
timeout = float(raw)
|
||||
if timeout <= 0:
|
||||
return
|
||||
import socket
|
||||
|
||||
socket.setdefaulttimeout(timeout)
|
||||
|
||||
|
||||
def _bootstrap() -> None:
|
||||
try:
|
||||
changed = _pin_recipes()
|
||||
if changed:
|
||||
_log(f"固定 {changed} 个 p4a recipe -> {VERSION}")
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"固定 recipe 失败:{exc!r}")
|
||||
try:
|
||||
_set_socket_timeout()
|
||||
except Exception as exc: # pragma: no cover
|
||||
_log(f"设置 socket 超时失败:{exc!r}")
|
||||
try:
|
||||
_install_hook()
|
||||
except Exception as exc: # pragma: no cover
|
||||
# 早期版本这里用 except: pass 吞掉了 NameError,导致补丁静默失效
|
||||
_log(f"安装 deploy_lib 补丁失败:{exc!r}")
|
||||
|
||||
|
||||
_bootstrap()
|
||||
168
tools/upload_release_chunked.py
Normal file
168
tools/upload_release_chunked.py
Normal file
@@ -0,0 +1,168 @@
|
||||
"""分片并发上传大文件到 Gitea Release(可固定 Cloudflare 边缘 IP)。
|
||||
|
||||
背景:
|
||||
* 单请求上传大文件会撞上 Cloudflare 的 100 秒超时(524/502);
|
||||
* 本机 DNS 可能被污染,需要把域名固定到可用的边缘 IP;
|
||||
* 因此这里把文件切成若干片,用系统 curl 并发上传,并生成合并脚本。
|
||||
|
||||
用法::
|
||||
|
||||
python tools/upload_release_chunked.py --token <token> \
|
||||
--file dist/xxx.apk [--edge-ip 104.21.9.133] \
|
||||
[--chunk-mb 4] [--parallel 8] [--clean-first]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from lnxgit import gitea # noqa: E402
|
||||
|
||||
|
||||
def upload_part(url: str, path: Path, token: str, edge_ip: str, host: str,
|
||||
attempts: int = 3) -> tuple[int, str]:
|
||||
"""用 curl 上传单个分片,返回 (HTTP 码, 错误信息)。"""
|
||||
cmd = [
|
||||
"curl", "-sS", "-o", "NUL" if sys.platform == "win32" else "/dev/null",
|
||||
"-w", "%{http_code}", "--max-time", "600",
|
||||
"-X", "POST",
|
||||
"-H", f"Authorization: token {token}",
|
||||
"-H", "User-Agent: Mozilla/5.0",
|
||||
"-H", "Content-Type: application/octet-stream",
|
||||
"--data-binary", f"@{path}",
|
||||
]
|
||||
if edge_ip:
|
||||
cmd += ["--resolve", f"{host}:443:{edge_ip}"]
|
||||
cmd.append(url)
|
||||
|
||||
last = ""
|
||||
for _ in range(attempts):
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=700)
|
||||
code = (result.stdout or "").strip()
|
||||
if code == "201":
|
||||
return 201, ""
|
||||
last = f"HTTP {code or '(空)'} {result.stderr.strip()[:120]}"
|
||||
except subprocess.TimeoutExpired:
|
||||
last = "curl 超时"
|
||||
time.sleep(2)
|
||||
return 0, last
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="分片并发上传 Release 附件")
|
||||
parser.add_argument("--token", required=True)
|
||||
parser.add_argument("--file", required=True)
|
||||
parser.add_argument("--base", default=gitea.DEFAULT_BASE)
|
||||
parser.add_argument("--owner", default="l")
|
||||
parser.add_argument("--repo", default="lnxgit")
|
||||
parser.add_argument("--release-id", type=int, default=1)
|
||||
parser.add_argument("--chunk-mb", type=int, default=4)
|
||||
parser.add_argument("--parallel", type=int, default=8)
|
||||
parser.add_argument("--edge-ip", default="104.21.9.133",
|
||||
help="固定使用的 Cloudflare 边缘 IP(留空则用系统 DNS)")
|
||||
parser.add_argument("--name", default="")
|
||||
parser.add_argument("--clean-first", action="store_true",
|
||||
help="先删除 Release 中的同名分片附件")
|
||||
args = parser.parse_args()
|
||||
|
||||
source = Path(args.file)
|
||||
if not source.is_file():
|
||||
print(f"文件不存在: {source}")
|
||||
return 1
|
||||
|
||||
base_name = args.name or source.name
|
||||
host = args.base.split("://", 1)[-1].split("/", 1)[0]
|
||||
|
||||
if args.clean_first:
|
||||
print("==> 清理旧的同名分片")
|
||||
try:
|
||||
release = gitea.request(args.base, f"/api/v1/repos/{args.owner}/{args.repo}"
|
||||
f"/releases/{args.release_id}",
|
||||
token=args.token)
|
||||
for asset in release.get("assets", []):
|
||||
if asset["name"].startswith(f"{base_name}.part"):
|
||||
gitea.request(args.base,
|
||||
f"/api/v1/repos/{args.owner}/{args.repo}/releases/"
|
||||
f"{args.release_id}/assets/{asset['id']}",
|
||||
token=args.token, method="DELETE")
|
||||
print(f" 已删除 {asset['name']}")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f" 清理失败(忽略): {type(exc).__name__}: {exc}")
|
||||
|
||||
data = source.read_bytes()
|
||||
chunk_size = args.chunk_mb * 1024 * 1024
|
||||
total = (len(data) + chunk_size - 1) // chunk_size
|
||||
print(f"文件: {base_name}({len(data) / 1024 / 1024:.1f} MB)")
|
||||
print(f"分片: {total} 片 × {args.chunk_mb} MB,并发 {args.parallel},边缘 IP {args.edge_ip or '系统 DNS'}")
|
||||
|
||||
workdir = Path(tempfile.mkdtemp(prefix="lnxgit-upload-"))
|
||||
parts: list[tuple[int, Path, str]] = []
|
||||
for index in range(total):
|
||||
chunk = data[index * chunk_size:(index + 1) * chunk_size]
|
||||
part_path = workdir / f"part{index + 1:03d}"
|
||||
part_path.write_bytes(chunk)
|
||||
url = (f"{args.base}/api/v1/repos/{args.owner}/{args.repo}/releases/"
|
||||
f"{args.release_id}/assets?name={base_name}.part{index + 1:03d}")
|
||||
parts.append((index, part_path, url))
|
||||
|
||||
results: dict[int, str] = {}
|
||||
started = time.time()
|
||||
|
||||
def worker(item: tuple[int, Path, str]) -> tuple[int, str]:
|
||||
index, path, url = item
|
||||
code, error = upload_part(url, path, args.token, args.edge_ip, host)
|
||||
return index, ("ok" if code == 201 else error)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=args.parallel) as pool:
|
||||
for index, status in pool.map(worker, parts):
|
||||
results[index] = status
|
||||
if status == "ok":
|
||||
print(f" [✓] {index + 1}/{total}", flush=True)
|
||||
|
||||
shutil.rmtree(workdir, ignore_errors=True)
|
||||
ok = sum(1 for v in results.values() if v == "ok")
|
||||
print(f"\n完成 {ok}/{total} 片,用时 {time.time() - started:.0f}s")
|
||||
if ok != total:
|
||||
for index, status in sorted(results.items()):
|
||||
if status != "ok":
|
||||
print(f" 失败: 第 {index + 1} 片 -> {status}")
|
||||
return 1
|
||||
|
||||
merge = ROOT / "dist" / "merge-apk.sh"
|
||||
merge.parent.mkdir(parents=True, exist_ok=True)
|
||||
merge.write_text(
|
||||
"#!/usr/bin/env bash\n"
|
||||
"# 合并分片还原 APK(分片由 tools/upload_release_chunked.py 上传)\n"
|
||||
"set -euo pipefail\n"
|
||||
f'NAME="{base_name}"\n'
|
||||
f'TOTAL={total}\n'
|
||||
'BASE="${1:-https://git.xnhw.cc/l/lnxgit/releases/download/v1.0.0}"\n'
|
||||
'OUT="${2:-$NAME}"\n'
|
||||
'rm -f "$OUT"\n'
|
||||
'for i in $(seq -w 1 "$TOTAL"); do\n'
|
||||
' url="$BASE/${NAME}.part0${i}"\n'
|
||||
' echo "下载 $url"\n'
|
||||
' curl -fL --retry 3 -o "part${i}" "$url"\n'
|
||||
' cat "part${i}" >> "$OUT"\n'
|
||||
' rm -f "part${i}"\n'
|
||||
'done\n'
|
||||
'echo "已生成 $OUT"\n'
|
||||
'sha256sum "$OUT"\n',
|
||||
encoding="utf-8")
|
||||
print(f"合并脚本已生成: {merge}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user