xts-gate-windows 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,599 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """XTS 工程门禁前检查器(零依赖,Windows / WSL / Linux 均可运行)。
4
+
5
+ 用法:
6
+ python check_xts_project.py <suite_dir> [--syntax auto|dyn|sta] [--strict] [--json]
7
+
8
+ 检查范围:
9
+ BUILD.gn 模板 / test_hap / hap_name(acts=Acts / hits=Hits)/ part / 父 group 注册
10
+ build-profile / hvigor-config / oh-package / Test.json / module.json5 / syscap
11
+ 动态/静态 RPC 类型、parameters 判空、globalThis、@tc.number 重复
12
+ 相对 import 大小写、srcEntry 大小写、预编译二进制、构建残留、License 头
13
+
14
+ 退出码: 有 FAIL -> 1;否则 0。--strict 时 WARN 也返回 1。
15
+ """
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+ import re
21
+ import sys
22
+
23
+ FAIL = "FAIL"
24
+ WARN = "WARN"
25
+ INFO = "INFO"
26
+
27
+
28
+ class Finding(object):
29
+ def __init__(self, level, code, message, file="", line=0):
30
+ self.level = level
31
+ self.code = code
32
+ self.message = message
33
+ self.file = file
34
+ self.line = line
35
+
36
+ def __str__(self):
37
+ loc = ""
38
+ if self.file:
39
+ loc = " (%s:%s)" % (self.file, self.line) if self.line else " (%s)" % self.file
40
+ return "[%s] %s %s%s" % (self.level, self.code, self.message, loc)
41
+
42
+
43
+ def read_text(path):
44
+ try:
45
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
46
+ return f.read()
47
+ except OSError:
48
+ return ""
49
+
50
+
51
+ def strip_json_comments(text):
52
+ out = []
53
+ i = 0
54
+ n = len(text)
55
+ quote = ""
56
+ in_str = False
57
+ while i < n:
58
+ c = text[i]
59
+ if in_str:
60
+ out.append(c)
61
+ if c == "\\" and i + 1 < n:
62
+ out.append(text[i + 1])
63
+ i += 2
64
+ continue
65
+ if c == quote:
66
+ in_str = False
67
+ i += 1
68
+ continue
69
+ if c in "\"'":
70
+ in_str = True
71
+ quote = c
72
+ out.append(c)
73
+ i += 1
74
+ continue
75
+ if text.startswith("//", i):
76
+ j = text.find("\n", i)
77
+ i = n if j < 0 else j
78
+ continue
79
+ if text.startswith("/*", i):
80
+ j = text.find("*/", i + 2)
81
+ i = n if j < 0 else j + 2
82
+ continue
83
+ out.append(c)
84
+ i += 1
85
+ return "".join(out)
86
+
87
+
88
+ def load_json5(path):
89
+ text = strip_json_comments(read_text(path))
90
+ text = re.sub(r",(\s*[}\]])", r"\1", text)
91
+ try:
92
+ return json.loads(text)
93
+ except ValueError:
94
+ return None
95
+
96
+
97
+ def get_quoted(text, key, default=None):
98
+ m = re.search(r"[\"']?%s[\"']?\s*:\s*[\"']([^\"']+)[\"']" % re.escape(key), text)
99
+ return m.group(1) if m else default
100
+
101
+
102
+ def get_assigned(text, key, default=None):
103
+ """GN style: key = "value"."""
104
+ m = re.search(r"%s\s*=\s*\"([^\"]+)\"" % re.escape(key), text)
105
+ return m.group(1) if m else default
106
+
107
+
108
+ def get_raw_value(text, key):
109
+ """Return (value, quoted) for 'key: value' where value is string/number/bool."""
110
+ m = re.search(
111
+ r"[\"']?%s[\"']?\s*:\s*(?:\"([^\"]*)\"|'([^']*)'|([0-9]+)|(true|false))" % re.escape(key),
112
+ text,
113
+ )
114
+ if not m:
115
+ return None, False
116
+ for idx in (1, 2):
117
+ if m.group(idx) is not None:
118
+ return m.group(idx), True
119
+ if m.group(3) is not None:
120
+ return m.group(3), False
121
+ return m.group(4), False
122
+
123
+
124
+ def api_major(value):
125
+ if value is None:
126
+ return None
127
+ m = re.match(r"(\d+)", str(value))
128
+ return int(m.group(1)) if m else None
129
+
130
+
131
+ def exact_exists(base, rel):
132
+ """Case-sensitive existence check by walking directory entries."""
133
+ cur = base
134
+ for part in rel.replace("\\", "/").split("/"):
135
+ if part in ("", "."):
136
+ continue
137
+ if part == "..":
138
+ cur = os.path.dirname(cur)
139
+ continue
140
+ try:
141
+ names = os.listdir(cur)
142
+ except OSError:
143
+ return False
144
+ if part not in names:
145
+ return False
146
+ cur = os.path.join(cur, part)
147
+ return os.path.exists(cur)
148
+
149
+
150
+ def find_exact(base, rel, suffixes=("", ".ets", ".ts", ".d.ets", ".d.ts")):
151
+ for suffix in suffixes:
152
+ cand = rel + suffix
153
+ if exact_exists(base, cand):
154
+ return cand
155
+ return None
156
+
157
+
158
+ class Checker(object):
159
+ def __init__(self, project, syntax="auto", strict=False):
160
+ self.project = os.path.abspath(project)
161
+ self.syntax = syntax
162
+ self.strict = strict
163
+ self.findings = []
164
+ self.repo_kind = "unknown"
165
+ self.target = ""
166
+ self.hap_name = ""
167
+ self.part_name = ""
168
+ self.subsystem_name = ""
169
+ self.bundle_name = ""
170
+ self.module_name = ""
171
+ self.module_json = ""
172
+ self.test_json = ""
173
+ self.syscap_paths = []
174
+ self.test_root = ""
175
+ self.build_gn = os.path.join(self.project, "BUILD.gn")
176
+ self.build_profile = os.path.join(self.project, "build-profile.json5")
177
+ self.oh_package = os.path.join(self.project, "oh-package.json5")
178
+ self.hvigor_config = os.path.join(self.project, "hvigor", "hvigor-config.json5")
179
+
180
+ def add(self, level, code, message, file="", line=0):
181
+ if file and os.path.isabs(file):
182
+ file = os.path.relpath(file, self.project)
183
+ self.findings.append(Finding(level, code, message, file, line))
184
+
185
+ def relpath(self, p):
186
+ return os.path.relpath(p, self.project)
187
+
188
+ # ---------- repo ----------
189
+ def detect_repo_kind(self):
190
+ p = self.project.replace("\\", "/").rstrip("/") + "/"
191
+ if "/test/xts/hits/" in p or p.endswith("/xts/hits/"):
192
+ self.repo_kind = "hits"
193
+ elif "/test/xts/acts/" in p or p.endswith("/xts_acts/"):
194
+ self.repo_kind = "acts"
195
+
196
+ # ---------- syntax ----------
197
+ def detect_syntax(self):
198
+ if self.syntax in ("dyn", "sta"):
199
+ return
200
+ text = read_text(self.build_profile)
201
+ if re.search(r"[\"']?arkTSVersion[\"']?\s*:\s*[\"']1\.2[\"']", text):
202
+ self.syntax = "sta"
203
+ else:
204
+ self.syntax = "dyn"
205
+
206
+ # ---------- BUILD.gn ----------
207
+ def check_build_gn(self):
208
+ if not os.path.isfile(self.build_gn):
209
+ self.add(FAIL, "GN001", "BUILD.gn 不存在")
210
+ return
211
+ text = read_text(self.build_gn)
212
+ uncommented = "\n".join(
213
+ line for line in text.splitlines() if not line.strip().startswith("#")
214
+ )
215
+ m = re.search(r'ohos_(js_app_suite|js_app_static_suite)\s*\(\s*"([^"]+)"\s*\)', uncommented)
216
+ if not m:
217
+ self.add(FAIL, "GN002", "BUILD.gn 未找到 ohos_js_app_suite / ohos_js_app_static_suite")
218
+ else:
219
+ template, self.target = m.group(1), m.group(2)
220
+ expected = "js_app_suite" if self.syntax == "dyn" else "js_app_static_suite"
221
+ if template != expected:
222
+ self.add(
223
+ FAIL,
224
+ "GN003",
225
+ "模板 %s 与语法 %s 不匹配,应为 %s" % (template, self.syntax, expected),
226
+ self.build_gn,
227
+ )
228
+ self.hap_name = get_assigned(uncommented, "hap_name", "") or ""
229
+ self.part_name = get_assigned(uncommented, "part_name", "") or ""
230
+ self.subsystem_name = get_assigned(uncommented, "subsystem_name", "") or ""
231
+ if not self.hap_name:
232
+ self.add(FAIL, "GN004", "BUILD.gn 缺少 hap_name")
233
+ else:
234
+ if self.repo_kind == "hits" and not self.hap_name.startswith("Hits"):
235
+ self.add(FAIL, "GN005", "HITS 工程 hap_name 必须以 Hits 开头: %s" % self.hap_name, self.build_gn)
236
+ elif self.repo_kind == "acts" and not self.hap_name.startswith("Acts"):
237
+ self.add(FAIL, "GN005", "acts 工程 hap_name 必须以 Acts 开头(门禁 R014): %s" % self.hap_name, self.build_gn)
238
+ elif self.repo_kind == "unknown" and not (
239
+ self.hap_name.startswith("Acts") or self.hap_name.startswith("Hits")
240
+ ):
241
+ self.add(FAIL, "GN005", "hap_name 必须按仓使用 Acts/Hits 前缀: %s" % self.hap_name, self.build_gn)
242
+ if not self.part_name:
243
+ self.add(FAIL, "GN006", "BUILD.gn 缺少 part_name")
244
+ if not self.subsystem_name:
245
+ self.add(FAIL, "GN007", "BUILD.gn 缺少 subsystem_name")
246
+ has_test_hap = bool(re.search(r"^\s*test_hap\s*=\s*true", uncommented, re.M))
247
+ if self.syntax == "dyn" and not has_test_hap:
248
+ self.add(FAIL, "GN008", "动态套件必须 test_hap = true", self.build_gn)
249
+ if self.syntax == "sta" and has_test_hap:
250
+ self.add(FAIL, "GN009", "静态套件不能使用 test_hap = true(静态没有 ohosTest)", self.build_gn)
251
+ cert = get_assigned(uncommented, "certificate_profile", "")
252
+ if cert:
253
+ if not exact_exists(self.project, cert.lstrip("./")):
254
+ self.add(FAIL, "GN010", "certificate_profile 文件不存在: %s" % cert, self.build_gn)
255
+ else:
256
+ self.add(WARN, "GN011", "BUILD.gn 未设置 certificate_profile(系统 API 需要系统签名)", self.build_gn)
257
+ self.check_parent_registration()
258
+
259
+ def check_parent_registration(self):
260
+ parent = os.path.dirname(self.project)
261
+ parent_gn = os.path.join(parent, "BUILD.gn")
262
+ if not os.path.isfile(parent_gn):
263
+ self.add(WARN, "REG001", "父目录没有 BUILD.gn,无法确认 group 注册: %s" % parent)
264
+ return
265
+ if not self.target:
266
+ return
267
+ text = read_text(parent_gn)
268
+ if self.target not in text:
269
+ self.add(
270
+ FAIL,
271
+ "REG002",
272
+ "父 BUILD.gn 未注册 target '%s'(门禁不会编译该 suite)" % self.target,
273
+ parent_gn,
274
+ )
275
+
276
+ # ---------- configs ----------
277
+ def check_build_profile(self):
278
+ text = read_text(self.build_profile)
279
+ if not text:
280
+ self.add(FAIL, "CFG001", "build-profile.json5 不存在")
281
+ return
282
+ compile_v, compile_q = get_raw_value(text, "compileSdkVersion")
283
+ compat_v, compat_q = get_raw_value(text, "compatibleSdkVersion")
284
+ major = api_major(compile_v)
285
+ if major is not None and major >= 26:
286
+ if not compile_q:
287
+ self.add(FAIL, "CFG002", "API >= 26 时 compileSdkVersion 必须是字符串(如 \"26.1.0\")")
288
+ if compat_v is not None and not compat_q:
289
+ self.add(FAIL, "CFG003", "API >= 26 时 compatibleSdkVersion 必须是字符串(如 \"26.0.0\")")
290
+ elif major is not None and major < 26:
291
+ if compile_q:
292
+ self.add(WARN, "CFG004", "API < 26 时 compileSdkVersion 建议用数字")
293
+ if compat_v is not None and compat_q:
294
+ self.add(WARN, "CFG005", "API < 26 时 compatibleSdkVersion 建议用数字")
295
+ runtime = get_quoted(text, "runtimeOS", "")
296
+ if runtime and runtime != "OpenHarmony":
297
+ self.add(WARN, "CFG006", "runtimeOS 不是 OpenHarmony: %s" % runtime)
298
+ if self.syntax == "sta":
299
+ ark = get_quoted(text, "arkTSVersion", "")
300
+ if ark != "1.2":
301
+ self.add(FAIL, "CFG007", "静态工程 build-profile.json5 必须 arkTSVersion: \"1.2\"")
302
+ strict = re.search(r"caseSensitiveCheck\s*:\s*(true|false)", text)
303
+ if not strict:
304
+ self.add(WARN, "CFG008", "建议开启 strictMode.caseSensitiveCheck")
305
+
306
+ def check_model_version(self):
307
+ for path in (self.hvigor_config, self.oh_package):
308
+ text = read_text(path)
309
+ mv = get_quoted(text, "modelVersion", "")
310
+ if not mv:
311
+ self.add(WARN, "CFG010", "%s 缺少 modelVersion" % self.relpath(path), path)
312
+ elif self.syntax == "dyn" and mv != "26.0.0":
313
+ self.add(
314
+ WARN,
315
+ "CFG011",
316
+ "%s modelVersion=%s;门禁 26.x 套件应为 26.0.0" % (self.relpath(path), mv),
317
+ path,
318
+ )
319
+
320
+ def check_oh_package(self):
321
+ text = read_text(self.oh_package)
322
+ if not text:
323
+ self.add(FAIL, "PKG001", "oh-package.json5 不存在")
324
+ return
325
+ hypium = "@ohos/hypium-dynamic" if self.syntax == "dyn" else "@ohos/hypium-static"
326
+ if hypium not in text:
327
+ self.add(FAIL, "PKG002", "oh-package.json5 缺少 %s 依赖" % hypium)
328
+ if "hypium_prepare" not in text or ".har" not in text:
329
+ self.add(
330
+ WARN,
331
+ "PKG003",
332
+ "%s 依赖未指向 tools/hypium_prepare/*.har;门禁使用固定 har" % hypium,
333
+ )
334
+ if re.search(r'"@ohos/hypium[^"]*"\s*:\s*"\^?[0-9]', text):
335
+ self.add(WARN, "PKG004", "hypium 依赖写了 registry 版本;门禁使用本地 har")
336
+ for m in re.finditer(r"file:([^\"']+)", text):
337
+ dep = m.group(1)
338
+ if re.search(r"\.(hsp|har)$", dep) and "hypium_prepare" not in dep:
339
+ self.add(
340
+ FAIL,
341
+ "BIN002",
342
+ "工程引用了预编译 %s;门禁要求源码模块编译,不能携带 HSP/HAR" % dep,
343
+ self.oh_package,
344
+ )
345
+
346
+ # ---------- Test.json / module.json5 ----------
347
+ def locate_files(self):
348
+ entry = os.path.join(self.project, "entry")
349
+ if self.syntax == "dyn":
350
+ self.module_json = os.path.join(entry, "src", "ohosTest", "module.json5")
351
+ self.test_json = os.path.join(self.project, "Test.json")
352
+ self.syscap_paths = [
353
+ os.path.join(entry, "src", "ohosTest", "syscap.json"),
354
+ os.path.join(entry, "src", "main", "syscap.json"),
355
+ ]
356
+ self.test_root = os.path.join(entry, "src", "ohosTest", "ets", "test")
357
+ else:
358
+ self.module_json = os.path.join(entry, "src", "main", "module.json5")
359
+ self.test_json = os.path.join(self.project, "Test.json")
360
+ self.syscap_paths = [os.path.join(entry, "src", "main", "syscap.json")]
361
+ self.test_root = os.path.join(entry, "src", "main", "src", "test")
362
+ app_json = os.path.join(self.project, "AppScope", "app.json5")
363
+ app_text = read_text(app_json)
364
+ self.bundle_name = get_quoted(app_text, "bundleName", "")
365
+ module_text = read_text(self.module_json)
366
+ m = re.search(r'"module"\s*:\s*\{', module_text)
367
+ if m:
368
+ self.module_name = get_quoted(module_text[m.start():], "name", "")
369
+ if not self.module_name:
370
+ m = re.search(r'"name"\s*:\s*"([^"]+)"', module_text)
371
+ self.module_name = m.group(1) if m else ""
372
+
373
+ def check_test_json(self):
374
+ if not os.path.isfile(self.test_json):
375
+ self.add(FAIL, "TST001", "Test.json 不存在")
376
+ return
377
+ try:
378
+ with open(self.test_json, "r", encoding="utf-8") as f:
379
+ data = json.load(f)
380
+ except ValueError as e:
381
+ self.add(FAIL, "TST002", "Test.json 不是合法 JSON: %s" % e, self.test_json)
382
+ return
383
+ driver = data.get("driver", {})
384
+ b = driver.get("bundle-name", "")
385
+ if self.bundle_name and b != self.bundle_name:
386
+ self.add(FAIL, "TST003", "Test.json bundle-name=%s,app.json5=%s" % (b, self.bundle_name), self.test_json)
387
+ m = driver.get("module-name", "")
388
+ if self.module_name and m != self.module_name:
389
+ self.add(FAIL, "TST004", "Test.json module-name=%s,module.json5=%s" % (m, self.module_name), self.test_json)
390
+ haps = []
391
+ for kit in data.get("kits", []):
392
+ haps.extend(kit.get("test-file-name", []) or [])
393
+ expected = (self.hap_name + ".hap") if self.hap_name else ""
394
+ if expected and expected not in haps:
395
+ self.add(FAIL, "TST005", "Test.json 未引用 %s(当前: %s)" % (expected, haps), self.test_json)
396
+
397
+ def check_module_json(self):
398
+ if not os.path.isfile(self.module_json):
399
+ self.add(FAIL, "MOD001", "module.json5 不存在: %s" % self.relpath(self.module_json))
400
+ return
401
+ text = read_text(self.module_json)
402
+ ext = re.search(r'"extensionAbilities"\s*:\s*\[', text)
403
+ if ext:
404
+ end = text.find("]", ext.end())
405
+ block = text[ext.end(): end if end > 0 else len(text)]
406
+ if re.search(r'"process"\s*:', block):
407
+ line = text[: ext.start()].count("\n") + 1
408
+ self.add(
409
+ FAIL,
410
+ "MOD002",
411
+ "extensionAbilities 不允许 process;改用 extensionProcessMode(bundle|type|instance)",
412
+ self.module_json,
413
+ line,
414
+ )
415
+ for mode in re.findall(r'"extensionProcessMode"\s*:\s*"([^"]+)"', block):
416
+ if mode not in ("bundle", "type", "instance"):
417
+ self.add(WARN, "MOD003", "未知 extensionProcessMode: %s" % mode, self.module_json)
418
+ for entry in re.findall(r'"srcEntry"\s*:\s*"([^"]+)"', text):
419
+ if entry.startswith("$"):
420
+ continue
421
+ if not exact_exists(os.path.dirname(self.module_json), entry.lstrip("./")):
422
+ self.add(FAIL, "MOD004", "srcEntry 文件不存在(注意大小写): %s" % entry, self.module_json)
423
+
424
+ def check_syscap(self):
425
+ checked = 0
426
+ for path in self.syscap_paths:
427
+ if not os.path.isfile(path):
428
+ continue
429
+ checked += 1
430
+ data = load_json5(path)
431
+ if data is None:
432
+ self.add(WARN, "SYS001", "syscap.json 解析失败: %s" % self.relpath(path), path)
433
+ continue
434
+ caps = []
435
+ try:
436
+ for dev in data.get("devices", {}).get("custom", []):
437
+ caps.extend(dev.get("xts", []) or [])
438
+ except AttributeError:
439
+ pass
440
+ if not caps:
441
+ self.add(FAIL, "SYS002", "syscap.json 的 custom[].xts 为空: %s" % self.relpath(path), path)
442
+ if checked == 0:
443
+ self.add(WARN, "SYS003", "未找到 syscap.json(动态检查 ohosTest/main,静态检查 main)")
444
+
445
+ # ---------- code ----------
446
+ def iter_sources(self):
447
+ root = os.path.join(self.project, "entry", "src")
448
+ for dp, dn, fn in os.walk(root):
449
+ dn[:] = [d for d in dn if d not in ("oh_modules", "build", ".hvigor")]
450
+ for f in fn:
451
+ if f.endswith((".ets", ".ts")):
452
+ yield os.path.join(dp, f)
453
+
454
+ def check_code(self):
455
+ tc_numbers = {}
456
+ for path in self.iter_sources():
457
+ text = read_text(path)
458
+ lines = text.splitlines()
459
+ rel = self.relpath(path)
460
+ for i, line in enumerate(lines, 1):
461
+ if "globalThis" in line:
462
+ self.add(FAIL, "COD001", "ArkTS 禁止 globalThis", rel, i)
463
+ if re.search(r"rpc\.MessageSequence", line) and self.syntax == "dyn" and "onRemoteRequest" in text:
464
+ self.add(FAIL, "COD002", "动态 onRemoteRequest 必须用 rpc.MessageParcel", rel, i)
465
+ if re.search(r"rpc\.MessageParcel", line) and self.syntax == "sta" and "onRemoteRequest" in text:
466
+ self.add(FAIL, "COD003", "静态 onRemoteRequest 必须用 rpc.MessageSequence", rel, i)
467
+ if ".parameters[" in line and "parameters" not in line.split(".parameters[")[0]:
468
+ # AbilityDelegatorRegistry.getArguments().parameters 在 SDK 中非可选,跳过
469
+ if "getArguments().parameters" in line or "abilityDelegatorArguments.parameters" in line:
470
+ continue
471
+ window = "\n".join(lines[max(0, i - 16): i])
472
+ if "parameters === undefined" not in window and "params === undefined" not in window:
473
+ self.add(WARN, "COD004", "parameters 可能为 undefined;先判空再取", rel, i)
474
+ if "console.log" in line:
475
+ self.add(WARN, "COD006", "测试代码不建议使用 console.log(用 hilog)", rel, i)
476
+ if re.search(r"[\"'](C:|D:|/data/)[^\"']*[\"']", line):
477
+ self.add(WARN, "COD007", "疑似硬编码设备/宿主路径", rel, i)
478
+ for m in re.finditer(r"@tc\.number\s+(\S+)", line):
479
+ tc_numbers.setdefault(m.group(1), []).append("%s:%s" % (rel, i))
480
+ for m in re.finditer(r"\bit\(\s*[\"']([^\"']+)[\"']", line):
481
+ if not m.group(1).startswith("SUB_"):
482
+ self.add(WARN, "COD008", "it() 名称建议以 SUB_ 开头: %s" % m.group(1), rel, i)
483
+ if "Apache License" not in "\n".join(lines[:30]):
484
+ self.add(WARN, "COD009", "文件缺少 Apache 2.0 License 头", rel)
485
+ self.check_imports(path, text)
486
+ for num, locs in tc_numbers.items():
487
+ if len(locs) > 1:
488
+ self.add(FAIL, "COD010", "@tc.number 重复: %s -> %s" % (num, ", ".join(locs)))
489
+
490
+ def check_imports(self, path, text):
491
+ base = os.path.dirname(path)
492
+ rel = self.relpath(path)
493
+ for line_no, line in enumerate(text.splitlines(), 1):
494
+ for m in re.finditer(r"(?:from\s+|import\s*)['\"](\.[^'\"]+)['\"]", line):
495
+ imp = m.group(1)
496
+ if find_exact(base, imp) is None:
497
+ self.add(
498
+ FAIL,
499
+ "IMP001",
500
+ "相对 import 不存在或大小写不匹配: %s(门禁 Linux 大小写敏感)" % imp,
501
+ rel,
502
+ line_no,
503
+ )
504
+
505
+ # ---------- binaries ----------
506
+ def check_binaries(self):
507
+ binary_exts = {
508
+ ".hsp", ".hap", ".har", ".so", ".a", ".abc",
509
+ ".jar", ".bin", ".exe", ".dll", ".dylib",
510
+ }
511
+ skip_dirs = {"oh_modules", "build", ".hvigor", ".git", "out", ".idea"}
512
+ for dp, dn, fn in os.walk(self.project):
513
+ dn[:] = [d for d in dn if d not in skip_dirs]
514
+ for f in fn:
515
+ ext = os.path.splitext(f)[1].lower()
516
+ if ext in binary_exts:
517
+ self.add(
518
+ FAIL,
519
+ "BIN001",
520
+ "工程携带预编译二进制/包 %s;所有模块必须在门禁中从源码编译" % f,
521
+ os.path.join(dp, f),
522
+ )
523
+
524
+ # ---------- hygiene ----------
525
+ def check_hygiene(self):
526
+ for name in ("oh_modules", "build", ".hvigor", "oh-package-lock.json5", "local.properties", "out"):
527
+ p = os.path.join(self.project, name)
528
+ if os.path.exists(p):
529
+ self.add(WARN, "HYG001", "存在构建残留 %s;提交前删除并加入 .gitignore" % name)
530
+ gitignore = read_text(os.path.join(self.project, ".gitignore"))
531
+ for name in ("oh_modules", "build", ".hvigor", "local.properties"):
532
+ if name not in gitignore:
533
+ self.add(WARN, "HYG002", ".gitignore 未包含 %s" % name)
534
+
535
+ # ---------- run ----------
536
+ def run(self):
537
+ if not os.path.isdir(self.project):
538
+ print("ERROR: project dir not found: %s" % self.project)
539
+ return 2
540
+ self.detect_repo_kind()
541
+ self.detect_syntax()
542
+ self.locate_files()
543
+ self.check_build_gn()
544
+ self.check_build_profile()
545
+ self.check_model_version()
546
+ self.check_oh_package()
547
+ self.check_test_json()
548
+ self.check_module_json()
549
+ self.check_syscap()
550
+ self.check_code()
551
+ self.check_binaries()
552
+ self.check_hygiene()
553
+ return 0
554
+
555
+ def report(self, as_json=False):
556
+ level_order = {FAIL: 0, WARN: 1, INFO: 2}
557
+ self.findings.sort(key=lambda f: (level_order.get(f.level, 9), f.code, f.file, f.line))
558
+ counts = {FAIL: 0, WARN: 0, INFO: 0}
559
+ for f in self.findings:
560
+ counts[f.level] = counts.get(f.level, 0) + 1
561
+ if as_json:
562
+ print(json.dumps({
563
+ "project": self.project,
564
+ "syntax": self.syntax,
565
+ "repo_kind": self.repo_kind,
566
+ "target": self.target,
567
+ "hap_name": self.hap_name,
568
+ "counts": counts,
569
+ "findings": [f.__dict__ for f in self.findings],
570
+ }, ensure_ascii=False, indent=2))
571
+ else:
572
+ print("XTS project: %s" % self.project)
573
+ print("syntax: %s repo: %s target: %s hap_name: %s" % (self.syntax, self.repo_kind, self.target, self.hap_name))
574
+ for f in self.findings:
575
+ print(f)
576
+ print("\nSummary: FAIL=%d WARN=%d INFO=%d" % (counts[FAIL], counts[WARN], counts[INFO]))
577
+ if counts[FAIL]:
578
+ return 1
579
+ if self.strict and counts[WARN]:
580
+ return 1
581
+ return 0
582
+
583
+
584
+ def main():
585
+ parser = argparse.ArgumentParser(description="XTS 工程门禁前检查器")
586
+ parser.add_argument("project", help="suite 根目录(含 BUILD.gn)")
587
+ parser.add_argument("--syntax", choices=["auto", "dyn", "sta"], default="auto")
588
+ parser.add_argument("--strict", action="store_true", help="WARN 也返回非 0")
589
+ parser.add_argument("--json", action="store_true", help="JSON 输出")
590
+ args = parser.parse_args()
591
+ checker = Checker(args.project, args.syntax, args.strict)
592
+ rc = checker.run()
593
+ if rc:
594
+ return rc
595
+ return checker.report(args.json)
596
+
597
+
598
+ if __name__ == "__main__":
599
+ sys.exit(main())
@@ -0,0 +1,79 @@
1
+ # Windows 侧调用 WSL 的 XTS 门禁编译包装。
2
+ #
3
+ # 该脚本不运行 Windows 原生 hvigor;它把参数传给 WSL 内的 run-gate-build.sh,
4
+ # 保证编译发生在 Linux 工具链上。
5
+ #
6
+ # 用法示例:
7
+ # .\run-gate-build.ps1 -Distro Ubuntu `
8
+ # -Project /root/ohos-gate/ws/test/xts/acts/.../ActsXxx `
9
+ # -Mode dyn `
10
+ # -NodeHome /root/ohos-gate/toolchain/node-v18.20.1-linux-x64 `
11
+ # -SdkRoot /root/ohos-gate/sdk `
12
+ # -HvigorHome /root/ohos-gate/toolchain/clt-26.0.1.290/hvigor `
13
+ # -JavaHome /usr/lib/jvm/java-17-openjdk-amd64
14
+ #
15
+ # 若 run-gate-build.sh 在 Windows 目录,脚本会自动转成 /mnt/<drive>/... 路径。
16
+
17
+ param(
18
+ [string]$Distro = "Ubuntu",
19
+ [Parameter(Mandatory = $true)][string]$Project,
20
+ [ValidateSet("dyn", "sta")][string]$Mode = "dyn",
21
+ [Parameter(Mandatory = $true)][string]$NodeHome,
22
+ [Parameter(Mandatory = $true)][string]$SdkRoot,
23
+ [Parameter(Mandatory = $true)][string]$HvigorHome,
24
+ [string]$JavaHome = "",
25
+ [string]$Ohpm = "",
26
+ [string]$ScriptPath = "",
27
+ [switch]$SkipInstall
28
+ )
29
+
30
+ $ErrorActionPreference = "Stop"
31
+
32
+ function To-WslPath([string]$Path) {
33
+ if ($Path -match '^([A-Za-z]):[\\/]*(.*)$') {
34
+ $drive = $Matches[1].ToLower()
35
+ $rest = $Matches[2] -replace '\\', '/'
36
+ return "/mnt/$drive/$rest"
37
+ }
38
+ return $Path
39
+ }
40
+
41
+ function Quote-Bash([string]$Value) {
42
+ # 单引号包裹,内部单引号用 '\'' 转义
43
+ return "'" + ($Value -replace "'", "'\''") + "'"
44
+ }
45
+
46
+ if ([string]::IsNullOrWhiteSpace($ScriptPath)) {
47
+ $ScriptPath = Join-Path $PSScriptRoot "run-gate-build.sh"
48
+ }
49
+ $ScriptInWsl = To-WslPath $ScriptPath
50
+
51
+ $cmdParts = @(
52
+ "bash", (Quote-Bash $ScriptInWsl),
53
+ "--project", (Quote-Bash $Project),
54
+ "--mode", (Quote-Bash $Mode),
55
+ "--node-home", (Quote-Bash $NodeHome),
56
+ "--sdk", (Quote-Bash $SdkRoot),
57
+ "--hvigor-home", (Quote-Bash $HvigorHome)
58
+ )
59
+ if (-not [string]::IsNullOrWhiteSpace($JavaHome)) {
60
+ $cmdParts += @("--java-home", (Quote-Bash $JavaHome))
61
+ }
62
+ if (-not [string]::IsNullOrWhiteSpace($Ohpm)) {
63
+ $cmdParts += @("--ohpm", (Quote-Bash $Ohpm))
64
+ }
65
+ if ($SkipInstall) {
66
+ $cmdParts += "--skip-install"
67
+ }
68
+
69
+ $bashCmd = $cmdParts -join " "
70
+ Write-Host ">>> wsl -d $Distro -- bash -lc $bashCmd" -ForegroundColor Cyan
71
+
72
+ # PowerShell 5.1 会把原生命令的 stderr 包成 ErrorRecord;$ErrorActionPreference=Stop
73
+ # 会让脚本在 hvigor 的 WARN 输出时误退出。调用 wsl 期间改为 Continue,按退出码判断。
74
+ $oldEap = $ErrorActionPreference
75
+ $ErrorActionPreference = "Continue"
76
+ & wsl -d $Distro -- bash -lc $bashCmd
77
+ $rc = $LASTEXITCODE
78
+ $ErrorActionPreference = $oldEap
79
+ exit $rc