feat: field_localization

This commit is contained in:
Jelly_Candy committed 2026-11-21 22:33:46 +08:00
1 parent 1bc0e176f6
commit 0843c6ade0
11 files changed
+1073 -13

No files matched your search

+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
from pathlib import Path
from collections import defaultdict
import argparse
import re
ROOT = Path(__file__).resolve().parent.parent
EXCLUDED_DIRS = {
".git",
".xmake",
"build",
"install",
"log",
"__pycache__",
".cache",
}
EXCLUDED_FILES = {
"compile_commands.json",
"CMakeCache.txt",
}
# 匹配 Linux 绝对路径,避免匹配 URL 中的 //
PATH_PATTERN = re.compile(
r'(?<![A-Za-z0-9_./-])'
r'/(?:[A-Za-z0-9._~+-]+(?:/[A-Za-z0-9._~+-]*)*)'
)
def classify(path):
if path.startswith("/opt/ros/"):
return "ROS 安装路径"
if path.startswith(("/home/", "/root/")):
return "用户目录路径"
if path.startswith(("/usr/", "/bin/", "/sbin/", "/lib/")):
return "系统路径"
if path.startswith(("/tmp/", "/var/tmp/")):
return "临时目录路径"
if path.startswith("/"):
return "其他绝对路径"
return "其他"
def should_skip(path):
if any(part in EXCLUDED_DIRS for part in path.parts):
return True
if path.name in EXCLUDED_FILES:
return True
return False
def main():
parser = argparse.ArgumentParser(
description="Scan repository for hardcoded absolute paths."
)
parser.add_argument(
"--max-lines",
type=int,
default=100,
help="Maximum findings to display (default: 100)"
)
parser.add_argument(
"--all",
action="store_true",
help="Show all findings without the display limit"
)
args = parser.parse_args()
findings = []
category_counts = defaultdict(int)
file_count = 0
for file in sorted(ROOT.rglob("*")):
if not file.is_file() or should_skip(file.relative_to(ROOT)):
continue
try:
content = file.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
continue
# 跳过二进制文件
if "\0" in content:
continue
file_count += 1
relative = file.relative_to(ROOT)
for line_no, line in enumerate(content.splitlines(), 1):
paths = list(dict.fromkeys(PATH_PATTERN.findall(line)))
for path in paths:
category = classify(path)
category_counts[category] += 1
excerpt = " ".join(line.strip().split())
if len(excerpt) > 140:
excerpt = excerpt[:137] + "..."
findings.append({
"file": str(relative),
"line": line_no,
"path": path,
"category": category,
"excerpt": excerpt,
})
print("=" * 72)
print("仓库绝对路径审计报告")
print("=" * 72)
print(f"仓库:{ROOT}")
print(f"扫描文件数:{file_count}")
print(f"发现路径数:{len(findings)}")
print()
print("[分类统计]")
for category, count in sorted(category_counts.items()):
print(f" {category:<18} {count:>5}")
print()
limit = len(findings) if args.all else max(0, args.max_lines)
shown = findings[:limit]
current_file = None
for item in shown:
if item["file"] != current_file:
current_file = item["file"]
print(f"\n[{current_file}]")
print(
f" L{item['line']:<5} "
f"[{item['category']}] {item['path']}"
)
print(f" {item['excerpt']}")
remaining = len(findings) - len(shown)
print("\n" + "=" * 72)
print(f"已显示:{len(shown)} / {len(findings)}")
if remaining:
print(f"其余隐藏:{remaining} 条")
print("需要完整报告时执行:python3 tools/audit_absolute_paths.py --all")
print("=" * 72)
if __name__ == "__main__":
main()