@harmonyos-arkts/d2h 0.1.29 → 0.1.32

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.
Files changed (104) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +6 -2
  3. package/agents/d2h.md +23 -14
  4. package/dist/bin/install-opencode.js +17 -4
  5. package/dist/src/install-opencode.js +6 -4
  6. package/dist/src/install-tui-extension.js +1 -1
  7. package/dist/src/metrics-plugin.js +4 -3
  8. package/dist/src/poc.js +53 -0
  9. package/docs/architecture-plan-guide.zh-CN.md +30 -46
  10. package/docs/poc-rule-evaluation.md +38 -0
  11. package/package.json +3 -2
  12. package/schemas/code-stats.schema.json +245 -0
  13. package/skills/android2hmos_resources_convert/SKILL.md +1 -9
  14. package/skills/d2h-app-solution/SKILL.md +3 -3
  15. package/skills/d2h-app-solution/references/inventory-schema.md +2 -2
  16. package/skills/d2h-architecture-plan/SKILL.md +23 -22
  17. package/skills/d2h-architecture-plan/references/architecture-plan.example.json +650 -76
  18. package/skills/d2h-architecture-plan/references/directory-creation.md +7 -7
  19. package/skills/d2h-architecture-plan/references/hybrid-design.md +63 -63
  20. package/skills/d2h-architecture-plan/references/json-contract.md +42 -27
  21. package/skills/d2h-architecture-plan/references/layout-reference.md +25 -72
  22. package/skills/d2h-architecture-plan/references/plan-contract.md +24 -34
  23. package/skills/d2h-architecture-plan/references/source-review.md +10 -7
  24. package/skills/d2h-architecture-plan/scripts/architecture_plan.py +50 -16
  25. package/skills/d2h-code-audit/SKILL.md +68 -0
  26. package/skills/d2h-code-audit/references/code-stats-schema.md +260 -0
  27. package/skills/d2h-code-audit/references/metrics.md +94 -0
  28. package/skills/d2h-code-audit/scripts/code_stats.py +600 -0
  29. package/skills/d2h-code-audit/scripts/validate_code_stats.py +446 -0
  30. package/skills/d2h-dashboard/SKILL.md +59 -33
  31. package/skills/d2h-dashboard/app/assets/Analysis-9GrmuIjp.css +1 -0
  32. package/skills/d2h-dashboard/app/assets/Analysis-Dj-4QEJi.js +1 -0
  33. package/skills/d2h-dashboard/app/assets/CodeAudit-Ctt3XEec.css +1 -0
  34. package/skills/d2h-dashboard/app/assets/CodeAudit-TcIcLwQL.js +1 -0
  35. package/skills/d2h-dashboard/app/assets/FeaturesList-C5yGUbRo.js +1 -0
  36. package/skills/d2h-dashboard/app/assets/FeaturesList-CZ40orVY.css +1 -0
  37. package/skills/d2h-dashboard/app/assets/Overview-CNkA3J9F.js +1 -0
  38. package/skills/d2h-dashboard/app/assets/Overview-Cmz8yjX-.css +1 -0
  39. package/skills/d2h-dashboard/app/assets/PageHeading-B5I3tpO8.js +1 -0
  40. package/skills/d2h-dashboard/app/assets/PageHeading-BIDu_a9G.css +1 -0
  41. package/skills/d2h-dashboard/app/assets/Project-BC9Tz1WY.js +1 -0
  42. package/skills/d2h-dashboard/app/assets/Project-BRyXCzsB.css +1 -0
  43. package/skills/d2h-dashboard/app/assets/Review-BfWvqlU9.js +1 -0
  44. package/skills/d2h-dashboard/app/assets/SpecDetail-BHB6smtT.css +1 -0
  45. package/skills/d2h-dashboard/app/assets/SpecDetail-DguVmqAE.js +1 -0
  46. package/skills/d2h-dashboard/app/assets/SpecItemDetail-7s7SaF3O.js +69 -0
  47. package/skills/d2h-dashboard/app/assets/SpecItemDetail-Bf4pGDEN.css +1 -0
  48. package/skills/d2h-dashboard/app/assets/_plugin-vue_export-helper-B9l48Cov.js +1 -0
  49. package/skills/d2h-dashboard/app/assets/batchReport-B3IzPnHF.js +1 -0
  50. package/skills/d2h-dashboard/app/assets/datetime-CHrzCsjX.js +1 -0
  51. package/skills/d2h-dashboard/app/assets/index-B3nfIPBm.js +3 -0
  52. package/skills/d2h-dashboard/app/assets/index-CnjP19Vs.css +1 -0
  53. package/skills/d2h-dashboard/app/assets/navigation-d1Uf6TR4.js +1 -0
  54. package/skills/d2h-dashboard/app/dataApi.mjs +387 -0
  55. package/skills/d2h-dashboard/app/index.html +14 -0
  56. package/skills/d2h-dashboard/app/package.json +12 -0
  57. package/skills/d2h-dashboard/app/serve.mjs +310 -0
  58. package/skills/d2h-hypium-forge/SKILL.md +6 -1
  59. package/skills/d2h-spec-develop/SKILL.md +24 -25
  60. package/skills/d2h-spec-develop/scripts/__pycache__/check_acceptance.cpython-313.pyc +0 -0
  61. package/skills/d2h-spec-develop/scripts/check_acceptance.py +66 -0
  62. package/skills/d2h-spec-generate/SKILL.md +2 -0
  63. package/skills/d2h-spec-plan/SKILL.md +6 -0
  64. package/skills/{cpp → language/cpp}/d2h-native-library-verify/scripts/__pycache__/native_common.cpython-313.pyc +0 -0
  65. package/skills/d2h-architecture-plan/scripts/test_architecture_plan.py +0 -241
  66. package/skills/d2h-spec-generate/assets/spec-template.md +0 -109
  67. package/skills/d2h-spec-generate/references/from-plan.md +0 -27
  68. package/skills/d2h-spec-generate/references/spec-content.md +0 -32
  69. package/skills/maintaining-migration-report/SKILL.md +0 -144
  70. package/skills/maintaining-migration-report/references/final-acceptance.md +0 -48
  71. package/skills/maintaining-migration-report/references/source-provenance.md +0 -66
  72. /package/skills/{cpp → language/cpp}/d2h-native-library-analyse/SKILL.md +0 -0
  73. /package/skills/{cpp → language/cpp}/d2h-native-library-analyse/scripts/analyse-android-so.py +0 -0
  74. /package/skills/{cpp → language/cpp}/d2h-native-library-build/SKILL.md +0 -0
  75. /package/skills/{cpp → language/cpp}/d2h-native-library-build/references/build-config-mapping.md +0 -0
  76. /package/skills/{cpp → language/cpp}/d2h-native-library-build/references/jni-to-napi-mapping.md +0 -0
  77. /package/skills/{cpp → language/cpp}/d2h-native-library-build/scripts/check-android-so.py +0 -0
  78. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/SKILL.md +0 -0
  79. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-build-sign-run.md +0 -0
  80. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/AppScope/app.json5 +0 -0
  81. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/AppScope/resources/base/element/string.json +0 -0
  82. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/README.md +0 -0
  83. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/build-profile.json5 +0 -0
  84. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/build-profile.json5 +0 -0
  85. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/hvigorfile.ts +0 -0
  86. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/oh-package.json5 +0 -0
  87. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/main/ets/entryability/EntryAbility.ets +0 -0
  88. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/main/ets/pages/Index.ets +0 -0
  89. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/main/ets/pages/NativeVerifyDemo.ets +0 -0
  90. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/main/module.json5 +0 -0
  91. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/main/resources/base/element/color.json +0 -0
  92. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/main/resources/base/element/string.json +0 -0
  93. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/main/resources/base/profile/main_pages.json +0 -0
  94. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/ohosTest/ets/test/FFmpegVerify.test.ets +0 -0
  95. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/ohosTest/ets/test/List.test.ets +0 -0
  96. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/entry/src/ohosTest/module.json5 +0 -0
  97. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/hvigor/hvigor-config.json5 +0 -0
  98. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/hvigorfile.ts +0 -0
  99. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-project-template/oh-package.json5 +0 -0
  100. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/demo-template.md +0 -0
  101. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/references/hypium-test-template.md +0 -0
  102. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/scripts/device-verify.py +0 -0
  103. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/scripts/native_common.py +0 -0
  104. /package/skills/{cpp → language/cpp}/d2h-native-library-verify/scripts/verify-ohos-native.py +0 -0
