122 lines
4.7 KiB
Python
122 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
||
"""从 rule/**/*.list 生成同目录同名的 .yaml(mihomo classical 规则集)。
|
||
|
||
.list 是唯一需要手工维护的文件,语法以 Surge / Loon 为准。
|
||
生成 .yaml 时自动转换 mihomo 写法不同的规则:
|
||
PROTOCOL,UDP / PROTOCOL,TCP -> NETWORK,UDP / NETWORK,TCP
|
||
DEST-PORT,x -> DST-PORT,x
|
||
PROCESS-NAME 含 * 或 ? -> PROCESS-NAME-WILDCARD(mihomo 的 PROCESS-NAME 是精确匹配)
|
||
|
||
用法:
|
||
python3 scripts/build_rules.py 检查 .list 并生成 / 更新全部 .yaml
|
||
python3 scripts/build_rules.py --check 只检查不写入;.list 有问题或 .yaml 过期时退出码为 1
|
||
"""
|
||
|
||
import argparse
|
||
import pathlib
|
||
import re
|
||
import sys
|
||
|
||
RULE_DIR = pathlib.Path(__file__).resolve().parent.parent / "rule"
|
||
|
||
# 规则集里允许出现的规则类型(三个客户端都支持,或能转换成 mihomo 写法)
|
||
SUPPORTED_TYPES = {
|
||
"DOMAIN", "DOMAIN-SUFFIX", "DOMAIN-KEYWORD", "DOMAIN-WILDCARD",
|
||
"IP-CIDR", "IP-CIDR6", "IP-ASN", "GEOIP",
|
||
"PROCESS-NAME", "DEST-PORT", "PROTOCOL",
|
||
"AND", "OR", "NOT",
|
||
}
|
||
IP_TYPES = {"IP-CIDR", "IP-CIDR6", "IP-ASN"}
|
||
|
||
|
||
def to_mihomo(rule: str) -> str:
|
||
rule = re.sub(r"\bPROTOCOL,(UDP|TCP)\b", r"NETWORK,\1", rule)
|
||
rule = re.sub(r"\bDEST-PORT,", "DST-PORT,", rule)
|
||
rule = re.sub(r"^PROCESS-NAME,([^,]*[*?][^,]*)$", r"PROCESS-NAME-WILDCARD,\1", rule)
|
||
return rule
|
||
|
||
|
||
def lint(path: pathlib.Path, text: str) -> list[str]:
|
||
errors = []
|
||
rel = path.relative_to(RULE_DIR.parent)
|
||
if text and not text.endswith("\n"):
|
||
errors.append(f"{rel}: 文件末尾缺少换行")
|
||
seen = {}
|
||
for no, raw in enumerate(text.splitlines(), 1):
|
||
line = raw.strip()
|
||
if not line or line.startswith("#"):
|
||
continue
|
||
where = f"{rel}:{no}"
|
||
if re.search(r"\s", line):
|
||
errors.append(f"{where}: 规则中有空白字符 → {line}")
|
||
rule_type = line.split(",", 1)[0]
|
||
if rule_type not in SUPPORTED_TYPES:
|
||
errors.append(f"{where}: 不支持的规则类型 {rule_type}")
|
||
if rule_type in IP_TYPES and not line.endswith(",no-resolve"):
|
||
errors.append(f"{where}: IP 规则缺少 no-resolve(会让未命中的域名触发本地 DNS 解析)")
|
||
if rule_type.startswith("DOMAIN") and line.endswith(",no-resolve"):
|
||
errors.append(f"{where}: 域名规则不需要 no-resolve")
|
||
if "PROTOCOL," in line and not re.search(r"PROTOCOL,(UDP|TCP)\b", line):
|
||
errors.append(f"{where}: mihomo 只能转换 PROTOCOL,UDP / PROTOCOL,TCP")
|
||
if line in seen:
|
||
errors.append(f"{where}: 与第 {seen[line]} 行重复")
|
||
seen.setdefault(line, no)
|
||
return errors
|
||
|
||
|
||
def render_yaml(list_path: pathlib.Path, text: str) -> str:
|
||
rel = list_path.relative_to(RULE_DIR.parent)
|
||
out = [f"# 由 scripts/build_rules.py 从 {rel} 生成,请修改 .list 后重新生成", "payload:"]
|
||
for raw in text.splitlines():
|
||
line = raw.strip()
|
||
if not line:
|
||
continue
|
||
if line.startswith("#"):
|
||
out.append(f" {line}")
|
||
else:
|
||
out.append(f" - {to_mihomo(line)}")
|
||
return "\n".join(out) + "\n"
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
parser.add_argument("--check", action="store_true", help="只检查不写入")
|
||
args = parser.parse_args()
|
||
|
||
errors, stale = [], []
|
||
lists = sorted(RULE_DIR.rglob("*.list"))
|
||
for list_path in lists:
|
||
text = list_path.read_text(encoding="utf-8")
|
||
errors += lint(list_path, text)
|
||
yaml_path = list_path.with_suffix(".yaml")
|
||
expected = render_yaml(list_path, text)
|
||
current = yaml_path.read_text(encoding="utf-8") if yaml_path.exists() else None
|
||
if current != expected:
|
||
stale.append((yaml_path, expected))
|
||
|
||
for yaml_path in sorted(RULE_DIR.rglob("*.yaml")):
|
||
if not yaml_path.with_suffix(".list").exists():
|
||
errors.append(f"{yaml_path.relative_to(RULE_DIR.parent)}: 没有对应的 .list")
|
||
|
||
for err in errors:
|
||
print(f"错误 {err}", file=sys.stderr)
|
||
if errors:
|
||
return 1
|
||
|
||
if args.check:
|
||
for yaml_path, _ in stale:
|
||
print(f"过期 {yaml_path.relative_to(RULE_DIR.parent)}", file=sys.stderr)
|
||
if not stale:
|
||
print(f"通过 {len(lists)} 个规则集")
|
||
return 1 if stale else 0
|
||
|
||
for yaml_path, expected in stale:
|
||
yaml_path.write_text(expected, encoding="utf-8")
|
||
print(f"生成 {yaml_path.relative_to(RULE_DIR.parent)}")
|
||
print(f"完成 {len(lists)} 个规则集,更新 {len(stale)} 个 .yaml")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|