govrule 0.1.0__tar.gz
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.
- govrule-0.1.0/LICENSE +16 -0
- govrule-0.1.0/PKG-INFO +111 -0
- govrule-0.1.0/README.md +91 -0
- govrule-0.1.0/govrule/__init__.py +7 -0
- govrule-0.1.0/govrule/__main__.py +3 -0
- govrule-0.1.0/govrule/astnodes.py +116 -0
- govrule-0.1.0/govrule/baseline.py +105 -0
- govrule-0.1.0/govrule/cli.py +175 -0
- govrule-0.1.0/govrule/diagnostics.py +72 -0
- govrule-0.1.0/govrule/evaluator.py +236 -0
- govrule-0.1.0/govrule/facts.py +158 -0
- govrule-0.1.0/govrule/lexer.py +127 -0
- govrule-0.1.0/govrule/parser.py +376 -0
- govrule-0.1.0/govrule/py.typed +0 -0
- govrule-0.1.0/govrule/values.py +64 -0
- govrule-0.1.0/govrule.egg-info/PKG-INFO +111 -0
- govrule-0.1.0/govrule.egg-info/SOURCES.txt +22 -0
- govrule-0.1.0/govrule.egg-info/dependency_links.txt +1 -0
- govrule-0.1.0/govrule.egg-info/entry_points.txt +2 -0
- govrule-0.1.0/govrule.egg-info/requires.txt +3 -0
- govrule-0.1.0/govrule.egg-info/top_level.txt +1 -0
- govrule-0.1.0/pyproject.toml +38 -0
- govrule-0.1.0/setup.cfg +4 -0
- govrule-0.1.0/tests/test_engine.py +208 -0
govrule-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
MIT No Attribution
|
|
2
|
+
|
|
3
|
+
Copyright 2026 siwpan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
|
6
|
+
software and associated documentation files (the "Software"), to deal in the Software
|
|
7
|
+
without restriction, including without limitation the rights to use, copy, modify,
|
|
8
|
+
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
|
9
|
+
permit persons to whom the Software is furnished to do so.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
12
|
+
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
|
13
|
+
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
14
|
+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
|
|
15
|
+
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
|
|
16
|
+
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
govrule-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: govrule
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 治理规则 DSL:四值判据 + 证据 + 基线棘轮(离线、零第三方依赖)
|
|
5
|
+
Author: siwpan
|
|
6
|
+
License-Expression: MIT-0
|
|
7
|
+
Keywords: governance,policy-as-code,dsl,gates,offline
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
14
|
+
Requires-Python: >=3.11
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# govrule
|
|
22
|
+
|
|
23
|
+
治理规则 DSL 的最小实现:把「判据」写成可读的规则文件,跑出**四值**结论、**可读证据**与**基线棘轮**。
|
|
24
|
+
|
|
25
|
+
> 定位:它不是编译器框架,也不是通用策略引擎。它只解决一件事——
|
|
26
|
+
> **让「没跑」「跳过」「判不了」不再长得像「通过」。**
|
|
27
|
+
|
|
28
|
+
## 为什么需要它
|
|
29
|
+
|
|
30
|
+
原有门禁是 20 个 Python 脚本,7,434 行判据 + 2,699 行共享管道 + 1,550 行自证夹具。
|
|
31
|
+
管道(枚举、读取、基线、报告、夹具沙箱)占了 79%,每写一条新判据都要重付一次。
|
|
32
|
+
把管道固化进语言,判据就只剩「选什么、抽什么、断言什么、为什么红」。
|
|
33
|
+
|
|
34
|
+
## 三个设计决定
|
|
35
|
+
|
|
36
|
+
**1. 四值,不是布尔**
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
Verdict = Pass | Fail | Skip | Unknown
|
|
40
|
+
combine(a, b) 取最坏(Fail > Unknown > Skip > Pass)
|
|
41
|
+
空集 → Skip;全 Skip → exit 3;Unknown → exit 3
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`bool(Verdict.UNKNOWN)` 会直接抛异常——不允许 `if verdict:` 把它当假。
|
|
45
|
+
|
|
46
|
+
**2. 判定集合与显示截断分离**
|
|
47
|
+
|
|
48
|
+
`--max-findings` 只影响打印。任何为了输出好看而做的截断,一旦进了判据,
|
|
49
|
+
就会把「截断」读成「漏报」——这是实测踩过的坑。
|
|
50
|
+
|
|
51
|
+
**3. 基线只能显式扩张**
|
|
52
|
+
|
|
53
|
+
`baseline-write` 遇「纯增长」(一条没修、只是账单变长)拒绝写入;
|
|
54
|
+
基线里有、当下不再命中的键是「过期账单」,默认判红。
|
|
55
|
+
|
|
56
|
+
## 快速开始
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
python -m govrule run --rules rules --root G:/repos/allin-governance
|
|
60
|
+
python -m govrule list --rules rules
|
|
61
|
+
python -m govrule baseline-write --rules rules --root . --out baseline.txt --reason "冻结存量"
|
|
62
|
+
python -m govrule run --rules rules --root . --baseline baseline.txt
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
退出码:`0` 干净 · `1` 有违规 · `2` 用法错 · `3` 不完整(Unknown / 全 Skip)。
|
|
66
|
+
|
|
67
|
+
## 规则长什么样
|
|
68
|
+
|
|
69
|
+
```
|
|
70
|
+
rule g01.dead-root
|
|
71
|
+
code F-DEAD-ROOT
|
|
72
|
+
scope repo "**/*" exclude ["**/.venv*/**"]
|
|
73
|
+
select each file
|
|
74
|
+
extract text-lines(comments)
|
|
75
|
+
where matches(line, /(?<![A-Za-z0-9_])[A-Za-z]:[\\\/][A-Za-z0-9_.~]/) and is-dead(line)
|
|
76
|
+
assert count == 0
|
|
77
|
+
evidence cite=line.span expected="仓内相对路径或盘符变量" found=line.text
|
|
78
|
+
severity blocking
|
|
79
|
+
applies platforms=[nt, posix]
|
|
80
|
+
|
|
81
|
+
exempt url when matches(line, /:\/\//)
|
|
82
|
+
exempt doc when matches(path, /\.(md|html?)$/i) severity warn
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
子句只有九个:`scope` / `select` / `extract` / `where` / `assert` / `evidence` /
|
|
86
|
+
`severity` / `applies` / `exempt`。没有循环、没有递归、没有函数定义——
|
|
87
|
+
**少不是未完成,是判据**:非图灵完备换来的是「规则不可能挂死」「判据可穷举」「解释器可零依赖」。
|
|
88
|
+
|
|
89
|
+
## 内建
|
|
90
|
+
|
|
91
|
+
| 名称 | 语义 |
|
|
92
|
+
|---|---|
|
|
93
|
+
| `text-lines(comments, fences)` | 逐行抽取;可选剔除注释行 / 围栏块 |
|
|
94
|
+
| `filename()` | 按文件名抽取 |
|
|
95
|
+
| `file-meta()` | 按文件元数据抽取(`line.size`) |
|
|
96
|
+
| `matches(x, /re/)` | 正则匹配;`/.../i` 大小写不敏感 |
|
|
97
|
+
| `is-dead(text)` | 行内盘符路径的**父目录不存在** → true |
|
|
98
|
+
| `and` / `or` / `not` | 布尔组合 |
|
|
99
|
+
|
|
100
|
+
绑定:`line`(当前行文本)、`path`(相对路径)、`line.span`、`line.size`、`line.name`。
|
|
101
|
+
|
|
102
|
+
## 边界(不要误用)
|
|
103
|
+
|
|
104
|
+
- **不是通用策略引擎**:没有 Datalog、没有 join、没有跨文档聚合。
|
|
105
|
+
- **不做语义分析**:`text-lines` 是文本层,不建 AST。
|
|
106
|
+
- **`is-dead` 是本机视角**:在 A 机上判「死」的路径,在 B 机上可能存在。
|
|
107
|
+
- **未声明 scope = 不可判定**,不是「全部」。
|
|
108
|
+
|
|
109
|
+
## 许可
|
|
110
|
+
|
|
111
|
+
MIT-0。
|
govrule-0.1.0/README.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# govrule
|
|
2
|
+
|
|
3
|
+
治理规则 DSL 的最小实现:把「判据」写成可读的规则文件,跑出**四值**结论、**可读证据**与**基线棘轮**。
|
|
4
|
+
|
|
5
|
+
> 定位:它不是编译器框架,也不是通用策略引擎。它只解决一件事——
|
|
6
|
+
> **让「没跑」「跳过」「判不了」不再长得像「通过」。**
|
|
7
|
+
|
|
8
|
+
## 为什么需要它
|
|
9
|
+
|
|
10
|
+
原有门禁是 20 个 Python 脚本,7,434 行判据 + 2,699 行共享管道 + 1,550 行自证夹具。
|
|
11
|
+
管道(枚举、读取、基线、报告、夹具沙箱)占了 79%,每写一条新判据都要重付一次。
|
|
12
|
+
把管道固化进语言,判据就只剩「选什么、抽什么、断言什么、为什么红」。
|
|
13
|
+
|
|
14
|
+
## 三个设计决定
|
|
15
|
+
|
|
16
|
+
**1. 四值,不是布尔**
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
Verdict = Pass | Fail | Skip | Unknown
|
|
20
|
+
combine(a, b) 取最坏(Fail > Unknown > Skip > Pass)
|
|
21
|
+
空集 → Skip;全 Skip → exit 3;Unknown → exit 3
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`bool(Verdict.UNKNOWN)` 会直接抛异常——不允许 `if verdict:` 把它当假。
|
|
25
|
+
|
|
26
|
+
**2. 判定集合与显示截断分离**
|
|
27
|
+
|
|
28
|
+
`--max-findings` 只影响打印。任何为了输出好看而做的截断,一旦进了判据,
|
|
29
|
+
就会把「截断」读成「漏报」——这是实测踩过的坑。
|
|
30
|
+
|
|
31
|
+
**3. 基线只能显式扩张**
|
|
32
|
+
|
|
33
|
+
`baseline-write` 遇「纯增长」(一条没修、只是账单变长)拒绝写入;
|
|
34
|
+
基线里有、当下不再命中的键是「过期账单」,默认判红。
|
|
35
|
+
|
|
36
|
+
## 快速开始
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
python -m govrule run --rules rules --root G:/repos/allin-governance
|
|
40
|
+
python -m govrule list --rules rules
|
|
41
|
+
python -m govrule baseline-write --rules rules --root . --out baseline.txt --reason "冻结存量"
|
|
42
|
+
python -m govrule run --rules rules --root . --baseline baseline.txt
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
退出码:`0` 干净 · `1` 有违规 · `2` 用法错 · `3` 不完整(Unknown / 全 Skip)。
|
|
46
|
+
|
|
47
|
+
## 规则长什么样
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
rule g01.dead-root
|
|
51
|
+
code F-DEAD-ROOT
|
|
52
|
+
scope repo "**/*" exclude ["**/.venv*/**"]
|
|
53
|
+
select each file
|
|
54
|
+
extract text-lines(comments)
|
|
55
|
+
where matches(line, /(?<![A-Za-z0-9_])[A-Za-z]:[\\\/][A-Za-z0-9_.~]/) and is-dead(line)
|
|
56
|
+
assert count == 0
|
|
57
|
+
evidence cite=line.span expected="仓内相对路径或盘符变量" found=line.text
|
|
58
|
+
severity blocking
|
|
59
|
+
applies platforms=[nt, posix]
|
|
60
|
+
|
|
61
|
+
exempt url when matches(line, /:\/\//)
|
|
62
|
+
exempt doc when matches(path, /\.(md|html?)$/i) severity warn
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
子句只有九个:`scope` / `select` / `extract` / `where` / `assert` / `evidence` /
|
|
66
|
+
`severity` / `applies` / `exempt`。没有循环、没有递归、没有函数定义——
|
|
67
|
+
**少不是未完成,是判据**:非图灵完备换来的是「规则不可能挂死」「判据可穷举」「解释器可零依赖」。
|
|
68
|
+
|
|
69
|
+
## 内建
|
|
70
|
+
|
|
71
|
+
| 名称 | 语义 |
|
|
72
|
+
|---|---|
|
|
73
|
+
| `text-lines(comments, fences)` | 逐行抽取;可选剔除注释行 / 围栏块 |
|
|
74
|
+
| `filename()` | 按文件名抽取 |
|
|
75
|
+
| `file-meta()` | 按文件元数据抽取(`line.size`) |
|
|
76
|
+
| `matches(x, /re/)` | 正则匹配;`/.../i` 大小写不敏感 |
|
|
77
|
+
| `is-dead(text)` | 行内盘符路径的**父目录不存在** → true |
|
|
78
|
+
| `and` / `or` / `not` | 布尔组合 |
|
|
79
|
+
|
|
80
|
+
绑定:`line`(当前行文本)、`path`(相对路径)、`line.span`、`line.size`、`line.name`。
|
|
81
|
+
|
|
82
|
+
## 边界(不要误用)
|
|
83
|
+
|
|
84
|
+
- **不是通用策略引擎**:没有 Datalog、没有 join、没有跨文档聚合。
|
|
85
|
+
- **不做语义分析**:`text-lines` 是文本层,不建 AST。
|
|
86
|
+
- **`is-dead` 是本机视角**:在 A 机上判「死」的路径,在 B 机上可能存在。
|
|
87
|
+
- **未声明 scope = 不可判定**,不是「全部」。
|
|
88
|
+
|
|
89
|
+
## 许可
|
|
90
|
+
|
|
91
|
+
MIT-0。
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""AST 节点。
|
|
2
|
+
|
|
3
|
+
刻意只有 10 个节点:这门语言的全部表达力都在这 10 个里,没有循环、没有函数定义、
|
|
4
|
+
没有递归。**少不是未完成,是判据**(报告 §5.4:图灵完备换不到任何东西)。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Str:
|
|
14
|
+
value: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Int:
|
|
19
|
+
value: int
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Regex:
|
|
24
|
+
pattern: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Ident:
|
|
29
|
+
name: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Member:
|
|
34
|
+
obj: "Expr"
|
|
35
|
+
attr: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Call:
|
|
40
|
+
name: str
|
|
41
|
+
args: tuple["Expr", ...]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class BinOp:
|
|
46
|
+
op: str
|
|
47
|
+
left: "Expr"
|
|
48
|
+
right: "Expr"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Unary:
|
|
53
|
+
op: str
|
|
54
|
+
operand: "Expr"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
Expr = Str | Int | Regex | Ident | Member | Call | BinOp | Unary
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class Scope:
|
|
62
|
+
kind: str # 目前只有 "repo"
|
|
63
|
+
pattern: str
|
|
64
|
+
exclude: tuple[str, ...] = ()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class Assertion:
|
|
69
|
+
op: str # == <= >= < >
|
|
70
|
+
value: int
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Exemption:
|
|
75
|
+
"""一条豁免:命中后不再计入阻断,但必须被计数。
|
|
76
|
+
|
|
77
|
+
报告 §5.1 的 `exempt` 抽象:豁免必须**同宽于「谁有权改」**,并且分类可见。
|
|
78
|
+
severity=warn 表示「报告但不阻断」,用于文档类命中(与 g01 的 report-only 同构)。
|
|
79
|
+
"""
|
|
80
|
+
name: str
|
|
81
|
+
when: "Expr"
|
|
82
|
+
severity: str = "exempt" # exempt(不计入)/ warn(计入报告不计入阻断)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class Evidence:
|
|
87
|
+
cite: Expr | None = None
|
|
88
|
+
expected: str = ""
|
|
89
|
+
found: Expr | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class Rule:
|
|
94
|
+
rule_id: str
|
|
95
|
+
line: int
|
|
96
|
+
scope: Scope | None = None
|
|
97
|
+
select: str | None = None # "file" | "line"
|
|
98
|
+
extract: Call | None = None
|
|
99
|
+
where: Expr | None = None
|
|
100
|
+
assertion: Assertion | None = None
|
|
101
|
+
evidence: Evidence = field(default_factory=Evidence)
|
|
102
|
+
severity: str = "blocking"
|
|
103
|
+
platforms: tuple[str, ...] = ("nt", "posix")
|
|
104
|
+
code: str = "F-DEAD-ROOT" # 诊断码,必须是 diagnostics.CODES 里的闭集成员
|
|
105
|
+
exemptions: list[Exemption] = field(default_factory=list)
|
|
106
|
+
|
|
107
|
+
#: 报告里每一条规则都必须能回答「我到底看了什么」
|
|
108
|
+
def describe(self) -> str:
|
|
109
|
+
bits = [self.rule_id]
|
|
110
|
+
if self.scope:
|
|
111
|
+
bits.append(f"scope={self.scope.pattern}")
|
|
112
|
+
if self.extract:
|
|
113
|
+
bits.append(f"extract={self.extract.name}")
|
|
114
|
+
if self.assertion:
|
|
115
|
+
bits.append(f"assert count {self.assertion.op} {self.assertion.value}")
|
|
116
|
+
return " ".join(bits)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""基线棘轮:把「存量」冻结成文件,新增即拦,修好要销账。
|
|
2
|
+
|
|
3
|
+
抄的是三处工业实践里被验证过的同一条纪律(报告 §6.4):
|
|
4
|
+
- **双向拦截**(Go 的 API 文件):加了不记账要红,改了删了也要红;
|
|
5
|
+
- **纯增长拒绝**(g19 的双向棘轮):`旧 ⊂ 新` 说明一条都没修,文件只是胖了 —— 拒绝写入;
|
|
6
|
+
- **stale 判红**(同上):基线里有、当下不再命中的键,是「过期账单」,必须销账。
|
|
7
|
+
|
|
8
|
+
键只用 `规则|路径|行号`,不用内容摘要:**摘要键会让一次无害的格式化把全部存量判成新增**
|
|
9
|
+
(报告 §6.4 的「计数键 vs 摘要键」陷阱)。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import datetime as _dt
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
Key = tuple[str, str, int]
|
|
19
|
+
|
|
20
|
+
HEADER_PREFIX = "# "
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Baseline:
|
|
25
|
+
keys: set[Key] = field(default_factory=set)
|
|
26
|
+
meta: dict[str, str] = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def has_meta(self) -> bool:
|
|
30
|
+
return bool(self.meta.get("written") and self.meta.get("reason"))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load(path: Path) -> Baseline:
|
|
34
|
+
if not path.exists():
|
|
35
|
+
return Baseline()
|
|
36
|
+
keys: set[Key] = set()
|
|
37
|
+
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
38
|
+
line = raw.strip()
|
|
39
|
+
if not line or line.startswith("#"):
|
|
40
|
+
continue
|
|
41
|
+
parts = line.split("|")
|
|
42
|
+
if len(parts) != 3:
|
|
43
|
+
continue
|
|
44
|
+
rule, p, ln = parts
|
|
45
|
+
try:
|
|
46
|
+
keys.add((rule, p, int(ln)))
|
|
47
|
+
except ValueError:
|
|
48
|
+
continue
|
|
49
|
+
return Baseline(keys=keys, meta=_parse_header(path))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _parse_header(path: Path) -> dict[str, str]:
|
|
53
|
+
"""头部按 `key: value` 逐行解析(同一行多字段也支持)。"""
|
|
54
|
+
meta: dict[str, str] = {}
|
|
55
|
+
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
56
|
+
if not raw.startswith("#"):
|
|
57
|
+
continue
|
|
58
|
+
body = raw[1:].strip()
|
|
59
|
+
for field_name in ("written", "commit", "reason"):
|
|
60
|
+
idx = body.find(field_name + ":")
|
|
61
|
+
if idx < 0:
|
|
62
|
+
continue
|
|
63
|
+
rest = body[idx + len(field_name) + 1:].strip()
|
|
64
|
+
for stop in ("written:", "commit:", "reason:"):
|
|
65
|
+
cut = rest.find(" " + stop)
|
|
66
|
+
if cut > 0:
|
|
67
|
+
rest = rest[:cut]
|
|
68
|
+
meta[field_name] = rest.strip()
|
|
69
|
+
return meta
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def save(path: Path, keys: set[Key], reason: str, commit: str = "none") -> None:
|
|
73
|
+
stamp = _dt.datetime.now().astimezone().isoformat(timespec="seconds")
|
|
74
|
+
lines = [
|
|
75
|
+
f"# written: {stamp} commit: {commit} reason: {reason or '未填写'}",
|
|
76
|
+
f"# keys: {len(keys)}",
|
|
77
|
+
]
|
|
78
|
+
lines += [f"{r}|{p}|{ln}" for r, p, ln in sorted(keys)]
|
|
79
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class Diff:
|
|
85
|
+
new: set[Key] = field(default_factory=set) # 当下有、基线没有
|
|
86
|
+
fixed: set[Key] = field(default_factory=set) # 基线有、当下没有
|
|
87
|
+
common: set[Key] = field(default_factory=set)
|
|
88
|
+
old_count: int = 0
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def pure_growth(self) -> bool:
|
|
92
|
+
"""旧 ⊂ 新 且确实有新增:一条都没修,只是账单变长。
|
|
93
|
+
|
|
94
|
+
首次建立基线(old_count == 0)不算增长 —— 否则新仓第一天就写不进基线。
|
|
95
|
+
这是边界条件,不是特例:纯增长禁的是「扩张」,不是「建立」。
|
|
96
|
+
"""
|
|
97
|
+
return self.old_count > 0 and not self.fixed and bool(self.new)
|
|
98
|
+
|
|
99
|
+
def render(self) -> str:
|
|
100
|
+
return f"counts: fixed={len(self.fixed)} new={len(self.new)} common={len(self.common)}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def diff(baseline: Baseline, current: set[Key]) -> Diff:
|
|
104
|
+
return Diff(new=current - baseline.keys, fixed=baseline.keys - current,
|
|
105
|
+
common=current & baseline.keys, old_count=len(baseline.keys))
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""CLI:把规则集作用到一个仓,输出四值汇总与退出码。
|
|
2
|
+
|
|
3
|
+
退出码词汇(与 allin-governance 对齐,但把 Unknown 单列):
|
|
4
|
+
|
|
5
|
+
0 全部 Pass
|
|
6
|
+
1 至少一条 Fail
|
|
7
|
+
2 用法错误
|
|
8
|
+
3 Incomplete —— 有 Unknown,或全部 Skip(「没量到」不等于「没问题」)
|
|
9
|
+
|
|
10
|
+
`3` 不给 `1` 是刻意的:如果「没量到」和「量到不合格」共用一个码,CI 日志里就再也
|
|
11
|
+
分不出「要修代码」还是「要修判据」。这正是报告 §5.1 说 Unknown 不能被吞掉的理由。
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from . import baseline as bl_mod
|
|
22
|
+
from .diagnostics import DiagnosticError
|
|
23
|
+
from .evaluator import RuleResult, evaluate
|
|
24
|
+
from .facts import Repo
|
|
25
|
+
from .parser import parse
|
|
26
|
+
from .values import EXIT_BLOCKING, EXIT_INCOMPLETE, EXIT_OK, EXIT_USAGE, Verdict, combine_all, exit_code
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def load_rules(rules_dir: Path) -> list:
|
|
30
|
+
rules = []
|
|
31
|
+
for p in sorted(rules_dir.glob("*.rule")):
|
|
32
|
+
rules.extend(parse(p.read_text(encoding="utf-8"), str(p)))
|
|
33
|
+
return rules
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def run_rules(rules_dir: Path, root: Path, platform: str = "nt") -> list[RuleResult]:
|
|
37
|
+
rules = load_rules(rules_dir)
|
|
38
|
+
repo = Repo(root)
|
|
39
|
+
return [evaluate(r, repo, platform) for r in rules]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _keys(results: list[RuleResult]) -> set[tuple[str, str, int]]:
|
|
43
|
+
return {(r.rule_id, f.path, f.line) for r in results for f in r.findings}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def aggregate(results: list[RuleResult]) -> tuple[Verdict, int]:
|
|
47
|
+
verdict = combine_all([r.verdict for r in results])
|
|
48
|
+
if all(r.verdict is Verdict.SKIP for r in results) and results:
|
|
49
|
+
return Verdict.SKIP, EXIT_INCOMPLETE
|
|
50
|
+
return verdict, exit_code(verdict)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def main(argv: list[str] | None = None) -> int:
|
|
54
|
+
ap = argparse.ArgumentParser(prog="govrule", description="治理规则 DSL(M0 子集)")
|
|
55
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
56
|
+
|
|
57
|
+
run = sub.add_parser("run", help="跑一个仓")
|
|
58
|
+
run.add_argument("--rules", required=True, type=Path)
|
|
59
|
+
run.add_argument("--root", required=True, type=Path)
|
|
60
|
+
run.add_argument("--platform", default="nt", choices=["nt", "posix"])
|
|
61
|
+
run.add_argument("--json", action="store_true")
|
|
62
|
+
run.add_argument("--quiet", action="store_true", help="只打汇总行")
|
|
63
|
+
run.add_argument("--max-findings", type=int, default=50, help="仅影响显示,不影响判定与退出码")
|
|
64
|
+
run.add_argument("--baseline", type=Path, help="基线文件:命中的存量不阻断,新增即拦")
|
|
65
|
+
run.add_argument("--pass-on-stale", action="store_true", help="允许过期账单通过(CI 下会被拒绝)")
|
|
66
|
+
run.add_argument("--ci", action="store_true", help="CI 模式:人手开关一律 exit 2")
|
|
67
|
+
|
|
68
|
+
bw = sub.add_parser("baseline-write", help="把当下命中写成基线(纯增长会被拒绝)")
|
|
69
|
+
bw.add_argument("--rules", required=True, type=Path)
|
|
70
|
+
bw.add_argument("--root", required=True, type=Path)
|
|
71
|
+
bw.add_argument("--out", required=True, type=Path)
|
|
72
|
+
bw.add_argument("--reason", required=True)
|
|
73
|
+
bw.add_argument("--allow-growth", action="store_true")
|
|
74
|
+
bw.add_argument("--ci", action="store_true")
|
|
75
|
+
bw.add_argument("--platform", default="nt", choices=["nt", "posix"])
|
|
76
|
+
|
|
77
|
+
lst = sub.add_parser("list", help="列出规则与它们声称的判定域")
|
|
78
|
+
lst.add_argument("--rules", required=True, type=Path)
|
|
79
|
+
|
|
80
|
+
args = ap.parse_args(argv)
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
if args.cmd == "baseline-write":
|
|
84
|
+
if args.ci and args.allow_growth:
|
|
85
|
+
print("CI 下不允许 --allow-growth(人手开关不能进无人值守)", file=sys.stderr)
|
|
86
|
+
return EXIT_USAGE
|
|
87
|
+
results = run_rules(args.rules, args.root, args.platform)
|
|
88
|
+
cur = _keys(results)
|
|
89
|
+
old = bl_mod.load(args.out)
|
|
90
|
+
d = bl_mod.diff(old, cur)
|
|
91
|
+
if d.pure_growth and not args.allow_growth:
|
|
92
|
+
print(f"拒绝写入:纯增长(fixed=0, new={len(d.new)})", file=sys.stderr)
|
|
93
|
+
print(" 「一条都没修,只是账单变长」——要写必须显式 --allow-growth", file=sys.stderr)
|
|
94
|
+
print(" " + d.render(), file=sys.stderr)
|
|
95
|
+
return EXIT_BLOCKING
|
|
96
|
+
bl_mod.save(args.out, cur, args.reason)
|
|
97
|
+
print(f"written {len(cur)} key(s) -> {args.out}")
|
|
98
|
+
print(" " + d.render())
|
|
99
|
+
return EXIT_OK
|
|
100
|
+
|
|
101
|
+
if args.cmd == "list":
|
|
102
|
+
for r in load_rules(args.rules):
|
|
103
|
+
print(f"{r.describe()} platforms={','.join(r.platforms)}")
|
|
104
|
+
return EXIT_OK
|
|
105
|
+
results = run_rules(args.rules, args.root, args.platform)
|
|
106
|
+
except DiagnosticError as e:
|
|
107
|
+
print(e.render_all(), file=sys.stderr)
|
|
108
|
+
return EXIT_USAGE
|
|
109
|
+
|
|
110
|
+
stale_note = ""
|
|
111
|
+
if args.baseline:
|
|
112
|
+
if args.ci and args.pass_on_stale:
|
|
113
|
+
print("CI 下不允许 --pass-on-stale", file=sys.stderr)
|
|
114
|
+
return EXIT_USAGE
|
|
115
|
+
base = bl_mod.load(args.baseline)
|
|
116
|
+
cur = _keys(results)
|
|
117
|
+
d = bl_mod.diff(base, cur)
|
|
118
|
+
if d.fixed:
|
|
119
|
+
print(f"baseline: -fixed {len(d.fixed)}")
|
|
120
|
+
if d.new:
|
|
121
|
+
print(f"baseline: +new {len(d.new)}")
|
|
122
|
+
for r in results:
|
|
123
|
+
r.findings = [f for f in r.findings if (r.rule_id, f.path, f.line) not in base.keys]
|
|
124
|
+
if r.verdict is Verdict.FAIL and not r.findings:
|
|
125
|
+
r.verdict = Verdict.PASS
|
|
126
|
+
if d.fixed and not d.new:
|
|
127
|
+
stale_note = "stale keys are fixed; rewrite the baseline to shrink it"
|
|
128
|
+
if d.fixed and args.pass_on_stale and not args.ci:
|
|
129
|
+
stale_note += " (pass-on-stale)"
|
|
130
|
+
|
|
131
|
+
verdict, code = aggregate(results)
|
|
132
|
+
|
|
133
|
+
if args.baseline and d.fixed and not args.pass_on_stale:
|
|
134
|
+
print(f"baseline stale: {len(d.fixed)} key(s) no longer occur -> exit 1(过期账单必须销账)",
|
|
135
|
+
file=sys.stderr)
|
|
136
|
+
code = EXIT_BLOCKING
|
|
137
|
+
|
|
138
|
+
if args.json:
|
|
139
|
+
print(json.dumps({
|
|
140
|
+
"root": str(args.root),
|
|
141
|
+
"platform": args.platform,
|
|
142
|
+
"verdict": verdict.value,
|
|
143
|
+
"exit": code,
|
|
144
|
+
"rules": [
|
|
145
|
+
{
|
|
146
|
+
"rule": r.rule_id,
|
|
147
|
+
"verdict": r.verdict.value,
|
|
148
|
+
"scanned": r.scanned,
|
|
149
|
+
"matched": r.matched,
|
|
150
|
+
"findings": [f.render() for f in r.findings],
|
|
151
|
+
"note": r.note,
|
|
152
|
+
}
|
|
153
|
+
for r in results
|
|
154
|
+
],
|
|
155
|
+
}, ensure_ascii=False, indent=2))
|
|
156
|
+
return code
|
|
157
|
+
|
|
158
|
+
for r in results:
|
|
159
|
+
print(r.summary())
|
|
160
|
+
if not args.quiet:
|
|
161
|
+
for f in r.findings[:args.max_findings]:
|
|
162
|
+
print(" " + f.render())
|
|
163
|
+
if len(r.findings) > args.max_findings:
|
|
164
|
+
print(f" ... 另有 {len(r.findings) - args.max_findings} 条未显示(判定与退出码仍按全量)")
|
|
165
|
+
if r.note:
|
|
166
|
+
print(" note: " + r.note)
|
|
167
|
+
total_scanned = sum(r.scanned for r in results)
|
|
168
|
+
total_findings = sum(len(r.findings) for r in results)
|
|
169
|
+
print(f"== {args.root} | {len(results)} rule(s) | scanned {total_scanned} | "
|
|
170
|
+
f"blocking {total_findings} | verdict {verdict.value} | exit {code}")
|
|
171
|
+
return code
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
if __name__ == "__main__":
|
|
175
|
+
raise SystemExit(main())
|