@sokeai/cli 1.0.116 → 1.0.118
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.
- package/README.md +2 -0
- package/docs/harmonyos.md +67 -0
- package/package.json +4 -1
- package/scripts/install.js +7 -21
- package/scripts/runtime-platform.js +32 -0
- package/skills/multi/demo-init/CHANGELOG.md +1241 -0
- package/skills/multi/demo-init/README.md +137 -0
- package/skills/multi/demo-init/SKILL.legacy.md +307 -0
- package/skills/multi/demo-init/assets/placeholder.pptx +0 -0
- package/skills/multi/demo-init/references/anti-patterns.md +83 -0
- package/skills/multi/demo-init/references/asset-design.md +230 -0
- package/skills/multi/demo-init/references/asset-spec.md +94 -0
- package/skills/multi/demo-init/references/blueprint-schema.md +174 -0
- package/skills/multi/demo-init/references/cli-onboarding.md +207 -0
- package/skills/multi/demo-init/references/cli-shared.md +183 -0
- package/skills/multi/demo-init/references/contracts.md +34 -0
- package/skills/multi/demo-init/references/course-setup.md +265 -0
- package/skills/multi/demo-init/references/demo-defaults.md +132 -0
- package/skills/multi/demo-init/references/demo-verify.md +355 -0
- package/skills/multi/demo-init/references/exam-setup.md +245 -0
- package/skills/multi/demo-init/references/gates-matrix.md +38 -0
- package/skills/multi/demo-init/references/map-setup.md +283 -0
- package/skills/multi/demo-init/references/plan-parse.md +185 -0
- package/skills/multi/demo-init/references/platform-access.md +55 -0
- package/skills/multi/demo-init/references/platform-commands.md +510 -0
- package/skills/multi/demo-init/references/point-setup.md +308 -0
- package/skills/multi/demo-init/references/portal-modules.md +130 -0
- package/skills/multi/demo-init/references/portal-setup.md +342 -0
- package/skills/multi/demo-init/references/project-setup.md +173 -0
- package/skills/multi/demo-init/references/run-protocol.md +208 -0
- package/skills/multi/demo-init/references/taxonomy-setup.md +101 -0
- package/skills/multi/demo-init/scripts/assign_backfill.py +281 -0
- package/skills/multi/demo-init/scripts/blueprint_lint.py +693 -0
- package/skills/multi/demo-init/scripts/blueprint_write.py +390 -0
- package/skills/multi/demo-init/scripts/category_bind.py +303 -0
- package/skills/multi/demo-init/scripts/category_create.py +748 -0
- package/skills/multi/demo-init/scripts/category_reassign.py +405 -0
- package/skills/multi/demo-init/scripts/category_verify.py +373 -0
- package/skills/multi/demo-init/scripts/cli_kit.py +597 -0
- package/skills/multi/demo-init/scripts/cli_probe.py +205 -0
- package/skills/multi/demo-init/scripts/course_build.py +857 -0
- package/skills/multi/demo-init/scripts/course_cover_repair.py +243 -0
- package/skills/multi/demo-init/scripts/doc_lint.py +619 -0
- package/skills/multi/demo-init/scripts/dup_cleanup.py +299 -0
- package/skills/multi/demo-init/scripts/dup_scan.py +368 -0
- package/skills/multi/demo-init/scripts/exam_build.py +551 -0
- package/skills/multi/demo-init/scripts/extract_docx.py +370 -0
- package/skills/multi/demo-init/scripts/gen_assets.py +1366 -0
- package/skills/multi/demo-init/scripts/guard.py +1272 -0
- package/skills/multi/demo-init/scripts/map_rebuild.py +391 -0
- package/skills/multi/demo-init/scripts/oss_image_upload.py +367 -0
- package/skills/multi/demo-init/scripts/portal_build.py +450 -0
- package/skills/multi/demo-init/scripts/portal_home_apply.py +255 -0
- package/skills/multi/demo-init/scripts/portal_home_layout.py +398 -0
- package/skills/multi/demo-init/scripts/project_build.py +309 -0
- package/skills/multi/demo-init/scripts/rebuild_taxonomy_map.py +100 -0
- package/skills/multi/demo-init/scripts/scope_plan.py +387 -0
- package/skills/multi/demo-init/scripts/selftest_all.py +211 -0
- package/skills/multi/demo-init/scripts/stock_probe.py +452 -0
- package/skills/multi/demo-init/scripts/taxonomy_build.py +512 -0
- package/skills/multi/demo-init-4.1.0.zip +0 -0
- package/skills/multi/demo-init-4.1.1.zip +0 -0
- package/skills/multi/demo-init-4.1.2.zip +0 -0
- package/skills/multi/demo-init-4.1.3.zip +0 -0
- package/skills/multi/ziQIJJpL +0 -0
- package/skills/multi/ziRsINis +0 -0
- package/skills/multi/ziUjKWRm +0 -0
- package/skills/multi/zipFWfuj +0 -0
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""cli_kit.py — 新增构建脚本(portal_build / exam_build / project_build)的共享底座
|
|
4
|
+
|
|
5
|
+
为什么单独一份:v4.0.0 起把三个"历史翻倍事故模块"脚本化,三份脚本的
|
|
6
|
+
CLI 调用、JSON 解析、幂等探测、日志落盘完全同构。抄三遍会出现"改一处漏两处",
|
|
7
|
+
所以抽成显式共享模块(不是隐藏依赖:`scripts/` 在 sys.path 里,import 即可)。
|
|
8
|
+
|
|
9
|
+
设计边界(与既有脚本一致):
|
|
10
|
+
· 只封装「怎么调 CLI / 怎么读返回 / 怎么写日志」,不含任何业务判断
|
|
11
|
+
· 默认 dry-run:构造好 argv 只打印不执行;`--apply` 才真发请求
|
|
12
|
+
· 成功判定不看 stderr 是否为空(CLI 的「发现新版本」banner 走 stderr)
|
|
13
|
+
· 截断 120 字符(与 references/run-protocol.md 口径一致)
|
|
14
|
+
|
|
15
|
+
用法(业务脚本):
|
|
16
|
+
from cli_kit import Cli, Report, jload, pick_uuid, rows_of, resp_ok
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import subprocess
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
import uuid as uuidlib
|
|
27
|
+
from datetime import datetime
|
|
28
|
+
|
|
29
|
+
TIMEOUT_MARKS = ("timeout", "timed out", "CURL error [28]")
|
|
30
|
+
DUP_MARKS = ("11004", "已存在", "已存在该", "already exist", "重复")
|
|
31
|
+
PERM_MARKS = ("12000", "无操作权限", "无权访问", "无权限")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ------------------------------------------------------------------ 纯函数
|
|
35
|
+
|
|
36
|
+
def jload(s):
|
|
37
|
+
"""从带 banner 的 stdout 里取第一个 JSON 对象(⛔ 禁止贪婪正则 `\\{.*\\}`)。"""
|
|
38
|
+
if not s:
|
|
39
|
+
return None
|
|
40
|
+
i = s.find("{")
|
|
41
|
+
if i < 0:
|
|
42
|
+
return None
|
|
43
|
+
try:
|
|
44
|
+
return json.JSONDecoder().raw_decode(s, i)[0]
|
|
45
|
+
except Exception:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def rows_of(data, _depth=0):
|
|
50
|
+
"""兼容 data / data.rows / data.list / data.list.all / data.list.rows 等任意嵌套形态。
|
|
51
|
+
|
|
52
|
+
平台列表返回信封在不同模块不一致(有的 data.rows,有的 data.list.all),
|
|
53
|
+
固定层级判断必然漏一种 → 改成有界递归,取第一个「元素是 dict 的数组」。
|
|
54
|
+
"""
|
|
55
|
+
if isinstance(data, list):
|
|
56
|
+
return [r for r in data if isinstance(r, dict)]
|
|
57
|
+
if not isinstance(data, dict) or _depth > 3:
|
|
58
|
+
return []
|
|
59
|
+
for k in ("rows", "list", "all", "items", "records", "data", "result"):
|
|
60
|
+
if k in data:
|
|
61
|
+
got = rows_of(data[k], _depth + 1)
|
|
62
|
+
if got:
|
|
63
|
+
return got
|
|
64
|
+
return []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def pick_uuid(obj):
|
|
68
|
+
"""create 返回结构不统一:data.uuid / data.info.uuid / data.paperInfo.uuid / data.id。"""
|
|
69
|
+
if not isinstance(obj, dict):
|
|
70
|
+
return None
|
|
71
|
+
d = obj.get("data")
|
|
72
|
+
for holder in (d, obj):
|
|
73
|
+
if isinstance(holder, dict):
|
|
74
|
+
info = holder.get("info")
|
|
75
|
+
cands = [holder.get("uuid")]
|
|
76
|
+
if isinstance(info, dict):
|
|
77
|
+
cands += [info.get("uuid"), info.get("id")]
|
|
78
|
+
for sub in ("paperInfo", "examInfo", "portalInfo"):
|
|
79
|
+
if isinstance(holder.get(sub), dict):
|
|
80
|
+
cands.append(holder[sub].get("uuid"))
|
|
81
|
+
cands.append(holder.get("id"))
|
|
82
|
+
for cand in cands:
|
|
83
|
+
if isinstance(cand, str) and cand.strip() and cand.strip() != "empty":
|
|
84
|
+
return cand.strip()
|
|
85
|
+
if isinstance(d, str) and d.strip() and d.strip() != "empty":
|
|
86
|
+
return d.strip()
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def pick_title(row):
|
|
91
|
+
return (row.get("title") or row.get("name") or row.get("className")
|
|
92
|
+
or row.get("examName") or row.get("poolName")) if isinstance(row, dict) else None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def hit(pair, marks):
|
|
96
|
+
blob = (pair[0] or "") + (pair[1] or "")
|
|
97
|
+
return any(m in blob for m in marks)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def resp_ok(out):
|
|
101
|
+
"""成功判定:JSON 信封 code∈2xx,或 data 为 >=1 的数字,或 data 为真值对象。"""
|
|
102
|
+
obj = jload(out)
|
|
103
|
+
if obj is None:
|
|
104
|
+
return False
|
|
105
|
+
code = str(obj.get("code") or "")
|
|
106
|
+
if str(obj.get("status", "")).lower() in ("error", "failed", "fail"):
|
|
107
|
+
return False
|
|
108
|
+
if code and code not in ("200", "201", "202", "204"):
|
|
109
|
+
return False
|
|
110
|
+
if code in ("200", "201", "202", "204"):
|
|
111
|
+
return True
|
|
112
|
+
data = obj.get("data")
|
|
113
|
+
if isinstance(data, int) and data >= 1:
|
|
114
|
+
return True
|
|
115
|
+
if isinstance(data, dict) and data:
|
|
116
|
+
return True
|
|
117
|
+
if isinstance(data, str) and data.strip().lower() in ("true", "success", "ok", "delete success"):
|
|
118
|
+
return True
|
|
119
|
+
return False
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def short(s, n=120):
|
|
123
|
+
s = (s or "").replace("\n", " ").replace("\r", " ").strip()
|
|
124
|
+
return s if len(s) <= n else s[:n] + "…"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def now():
|
|
128
|
+
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def norm_status(obj):
|
|
132
|
+
"""从详情信封里取 status(草稿 0 / 已发布 1),取不到返回 None。"""
|
|
133
|
+
if not isinstance(obj, dict):
|
|
134
|
+
return None
|
|
135
|
+
for holder in (obj.get("data"), obj):
|
|
136
|
+
if isinstance(holder, dict):
|
|
137
|
+
info = holder.get("info")
|
|
138
|
+
for src in (holder, info):
|
|
139
|
+
if isinstance(src, dict) and "status" in src:
|
|
140
|
+
try:
|
|
141
|
+
return int(src["status"])
|
|
142
|
+
except (TypeError, ValueError):
|
|
143
|
+
return None
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# ------------------------------------------------------------------ CLI 封装
|
|
148
|
+
|
|
149
|
+
def _default_runner(argv, timeout=90):
|
|
150
|
+
p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
|
|
151
|
+
return p.returncode, p.stdout or "", p.stderr or ""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
_RUNNER = _default_runner
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class Cli:
|
|
158
|
+
"""统一 CLI 调用器。dry=True 时只打印 argv,不发请求。"""
|
|
159
|
+
|
|
160
|
+
def __init__(self, exe, log_path=None, dry=True, echo=True):
|
|
161
|
+
self.exe = exe
|
|
162
|
+
self.log_path = log_path
|
|
163
|
+
self.dry = dry
|
|
164
|
+
self.echo = echo
|
|
165
|
+
self.calls = 0
|
|
166
|
+
self.writes = 0
|
|
167
|
+
|
|
168
|
+
# -- 日志 ------------------------------------------------------
|
|
169
|
+
def log(self, module, msg):
|
|
170
|
+
line = "[%s] [%s] %s" % (now(), module, short(msg, 120))
|
|
171
|
+
if self.echo:
|
|
172
|
+
print(line)
|
|
173
|
+
if self.log_path:
|
|
174
|
+
with open(self.log_path, "a", encoding="utf-8") as fh:
|
|
175
|
+
fh.write(line + "\n")
|
|
176
|
+
|
|
177
|
+
# -- 调用 ------------------------------------------------------
|
|
178
|
+
def run(self, args, timeout=90, retries=0, sleep=3.0):
|
|
179
|
+
args = list(args)
|
|
180
|
+
# 创建不是幂等请求;即使调用方误传 retries,也不得因超时重复发送。
|
|
181
|
+
if any(arg in ("+create", "+lesson-create", "+banner-add") for arg in args):
|
|
182
|
+
retries = 0
|
|
183
|
+
argv = [self.exe] + args
|
|
184
|
+
if self.dry:
|
|
185
|
+
if self.echo:
|
|
186
|
+
print(" DRY " + " ".join(argv[1:]))
|
|
187
|
+
return 0, "", "dry-run"
|
|
188
|
+
last = (0, "", "")
|
|
189
|
+
for i in range(retries + 1):
|
|
190
|
+
self.calls += 1
|
|
191
|
+
try:
|
|
192
|
+
rc, out, err = _RUNNER(argv, timeout)
|
|
193
|
+
except subprocess.TimeoutExpired:
|
|
194
|
+
rc, out, err = 124, "", "timeout after %ss" % timeout
|
|
195
|
+
last = (rc, out, err)
|
|
196
|
+
if not (rc != 0 and hit((out, err), TIMEOUT_MARKS)):
|
|
197
|
+
return last
|
|
198
|
+
if i < retries:
|
|
199
|
+
time.sleep(sleep * (i + 1))
|
|
200
|
+
return last
|
|
201
|
+
|
|
202
|
+
def call(self, args, timeout=90, retries=0):
|
|
203
|
+
"""返回 (ok, obj, out, err)。ok 按信封判定,不看 rc(CLI 出错常返回 0)。"""
|
|
204
|
+
try:
|
|
205
|
+
rc, out, err = self.run(args, timeout=timeout, retries=retries)
|
|
206
|
+
except OSError as exc:
|
|
207
|
+
return False, {}, "", str(exc)
|
|
208
|
+
if self.dry:
|
|
209
|
+
return True, {}, out, err
|
|
210
|
+
ok = resp_ok(out) and not hit((out, err), PERM_MARKS)
|
|
211
|
+
return ok, (jload(out) or {}), out, err
|
|
212
|
+
|
|
213
|
+
def read(self, args, timeout=90):
|
|
214
|
+
"""只读命令:返回 (ok, obj)。读命令不参与写节流。"""
|
|
215
|
+
rc, out, err = self.run(args, timeout=timeout)
|
|
216
|
+
if self.dry:
|
|
217
|
+
return True, {}
|
|
218
|
+
return resp_ok(out), (jload(out) or {"_read_error": short(out or err, 400)})
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# ------------------------------------------------------------------ 创建尝试与保守恢复
|
|
222
|
+
|
|
223
|
+
class CreateJournal:
|
|
224
|
+
"""创建前落盘;恢复只信本次返回 UUID,名称只能辅助诊断。需由模块锁串行调用。"""
|
|
225
|
+
|
|
226
|
+
def __init__(self, path, module):
|
|
227
|
+
self.path = path
|
|
228
|
+
self.module = module
|
|
229
|
+
if os.path.exists(path):
|
|
230
|
+
with open(path, encoding="utf-8") as fh:
|
|
231
|
+
self.data = json.load(fh)
|
|
232
|
+
if self.data.get("module") != module or not isinstance(self.data.get("objects"), dict):
|
|
233
|
+
raise ValueError("创建记录不完整或模块不符,停止写入:%s" % path)
|
|
234
|
+
else:
|
|
235
|
+
self.data = {"module": module, "objects": {}}
|
|
236
|
+
|
|
237
|
+
def get(self, key):
|
|
238
|
+
return self.data["objects"].get(key)
|
|
239
|
+
|
|
240
|
+
def _save(self):
|
|
241
|
+
parent = os.path.dirname(os.path.abspath(self.path))
|
|
242
|
+
os.makedirs(parent, exist_ok=True)
|
|
243
|
+
tmp = self.path + ".tmp"
|
|
244
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
245
|
+
json.dump(self.data, fh, ensure_ascii=False, indent=2)
|
|
246
|
+
fh.flush()
|
|
247
|
+
os.fsync(fh.fileno())
|
|
248
|
+
os.replace(tmp, self.path)
|
|
249
|
+
|
|
250
|
+
def begin(self, key, name):
|
|
251
|
+
prev = self.get(key)
|
|
252
|
+
if prev and prev.get("state") != "deleted":
|
|
253
|
+
raise RuntimeError("已有创建尝试,须先恢复,不得直接再次 create")
|
|
254
|
+
count = (prev or {}).get("attempt_count", 0) + 1
|
|
255
|
+
if count > 2:
|
|
256
|
+
raise RuntimeError("本对象已用完一次重建机会")
|
|
257
|
+
row = {"attempt_id": uuidlib.uuid4().hex, "name": name,
|
|
258
|
+
"attempt_count": count, "state": "requested", "uuid": None,
|
|
259
|
+
"owned": False, "started_at": now(), "previous": prev}
|
|
260
|
+
self.data["objects"][key] = row
|
|
261
|
+
self._save()
|
|
262
|
+
return row
|
|
263
|
+
|
|
264
|
+
def returned(self, key, ok, obj, detail="", created_evidence=False):
|
|
265
|
+
row = self.get(key)
|
|
266
|
+
uid = pick_uuid(obj)
|
|
267
|
+
row.update(uuid=uid, owned=bool(uid and (ok or created_evidence)),
|
|
268
|
+
state="created" if ok and uid else "create_failed",
|
|
269
|
+
response=obj, detail=short(detail, 300), returned_at=now())
|
|
270
|
+
self._save()
|
|
271
|
+
return uid
|
|
272
|
+
|
|
273
|
+
def failure(self, key, detail):
|
|
274
|
+
row = self.get(key)
|
|
275
|
+
if row:
|
|
276
|
+
# 创建已成功时只记配置失败;禁止把成功对象降级为可删除残留。
|
|
277
|
+
row.update(detail=short(detail, 300), failed_at=now())
|
|
278
|
+
self._save()
|
|
279
|
+
|
|
280
|
+
def step(self, key, step, state=None):
|
|
281
|
+
row = self.get(key)
|
|
282
|
+
steps = row.setdefault("steps", {})
|
|
283
|
+
if state is not None:
|
|
284
|
+
steps[step] = state
|
|
285
|
+
self._save()
|
|
286
|
+
return steps.get(step)
|
|
287
|
+
|
|
288
|
+
def complete(self, key):
|
|
289
|
+
row = self.get(key)
|
|
290
|
+
if row:
|
|
291
|
+
row.update(state="complete", completed_at=now())
|
|
292
|
+
self._save()
|
|
293
|
+
|
|
294
|
+
def prepare(self, key, inspect, discover=None, delete=None):
|
|
295
|
+
"""返回 (create|repair|done|pending, uuid, 原因)。适配器异常一律停止。
|
|
296
|
+
|
|
297
|
+
inspect(uuid) 必须明确返回 state=exists/missing/unknown;只有业务回读
|
|
298
|
+
明证未发布才置 unpublished=True。delete 是已验证的真实删除通道。
|
|
299
|
+
"""
|
|
300
|
+
row = self.get(key)
|
|
301
|
+
if not row:
|
|
302
|
+
return "create", None, "首次直接创建,不做同名查询"
|
|
303
|
+
uid = row.get("uuid")
|
|
304
|
+
if row.get("state") == "deleted":
|
|
305
|
+
if row.get("attempt_count", 0) >= 2:
|
|
306
|
+
return "pending", uid, "已用完一次重建机会"
|
|
307
|
+
return "create", None, "失败残留已删除并回读确认,允许重建一次"
|
|
308
|
+
if not uid:
|
|
309
|
+
if discover:
|
|
310
|
+
try:
|
|
311
|
+
row["name_diagnostics"] = discover(row["name"])
|
|
312
|
+
except Exception as exc:
|
|
313
|
+
row["name_diagnostics_error"] = short(str(exc))
|
|
314
|
+
self._save()
|
|
315
|
+
return "pending", None, "创建结果不明且无 UUID;同名不等于本次归属,禁止删除或自动重建"
|
|
316
|
+
try:
|
|
317
|
+
current = inspect(uid)
|
|
318
|
+
except Exception as exc:
|
|
319
|
+
return "pending", uid, "UUID 回读失败,禁止删除或重建:%s" % short(str(exc))
|
|
320
|
+
if row.get("delete_requested_at"):
|
|
321
|
+
if current.get("state") == "missing" and row.get("backup_path") and row.get("owned"):
|
|
322
|
+
row.update(state="deleted", deleted_at=now(), delete_readback=current)
|
|
323
|
+
self._save()
|
|
324
|
+
return "create", None, "先前删除现已明确回读不存在,允许重建一次"
|
|
325
|
+
return "pending", uid, "先前删除结果尚未确认,不重复发送删除、不重建"
|
|
326
|
+
if (current.get("state") == "missing" and row.get("owned")
|
|
327
|
+
and row.get("state") == "create_failed" and row.get("attempt_count", 0) < 2):
|
|
328
|
+
row.update(state="deleted", no_object_readback=current, deleted_at=now())
|
|
329
|
+
self._save()
|
|
330
|
+
return "create", None, "本次失败 UUID 已明确回读不存在,无需删除,允许重建一次"
|
|
331
|
+
if current.get("state") != "exists":
|
|
332
|
+
return "pending", uid, "UUID 未查到或回读不确定,禁止推定删除成功或直接重建"
|
|
333
|
+
if not row.get("owned"):
|
|
334
|
+
return "pending", uid, "只有返回 UUID、没有本次创建归属证据,禁止删除或自动重建"
|
|
335
|
+
if row.get("state") in ("created", "complete"):
|
|
336
|
+
return ("done" if row["state"] == "complete" else "repair"), uid, "本次创建已成功,保留对象,仅补配置/发布/指派"
|
|
337
|
+
if row.get("state") != "create_failed":
|
|
338
|
+
return "pending", uid, "创建状态不明,禁止删除或重建"
|
|
339
|
+
if not current.get("unpublished"):
|
|
340
|
+
return "pending", uid, "失败对象未能证明确为未发布,禁止删除"
|
|
341
|
+
if not delete:
|
|
342
|
+
return "pending", uid, "无经过验证的删除通道,保留失败对象待处理,不编造命令"
|
|
343
|
+
if row.get("attempt_count", 0) >= 2:
|
|
344
|
+
return "pending", uid, "已用完一次重建机会,保留对象待处理"
|
|
345
|
+
backup_path = self.path + "." + row["attempt_id"] + ".backup.json"
|
|
346
|
+
with open(backup_path, "w", encoding="utf-8") as fh:
|
|
347
|
+
json.dump({"attempt": row, "readback": current, "saved_at": now()},
|
|
348
|
+
fh, ensure_ascii=False, indent=2)
|
|
349
|
+
fh.flush()
|
|
350
|
+
os.fsync(fh.fileno())
|
|
351
|
+
row.update(backup_path=backup_path, delete_requested_at=now())
|
|
352
|
+
self._save()
|
|
353
|
+
try:
|
|
354
|
+
# 超时或失败不重发删除;只用后续 UUID 回读判断是否已经不存在。
|
|
355
|
+
delete(uid)
|
|
356
|
+
except Exception as exc:
|
|
357
|
+
row["delete_error"] = short(str(exc))
|
|
358
|
+
try:
|
|
359
|
+
after = inspect(uid)
|
|
360
|
+
except Exception as exc:
|
|
361
|
+
row["delete_verify_error"] = short(str(exc))
|
|
362
|
+
self._save()
|
|
363
|
+
return "pending", uid, "删除后回读失败,禁止重建"
|
|
364
|
+
row["delete_readback"] = after
|
|
365
|
+
if after.get("state") != "missing":
|
|
366
|
+
self._save()
|
|
367
|
+
return "pending", uid, "删除后未明确确认不存在,禁止重建"
|
|
368
|
+
row.update(state="deleted", deleted_at=now())
|
|
369
|
+
self._save()
|
|
370
|
+
return "create", None, "已备份并删除本次失败未发布残留,回读确认不存在,允许重建一次"
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
# ------------------------------------------------------------------ 结果汇总
|
|
374
|
+
|
|
375
|
+
class Report:
|
|
376
|
+
"""逐对象结果 + 计数汇总 + JSON 落盘(口径与 run-protocol 的 RUN SUMMARY 对齐)。"""
|
|
377
|
+
|
|
378
|
+
def __init__(self, module, out_path=None):
|
|
379
|
+
self.module = module
|
|
380
|
+
self.out_path = out_path
|
|
381
|
+
self.rows = []
|
|
382
|
+
|
|
383
|
+
def add(self, target, status, detail="", **extra):
|
|
384
|
+
row = {"target": target, "status": status, "detail": short(detail, 200)}
|
|
385
|
+
row.update(extra)
|
|
386
|
+
self.rows.append(row)
|
|
387
|
+
return row
|
|
388
|
+
|
|
389
|
+
def counts(self):
|
|
390
|
+
c = {"created": 0, "reused": 0, "published": 0, "assigned": 0,
|
|
391
|
+
"verified": 0, "planned": 0, "failed": 0, "skipped": 0, "blocked": 0, "pending": 0}
|
|
392
|
+
for r in self.rows:
|
|
393
|
+
st = r["status"]
|
|
394
|
+
if st in c:
|
|
395
|
+
c[st] += 1
|
|
396
|
+
return c
|
|
397
|
+
|
|
398
|
+
def summary_line(self):
|
|
399
|
+
c = self.counts()
|
|
400
|
+
return ("RUN SUMMARY %s created=%d reused=%d published=%d assigned=%d verified=%d planned=%d failed=%d skipped=%d blocked=%d pending=%d total=%d"
|
|
401
|
+
% (self.module, c["created"], c["reused"], c["published"],
|
|
402
|
+
c["assigned"], c["verified"], c["planned"], c["failed"],
|
|
403
|
+
c["skipped"], c["blocked"], c["pending"], len(self.rows)))
|
|
404
|
+
|
|
405
|
+
def to_json(self):
|
|
406
|
+
ok = not any(r["status"] in ("failed", "blocked", "pending") or r.get("pending")
|
|
407
|
+
for r in self.rows)
|
|
408
|
+
return {"module": self.module, "ok": ok, "counts": self.counts(),
|
|
409
|
+
"rows": self.rows, "generated_at": now()}
|
|
410
|
+
|
|
411
|
+
def dump(self):
|
|
412
|
+
payload = self.to_json()
|
|
413
|
+
if self.out_path:
|
|
414
|
+
os.makedirs(os.path.dirname(os.path.abspath(self.out_path)), exist_ok=True)
|
|
415
|
+
with open(self.out_path, "w", encoding="utf-8") as fh:
|
|
416
|
+
json.dump(payload, fh, ensure_ascii=False, indent=2)
|
|
417
|
+
print(self.summary_line())
|
|
418
|
+
return 0 if payload["ok"] else 2
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
# ------------------------------------------------------------------ 公共小工具
|
|
422
|
+
|
|
423
|
+
def load_json(path, default=None):
|
|
424
|
+
try:
|
|
425
|
+
with open(path, encoding="utf-8") as fh:
|
|
426
|
+
return json.load(fh)
|
|
427
|
+
except Exception:
|
|
428
|
+
return default
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def save_json(path, data):
|
|
432
|
+
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
|
433
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
434
|
+
json.dump(data, fh, ensure_ascii=False, indent=2)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def ensure_utf8_stdio():
|
|
438
|
+
"""Windows 控制台默认 GBK,打印中文会 UnicodeEncodeError。"""
|
|
439
|
+
for stream in (sys.stdout, sys.stderr):
|
|
440
|
+
try:
|
|
441
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
442
|
+
except Exception:
|
|
443
|
+
pass
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def bp_dir(demo_root, blueprint_id):
|
|
447
|
+
return os.path.join(os.path.abspath(demo_root), "demo-assets", blueprint_id)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def arg_demo_root(ap):
|
|
451
|
+
ap.add_argument("--demo-root", required=True,
|
|
452
|
+
help="工作根锚点(state.json 里的 demo_root,绝对路径)")
|
|
453
|
+
ap.add_argument("--blueprint-id", required=True, help="蓝图 ID(demo-assets 下的目录名)")
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
# ------------------------------------------------------------------ 自测
|
|
457
|
+
|
|
458
|
+
def self_test():
|
|
459
|
+
cases = []
|
|
460
|
+
|
|
461
|
+
def ck(cond, label):
|
|
462
|
+
cases.append((bool(cond), label))
|
|
463
|
+
|
|
464
|
+
# jload:带 banner / 纯 JSON / 无 JSON / 尾随垃圾
|
|
465
|
+
ck((jload('banner\n{"code":200,"data":1}') or {}).get("data") == 1, "jload 跳过 banner")
|
|
466
|
+
ck(jload('{"a":{"b":[1,2]}}')["a"]["b"] == [1, 2], "jload 嵌套")
|
|
467
|
+
ck(jload("no json here") is None, "jload 无 JSON 返回 None")
|
|
468
|
+
ck((jload('{"a":1} trailing') or {}).get("a") == 1, "jload 尾随垃圾")
|
|
469
|
+
|
|
470
|
+
# rows_of:四种形态
|
|
471
|
+
ck(len(rows_of({"data": {"rows": [{"title": "a"}]}})) == 1, "rows_of data.rows")
|
|
472
|
+
ck(len(rows_of({"data": {"list": [{"title": "a"}]}})) == 1, "rows_of data.list")
|
|
473
|
+
ck(len(rows_of({"data": {"list": {"all": [{"title": "a"}]}}})) == 1, "rows_of data.list.all")
|
|
474
|
+
ck(len(rows_of([{"title": "a"}, "junk"])) == 1, "rows_of 顶层数组过滤非 dict")
|
|
475
|
+
ck(rows_of({"code": 200}) == [], "rows_of 无列表返回空")
|
|
476
|
+
|
|
477
|
+
# pick_uuid:五条路径
|
|
478
|
+
ck(pick_uuid({"data": {"uuid": "u1"}}) == "u1", "pick_uuid data.uuid")
|
|
479
|
+
ck(pick_uuid({"data": {"info": {"uuid": "u2"}}}) == "u2", "pick_uuid data.info.uuid")
|
|
480
|
+
ck(pick_uuid({"data": {"id": 7}}) is None, "pick_uuid 数字 id 不取")
|
|
481
|
+
ck(pick_uuid({"data": {"paperInfo": {"uuid": "p1"}}}) == "p1", "pick_uuid paperInfo")
|
|
482
|
+
ck(pick_uuid({"data": "u3"}) == "u3", "pick_uuid data 字符串")
|
|
483
|
+
ck(pick_uuid({"data": {"uuid": "empty"}}) is None, "pick_uuid empty 占位不取")
|
|
484
|
+
|
|
485
|
+
# resp_ok:成功/失败/权限
|
|
486
|
+
ck(resp_ok('{"code":200,"data":{}}'), "resp_ok code 200")
|
|
487
|
+
ck(resp_ok('{"code":202}'), "resp_ok 202 Accepted")
|
|
488
|
+
ck(resp_ok('{"code":0,"data":1}'), "resp_ok data=1")
|
|
489
|
+
ck(not resp_ok('{"code":500,"data":null}'), "resp_ok 500 判失败")
|
|
490
|
+
ck(not resp_ok('{"code":500,"data":{"uuid":"u"}}'), "失败信封含 UUID 不误判成功")
|
|
491
|
+
ck(not resp_ok(""), "resp_ok 空输出判失败")
|
|
492
|
+
ck(not resp_ok("Error: unknown flag --name"), "resp_ok 纯文本错误判失败")
|
|
493
|
+
|
|
494
|
+
# hit:错误分类
|
|
495
|
+
ck(hit(("", "[12000] 无权限"), PERM_MARKS), "hit 权限码")
|
|
496
|
+
ck(hit(("分类名已存在", ""), DUP_MARKS), "hit 重名")
|
|
497
|
+
ck(not hit(("ok", ""), DUP_MARKS), "hit 不误伤成功")
|
|
498
|
+
|
|
499
|
+
# norm_status
|
|
500
|
+
ck(norm_status({"data": {"status": 1}}) == 1, "norm_status data.status")
|
|
501
|
+
ck(norm_status({"data": {"info": {"status": "0"}}}) == 0, "norm_status info 字符串")
|
|
502
|
+
ck(norm_status({"code": 200}) is None, "norm_status 无 status 返回 None")
|
|
503
|
+
|
|
504
|
+
# short:截断 120
|
|
505
|
+
ck(len(short("x" * 300)) == 121, "short 截断到 120+省略号")
|
|
506
|
+
ck(short("a\nb") == "a b", "short 换行压平")
|
|
507
|
+
|
|
508
|
+
# Report
|
|
509
|
+
rep = Report("demo")
|
|
510
|
+
rep.add("a", "created")
|
|
511
|
+
rep.add("b", "reused")
|
|
512
|
+
rep.add("c", "failed", "boom")
|
|
513
|
+
ck(rep.counts()["created"] == 1 and rep.counts()["failed"] == 1, "Report 计数")
|
|
514
|
+
ck(rep.to_json()["ok"] is False, "Report 有 failed 则 ok=False")
|
|
515
|
+
ck("created=1" in rep.summary_line(), "Report 摘要含计数")
|
|
516
|
+
|
|
517
|
+
# Cli dry-run:不发请求,calls 不涨
|
|
518
|
+
cli = Cli("soke-cli", dry=True, echo=False)
|
|
519
|
+
ok, obj, _, _ = cli.call(["+list", "--format", "json"])
|
|
520
|
+
ck(ok and obj == {} and cli.calls == 0, "Cli dry-run 不执行")
|
|
521
|
+
|
|
522
|
+
# 创建恢复全过程均使用离线桩和临时目录。
|
|
523
|
+
import tempfile
|
|
524
|
+
from unittest.mock import Mock, patch
|
|
525
|
+
with tempfile.TemporaryDirectory(prefix="create-journal-") as tmp:
|
|
526
|
+
path = os.path.join(tmp, "attempts.json")
|
|
527
|
+
journal = CreateJournal(path, "test")
|
|
528
|
+
inspect, discover, delete = Mock(), Mock(return_value=[{"uuid": "old"}]), Mock()
|
|
529
|
+
ck(journal.prepare("a", inspect, discover)[0] == "create"
|
|
530
|
+
and not inspect.called and not discover.called, "首次零回读零同名 list")
|
|
531
|
+
journal.begin("a", "完整标题")
|
|
532
|
+
journal = CreateJournal(path, "test")
|
|
533
|
+
ck(journal.prepare("a", inspect, discover)[0] == "pending"
|
|
534
|
+
and discover.called and not delete.called, "请求超时无 UUID 重启后仅诊断且不重建")
|
|
535
|
+
journal.returned("a", True, {"code": 200, "data": {"uuid": "own"}})
|
|
536
|
+
inspect.return_value = {"state": "exists", "unpublished": True}
|
|
537
|
+
journal.failure("a", "配置失败")
|
|
538
|
+
ck(journal.prepare("a", inspect, discover, delete)[0] == "repair"
|
|
539
|
+
and not delete.called, "创建成功配置失败只修补不删")
|
|
540
|
+
journal.begin("b", "失败对象")
|
|
541
|
+
journal.returned("b", False, {"code": 500, "data": {"uuid": "unknown-owner"}})
|
|
542
|
+
ck(journal.prepare("b", inspect, discover, delete)[0] == "pending"
|
|
543
|
+
and not delete.called, "失败返回 UUID 无归属证据不删")
|
|
544
|
+
journal.begin("missing", "明确不存在失败对象")
|
|
545
|
+
journal.returned("missing", False, {"data": {"uuid": "own-missing"}}, created_evidence=True)
|
|
546
|
+
inspect.return_value = {"state": "missing"}
|
|
547
|
+
ck(journal.prepare("missing", inspect, delete=delete)[0] == "create"
|
|
548
|
+
and not delete.called, "本次失败 UUID 明确不存在无需删除即可重建一次")
|
|
549
|
+
journal.begin("missing", "明确不存在失败对象")
|
|
550
|
+
journal.returned("missing", False, {"data": {"uuid": "missing-again"}}, created_evidence=True)
|
|
551
|
+
ck(journal.prepare("missing", inspect, delete=delete)[0] == "pending", "明确不存在也最多重建一次")
|
|
552
|
+
inspect.return_value = {"state": "exists", "unpublished": True}
|
|
553
|
+
journal.begin("c", "可证明本次失败")
|
|
554
|
+
journal.returned("c", False, {"code": 500, "data": {"uuid": "failed-own"}}, created_evidence=True)
|
|
555
|
+
ck(journal.prepare("c", inspect)[0] == "pending", "无真实删除通道不编造命令")
|
|
556
|
+
inspect.return_value = {"state": "exists", "unpublished": False}
|
|
557
|
+
ck(journal.prepare("c", inspect, delete=delete)[0] == "pending"
|
|
558
|
+
and not delete.called, "已发布或状态不明对象禁止删除")
|
|
559
|
+
inspect.side_effect = [{"state": "exists", "unpublished": True}, {"state": "unknown"}]
|
|
560
|
+
ck(journal.prepare("c", inspect, delete=delete)[0] == "pending", "删除后回读不确定不得重建")
|
|
561
|
+
delete_count = delete.call_count
|
|
562
|
+
inspect.side_effect = [{"state": "missing"}]
|
|
563
|
+
ck(journal.prepare("c", inspect, delete=delete)[0] == "create"
|
|
564
|
+
and os.path.isfile(journal.get("c")["backup_path"])
|
|
565
|
+
and delete.call_count == delete_count, "备份删除回读确认后才准重建且不重发删除")
|
|
566
|
+
journal.begin("c", "可证明本次失败")
|
|
567
|
+
journal.returned("c", False, {"data": {"uuid": "second"}}, created_evidence=True)
|
|
568
|
+
inspect.side_effect = None
|
|
569
|
+
inspect.return_value = {"state": "exists", "unpublished": True}
|
|
570
|
+
ck(journal.prepare("c", inspect, delete=delete)[0] == "pending", "最多重建一次")
|
|
571
|
+
try:
|
|
572
|
+
journal.begin("a", "完整标题")
|
|
573
|
+
ck(False, "禁止绕过恢复直接 begin")
|
|
574
|
+
except RuntimeError:
|
|
575
|
+
ck(True, "禁止绕过恢复直接 begin")
|
|
576
|
+
runner = Mock(return_value=(124, "", "timeout"))
|
|
577
|
+
with patch(__name__ + "._RUNNER", runner):
|
|
578
|
+
Cli("unused", dry=False, echo=False).run(["portal", "+create"], retries=3, sleep=0)
|
|
579
|
+
ck(runner.call_count == 1, "创建接口即使传 retries 也只发一次")
|
|
580
|
+
|
|
581
|
+
failed = [label for ok, label in cases if not ok]
|
|
582
|
+
for ok, label in cases:
|
|
583
|
+
print(" %s %s" % ("PASS" if ok else "FAIL", label))
|
|
584
|
+
print("[self-test] %d/%d PASS" % (len(cases) - len(failed), len(cases)))
|
|
585
|
+
return 0 if not failed else 1
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def main(argv=None):
|
|
589
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
590
|
+
if "--self-test" in argv:
|
|
591
|
+
return self_test()
|
|
592
|
+
print("cli_kit 是共享模块,不单独运行;请用 portal_build.py / exam_build.py / project_build.py")
|
|
593
|
+
return 0
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
if __name__ == "__main__":
|
|
597
|
+
sys.exit(main())
|