apkdiff-core 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- apkdiff_core/__init__.py +80 -0
- apkdiff_core/apk.py +241 -0
- apkdiff_core/dex.py +900 -0
- apkdiff_core/diff.py +311 -0
- apkdiff_core/mapping.py +84 -0
- apkdiff_core/report.py +418 -0
- apkdiff_core/util.py +92 -0
- apkdiff_core-1.0.0.dist-info/METADATA +77 -0
- apkdiff_core-1.0.0.dist-info/RECORD +11 -0
- apkdiff_core-1.0.0.dist-info/WHEEL +5 -0
- apkdiff_core-1.0.0.dist-info/top_level.txt +1 -0
apkdiff_core/report.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Render diff results for humans: console / JSON / HTML / Markdown.
|
|
2
|
+
|
|
3
|
+
diff.py produces Change objects; this module turns them into four outputs:
|
|
4
|
+
|
|
5
|
+
console terminal tables with + / - / ~ markers
|
|
6
|
+
JSON complete structured data for tools
|
|
7
|
+
HTML self-contained page with search, sorting and status filters
|
|
8
|
+
Markdown tables for a repository or PR diff
|
|
9
|
+
|
|
10
|
+
All formats share DiffResult and the size formatters (human_size/human_delta),
|
|
11
|
+
so the same number reads identically everywhere.
|
|
12
|
+
|
|
13
|
+
JSON stores exact integer byte counts; only human-facing console/HTML/Markdown
|
|
14
|
+
convert to KB with two decimals.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import html
|
|
20
|
+
import json
|
|
21
|
+
import unicodedata
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from .diff import ADDED, DELETED, MODIFIED, RENAMED, STATUS_LABEL, Change, DiffResult
|
|
25
|
+
from .util import human_delta, human_size
|
|
26
|
+
|
|
27
|
+
STATUS_MARK = {ADDED: "+", DELETED: "-", MODIFIED: "~", RENAMED: ">"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _metric_unit(metric: str) -> str:
|
|
31
|
+
return "APK 压缩字节" if metric == "compressed" else "未压缩字节"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _write_text(path: str, text: str) -> None:
|
|
35
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
with open(path, "w", encoding="utf-8", newline="\n") as fh:
|
|
37
|
+
fh.write(text)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _display_width(text: str) -> int:
|
|
41
|
+
return sum(2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1 for ch in text)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _pad(text: str, width: int) -> str:
|
|
45
|
+
return text + " " * max(0, width - _display_width(text))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _by_impact(changes: list[Change], metric: str) -> list[Change]:
|
|
49
|
+
return sorted(changes, key=lambda c: abs(c.size_for(metric)), reverse=True)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _print_table(title: str, changes: list[Change], metric: str, limit: int) -> None:
|
|
53
|
+
print()
|
|
54
|
+
print(f"{title} (共 {len(changes)} 项,显示前 {min(limit, len(changes))} 项)")
|
|
55
|
+
if not changes:
|
|
56
|
+
print(" (无)")
|
|
57
|
+
return
|
|
58
|
+
shown = _by_impact(changes, metric)[:limit]
|
|
59
|
+
name_w = min(72, max(_display_width(c.key) for c in shown))
|
|
60
|
+
name_w = max(name_w, 12)
|
|
61
|
+
old_w, new_w, delta_w = 11, 11, 13
|
|
62
|
+
header = (
|
|
63
|
+
f" {'':2} {'状态':<6} {_pad('名称', name_w)} "
|
|
64
|
+
f"{_pad('旧', old_w)} {_pad('新', new_w)} {_pad('Δ', delta_w)}"
|
|
65
|
+
)
|
|
66
|
+
print(header)
|
|
67
|
+
print(" " + "-" * (len(header) - 2))
|
|
68
|
+
for c in shown:
|
|
69
|
+
name = c.key
|
|
70
|
+
if _display_width(name) > name_w:
|
|
71
|
+
name = name[: name_w - 3] + "..."
|
|
72
|
+
old = c.old_for(metric)
|
|
73
|
+
new = c.new_for(metric)
|
|
74
|
+
delta = c.size_for(metric)
|
|
75
|
+
print(
|
|
76
|
+
f" {STATUS_MARK.get(c.status, '?')} {_pad(STATUS_LABEL.get(c.status, c.status), 6)} "
|
|
77
|
+
f"{_pad(name, name_w)} {_pad(human_size(old), old_w)} "
|
|
78
|
+
f"{_pad(human_size(new), new_w)} {_pad(human_delta(delta), delta_w)}"
|
|
79
|
+
)
|
|
80
|
+
if c.status == RENAMED and c.detail.get("renamed_from"):
|
|
81
|
+
print(f" └─ 原路径: {c.detail['renamed_from']}")
|
|
82
|
+
if c.detail.get("breakdown_delta"):
|
|
83
|
+
parts = [
|
|
84
|
+
f"{k} {human_delta(v)}" for k, v in c.detail["breakdown_delta"].items() if v
|
|
85
|
+
]
|
|
86
|
+
if parts:
|
|
87
|
+
print(f" └─ 明细: {' '.join(parts)}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def print_console(result: DiffResult, metric: str = "compressed", top: int = 30,
|
|
91
|
+
full: bool = False) -> None:
|
|
92
|
+
s = result.summary
|
|
93
|
+
limit = 10**9 if full else top
|
|
94
|
+
unit = _metric_unit(metric)
|
|
95
|
+
|
|
96
|
+
print("=" * 78)
|
|
97
|
+
print("APK DIFF REPORT")
|
|
98
|
+
print("=" * 78)
|
|
99
|
+
print(f" 旧版本: {result.old.path}")
|
|
100
|
+
print(f" 新版本: {result.new.path}")
|
|
101
|
+
print(f" 排序/主指标: {unit}")
|
|
102
|
+
print()
|
|
103
|
+
print(" ── 包体总览 ──")
|
|
104
|
+
print(
|
|
105
|
+
f" APK 文件 {human_size(s['old_apk_size'])} → "
|
|
106
|
+
f"{human_size(s['new_apk_size'])} Δ {human_delta(s['apk_size_delta'])}"
|
|
107
|
+
)
|
|
108
|
+
print(
|
|
109
|
+
f" 代码(DEX,估算压缩) {human_size(s['old_class_compressed'])} → "
|
|
110
|
+
f"{human_size(s['new_class_compressed'])} Δ {human_delta(s['class_compressed_delta'])}"
|
|
111
|
+
)
|
|
112
|
+
print(
|
|
113
|
+
f" 代码(DEX,归属原始) {human_size(s['old_class_bytes'])} → "
|
|
114
|
+
f"{human_size(s['new_class_bytes'])} Δ {human_delta(s['class_bytes_delta'])}"
|
|
115
|
+
)
|
|
116
|
+
print(
|
|
117
|
+
f" 资源(压缩) {human_size(s['old_resource_compressed'])} → "
|
|
118
|
+
f"{human_size(s['new_resource_compressed'])} Δ {human_delta(s['resource_compressed_delta'])}"
|
|
119
|
+
)
|
|
120
|
+
print(
|
|
121
|
+
f" 资源(原始) {human_size(s['old_resource_bytes'])} → "
|
|
122
|
+
f"{human_size(s['new_resource_bytes'])} Δ {human_delta(s['resource_bytes_delta'])}"
|
|
123
|
+
)
|
|
124
|
+
print()
|
|
125
|
+
print(" ── 变更统计 ──")
|
|
126
|
+
print(
|
|
127
|
+
f" 类: 新增 {s['class_added']:>4} 删除 {s['class_deleted']:>4} "
|
|
128
|
+
f"修改 {s['class_modified']:>4} (旧 {s['class_count_old']} → 新 {s['class_count_new']})"
|
|
129
|
+
)
|
|
130
|
+
print(
|
|
131
|
+
f" 资源: 新增 {s['resource_added']:>4} 删除 {s['resource_deleted']:>4} "
|
|
132
|
+
f"修改 {s['resource_modified']:>4} 重命名 {s['resource_renamed']:>4}"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
_print_table("代码类变更", result.classes, metric, limit)
|
|
136
|
+
_print_table("资源文件变更", result.resources, metric, limit)
|
|
137
|
+
|
|
138
|
+
warnings = result.old.warnings + result.new.warnings
|
|
139
|
+
if warnings:
|
|
140
|
+
print()
|
|
141
|
+
print(f" ⚠ 解析警告 {len(warnings)} 条:")
|
|
142
|
+
for w in warnings[:20]:
|
|
143
|
+
print(f" - {w}")
|
|
144
|
+
if len(warnings) > 20:
|
|
145
|
+
print(f" ... 另有 {len(warnings) - 20} 条")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def build_json(result: DiffResult, metric: str) -> dict:
|
|
149
|
+
return {
|
|
150
|
+
"schema_version": 1,
|
|
151
|
+
"metric": metric,
|
|
152
|
+
"old": {"path": result.old.path, "file_size": result.old.file_size,
|
|
153
|
+
"warnings": result.old.warnings},
|
|
154
|
+
"new": {"path": result.new.path, "file_size": result.new.file_size,
|
|
155
|
+
"warnings": result.new.warnings},
|
|
156
|
+
"summary": result.summary,
|
|
157
|
+
"classes": [c.as_dict() for c in _by_impact(result.classes, metric)],
|
|
158
|
+
"resources": [c.as_dict() for c in _by_impact(result.resources, metric)],
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def write_json(result: DiffResult, path: str, metric: str) -> None:
|
|
163
|
+
_write_text(path, json.dumps(build_json(result, metric), ensure_ascii=False, indent=2))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def write_markdown(result: DiffResult, path: str, metric: str) -> None:
|
|
167
|
+
s = result.summary
|
|
168
|
+
lines = [
|
|
169
|
+
"# APK Diff Report",
|
|
170
|
+
"",
|
|
171
|
+
f"- 旧版本: `{result.old.path}`",
|
|
172
|
+
f"- 新版本: `{result.new.path}`",
|
|
173
|
+
f"- 主指标: {_metric_unit(metric)}",
|
|
174
|
+
"",
|
|
175
|
+
"## 总览",
|
|
176
|
+
"",
|
|
177
|
+
"| 指标 | 旧 | 新 | Δ |",
|
|
178
|
+
"| --- | ---: | ---: | ---: |",
|
|
179
|
+
]
|
|
180
|
+
rows = [
|
|
181
|
+
("APK 文件", s["old_apk_size"], s["new_apk_size"], s["apk_size_delta"]),
|
|
182
|
+
("代码 (DEX 归属, 原始)", s["old_class_bytes"], s["new_class_bytes"], s["class_bytes_delta"]),
|
|
183
|
+
("代码 (DEX 归属, 压缩估算)", s["old_class_compressed"], s["new_class_compressed"], s["class_compressed_delta"]),
|
|
184
|
+
("资源 (原始)", s["old_resource_bytes"], s["new_resource_bytes"], s["resource_bytes_delta"]),
|
|
185
|
+
("资源 (压缩)", s["old_resource_compressed"], s["new_resource_compressed"], s["resource_compressed_delta"]),
|
|
186
|
+
]
|
|
187
|
+
for name, old, new, delta in rows:
|
|
188
|
+
lines.append(f"| {name} | {human_size(old)} | {human_size(new)} | {human_delta(delta)} |")
|
|
189
|
+
lines += [
|
|
190
|
+
"",
|
|
191
|
+
"## 统计",
|
|
192
|
+
"",
|
|
193
|
+
f"- 类: 新增 {s['class_added']} / 删除 {s['class_deleted']} / 修改 {s['class_modified']}",
|
|
194
|
+
f"- 资源: 新增 {s['resource_added']} / 删除 {s['resource_deleted']} / "
|
|
195
|
+
f"修改 {s['resource_modified']} / 重命名 {s['resource_renamed']}",
|
|
196
|
+
"",
|
|
197
|
+
]
|
|
198
|
+
|
|
199
|
+
def table(title: str, changes: list[Change]) -> None:
|
|
200
|
+
lines.extend([f"## {title}", ""])
|
|
201
|
+
if not changes:
|
|
202
|
+
lines.append("(无)")
|
|
203
|
+
return
|
|
204
|
+
lines.extend(["| 状态 | 名称 | 旧 | 新 | Δ |", "| --- | --- | ---: | ---: | ---: |"])
|
|
205
|
+
for c in _by_impact(changes, metric):
|
|
206
|
+
old = c.old_for(metric)
|
|
207
|
+
new = c.new_for(metric)
|
|
208
|
+
name = c.key.replace("|", "\\|")
|
|
209
|
+
extra = f" ← `{c.detail['renamed_from']}`" if c.detail.get("renamed_from") else ""
|
|
210
|
+
lines.append(
|
|
211
|
+
f"| {STATUS_LABEL.get(c.status, c.status)} | `{name}`{extra} | "
|
|
212
|
+
f"{human_size(old)} | {human_size(new)} | {human_delta(c.size_for(metric))} |"
|
|
213
|
+
)
|
|
214
|
+
lines.append("")
|
|
215
|
+
|
|
216
|
+
table("代码类变更", result.classes)
|
|
217
|
+
table("资源文件变更", result.resources)
|
|
218
|
+
_write_text(path, "\n".join(lines))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
_HTML_TEMPLATE = r"""<!DOCTYPE html>
|
|
222
|
+
<html lang="zh-CN">
|
|
223
|
+
<head>
|
|
224
|
+
<meta charset="utf-8">
|
|
225
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
226
|
+
<title>APK Diff Report</title>
|
|
227
|
+
<style>
|
|
228
|
+
:root { --bg:#f7f8fa; --card:#fff; --text:#1f2329; --muted:#646a73; --border:#e5e6eb;
|
|
229
|
+
--red:#d92c20; --green:#0f9d58; --blue:#2563eb; --accent:#f2f3f5; }
|
|
230
|
+
* { box-sizing:border-box; }
|
|
231
|
+
body { margin:0; background:var(--bg); color:var(--text);
|
|
232
|
+
font:14px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; }
|
|
233
|
+
.wrap { max-width:1280px; margin:0 auto; padding:28px 24px 64px; }
|
|
234
|
+
h1 { font-size:24px; margin:0 0 4px; }
|
|
235
|
+
h2 { font-size:17px; margin:28px 0 12px; }
|
|
236
|
+
.sub { color:var(--muted); font-size:13px; margin-bottom:20px; }
|
|
237
|
+
.cards { display:grid; grid-template-columns:repeat(auto-fit,minmax(210px,1fr)); gap:12px; }
|
|
238
|
+
.card { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:14px 16px; }
|
|
239
|
+
.card .label { color:var(--muted); font-size:12px; }
|
|
240
|
+
.card .value { font-size:20px; font-weight:600; margin-top:4px; }
|
|
241
|
+
.card .delta { font-size:13px; margin-top:2px; }
|
|
242
|
+
.up { color:var(--red); } .down { color:var(--green); } .flat { color:var(--muted); }
|
|
243
|
+
.panel { background:var(--card); border:1px solid var(--border); border-radius:10px; margin-top:16px; overflow:hidden; }
|
|
244
|
+
.toolbar { display:flex; gap:10px; padding:12px 14px; border-bottom:1px solid var(--border); align-items:center; flex-wrap:wrap; }
|
|
245
|
+
.toolbar input { flex:1; min-width:200px; padding:7px 10px; border:1px solid var(--border); border-radius:6px; font-size:13px; background:#fff; color:var(--text); }
|
|
246
|
+
.pill { padding:4px 10px; border-radius:99px; background:var(--accent); font-size:12px; cursor:pointer; border:1px solid transparent; }
|
|
247
|
+
.pill.active { background:var(--blue); color:#fff; }
|
|
248
|
+
table { width:100%; border-collapse:collapse; }
|
|
249
|
+
th,td { padding:8px 12px; text-align:left; border-bottom:1px solid var(--border); vertical-align:top; }
|
|
250
|
+
th { font-size:12px; color:var(--muted); font-weight:500; background:#fafbfc; position:sticky; top:0; cursor:pointer; user-select:none; }
|
|
251
|
+
td.num, th.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; }
|
|
252
|
+
tr:hover td { background:#fafbfc; }
|
|
253
|
+
.tag { display:inline-block; min-width:44px; text-align:center; padding:1px 7px; border-radius:4px; font-size:12px; }
|
|
254
|
+
.tag.added { background:#e8f7ee; color:var(--green); }
|
|
255
|
+
.tag.deleted { background:#fdecea; color:var(--red); }
|
|
256
|
+
.tag.modified { background:#fff4e5; color:#b76e00; }
|
|
257
|
+
.tag.renamed { background:#eef2ff; color:var(--blue); }
|
|
258
|
+
.name { font-family:ui-monospace,SFMono-Regular,Consolas,monospace; font-size:12.5px; word-break:break-all; }
|
|
259
|
+
.detail { color:var(--muted); font-size:11.5px; margin-top:2px; }
|
|
260
|
+
.bar { height:4px; border-radius:2px; margin-top:4px; background:var(--accent); }
|
|
261
|
+
.bar i { display:block; height:100%; border-radius:2px; }
|
|
262
|
+
.warn { background:#fff8e6; border:1px solid #ffe0a3; border-radius:8px; padding:10px 14px; margin-top:16px; font-size:12.5px; }
|
|
263
|
+
footer { color:var(--muted); font-size:12px; margin-top:24px; }
|
|
264
|
+
</style>
|
|
265
|
+
</head>
|
|
266
|
+
<body>
|
|
267
|
+
<div class="wrap">
|
|
268
|
+
<h1>APK Diff Report</h1>
|
|
269
|
+
<div class="sub">旧: __OLD__ · 新: __NEW__ · 指标: __METRIC__</div>
|
|
270
|
+
<div class="cards">__CARDS__</div>
|
|
271
|
+
<div class="panel">__CLASS_TABLE__</div>
|
|
272
|
+
<div class="panel">__RES_TABLE__</div>
|
|
273
|
+
__WARNINGS__
|
|
274
|
+
<footer>由 apkdiff 生成 · 类体积为 DEX 归属字节,压缩值按各 dex 压缩率估算</footer>
|
|
275
|
+
</div>
|
|
276
|
+
<script>
|
|
277
|
+
function bindTable(inputId, tableId, pills) {
|
|
278
|
+
const input = document.getElementById(inputId);
|
|
279
|
+
const table = document.getElementById(tableId);
|
|
280
|
+
const tbody = table.querySelector('tbody');
|
|
281
|
+
const rows = Array.from(tbody.querySelectorAll('tr'));
|
|
282
|
+
let status = 'all';
|
|
283
|
+
function apply() {
|
|
284
|
+
const q = input.value.toLowerCase();
|
|
285
|
+
rows.forEach(r => {
|
|
286
|
+
const text = r.dataset.search.toLowerCase();
|
|
287
|
+
const okStatus = status === 'all' || r.dataset.status === status;
|
|
288
|
+
r.style.display = (okStatus && text.includes(q)) ? '' : 'none';
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
input.addEventListener('input', apply);
|
|
292
|
+
pills.forEach(p => p.addEventListener('click', () => {
|
|
293
|
+
document.querySelectorAll('[data-pill-group="' + tableId + '"]').forEach(x => x.classList.remove('active'));
|
|
294
|
+
p.classList.add('active'); status = p.dataset.status; apply();
|
|
295
|
+
}));
|
|
296
|
+
table.querySelectorAll('th[data-sort]').forEach(th => {
|
|
297
|
+
th.addEventListener('click', () => {
|
|
298
|
+
const idx = Array.from(th.parentNode.children).indexOf(th);
|
|
299
|
+
const dir = th.dataset.dir === 'asc' ? -1 : 1;
|
|
300
|
+
th.dataset.dir = dir === 1 ? 'asc' : 'desc';
|
|
301
|
+
const sorted = rows.slice().sort((a,b) => {
|
|
302
|
+
const av=a.children[idx].dataset.v, bv=b.children[idx].dataset.v;
|
|
303
|
+
const an=Number(av), bn=Number(bv);
|
|
304
|
+
if (!isNaN(an) && !isNaN(bn)) return (an-bn)*dir;
|
|
305
|
+
return av.localeCompare(bv)*dir;
|
|
306
|
+
});
|
|
307
|
+
sorted.forEach(r => tbody.appendChild(r));
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
__JS_BIND__
|
|
312
|
+
</script>
|
|
313
|
+
</body>
|
|
314
|
+
</html>
|
|
315
|
+
"""
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _html_rows(changes: list[Change], metric: str) -> str:
|
|
319
|
+
if not changes:
|
|
320
|
+
return '<tr><td colspan="6" class="detail">(无变更)</td></tr>'
|
|
321
|
+
max_impact = max(abs(c.size_for(metric)) for c in changes) or 1
|
|
322
|
+
parts = []
|
|
323
|
+
for c in _by_impact(changes, metric):
|
|
324
|
+
old = c.old_for(metric)
|
|
325
|
+
new = c.new_for(metric)
|
|
326
|
+
delta = c.size_for(metric)
|
|
327
|
+
cls = "up" if delta > 0 else ("down" if delta < 0 else "flat")
|
|
328
|
+
bar_color = "var(--red)" if delta > 0 else "var(--green)"
|
|
329
|
+
width = max(2, round(abs(delta) / max_impact * 100))
|
|
330
|
+
detail_parts = []
|
|
331
|
+
if c.detail.get("renamed_from"):
|
|
332
|
+
detail_parts.append(f"原路径 {html.escape(c.detail['renamed_from'])}")
|
|
333
|
+
if c.detail.get("breakdown_delta"):
|
|
334
|
+
detail_parts.append(" ".join(
|
|
335
|
+
f"{k} {human_delta(v)}" for k, v in c.detail["breakdown_delta"].items() if v
|
|
336
|
+
))
|
|
337
|
+
if c.detail.get("dex"):
|
|
338
|
+
detail_parts.append(f"dex: {html.escape(str(c.detail['dex']))}")
|
|
339
|
+
detail = " · ".join(detail_parts)
|
|
340
|
+
detail_html = f'<div class="detail">{detail}</div>' if detail else ""
|
|
341
|
+
parts.append(
|
|
342
|
+
f'<tr data-status="{c.status}" data-search="{html.escape(c.key.lower())}">'
|
|
343
|
+
f'<td><span class="tag {c.status}">{STATUS_LABEL.get(c.status, c.status)}</span></td>'
|
|
344
|
+
f'<td><div class="name">{html.escape(c.key)}</div>{detail_html}'
|
|
345
|
+
f'<div class="bar"><i style="width:{width}%;background:{bar_color}"></i></div></td>'
|
|
346
|
+
f'<td class="num" data-v="{old}">{human_size(old)}</td>'
|
|
347
|
+
f'<td class="num" data-v="{new}">{human_size(new)}</td>'
|
|
348
|
+
f'<td class="num {cls}" data-v="{delta}">{human_delta(delta)}</td>'
|
|
349
|
+
f'<td class="num" data-v="{abs(delta)}">{human_size(abs(delta))}</td>'
|
|
350
|
+
f'</tr>'
|
|
351
|
+
)
|
|
352
|
+
return "".join(parts)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _html_table(table_id: str, title: str, changes: list[Change], metric: str) -> str:
|
|
356
|
+
counts = {s: sum(1 for c in changes if c.status == s)
|
|
357
|
+
for s in (ADDED, DELETED, MODIFIED, RENAMED)}
|
|
358
|
+
pills = "".join(
|
|
359
|
+
f'<span class="pill {"active" if s == "all" else ""}" data-pill-group="{table_id}" '
|
|
360
|
+
f'data-status="{s}">{label} {counts[s] if s in counts else len(changes)}</span>'
|
|
361
|
+
for s, label in [("all", "全部"), (ADDED, "新增"), (DELETED, "删除"),
|
|
362
|
+
(MODIFIED, "修改"), (RENAMED, "重命名")]
|
|
363
|
+
)
|
|
364
|
+
return f"""
|
|
365
|
+
<h2>{title} <span class="sub" style="display:inline">({len(changes)} 项)</span></h2>
|
|
366
|
+
<div class="panel">
|
|
367
|
+
<div class="toolbar">
|
|
368
|
+
<input id="q_{table_id}" type="text" placeholder="搜索类名 / 文件名…">
|
|
369
|
+
{pills}
|
|
370
|
+
</div>
|
|
371
|
+
<table id="{table_id}">
|
|
372
|
+
<thead><tr>
|
|
373
|
+
<th data-sort>状态</th><th data-sort>名称</th>
|
|
374
|
+
<th class="num" data-sort>旧</th><th class="num" data-sort>新</th>
|
|
375
|
+
<th class="num" data-sort>Δ</th><th class="num" data-sort>Δ 大小</th>
|
|
376
|
+
</tr></thead>
|
|
377
|
+
<tbody>{_html_rows(changes, metric)}</tbody>
|
|
378
|
+
</table>
|
|
379
|
+
</div>"""
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def write_html(result: DiffResult, path: str, metric: str) -> None:
|
|
383
|
+
s = result.summary
|
|
384
|
+
cards = [
|
|
385
|
+
("APK 文件", s["old_apk_size"], s["new_apk_size"], s["apk_size_delta"]),
|
|
386
|
+
("代码 (压缩估算)", s["old_class_compressed"], s["new_class_compressed"], s["class_compressed_delta"]),
|
|
387
|
+
("代码 (原始归属)", s["old_class_bytes"], s["new_class_bytes"], s["class_bytes_delta"]),
|
|
388
|
+
("资源 (压缩)", s["old_resource_compressed"], s["new_resource_compressed"], s["resource_compressed_delta"]),
|
|
389
|
+
("资源 (原始)", s["old_resource_bytes"], s["new_resource_bytes"], s["resource_bytes_delta"]),
|
|
390
|
+
]
|
|
391
|
+
card_html = ""
|
|
392
|
+
for label, old, new, delta in cards:
|
|
393
|
+
cls = "up" if delta > 0 else ("down" if delta < 0 else "flat")
|
|
394
|
+
card_html += (
|
|
395
|
+
f'<div class="card"><div class="label">{label}</div>'
|
|
396
|
+
f'<div class="value">{human_size(new)}</div>'
|
|
397
|
+
f'<div class="delta {cls}">{human_delta(delta)} (旧 {human_size(old)})</div></div>'
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
warnings = result.old.warnings + result.new.warnings
|
|
401
|
+
warn_html = ""
|
|
402
|
+
if warnings:
|
|
403
|
+
items = "".join(f"<li>{html.escape(w)}</li>" for w in warnings[:50])
|
|
404
|
+
warn_html = f'<div class="warn"><b>解析警告 ({len(warnings)})</b><ul>{items}</ul></div>'
|
|
405
|
+
|
|
406
|
+
body = _HTML_TEMPLATE
|
|
407
|
+
body = body.replace("__OLD__", html.escape(result.old.path))
|
|
408
|
+
body = body.replace("__NEW__", html.escape(result.new.path))
|
|
409
|
+
body = body.replace("__METRIC__", _metric_unit(metric))
|
|
410
|
+
body = body.replace("__CARDS__", card_html)
|
|
411
|
+
body = body.replace("__CLASS_TABLE__", _html_table("classes", "代码类变更", result.classes, metric))
|
|
412
|
+
body = body.replace("__RES_TABLE__", _html_table("resources", "资源文件变更", result.resources, metric))
|
|
413
|
+
body = body.replace("__WARNINGS__", warn_html)
|
|
414
|
+
body = body.replace("__JS_BIND__",
|
|
415
|
+
"bindTable('q_classes','classes',document.querySelectorAll('[data-pill-group=classes]'));\n"
|
|
416
|
+
"bindTable('q_resources','resources',document.querySelectorAll('[data-pill-group=resources]'));")
|
|
417
|
+
|
|
418
|
+
_write_text(path, body)
|
apkdiff_core/util.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Shared helpers: size formatting, hashing and the per-class byte breakdown.
|
|
2
|
+
|
|
3
|
+
1. Size formatting (human_size / human_delta)
|
|
4
|
+
Byte counts render with KB as the smallest unit and two decimals:
|
|
5
|
+
257 -> "0.25 KB", 7685 -> "7.50 KB". human_delta adds a sign.
|
|
6
|
+
|
|
7
|
+
2. SizeBreakdown
|
|
8
|
+
Records how a class's bytes split across code, debug info, strings, etc.
|
|
9
|
+
The per-class detail in reports comes from this structure.
|
|
10
|
+
|
|
11
|
+
Kept in one module because dex.py, apk.py and report.py all use it, avoiding
|
|
12
|
+
circular imports.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _human(num: int | None, signed: bool) -> str:
|
|
21
|
+
"""Format a byte count with KB as the smallest unit and 2 decimals."""
|
|
22
|
+
if num is None:
|
|
23
|
+
return "-"
|
|
24
|
+
if signed:
|
|
25
|
+
sign = "+" if num > 0 else ("-" if num < 0 else "")
|
|
26
|
+
else:
|
|
27
|
+
sign = "-" if num < 0 else ""
|
|
28
|
+
n = abs(float(num)) / 1024.0
|
|
29
|
+
for unit in ("KB", "MB", "GB", "TB"):
|
|
30
|
+
if n < 1024.0 or unit == "TB":
|
|
31
|
+
return f"{sign}{n:.2f} {unit}"
|
|
32
|
+
n /= 1024.0
|
|
33
|
+
return f"{sign}{n:.2f} TB"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def human_size(num: int | None) -> str:
|
|
37
|
+
"""Human readable size, e.g. 0.25 KB / 7.51 KB / 90.85 KB (2 decimals)."""
|
|
38
|
+
return _human(num, signed=False)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def human_delta(num: int | None) -> str:
|
|
42
|
+
"""Signed human readable size change, e.g. +7.51 KB / -0.25 KB."""
|
|
43
|
+
return _human(num, signed=True)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class SizeBreakdown:
|
|
48
|
+
"""Where the bytes attributed to a single class came from."""
|
|
49
|
+
|
|
50
|
+
def_item: int = 0
|
|
51
|
+
class_data: int = 0
|
|
52
|
+
code: int = 0
|
|
53
|
+
debug_info: int = 0
|
|
54
|
+
annotations: int = 0
|
|
55
|
+
static_values: int = 0
|
|
56
|
+
identifiers: int = 0
|
|
57
|
+
strings: int = 0
|
|
58
|
+
type_lists: int = 0
|
|
59
|
+
|
|
60
|
+
def as_dict(self) -> dict[str, int]:
|
|
61
|
+
return {
|
|
62
|
+
"def_item": self.def_item,
|
|
63
|
+
"class_data": self.class_data,
|
|
64
|
+
"code": self.code,
|
|
65
|
+
"debug_info": self.debug_info,
|
|
66
|
+
"annotations": self.annotations,
|
|
67
|
+
"static_values": self.static_values,
|
|
68
|
+
"identifiers": self.identifiers,
|
|
69
|
+
"strings": self.strings,
|
|
70
|
+
"type_lists": self.type_lists,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def total(self) -> int:
|
|
75
|
+
return (
|
|
76
|
+
self.def_item + self.class_data + self.code + self.debug_info
|
|
77
|
+
+ self.annotations + self.static_values + self.identifiers
|
|
78
|
+
+ self.strings + self.type_lists
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def plus(self, other: SizeBreakdown) -> SizeBreakdown:
|
|
82
|
+
return SizeBreakdown(
|
|
83
|
+
self.def_item + other.def_item,
|
|
84
|
+
self.class_data + other.class_data,
|
|
85
|
+
self.code + other.code,
|
|
86
|
+
self.debug_info + other.debug_info,
|
|
87
|
+
self.annotations + other.annotations,
|
|
88
|
+
self.static_values + other.static_values,
|
|
89
|
+
self.identifiers + other.identifiers,
|
|
90
|
+
self.strings + other.strings,
|
|
91
|
+
self.type_lists + other.type_lists,
|
|
92
|
+
)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: apkdiff-core
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: APK size diff core library: attributes DEX bytes to classes, compares classes and resources, and renders console/JSON/HTML/Markdown reports
|
|
5
|
+
Author: Jayvin
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Jayvinz/apkdiff
|
|
8
|
+
Project-URL: Repository, https://github.com/Jayvinz/apkdiff
|
|
9
|
+
Project-URL: Source, https://github.com/Jayvinz/apkdiff/tree/main/py
|
|
10
|
+
Keywords: apk,dex,android,size,diff,r8,proguard
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
25
|
+
Requires-Python: >=3.7
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
[English](README.md) | [简体中文](README.zh-CN.md)
|
|
29
|
+
|
|
30
|
+
# apkdiff-core
|
|
31
|
+
|
|
32
|
+
APK size diff core library (pure Python standard library, zero runtime dependencies).
|
|
33
|
+
|
|
34
|
+
Attributes DEX bytes to classes, compares classes and resources between two APKs, and
|
|
35
|
+
renders console / JSON / HTML / Markdown reports.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install apkdiff-core
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Python 3.7 or newer.
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from apkdiff_core import (
|
|
49
|
+
analyze_apk,
|
|
50
|
+
diff_apks,
|
|
51
|
+
load_mapping,
|
|
52
|
+
print_console,
|
|
53
|
+
write_html,
|
|
54
|
+
write_json,
|
|
55
|
+
write_markdown,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
old = analyze_apk("old.apk", load_mapping("old/mapping.txt"))
|
|
59
|
+
new = analyze_apk("new.apk", load_mapping("new/mapping.txt"))
|
|
60
|
+
result = diff_apks(old, new, include_meta=False, detect_renames=True)
|
|
61
|
+
|
|
62
|
+
print_console(result, metric="compressed", top=30)
|
|
63
|
+
write_json(result, "report/apkdiff.json", "compressed")
|
|
64
|
+
write_html(result, "report/apkdiff.html", "compressed")
|
|
65
|
+
write_markdown(result, "report/apkdiff.md", "compressed")
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Public API:
|
|
69
|
+
|
|
70
|
+
- `analyze_apk(path, mapping=None, hash_content=True)`
|
|
71
|
+
- `load_mapping(path)` / `Mapping.parse(path)`
|
|
72
|
+
- `diff_apks(old, new, include_meta=False, detect_renames=False)`
|
|
73
|
+
- `print_console` / `build_json` / `write_json` / `write_html` / `write_markdown`
|
|
74
|
+
- `human_size` / `human_delta`
|
|
75
|
+
- data classes: `ApkAnalysis`, `ApkClass`, `ApkEntry`, `DexAnalysis`, `DexClass`, `Change`, `DiffResult`
|
|
76
|
+
|
|
77
|
+
Reports are byte-for-byte identical to the JVM and Node.js implementations.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
apkdiff_core/__init__.py,sha256=emNFPwG0uCxEaXGb72LTGpjgKA_kJ1OpXHYVS3OgEz0,1695
|
|
2
|
+
apkdiff_core/apk.py,sha256=pQBDI40iw3g0sNyeEqRx84AbaYr2tpqikIg0aZPDtYQ,8919
|
|
3
|
+
apkdiff_core/dex.py,sha256=Ba7tSdlEgmvcvWbNk0l0-1tSNWzHxKv9UIBZ93Q7zwo,39038
|
|
4
|
+
apkdiff_core/diff.py,sha256=WjKV2YwvCQuq2XxEfuwcNjaOWW5OxAve7llVwoDaYbE,11716
|
|
5
|
+
apkdiff_core/mapping.py,sha256=F0wt2efeFvoM76piapsFcQs-4eNfW3bOUNHcDdTcDd4,3124
|
|
6
|
+
apkdiff_core/report.py,sha256=_0HFxF7l1L6pwBGC2sZFgK1cbZYB4nEqlv5piTYeQoY,18941
|
|
7
|
+
apkdiff_core/util.py,sha256=EKXtwzJLeDDzzOcSUgtZE8h2leuq1BwBaiE4JSogvBQ,2926
|
|
8
|
+
apkdiff_core-1.0.0.dist-info/METADATA,sha256=FRY7WJENl8tosSLpk1faWpN39qbTzGh3qK6Dpgr4ECw,2765
|
|
9
|
+
apkdiff_core-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
apkdiff_core-1.0.0.dist-info/top_level.txt,sha256=vr55Yi77F2ID_KYqNUWpoT9a6w3Tx1vDu_ZaWjHyvJs,13
|
|
11
|
+
apkdiff_core-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
apkdiff_core
|