evidgate 0.9.2__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.
- evidgate/__init__.py +6 -0
- evidgate/cli.py +599 -0
- evidgate/core/__init__.py +10 -0
- evidgate/core/builtin.py +105 -0
- evidgate/core/check.py +175 -0
- evidgate/core/evidence.py +243 -0
- evidgate/core/gate.py +154 -0
- evidgate/core/packs.py +90 -0
- evidgate/core/suggest.py +185 -0
- evidgate/ledger/__init__.py +4 -0
- evidgate/ledger/table.py +135 -0
- evidgate/packs/build.yaml +25 -0
- evidgate/packs/figures.yaml +29 -0
- evidgate/packs/repo.yaml +17 -0
- evidgate/plugins/__init__.py +1 -0
- evidgate/plugins/artifact.py +303 -0
- evidgate/plugins/prose.py +181 -0
- evidgate-0.9.2.dist-info/METADATA +386 -0
- evidgate-0.9.2.dist-info/RECORD +23 -0
- evidgate-0.9.2.dist-info/WHEEL +5 -0
- evidgate-0.9.2.dist-info/entry_points.txt +2 -0
- evidgate-0.9.2.dist-info/licenses/LICENSE +21 -0
- evidgate-0.9.2.dist-info/top_level.txt +1 -0
evidgate/__init__.py
ADDED
evidgate/cli.py
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
"""evidgate CLI: init / run / resume / report / mutate / prose."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Dict
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .core import builtin
|
|
14
|
+
from .core.check import load_checks
|
|
15
|
+
from .core.gate import (
|
|
16
|
+
FAIL,
|
|
17
|
+
LABEL,
|
|
18
|
+
PASS,
|
|
19
|
+
PENDING,
|
|
20
|
+
SKIP,
|
|
21
|
+
Verdict,
|
|
22
|
+
release_allowed,
|
|
23
|
+
run_check,
|
|
24
|
+
summarize,
|
|
25
|
+
)
|
|
26
|
+
from .ledger import build, load_rows, resume_cids
|
|
27
|
+
from .plugins import prose
|
|
28
|
+
|
|
29
|
+
CONFIG = "evidgate.yaml"
|
|
30
|
+
|
|
31
|
+
# Shell syntax that direct exec() cannot honour: a check using any of these must
|
|
32
|
+
# declare `shell:`, otherwise it fails for a reason that has nothing to do with
|
|
33
|
+
# the project. `|`, `>`, `<` are only counted outside quotes, because
|
|
34
|
+
# `grep -E "a|b"` inside quotes is a regex, not a pipe.
|
|
35
|
+
_SHELL_META = re.compile(r"&&|\|\||\$\(|>>|[<>]|`")
|
|
36
|
+
|
|
37
|
+
def _needs_shell(method: str) -> bool:
|
|
38
|
+
"""True when the command uses shell syntax that direct exec cannot honour.
|
|
39
|
+
|
|
40
|
+
Single quotes suppress expansion, so their content is dropped; double quotes
|
|
41
|
+
do NOT suppress command substitution, so `"$(ls ...)"` still needs a shell.
|
|
42
|
+
"""
|
|
43
|
+
no_single = re.sub(r"'[^']*'", "", method)
|
|
44
|
+
bare = re.sub(r'"[^"]*"', "", no_single)
|
|
45
|
+
if _SHELL_META.search(bare):
|
|
46
|
+
return True
|
|
47
|
+
return bool(re.search(r"\$\(|`", no_single))
|
|
48
|
+
|
|
49
|
+
TPL_ACTIVE = """# evidgate config. One check = one command + one assertion + one counter-test.
|
|
50
|
+
project: {project}
|
|
51
|
+
ledger: evidgate_ledger.md
|
|
52
|
+
|
|
53
|
+
checks:
|
|
54
|
+
- cid: C1
|
|
55
|
+
shell: bash
|
|
56
|
+
name: 交付文件存在且非空
|
|
57
|
+
method: test -s {target} && wc -c < {target}
|
|
58
|
+
expect: exit:0; regex:\\d
|
|
59
|
+
counter: 删掉 {target} 或清空它,本项必须变红
|
|
60
|
+
severity: red
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
TPL_EMPTY = """# evidgate config. 这个目录里没找到可交付文件,所以下面是注释模板。
|
|
64
|
+
# 写第一条检查: method 是一条会给出确定退出码的命令, counter 是「怎么让它变红」。
|
|
65
|
+
project: {project}
|
|
66
|
+
ledger: evidgate_ledger.md
|
|
67
|
+
|
|
68
|
+
checks:
|
|
69
|
+
# 复制下面三行, 去掉 #, 改成你自己的
|
|
70
|
+
# - cid: C1
|
|
71
|
+
# shell: bash # 命令里有 && | > < $( ` 时必须声明,否则会假红
|
|
72
|
+
# name: 交付文件存在且非空
|
|
73
|
+
# method: test -s your_output.md && wc -c < your_output.md
|
|
74
|
+
# expect: exit:0; regex:\\d
|
|
75
|
+
# counter: 删掉 your_output.md 或清空它, 本项必须变红
|
|
76
|
+
# severity: red
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
NOTE = "note: PASS 表示「证据存在且可复现」,不表示数值本身正确。"
|
|
80
|
+
CANDIDATES = ("report.md", "draft.md", "paper.md", "README.md", "main.py", "src")
|
|
81
|
+
|
|
82
|
+
PROSE_TEMPLATE = """
|
|
83
|
+
- cid: {cid}
|
|
84
|
+
name: {name}
|
|
85
|
+
method: builtin:prose:{rule} {paper}
|
|
86
|
+
expect: exit:0
|
|
87
|
+
counter: {counter}
|
|
88
|
+
severity: {sev}
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
PROSE_CHECKS = [
|
|
92
|
+
("P1", "正文可分词(分母可算)", "denominator", "yellow",
|
|
93
|
+
"给一个空文件或纯表格文件,本项应报错而不是静默 0 句"),
|
|
94
|
+
("P2", "绝对化词带范围或检索日期", "absolutes", "red",
|
|
95
|
+
"写一句「本文首次实现 X」且不给检索日期,本项必须变红"),
|
|
96
|
+
("P3", "结论句带引用或实测标记", "uncited", "yellow",
|
|
97
|
+
"写一句「结果说明 A 优于 B」不给引用,本项应变黄"),
|
|
98
|
+
("P4", "统计数字带口径", "numeral_scope", "yellow",
|
|
99
|
+
"写「降幅 21.2%」不写 n 与协议,本项应变黄"),
|
|
100
|
+
("P5", "正文引用与文献表双向对上", "citation_chain", "red",
|
|
101
|
+
"正文写 [9] 而文献表只到 [8],本项必须变红"),
|
|
102
|
+
]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _load(dir_: str):
|
|
106
|
+
cfg_path = os.path.join(dir_, CONFIG)
|
|
107
|
+
if not os.path.exists(cfg_path):
|
|
108
|
+
sys.exit(f"no {CONFIG} in {dir_}. run: evidgate init --dir {dir_}")
|
|
109
|
+
from .core.check import _mini_yaml
|
|
110
|
+
with open(cfg_path, encoding="utf-8") as fh:
|
|
111
|
+
cfg = _mini_yaml(fh.read())
|
|
112
|
+
packs = cfg.get("packs") or []
|
|
113
|
+
if isinstance(packs, str):
|
|
114
|
+
# `figures, build:outdir=dist` — a comma separates packs. A piece without a
|
|
115
|
+
# colon is a continuation of the previous pack's options, which is what makes
|
|
116
|
+
# `repo:test_cmd=...,pattern=...` expressible on one line.
|
|
117
|
+
entries = []
|
|
118
|
+
for piece in (x.strip() for x in packs.strip("[]").split(",")):
|
|
119
|
+
if not piece:
|
|
120
|
+
continue
|
|
121
|
+
if entries and ":" not in piece:
|
|
122
|
+
entries[-1] += "," + piece
|
|
123
|
+
else:
|
|
124
|
+
entries.append(piece)
|
|
125
|
+
packs = entries
|
|
126
|
+
elif isinstance(packs, dict):
|
|
127
|
+
# `packs:` written as a mapping, which is what YAML users reach for first.
|
|
128
|
+
# Both shapes are accepted, and neither may silently fall back to defaults:
|
|
129
|
+
# packs: {repo: "test_cmd=...", figures: ""}
|
|
130
|
+
# packs: {repo: {test_cmd: "..."}}
|
|
131
|
+
norm = []
|
|
132
|
+
for name, opts in packs.items():
|
|
133
|
+
if isinstance(opts, dict):
|
|
134
|
+
pairs = ",".join(f"{k}={v}" for k, v in opts.items())
|
|
135
|
+
else:
|
|
136
|
+
pairs = str(opts or "").strip().strip("{}")
|
|
137
|
+
norm.append(f"{name}:{pairs}" if pairs else str(name))
|
|
138
|
+
packs = norm
|
|
139
|
+
try:
|
|
140
|
+
checks = load_checks(cfg_path, allow_empty=bool(packs))
|
|
141
|
+
except ValueError as exc:
|
|
142
|
+
sys.exit(str(exc))
|
|
143
|
+
if packs:
|
|
144
|
+
from .core.packs import load_packs
|
|
145
|
+
packed = load_packs(packs)
|
|
146
|
+
own = {c.cid for c in checks}
|
|
147
|
+
dup = sorted({c.cid for c in packed if c.cid in own})
|
|
148
|
+
if dup:
|
|
149
|
+
sys.exit(f"pack 检查项编号与本项目的冲突:{dup}。改 pack 的 cid 或删掉自有同名项。")
|
|
150
|
+
checks = checks + packed
|
|
151
|
+
ledger = cfg.get("ledger", "evidgate_ledger.md")
|
|
152
|
+
project = cfg.get("project", os.path.basename(os.path.abspath(dir_)))
|
|
153
|
+
return cfg, checks, os.path.join(dir_, ledger), project
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _run(checks, dir_: str, only=None) -> Dict[str, Verdict]:
|
|
157
|
+
verdicts: Dict[str, Verdict] = {}
|
|
158
|
+
for c in checks:
|
|
159
|
+
if only and c.cid not in only:
|
|
160
|
+
continue
|
|
161
|
+
v = run_check(c, cwd=dir_)
|
|
162
|
+
verdicts[c.cid] = v
|
|
163
|
+
print(f" {v.cid:>3} {LABEL.get(v.status, v.status):<8} {c.name} ─ {v.detail[:100]}")
|
|
164
|
+
return verdicts
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _summary_line(verdicts) -> str:
|
|
168
|
+
s = summarize(list(verdicts.values()))
|
|
169
|
+
return (f"PASS {s[PASS]} · DIFF(黄) {s['DIFF']} · FAIL(红) {s[FAIL]} · "
|
|
170
|
+
f"待补 {s[PENDING]} · 未覆盖 {s.get('SKIP', 0)} | "
|
|
171
|
+
f"coverage {s['done']}/{s['total']} ({round(100*s['coverage'],1)}%)")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
PACK_TPL = """# evidgate · {project}
|
|
175
|
+
# 检查项来自 packs,不需要手写。
|
|
176
|
+
project: {project}
|
|
177
|
+
ledger: evidgate_ledger.md
|
|
178
|
+
packs: {packs}
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def cmd_init(a) -> int:
|
|
183
|
+
d = a.dir
|
|
184
|
+
os.makedirs(d, exist_ok=True)
|
|
185
|
+
p = os.path.join(d, CONFIG)
|
|
186
|
+
project = os.path.basename(os.path.abspath(d))
|
|
187
|
+
if getattr(a, "packs", ""):
|
|
188
|
+
body = PACK_TPL.format(project=project, packs=a.packs)
|
|
189
|
+
if os.path.exists(p) and not a.force:
|
|
190
|
+
print(f"{p} exists (use --force to overwrite)")
|
|
191
|
+
return 0
|
|
192
|
+
with open(p, "w", encoding="utf-8", newline="\n") as fh:
|
|
193
|
+
fh.write(body)
|
|
194
|
+
print(f"wrote {p} (packs: {a.packs})")
|
|
195
|
+
print(f"next: evidgate run --dir {d}")
|
|
196
|
+
return 0
|
|
197
|
+
target = next((c for c in CANDIDATES if os.path.exists(os.path.join(d, c))), None)
|
|
198
|
+
tpl = TPL_ACTIVE if target else TPL_EMPTY
|
|
199
|
+
body = tpl.format(project=project, target=target or "report.md")
|
|
200
|
+
if os.path.exists(p) and not a.force:
|
|
201
|
+
print(f"{p} exists (use --force to overwrite)")
|
|
202
|
+
else:
|
|
203
|
+
with open(p, "w", encoding="utf-8", newline="\n") as fh:
|
|
204
|
+
fh.write(body)
|
|
205
|
+
print(f"wrote {p}")
|
|
206
|
+
if target:
|
|
207
|
+
print(f" starter check targets existing file: {target}")
|
|
208
|
+
else:
|
|
209
|
+
print(" 目录里没有可交付文件,已生成注释模板;写下你的第一条检查后再 run")
|
|
210
|
+
print(f"next: evidgate doctor --dir {d} → evidgate run --dir {d}")
|
|
211
|
+
return 0
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def cmd_prose_init(a) -> int:
|
|
215
|
+
d = a.dir
|
|
216
|
+
p = os.path.join(d, CONFIG)
|
|
217
|
+
if not os.path.exists(p):
|
|
218
|
+
sys.exit(f"no {CONFIG}; run `evidgate init --dir {d}` first")
|
|
219
|
+
text = open(p, encoding="utf-8").read().rstrip("\n")
|
|
220
|
+
if "cid: P1" in text:
|
|
221
|
+
print("prose checks already present")
|
|
222
|
+
return 0
|
|
223
|
+
add = []
|
|
224
|
+
for cid, name, rule, sev, counter in PROSE_CHECKS:
|
|
225
|
+
add.append(PROSE_TEMPLATE.format(cid=cid, name=name, paper=a.file,
|
|
226
|
+
rule=rule, counter=counter, sev=sev))
|
|
227
|
+
open(p, "w", encoding="utf-8", newline="\n").write(text + "\n" + "".join(add))
|
|
228
|
+
print(f"appended {len(PROSE_CHECKS)} prose checks to {p}")
|
|
229
|
+
return 0
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def cmd_artifact_init(a) -> int:
|
|
235
|
+
"""Scan a directory into a first-draft manifest, so nobody has to write JSON by hand."""
|
|
236
|
+
from .plugins import artifact as art
|
|
237
|
+
d = a.dir
|
|
238
|
+
out = os.path.join(d, a.out)
|
|
239
|
+
if os.path.exists(out) and not a.force:
|
|
240
|
+
sys.exit(f"{out} exists (use --force to overwrite)")
|
|
241
|
+
items, skipped = [], []
|
|
242
|
+
for dp, dn, fn in os.walk(d):
|
|
243
|
+
dn[:] = [x for x in dn if x not in art.SKIP_DIRS]
|
|
244
|
+
for f in fn:
|
|
245
|
+
if f in art.SKIP_FILES or f == a.out or f.startswith(".#"):
|
|
246
|
+
# ".#x" is an Emacs lock (usually a dangling symlink); it is not an artifact
|
|
247
|
+
continue
|
|
248
|
+
full = os.path.join(dp, f)
|
|
249
|
+
rel = os.path.relpath(full, d).replace(os.sep, "/")
|
|
250
|
+
if os.path.islink(full) or not os.path.isfile(full):
|
|
251
|
+
skipped.append(rel)
|
|
252
|
+
continue
|
|
253
|
+
try:
|
|
254
|
+
digest = art._md5(full)
|
|
255
|
+
except OSError:
|
|
256
|
+
# one unreadable file must not abort the whole scan
|
|
257
|
+
skipped.append(rel)
|
|
258
|
+
continue
|
|
259
|
+
items.append({"path": rel, "role": "source", "md5": digest})
|
|
260
|
+
with open(out, "w", encoding="utf-8", newline="\n") as fh:
|
|
261
|
+
json.dump({"root": ".", "items": items}, fh, ensure_ascii=False, indent=2)
|
|
262
|
+
fh.write("\n")
|
|
263
|
+
print(f"wrote {out} ({len(items)} files, all role=source)")
|
|
264
|
+
if skipped:
|
|
265
|
+
print(f" skipped {len(skipped)} unreadable/link entries (e.g. {skipped[0]})")
|
|
266
|
+
print("next: 把派生文件改成 role=derivative 并填 source;手改过的副本加 same_as_source: true")
|
|
267
|
+
return 0
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def cmd_artifact_stamp(a) -> int:
|
|
273
|
+
"""Record that a derivative was just generated from the current source."""
|
|
274
|
+
from .plugins import artifact as art
|
|
275
|
+
out = os.path.join(a.dir, a.manifest)
|
|
276
|
+
if not os.path.exists(out):
|
|
277
|
+
sys.exit(f"{out} 不存在;先跑 artifact-init")
|
|
278
|
+
paths = a.path or []
|
|
279
|
+
if not paths:
|
|
280
|
+
sys.exit("--path 至少给一个派生文件,例如: --path build/report.html")
|
|
281
|
+
n = art.stamp(out, paths)
|
|
282
|
+
print(f"已盖章 {n} 项(记录当前源哈希)")
|
|
283
|
+
print("只对刚刚重新生成的文件盖章;批量盖章等于宣称全都是新的。")
|
|
284
|
+
return 0
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def cmd_artifact_update(a) -> int:
|
|
288
|
+
"""Recompute recorded hashes after a deliberate regeneration."""
|
|
289
|
+
from .plugins import artifact as art
|
|
290
|
+
out = os.path.join(a.dir, a.manifest)
|
|
291
|
+
if not os.path.exists(out):
|
|
292
|
+
sys.exit(f"{out} 不存在;先跑 artifact-init")
|
|
293
|
+
n = art.refresh(out)
|
|
294
|
+
print(f"{out}: 更新了 {n} 个 md5(未动 source_md5;那要用 artifact-stamp 显式盖章)")
|
|
295
|
+
print("now re-run the gate: evidgate run --dir " + a.dir)
|
|
296
|
+
return 0
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def cmd_suggest(a) -> int:
|
|
300
|
+
from .core.suggest import probe, render
|
|
301
|
+
result = probe(a.dir)
|
|
302
|
+
print(render(result))
|
|
303
|
+
if getattr(a, "write", False) and result["packs"]:
|
|
304
|
+
ns = type("A", (), {"dir": a.dir, "force": False, "packs": ",".join(result["packs"])})()
|
|
305
|
+
return cmd_init(ns)
|
|
306
|
+
return 0
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def cmd_pack(a) -> int:
|
|
310
|
+
from .core.packs import DEFAULTS, available, load_packs
|
|
311
|
+
if a.action == "list":
|
|
312
|
+
names = available()
|
|
313
|
+
if not names:
|
|
314
|
+
print("没有可用的 pack")
|
|
315
|
+
return 0
|
|
316
|
+
print("可用 pack(在 evidgate.yaml 里写 packs: 名字, 名字2:参数=值)\n")
|
|
317
|
+
for n in names:
|
|
318
|
+
try:
|
|
319
|
+
n_chk = load_packs([n])
|
|
320
|
+
print(f" {n:9s} {len(n_chk)} 条 · " + "; ".join(c.name for c in n_chk))
|
|
321
|
+
except SystemExit as exc:
|
|
322
|
+
print(f" {n:9s} 加载失败:{exc}")
|
|
323
|
+
params = DEFAULTS.get(n) or {}
|
|
324
|
+
if params:
|
|
325
|
+
print(f" {'':9s} 参数:{' '.join(f'{k}=…' for k in params)}")
|
|
326
|
+
return 0
|
|
327
|
+
if not a.name:
|
|
328
|
+
print("用法:evidgate pack show <名字>")
|
|
329
|
+
return 2
|
|
330
|
+
for c in load_packs([a.name]):
|
|
331
|
+
print(f"{c.cid:6s} [{c.severity}] {c.name}")
|
|
332
|
+
print(f" method : {c.method}")
|
|
333
|
+
print(f" expect : {c.expect}")
|
|
334
|
+
print(f" counter: {c.counter}")
|
|
335
|
+
return 0
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def cmd_doctor(a) -> int:
|
|
339
|
+
"""Check the environment before blaming the project."""
|
|
340
|
+
d = a.dir
|
|
341
|
+
print(f"evidgate doctor · {os.path.abspath(d)}")
|
|
342
|
+
cfg = os.path.join(d, CONFIG)
|
|
343
|
+
if not os.path.exists(cfg):
|
|
344
|
+
print(f" [BAD ] {CONFIG} 不存在 —— 先跑: evidgate init --dir {d}")
|
|
345
|
+
return 1
|
|
346
|
+
try:
|
|
347
|
+
_, checks, ledger_path, project = _load(d)
|
|
348
|
+
except SystemExit as exc:
|
|
349
|
+
if exc.code not in (0, None):
|
|
350
|
+
print(f" [BAD ] {exc.code}")
|
|
351
|
+
return 1
|
|
352
|
+
except Exception as exc:
|
|
353
|
+
print(f" [BAD ] yaml 解析失败: {exc}")
|
|
354
|
+
return 1
|
|
355
|
+
print(f" [OK ] yaml 可解析 · {len(checks)} 条检查 · project={project}")
|
|
356
|
+
import shutil as _sh
|
|
357
|
+
if os.name == "nt":
|
|
358
|
+
bash = _sh.which("bash")
|
|
359
|
+
from .core.evidence import find_posix_shell as _fps
|
|
360
|
+
posix = _fps()
|
|
361
|
+
print(" [WARN] 未声明 shell 的检查项直接执行;声明 shell: bash 的需要 Git Bash")
|
|
362
|
+
if posix:
|
|
363
|
+
print(f" 探测到 Git Bash:{posix}")
|
|
364
|
+
if bash:
|
|
365
|
+
print(f" 本机有 bash({bash}),但 evidgate 不会用它;"
|
|
366
|
+
"Windows 请优先用 builtin: 检查项")
|
|
367
|
+
else:
|
|
368
|
+
print(" 建议:安装 Git Bash,或把检查项换成 builtin:"
|
|
369
|
+
"(build/repo 包已提供 builtin 版)")
|
|
370
|
+
else:
|
|
371
|
+
posix = _sh.which("bash") or _sh.which("sh") or "(none)"
|
|
372
|
+
print(f" [OK ] 默认不经 shell 执行;声明 shell: bash 时用 {posix}")
|
|
373
|
+
all_ok = True
|
|
374
|
+
from .core.evidence import find_posix_shell as _posix
|
|
375
|
+
for c in checks:
|
|
376
|
+
m = c.method.strip()
|
|
377
|
+
if builtin.is_builtin(m):
|
|
378
|
+
verdict = builtin.describe(m, cwd=d)
|
|
379
|
+
elif c.shell:
|
|
380
|
+
exe = (_posix() if (os.name == "nt" and c.shell in ("bash", "sh"))
|
|
381
|
+
else shutil.which(c.shell))
|
|
382
|
+
verdict = (f"OK (shell: {c.shell})" if exe
|
|
383
|
+
else f"BAD: 声明了 shell: {c.shell},本机找不到它")
|
|
384
|
+
elif _needs_shell(m):
|
|
385
|
+
verdict = ("BAD: 命令含 shell 语法(&& | > < $( `)却没声明 shell "
|
|
386
|
+
"—— 加 shell: bash,或改用 builtin: 检查项")
|
|
387
|
+
else:
|
|
388
|
+
head = (m.split() or [""])[0]
|
|
389
|
+
shell_builtin = {"cd", "test", "echo", "true", "false", "export", "set",
|
|
390
|
+
"source", ".", "printf", "read", "if", "for", "while"}
|
|
391
|
+
if not head:
|
|
392
|
+
verdict = "BAD: method 为空"
|
|
393
|
+
elif head in shell_builtin:
|
|
394
|
+
verdict = "OK (shell 内建)"
|
|
395
|
+
elif shutil.which(head):
|
|
396
|
+
verdict = "OK (在 PATH 中)"
|
|
397
|
+
elif os.path.exists(os.path.join(d, head)):
|
|
398
|
+
verdict = "OK (项目内文件)"
|
|
399
|
+
else:
|
|
400
|
+
verdict = f"BAD: 命令 {head!r} 不在 PATH,也不是项目内文件"
|
|
401
|
+
bad = verdict.startswith("BAD")
|
|
402
|
+
all_ok = all_ok and not bad
|
|
403
|
+
print(f" [{'BAD ' if bad else 'OK '}] {c.cid:>4} {c.name[:26]:26s} {verdict}")
|
|
404
|
+
print(f" ledger: {ledger_path}")
|
|
405
|
+
print(" " + ("环境就绪,可以 run" if all_ok else "先修上面 BAD 项,再 run"))
|
|
406
|
+
return 0 if all_ok else 1
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def cmd_run(a) -> int:
|
|
410
|
+
cfg, checks, ledger_path, project = _load(a.dir)
|
|
411
|
+
only = set(x.strip() for x in a.only.split(",")) if a.only else None
|
|
412
|
+
print(f"evidgate {__version__} · {project} · {len(checks)} checks"
|
|
413
|
+
+ (f" (only {sorted(only)})" if only else ""))
|
|
414
|
+
verdicts = _run(checks, a.dir, only)
|
|
415
|
+
build(ledger_path, checks, verdicts, project)
|
|
416
|
+
print("\n" + _summary_line(verdicts))
|
|
417
|
+
ok, why = release_allowed(list(verdicts.values()))
|
|
418
|
+
print(("RELEASE OK " if ok else "RELEASE BLOCKED ") + why)
|
|
419
|
+
print(f"ledger: {ledger_path}")
|
|
420
|
+
print(NOTE)
|
|
421
|
+
return 0 if ok else 1
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def cmd_resume(a) -> int:
|
|
425
|
+
cfg, checks, ledger_path, project = _load(a.dir)
|
|
426
|
+
rows = load_rows(ledger_path)
|
|
427
|
+
todo = resume_cids(checks, rows)
|
|
428
|
+
if not todo:
|
|
429
|
+
print("nothing to resume: every check has a verdict")
|
|
430
|
+
return 0
|
|
431
|
+
print(f"resuming {len(todo)} unresolved check(s): {', '.join(todo)}")
|
|
432
|
+
verdicts = _run([c for c in checks if c.cid in todo], a.dir)
|
|
433
|
+
# keep earlier verdicts from the ledger
|
|
434
|
+
for cid, row in rows.items():
|
|
435
|
+
if cid not in verdicts and row["status"] not in ("—", ""):
|
|
436
|
+
pass
|
|
437
|
+
build(ledger_path, checks, verdicts, project, previous=rows)
|
|
438
|
+
print("\n" + _summary_line(verdicts) + " (partial: only resumed rows rerun)")
|
|
439
|
+
return 0
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def cmd_report(a) -> int:
|
|
443
|
+
cfg, checks, ledger_path, project = _load(a.dir)
|
|
444
|
+
if not os.path.exists(ledger_path):
|
|
445
|
+
sys.exit("no ledger yet; run `evidgate run` first")
|
|
446
|
+
rows = load_rows(ledger_path)
|
|
447
|
+
verdicts = {cid: type("V", (), {"cid": cid, "status": r["status"],
|
|
448
|
+
"detail": r["evidence"], "evidence": None})()
|
|
449
|
+
for cid, r in rows.items()}
|
|
450
|
+
label_to_status = {v: k for k, v in LABEL.items()}
|
|
451
|
+
for cid, v in verdicts.items():
|
|
452
|
+
v.status = label_to_status.get(v.status, v.status)
|
|
453
|
+
fails = [c.cid for c in checks if verdicts.get(c.cid) and verdicts[c.cid].status == FAIL]
|
|
454
|
+
pend = [c.cid for c in checks if not verdicts.get(c.cid) or verdicts[c.cid].status == PENDING]
|
|
455
|
+
yellows = [c.cid for c in checks if verdicts.get(c.cid) and verdicts[c.cid].status == "DIFF"]
|
|
456
|
+
skips = [c.cid for c in checks if verdicts.get(c.cid) and verdicts[c.cid].status == SKIP]
|
|
457
|
+
out = [
|
|
458
|
+
f"# release gate report · {project}", "",
|
|
459
|
+
"## 1. 检查表", "", "| cid | check | status | evidence |", "|---|---|---|---|",
|
|
460
|
+
]
|
|
461
|
+
for c in checks:
|
|
462
|
+
v = verdicts.get(c.cid)
|
|
463
|
+
out.append(f"| {c.cid} | {c.name} | {LABEL.get(v.status,'—') if v else '—'} | "
|
|
464
|
+
f"{(v.detail if v else '—')[:120]} |")
|
|
465
|
+
out += ["", "## 2. 待确认(黄项)", ""]
|
|
466
|
+
out += [f"- {cid}" for cid in yellows] or ["- 无"]
|
|
467
|
+
out += ["", "## 3. 待补与未覆盖", ""]
|
|
468
|
+
out.append("**待补(没核过)**:" + ("、".join(pend) if pend else "无"))
|
|
469
|
+
out.append("")
|
|
470
|
+
out.append("**未覆盖(optional/不适用,不阻塞)**:" + ("、".join(skips) if skips else "无"))
|
|
471
|
+
out += ["", "## 4. 放行结论", ""]
|
|
472
|
+
if fails or pend:
|
|
473
|
+
out.append(f"- **不可放行**:红项 {fails or '无'};待补 {pend or '无'}")
|
|
474
|
+
else:
|
|
475
|
+
out.append("- **可进下一阶段**")
|
|
476
|
+
if skips:
|
|
477
|
+
out.append(f"- 另有 {len(skips)} 项未覆盖({', '.join(skips)}):不阻塞,但确实没验过")
|
|
478
|
+
report_path = os.path.join(a.dir, "gate_report.md")
|
|
479
|
+
with open(report_path, "w", encoding="utf-8", newline=chr(10)) as fh:
|
|
480
|
+
fh.write("\n".join(out) + "\n")
|
|
481
|
+
print(f"wrote {report_path}")
|
|
482
|
+
return 0 if not fails and not pend else 1
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def cmd_mutate(a) -> int:
|
|
486
|
+
"""Detection power: the same checks must pass on the baseline and go red on the mutant."""
|
|
487
|
+
cfg, checks, _, _ = _load(a.dir)
|
|
488
|
+
if a.only:
|
|
489
|
+
keep = {x.strip() for x in a.only.split(",")}
|
|
490
|
+
checks = [c for c in checks if c.cid in keep]
|
|
491
|
+
base_v = {c.cid: run_check(c, cwd=a.baseline) for c in checks}
|
|
492
|
+
mut_v = {c.cid: run_check(c, cwd=a.mutant) for c in checks}
|
|
493
|
+
rows, caught = [], 0
|
|
494
|
+
for c in checks:
|
|
495
|
+
b, m = base_v[c.cid], mut_v[c.cid]
|
|
496
|
+
ok = b.status == PASS and m.status != PASS
|
|
497
|
+
caught += 1 if ok else 0
|
|
498
|
+
rows.append((c.cid, c.name, b.status, m.status, "caught" if ok else "NOT caught"))
|
|
499
|
+
print("| cid | check | baseline | mutant | detection |")
|
|
500
|
+
print("|---|---|---|---|---|")
|
|
501
|
+
for r in rows:
|
|
502
|
+
print(f"| {r[0]} | {r[1][:36]} | {r[2]} | {r[3]} | {r[4]} |")
|
|
503
|
+
print(f"\ndetection power: {caught}/{len(checks)}")
|
|
504
|
+
return 0 if caught == len(checks) else 1
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _fix_console() -> None:
|
|
508
|
+
"""Never die on a console that cannot encode our output.
|
|
509
|
+
|
|
510
|
+
A Chinese Windows console is GBK; printing a replacement character there raises
|
|
511
|
+
UnicodeEncodeError and kills the run halfway through the checks.
|
|
512
|
+
"""
|
|
513
|
+
for stream in (sys.stdout, sys.stderr):
|
|
514
|
+
try:
|
|
515
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
516
|
+
except Exception:
|
|
517
|
+
pass
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def main(argv=None) -> int:
|
|
521
|
+
_fix_console()
|
|
522
|
+
ap = argparse.ArgumentParser(prog="evidgate", description="evidence gates for documents")
|
|
523
|
+
ap.add_argument("--version", action="version", version=f"evidgate {__version__}")
|
|
524
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
525
|
+
|
|
526
|
+
p = sub.add_parser("init", help="write a starter evidgate.yaml")
|
|
527
|
+
p.add_argument("--dir", default=".")
|
|
528
|
+
p.add_argument("--packs", default="", help="e.g. figures,build — write a packs-only config")
|
|
529
|
+
p.add_argument("--force", action="store_true")
|
|
530
|
+
p.set_defaults(fn=cmd_init)
|
|
531
|
+
|
|
532
|
+
p = sub.add_parser("run", help="run every check, rebuild the ledger")
|
|
533
|
+
p.add_argument("--dir", default=".")
|
|
534
|
+
p.add_argument("--only", default="")
|
|
535
|
+
p.set_defaults(fn=cmd_run)
|
|
536
|
+
|
|
537
|
+
p = sub.add_parser("resume", help="rerun only unresolved checks")
|
|
538
|
+
p.add_argument("--dir", default=".")
|
|
539
|
+
p.set_defaults(fn=cmd_resume)
|
|
540
|
+
|
|
541
|
+
p = sub.add_parser("report", help="write gate_report.md from the ledger")
|
|
542
|
+
p.add_argument("--dir", default=".")
|
|
543
|
+
p.set_defaults(fn=cmd_report)
|
|
544
|
+
|
|
545
|
+
p = sub.add_parser("artifact-init", help="scan a directory into a first-draft artifacts.json")
|
|
546
|
+
p.add_argument("--dir", default=".")
|
|
547
|
+
p.add_argument("--out", default="artifacts.json")
|
|
548
|
+
p.add_argument("--force", action="store_true")
|
|
549
|
+
p.set_defaults(fn=cmd_artifact_init)
|
|
550
|
+
|
|
551
|
+
p = sub.add_parser("artifact-stamp", help="record that a derivative was just regenerated")
|
|
552
|
+
p.add_argument("--dir", default=".")
|
|
553
|
+
p.add_argument("--manifest", default="artifacts.json")
|
|
554
|
+
p.add_argument("--path", action="append", help="derivative path (repeatable)")
|
|
555
|
+
p.set_defaults(fn=cmd_artifact_stamp)
|
|
556
|
+
|
|
557
|
+
p = sub.add_parser("artifact-update", help="recompute an artifact's own recorded hash")
|
|
558
|
+
p.add_argument("--dir", default=".")
|
|
559
|
+
p.add_argument("--manifest", default="artifacts.json")
|
|
560
|
+
p.set_defaults(fn=cmd_artifact_update)
|
|
561
|
+
|
|
562
|
+
p = sub.add_parser("suggest", help="scan a project and say which packs apply")
|
|
563
|
+
p.add_argument("--dir", default=".")
|
|
564
|
+
p.add_argument("--write", action="store_true", help="also write evidgate.yaml")
|
|
565
|
+
p.set_defaults(fn=cmd_suggest)
|
|
566
|
+
|
|
567
|
+
p = sub.add_parser("pack", help="list reusable check packs, or show one expanded")
|
|
568
|
+
p.add_argument("action", nargs="?", default="list", choices=["list", "show"])
|
|
569
|
+
p.add_argument("name", nargs="?", default="")
|
|
570
|
+
p.set_defaults(fn=cmd_pack)
|
|
571
|
+
|
|
572
|
+
p = sub.add_parser("doctor", help="check yaml + commands before blaming the project")
|
|
573
|
+
p.add_argument("--dir", default=".")
|
|
574
|
+
p.set_defaults(fn=cmd_doctor)
|
|
575
|
+
|
|
576
|
+
p = sub.add_parser("mutate", help="prove the checks can go red")
|
|
577
|
+
p.add_argument("--dir", default=".")
|
|
578
|
+
p.add_argument("--baseline", required=True)
|
|
579
|
+
p.add_argument("--mutant", required=True)
|
|
580
|
+
p.add_argument("--only", default="")
|
|
581
|
+
p.set_defaults(fn=cmd_mutate)
|
|
582
|
+
|
|
583
|
+
p = sub.add_parser("prose", help="Chinese prose rules")
|
|
584
|
+
p.add_argument("rest", nargs=argparse.REMAINDER)
|
|
585
|
+
p.set_defaults(fn=None)
|
|
586
|
+
|
|
587
|
+
p = sub.add_parser("prose-init", help="append prose checks to evidgate.yaml")
|
|
588
|
+
p.add_argument("--dir", default=".")
|
|
589
|
+
p.add_argument("--file", default="paper.md")
|
|
590
|
+
p.set_defaults(fn=cmd_prose_init)
|
|
591
|
+
|
|
592
|
+
a = ap.parse_args(argv)
|
|
593
|
+
if a.cmd == "prose":
|
|
594
|
+
return prose.main(a.rest)
|
|
595
|
+
return a.fn(a)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
if __name__ == "__main__":
|
|
599
|
+
sys.exit(main())
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Gate engine: check registry -> evidence -> three-state -> release rule."""
|
|
2
|
+
from .check import SEVERITIES, Check, load_checks
|
|
3
|
+
from .evidence import Evidence, collect
|
|
4
|
+
from .gate import Verdict, release_allowed, run_check, summarize
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"Check", "load_checks", "SEVERITIES",
|
|
8
|
+
"Evidence", "collect",
|
|
9
|
+
"Verdict", "run_check", "summarize", "release_allowed",
|
|
10
|
+
]
|