@@ -0,0 +1,600 @@
1
+ #!/usr/bin/env python3
2
+ """Deterministic dual-platform (Android + HarmonyOS) code statistics scanner.
3
+
4
+ Produces code-stats.json per schemas/code-stats.schema.json and
5
+ skills/d2h-code-audit/references/code-stats-schema.md.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ from collections import OrderedDict
17
+ from datetime import datetime
18
+ from pathlib import Path
19
+
20
+ SCHEMA_VERSION = "1.0"
21
+ TITLE = "双端代码静态审计"
22
+ GENERATED_BY = "d2h-code-audit/scripts/code_stats.py"
23
+
24
+ CORE_EXTENSION_MAP = OrderedDict([
25
+ (".kt", "kotlin"),
26
+ (".java", "java"),
27
+ (".ets", "arkts"),
28
+ (".ts", "typescript"),
29
+ (".js", "javascript"),
30
+ (".jsx", "javascript"),
31
+ (".mjs", "javascript"),
32
+ (".cjs", "javascript"),
33
+ (".dart", "dart"),
34
+ (".vue", "vue"),
35
+ (".c", "cpp"),
36
+ (".cc", "cpp"),
37
+ (".cpp", "cpp"),
38
+ (".cxx", "cpp"),
39
+ (".h", "cpp"),
40
+ (".hpp", "cpp"),
41
+ (".xml", "xml"),
42
+ ])
43
+
44
+ KNOWN_LANGUAGES = sorted(set(CORE_EXTENSION_MAP.values()))
45
+
46
+ BINARY_EXTENSIONS = {
47
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".ico", ".svgz",
48
+ ".so", ".dll", ".dylib", ".a", ".o", ".lib", ".exe", ".bin",
49
+ ".zip", ".jar", ".aar", ".apk", ".hap", ".har", ".hsp", ".7z", ".gz",
50
+ ".xz", ".br", ".tar", ".zst",
51
+ ".pdf", ".woff", ".woff2", ".ttf", ".otf", ".eot",
52
+ ".mp3", ".mp4", ".wav", ".ogg", ".aac", ".flac", ".avi", ".mov", ".webm",
53
+ ".class", ".dex", ".db", ".sqlite", ".wasm", ".proto-bin",
54
+ }
55
+
56
+ ABI_DIR_NAMES = {
57
+ "armeabi", "armeabi-v7a", "arm64-v8a", "x86", "x86_64", "mips", "mips64",
58
+ }
59
+
60
+ COMMON_EXCLUDED_PARTS = {
61
+ ".git", ".hg", ".svn", ".idea", ".vscode", ".gradle", ".hvigor", ".cxx",
62
+ "node_modules", "oh_modules", "build",
63
+ }
64
+
65
+ PLATFORM_EXCLUDED_PARTS = {
66
+ "android": COMMON_EXCLUDED_PARTS | {"test", "androidTest", "generated"},
67
+ "harmony": COMMON_EXCLUDED_PARTS | {"test", "ohosTest"},
68
+ }
69
+
70
+ NATIVE_LIB_DIR_PARTS = {"jniLibs", "libs"}
71
+ NATIVE_LIB_EXTENSIONS = {".so", ".jar", ".aar"}
72
+
73
+ HEAVY_UNRECOGNIZED_LINES = 500
74
+
75
+ GRADLE_INCLUDE_RE = re.compile(r"include\s*(?:\((.*?)\)|([^\n]+))", re.S)
76
+ QUOTED_TOKEN_RE = re.compile(r"['\"]([^'\"]+)['\"]")
77
+ GRADLE_DEP_RE = re.compile(
78
+ r"""^\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:\(\s*)?['"]([^'"]+):([^'":]+):([^'"]+)['\"]\s*\)?"""
79
+ )
80
+
81
+ LANGUAGE_RE = re.compile(r"^[a-z][a-z0-9-]*$")
82
+
83
+
84
+ def rel_posix(root: Path, path: Path) -> str:
85
+ return path.relative_to(root).as_posix()
86
+
87
+
88
+ def read_text(path: Path) -> str:
89
+ return path.read_text(encoding="utf-8", errors="replace")
90
+
91
+
92
+ def strip_json5_comments(text: str) -> str:
93
+ text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
94
+ # Drop // comments but keep URLs like https:// (colon before //).
95
+ text = re.sub(r"(?m)(?<![:\w])//.*$", "", text)
96
+ return text
97
+
98
+
99
+ def _mask_json_strings(text: str):
100
+ """Replace double-quoted string literals with placeholders free of , [ { : chars."""
101
+ masked = []
102
+ strings = []
103
+ i = 0
104
+ n = len(text)
105
+ while i < n:
106
+ ch = text[i]
107
+ if ch == '"':
108
+ j = i + 1
109
+ while j < n:
110
+ if text[j] == "\\":
111
+ j += 2
112
+ continue
113
+ if text[j] == '"':
114
+ break
115
+ j += 1
116
+ j = min(j, n - 1)
117
+ strings.append(text[i:j + 1])
118
+ masked.append('"\\x00{}\\x00"'.format(len(strings) - 1))
119
+ i = j + 1
120
+ else:
121
+ masked.append(ch)
122
+ i += 1
123
+ return "".join(masked), strings
124
+
125
+
126
+ def _unmask_json_strings(masked: str, strings: list) -> str:
127
+ # Placeholders are the literal 4-char text "\x00"; double the backslash so the
128
+ # regex matches that text instead of the NUL character.
129
+ return re.sub(r'"\\x00(\d+)\\x00"', lambda m: strings[int(m.group(1))], masked)
130
+
131
+
132
+ def _single_quoted_to_double(match: re.Match, strings: list) -> str:
133
+ body = match.group(1).replace("\\'", "'").replace('"', '\\"')
134
+ strings.append('"' + body + '"')
135
+ return '"\\x00{}\\x00"'.format(len(strings) - 1)
136
+
137
+
138
+ def load_json5(path: Path):
139
+ text = strip_json5_comments(read_text(path))
140
+ # JSON5 tolerances: single-quoted strings, bare keys, trailing commas.
141
+ # String literals are masked first so transforms cannot corrupt their content.
142
+ masked, strings = _mask_json_strings(text)
143
+ masked = re.sub(r"'((?:[^'\\]|\\.)*)'",
144
+ lambda m: _single_quoted_to_double(m, strings), masked, flags=re.S)
145
+ masked = re.sub(r"([{,\[]\s*)([A-Za-z_$][A-Za-z0-9_$-]*)\s*(?=:)", r'\1"\2"', masked)
146
+ masked = re.sub(r",\s*(?=[}\]])", "", masked)
147
+ return json.loads(_unmask_json_strings(masked, strings))
148
+
149
+
150
+ def count_physical_lines(data: bytes) -> int:
151
+ if not data:
152
+ return 0
153
+ lines = data.count(b"\n")
154
+ if not data.endswith(b"\n"):
155
+ lines += 1
156
+ return lines
157
+
158
+
159
+ def looks_binary(data: bytes) -> bool:
160
+ return b"\x00" in data[:8192]
161
+
162
+
163
+ def git_revision(root: Path) -> str:
164
+ try:
165
+ result = subprocess.run(
166
+ ["git", "rev-parse", "--short=12", "HEAD"],
167
+ cwd=str(root), capture_output=True, text=True, timeout=10,
168
+ )
169
+ if result.returncode == 0:
170
+ return result.stdout.strip()
171
+ except (OSError, subprocess.SubprocessError):
172
+ pass
173
+ return "working-tree"
174
+
175
+
176
+ def walk_files(root: Path, excluded_parts: set):
177
+ for dirpath, dirnames, filenames in os.walk(root):
178
+ # Dot-prefixed dirs (.git/.idea/.hypium_forge/...) are tool artifacts; skip them all.
179
+ dirnames[:] = [d for d in dirnames if d not in excluded_parts and not d.startswith(".")]
180
+ for name in filenames:
181
+ yield Path(dirpath) / name
182
+
183
+
184
+ def detect_extension(path: Path) -> str:
185
+ return path.suffix.lower()
186
+
187
+
188
+ def collect_module_paths(modules) -> dict:
189
+ return {m["path"]: m["name"] for m in modules}
190
+
191
+
192
+ def attribute_module(rel: str, module_paths: dict):
193
+ best = ""
194
+ best_name = "unknown"
195
+ for mpath, mname in module_paths.items():
196
+ if rel == mpath or rel.startswith(mpath + "/"):
197
+ if len(mpath) > len(best):
198
+ best = mpath
199
+ best_name = mname
200
+ return best_name
201
+
202
+
203
+ def parse_android_modules(root: Path, excluded_parts: set):
204
+ text = None
205
+ for candidate in ("settings.gradle", "settings.gradle.kts"):
206
+ path = root / candidate
207
+ if path.is_file():
208
+ text = re.sub(r"/\*.*?\*/", "", read_text(path), flags=re.S)
209
+ text = re.sub(r"(?m)(?<![:\w])//.*$", "", text)
210
+ break
211
+ if text is None:
212
+ return []
213
+ tokens = []
214
+ for match in GRADLE_INCLUDE_RE.finditer(text):
215
+ body = match.group(1) if match.group(1) is not None else match.group(2) or ""
216
+ for token in QUOTED_TOKEN_RE.findall(body):
217
+ token = token.strip()
218
+ if token.startswith(":") and len(token) > 1:
219
+ tokens.append(token.lstrip(":"))
220
+ seen = set()
221
+ modules = []
222
+ for token in tokens:
223
+ if token in seen:
224
+ continue
225
+ seen.add(token)
226
+ mpath = token.replace(":", "/")
227
+ kind = "unknown"
228
+ for gradle_name in ("build.gradle", "build.gradle.kts"):
229
+ gradle_file = root / mpath / gradle_name
230
+ if gradle_file.is_file():
231
+ gradle_text = read_text(gradle_file)
232
+ if re.search(r"com\.android\.application", gradle_text):
233
+ kind = "app"
234
+ elif re.search(r"com\.android\.library|java-library", gradle_text):
235
+ kind = "library"
236
+ break
237
+ modules.append({"name": token, "path": mpath, "kind": kind})
238
+ modules.sort(key=lambda m: m["name"])
239
+ return modules
240
+
241
+
242
+ def parse_harmony_modules(root: Path, excluded_parts: set):
243
+ profile = root / "build-profile.json5"
244
+ if not profile.is_file():
245
+ return []
246
+ try:
247
+ data = load_json5(profile)
248
+ except (json.JSONDecodeError, OSError):
249
+ return []
250
+ modules = []
251
+ for item in data.get("modules", []) or []:
252
+ if not isinstance(item, dict):
253
+ continue
254
+ name = str(item.get("name", "")).strip()
255
+ src_path = str(item.get("srcPath", "")).strip().replace("\\", "/")
256
+ src_path = re.sub(r"^\./", "", src_path)
257
+ if not name or not src_path:
258
+ continue
259
+ kind = "unknown"
260
+ module_json = root / src_path / "src" / "main" / "module.json5"
261
+ if module_json.is_file():
262
+ try:
263
+ module_data = load_json5(module_json)
264
+ module_type = str((module_data.get("module") or {}).get("type", "")).lower()
265
+ if module_type in {"entry", "feature"}:
266
+ kind = module_type
267
+ except (json.JSONDecodeError, OSError):
268
+ pass
269
+ elif (root / src_path / "oh-package.json5").is_file():
270
+ kind = "library"
271
+ modules.append({"name": name, "path": src_path, "kind": kind})
272
+ modules.sort(key=lambda m: m["name"])
273
+ return modules
274
+
275
+
276
+ def collect_android_dependencies(root: Path, excluded_parts: set):
277
+ deps = OrderedDict()
278
+ for path in sorted(walk_files(root, excluded_parts)):
279
+ if path.name not in {"build.gradle", "build.gradle.kts"}:
280
+ continue
281
+ lines = read_text(path).splitlines()
282
+ rel = rel_posix(root, path)
283
+ for index, line in enumerate(lines, start=1):
284
+ match = GRADLE_DEP_RE.match(line)
285
+ if not match:
286
+ continue
287
+ scope, group, artifact, version = match.groups()
288
+ name = "{}:{}".format(group, artifact)
289
+ entry = deps.setdefault(name, {
290
+ "name": name,
291
+ "version": version,
292
+ "declarations": [],
293
+ })
294
+ entry["declarations"].append({
295
+ "path": rel,
296
+ "line_start": index,
297
+ "scope": scope,
298
+ "version": version,
299
+ })
300
+ return sorted(deps.values(), key=lambda d: d["name"])
301
+
302
+
303
+ def collect_harmony_dependencies(root: Path, excluded_parts: set):
304
+ deps = OrderedDict()
305
+ for path in sorted(walk_files(root, excluded_parts)):
306
+ if path.name != "oh-package.json5":
307
+ continue
308
+ rel = rel_posix(root, path)
309
+ try:
310
+ data = load_json5(path)
311
+ except (json.JSONDecodeError, OSError):
312
+ continue
313
+ raw_lines = read_text(path).splitlines()
314
+ for section in ("dependencies", "devDependencies"):
315
+ section_data = data.get(section) or {}
316
+ if not isinstance(section_data, dict):
317
+ continue
318
+ for dep_name, dep_version in section_data.items():
319
+ version = str(dep_version)
320
+ if version.startswith("file:"):
321
+ continue
322
+ line_start = None
323
+ pattern = re.compile(r"['\"]?{}['\"]?\s*:".format(re.escape(str(dep_name))))
324
+ for line_index, raw_line in enumerate(raw_lines, start=1):
325
+ if pattern.search(raw_line):
326
+ line_start = line_index
327
+ break
328
+ declaration = {"path": rel, "scope": section, "version": version}
329
+ if line_start is not None:
330
+ declaration["line_start"] = line_start
331
+ entry = deps.setdefault(str(dep_name), {
332
+ "name": str(dep_name),
333
+ "version": version,
334
+ "declarations": [],
335
+ })
336
+ entry["declarations"].append(declaration)
337
+ return sorted(deps.values(), key=lambda d: d["name"])
338
+
339
+
340
+ def collect_native_libraries(root: Path, excluded_parts: set):
341
+ entries = []
342
+ for path in sorted(walk_files(root, excluded_parts)):
343
+ ext = detect_extension(path)
344
+ if ext not in NATIVE_LIB_EXTENSIONS:
345
+ continue
346
+ if not any(part in NATIVE_LIB_DIR_PARTS for part in path.relative_to(root).parts[:-1]):
347
+ continue
348
+ parent_name = path.parent.name
349
+ entries.append({
350
+ "name": path.name,
351
+ "kind": ext.lstrip("."),
352
+ "abi": parent_name if parent_name in ABI_DIR_NAMES else "unknown",
353
+ "size_bytes": path.stat().st_size,
354
+ "path": rel_posix(root, path),
355
+ })
356
+ entries.sort(key=lambda e: (e["name"], e["path"]))
357
+ return entries
358
+
359
+
360
+ def scan_code(root: Path, excluded_parts: set, extension_map: dict, threshold: int):
361
+ by_language = {}
362
+ other_extensions = {}
363
+ skipped_binary = {}
364
+ oversized = []
365
+ total_files = 0
366
+ total_lines = 0
367
+
368
+ for path in sorted(walk_files(root, excluded_parts)):
369
+ ext = detect_extension(path)
370
+ if ext in BINARY_EXTENSIONS:
371
+ skipped_binary[ext] = skipped_binary.get(ext, 0) + 1
372
+ continue
373
+ try:
374
+ data = path.read_bytes()
375
+ except OSError:
376
+ continue
377
+ if looks_binary(data):
378
+ skipped_binary[ext] = skipped_binary.get(ext, 0) + 1
379
+ continue
380
+ lines = count_physical_lines(data)
381
+ rel = rel_posix(root, path)
382
+ language = extension_map.get(ext)
383
+ if language is not None:
384
+ bucket = by_language.setdefault(language, {"language": language, "files": 0, "lines": 0})
385
+ bucket["files"] += 1
386
+ bucket["lines"] += lines
387
+ else:
388
+ bucket = other_extensions.setdefault(ext, {"extension": ext, "files": 0, "lines": 0})
389
+ bucket["files"] += 1
390
+ bucket["lines"] += lines
391
+ language = "other"
392
+ total_files += 1
393
+ total_lines += lines
394
+ if lines >= threshold:
395
+ oversized.append({
396
+ "path": rel,
397
+ "lines": lines,
398
+ "language": language,
399
+ "module": None, # filled by caller
400
+ **({"extension": ext} if language == "other" else {}),
401
+ })
402
+
403
+ code = {
404
+ "total_files": total_files,
405
+ "total_lines": total_lines,
406
+ "by_language": sorted(by_language.values(), key=lambda b: (-b["lines"], b["language"])),
407
+ "other_extensions": sorted(other_extensions.values(), key=lambda b: (-b["lines"], b["extension"])),
408
+ "skipped_binary": [
409
+ {"extension": ext, "files": count}
410
+ for ext, count in sorted(skipped_binary.items())
411
+ ],
412
+ "scanned_extensions": sorted(extension_map.keys()),
413
+ "excluded_patterns": sorted(excluded_parts),
414
+ }
415
+ oversized.sort(key=lambda e: (-e["lines"], e["path"]))
416
+ return code, oversized
417
+
418
+
419
+ def scan_side(side_id: str, root: Path, threshold: int, extension_map: dict, extra_excludes: set):
420
+ excluded_parts = set(PLATFORM_EXCLUDED_PARTS[side_id]) | extra_excludes
421
+ if side_id == "android":
422
+ modules = parse_android_modules(root, excluded_parts)
423
+ dependencies = collect_android_dependencies(root, excluded_parts)
424
+ else:
425
+ modules = parse_harmony_modules(root, excluded_parts)
426
+ dependencies = collect_harmony_dependencies(root, excluded_parts)
427
+
428
+ native_libraries = collect_native_libraries(root, excluded_parts)
429
+ code, oversized = scan_code(root, excluded_parts, extension_map, threshold)
430
+
431
+ module_paths = collect_module_paths(modules)
432
+ for entry in oversized:
433
+ entry["module"] = attribute_module(entry["path"], module_paths)
434
+
435
+ notes = []
436
+ if not modules:
437
+ hint = ("未能从 settings.gradle 解析到 Gradle 模块,可能是 Flutter/uni-app 或非标准工程"
438
+ if side_id == "android"
439
+ else "未能从 build-profile.json5 解析到 HarmonyOS 模块,可能是非标准工程")
440
+ notes.append(hint)
441
+ for bucket in code["other_extensions"]:
442
+ if bucket["lines"] >= HEAVY_UNRECOGNIZED_LINES:
443
+ notes.append(
444
+ "扩展名 {} 共 {} 行未映射到核心语言桶;如属核心语言,请扩展 EXTENSION_MAP 或使用 --map-ext".format(
445
+ bucket["extension"] or "(无扩展名)", bucket["lines"]
446
+ )
447
+ )
448
+
449
+ side = {
450
+ "modules": modules,
451
+ "module_count": len(modules),
452
+ "third_party_dependencies": dependencies,
453
+ "third_party_dependency_count": len(dependencies),
454
+ "native_libraries": native_libraries,
455
+ "native_library_count": len({e["name"] for e in native_libraries}),
456
+ "code": code,
457
+ "oversized_files": oversized,
458
+ }
459
+ return side, notes
460
+
461
+
462
+ def build_comparison(sides: dict):
463
+ if set(sides.keys()) != {"android", "harmony"}:
464
+ return None
465
+ return {
466
+ "oversized": {
467
+ "android_count": len(sides["android"]["oversized_files"]),
468
+ "harmony_count": len(sides["harmony"]["oversized_files"]),
469
+ },
470
+ "modules": {
471
+ "android": sides["android"]["module_count"],
472
+ "harmony": sides["harmony"]["module_count"],
473
+ },
474
+ "third_party_dependencies": {
475
+ "android": sides["android"]["third_party_dependency_count"],
476
+ "harmony": sides["harmony"]["third_party_dependency_count"],
477
+ },
478
+ "native_libraries": {
479
+ "android": len({e["name"] for e in sides["android"]["native_libraries"]}),
480
+ "harmony": len({e["name"] for e in sides["harmony"]["native_libraries"]}),
481
+ },
482
+ "total_lines": {
483
+ "android": sides["android"]["code"]["total_lines"],
484
+ "harmony": sides["harmony"]["code"]["total_lines"],
485
+ },
486
+ }
487
+
488
+
489
+ def parse_map_ext(value: str, extension_map: dict):
490
+ if "=" not in value:
491
+ raise argparse.ArgumentTypeError("--map-ext 需要 ext=language 形式,例如 .scala=scala")
492
+ ext, language = value.split("=", 1)
493
+ ext = ext.strip().lower()
494
+ if not ext.startswith("."):
495
+ ext = "." + ext
496
+ language = language.strip()
497
+ if not LANGUAGE_RE.match(language):
498
+ raise argparse.ArgumentTypeError("language 需匹配 ^[a-z][a-z0-9-]*$:{}".format(language))
499
+ extension_map[ext] = language
500
+ return extension_map
501
+
502
+
503
+ def main() -> int:
504
+ parser = argparse.ArgumentParser(description=__doc__)
505
+ parser.add_argument("--android", type=Path, help="Android 工程根目录")
506
+ parser.add_argument("--harmony", type=Path, help="HarmonyOS 工程根目录")
507
+ parser.add_argument("--output", type=Path, default=Path("."), help="输出目录(默认当前目录)")
508
+ parser.add_argument("--threshold", type=int, default=2000, help="超大文件行数阈值(默认 2000)")
509
+ parser.add_argument(
510
+ "--map-ext", action="append", default=[], metavar="EXT=LANGUAGE",
511
+ help="临时扩展语言映射,如 .scala=scala,可重复",
512
+ )
513
+ parser.add_argument(
514
+ "--exclude", action="append", default=[], metavar="DIRNAME",
515
+ help="追加排除的目录名(两端生效),可重复",
516
+ )
517
+ args = parser.parse_args()
518
+
519
+ if args.threshold <= 0:
520
+ parser.error("--threshold 必须为正整数")
521
+ if not args.android and not args.harmony:
522
+ parser.error("至少提供 --android 或 --harmony 之一")
523
+
524
+ extension_map = dict(CORE_EXTENSION_MAP)
525
+ for mapping in args.map_ext:
526
+ parse_map_ext(mapping, extension_map)
527
+ extra_excludes = {name.strip() for name in args.exclude if name.strip()}
528
+
529
+ repositories = []
530
+ sides = OrderedDict()
531
+ notes = []
532
+ for side_id, arg_path, platform, label in (
533
+ ("android", args.android, "android", "Android"),
534
+ ("harmony", args.harmony, "harmonyos", "HarmonyOS"),
535
+ ):
536
+ if arg_path is None:
537
+ continue
538
+ root = arg_path.expanduser().resolve()
539
+ if not root.is_dir():
540
+ print("错误:{} 工程路径不存在或不是目录:{}".format(label, root), file=sys.stderr)
541
+ return 1
542
+ repositories.append({
543
+ "id": side_id,
544
+ "label": label,
545
+ "path": str(root),
546
+ "platform": platform,
547
+ "revision": git_revision(root),
548
+ })
549
+ side, side_notes = scan_side(side_id, root, args.threshold, extension_map, extra_excludes)
550
+ sides[side_id] = side
551
+ notes.extend("{}:{}".format(label, q) for q in side_notes)
552
+
553
+ if len(sides) == 1:
554
+ only_label = "Android" if "android" in sides else "HarmonyOS"
555
+ notes.append("仅统计 {} 侧,未提供另一端工程路径,comparison 未生成".format(only_label))
556
+
557
+ report = {
558
+ "schema_version": SCHEMA_VERSION,
559
+ "title": TITLE,
560
+ "language": "zh-CN",
561
+ "generated_by": GENERATED_BY,
562
+ "generated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
563
+ "thresholds": {"oversized_file_lines": args.threshold},
564
+ "repositories": repositories,
565
+ "sides": sides,
566
+ "notes": notes,
567
+ }
568
+ comparison = build_comparison(sides)
569
+ if comparison is not None:
570
+ report["comparison"] = comparison
571
+
572
+ args.output.mkdir(parents=True, exist_ok=True)
573
+ out_path = args.output / "code-stats.json"
574
+ out_path.write_text(
575
+ json.dumps(report, ensure_ascii=False, indent=2) + "\n",
576
+ encoding="utf-8",
577
+ )
578
+
579
+ print("code-stats.json: {}".format(out_path))
580
+ for side_id, side in sides.items():
581
+ print("[{}] modules={} deps={} native={} files={} lines={} oversized={}".format(
582
+ side_id,
583
+ side["module_count"],
584
+ side["third_party_dependency_count"],
585
+ side["native_library_count"],
586
+ side["code"]["total_files"],
587
+ side["code"]["total_lines"],
588
+ len(side["oversized_files"]),
589
+ ))
590
+ if comparison:
591
+ print("[comparison] oversized android={android_count} harmony={harmony_count}".format(
592
+ **comparison["oversized"]
593
+ ))
594
+ for note in notes:
595
+ print("[note] {}".format(note))
596
+ return 0
597
+
598
+
599
+ if __name__ == "__main__":
600
+ sys.exit(main())