Files
lnxgit/tools/graph_test.py
LnxGit a8ab8e7906 分支地图:当前分支选择框、按分支配色与颜色图例;原生提示改中文
分支选择框(图谱页顶部)
* 「全部引用」+ 各本地分支(当前分支标注「(当前)」)+ 末项「+ 新建分支…」
* 选中某个分支就只看它的历史(走 gitcore 的 branch 过滤),留空则铺开全部引用
* 选「新建分支…」弹输入框,创建并切换后回到全部引用视图;ComboBox 不支持
  空选项,所以先把 currentIndex 还原再弹窗

按分支配色 + 颜色标识
* 颜色从「按轨道」改为「按分支名」分配:同一分支的提交与连线同色;中间的
  提交没有引用,就继承第一个引用它的子提交所属的分支。
* 新增 _branches_by_sha():只取分支引用。一个提交同时挂着分支和标签时
  (main 上打了 v1.0),标签名不该顶替分支名 —— 否则图例会显示 v1.0 而没有 main。
* 接口返回 mapLegend(分支名 → 颜色),图谱页顶部渲染成一行色点 + 名字,
  可横向滚动。

原生提示改中文
* p4a 的 Java 模板里硬编码了返回键提示 "Click again to close the app",
  新增 scripts/wsl_patch_bootstrap_text.sh 在构建时替换为中文;中文写成
  \uXXXX 转义,绕开 javac 的 -encoding 差异。
* 该补丁放在 wsl_build.sh 的 root 阶段执行 —— p4a 源码不一定属于 builder。

测试
* graph_test 新增三条断言:同一分支颜色必须一致、图例与提交实际颜色必须
  对得上、按分支过滤时不能混进其它分支的提交。

已验证:分支选择框与图例(● hotfix ● main ● feature)在模拟器截图确认;
退出提示已变成中文「再按一次返回键退出」。
2026-09-23 03:20:49 +08:00

383 lines
16 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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())