pystepmap-core 0.1.0__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.
pystepmap/selfcheck.py ADDED
@@ -0,0 +1,112 @@
1
+ """图自检:走不到的节点、没有出路的节点,以及目标不明(unresolved)/ 猜测的调用数量和分类。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass, field
7
+
8
+ from pystepmap.config import NOISE_RECEIVERS
9
+ from pystepmap.model import FunctionGraph, SelfCheck
10
+ from pystepmap.resolve import BUILTIN_METHOD_NAMES, COMMON_NAMES
11
+
12
+
13
+ def _reachable(fg: FunctionGraph) -> set[str]:
14
+ out: dict[str, list[str]] = {}
15
+ for e in fg.edges:
16
+ out.setdefault(e.src, []).append(e.dst)
17
+ seen = {n.id for n in fg.nodes if n.type == "start"}
18
+ stack = list(seen)
19
+ while stack:
20
+ for dst in out.get(stack.pop(), []):
21
+ if dst not in seen:
22
+ seen.add(dst)
23
+ stack.append(dst)
24
+ return seen
25
+
26
+
27
+ def _closing(fg: FunctionGraph) -> set[str]:
28
+ """结局、没被捕获的异常进入的 finally 体里的节点(从结局出发的 finally 连线、raise 连线的终点往后能走到的)。
29
+ try / except / else 没有正常出口时,出了 finally 体函数就结束,finally 体最后一个节点没有出边:不算没有出路。"""
30
+ ends = {n.id for n in fg.nodes if n.type == "end"}
31
+ out: dict[str, list[str]] = {}
32
+ for e in fg.edges:
33
+ out.setdefault(e.src, []).append(e.dst)
34
+ seen = {e.dst for e in fg.edges if e.kind == "raise" or (e.kind == "finally" and e.src in ends)}
35
+ stack = list(seen)
36
+ while stack:
37
+ for dst in out.get(stack.pop(), []):
38
+ if dst not in seen:
39
+ seen.add(dst)
40
+ stack.append(dst)
41
+ return seen
42
+
43
+
44
+ def run_selfcheck(functions: dict[str, FunctionGraph], skipped_files: list[tuple[str, str]]) -> SelfCheck:
45
+ unreachable: list[tuple[str, str]] = []
46
+ dead_ends: list[tuple[str, str]] = []
47
+ unresolved = guessed = 0
48
+ for key, fg in functions.items():
49
+ unresolved += len(fg.unresolved) # 函数体里所有无法判断目标的调用(每个函数按 (行, 名字) 去重),不只是留在节点上的
50
+ reach = _reachable(fg)
51
+ has_out = {e.src for e in fg.edges}
52
+ closing = _closing(fg)
53
+ for n in fg.nodes:
54
+ implicit_exc = n.type == "end" and n.line == 0 and n.end_kind == "exception"
55
+ if n.id not in reach and not implicit_exc:
56
+ unreachable.append((key, n.id))
57
+ if n.type != "end" and n.id not in has_out and n.id not in closing:
58
+ dead_ends.append((key, n.id))
59
+ for ref in n.calls:
60
+ guessed += ref.resolution == "guessed"
61
+ return SelfCheck(unreachable=sorted(unreachable), dead_ends=sorted(dead_ends),
62
+ unresolved_calls=unresolved, guessed_calls=guessed, skipped_files=list(skipped_files))
63
+
64
+
65
+ # ---------- 目标不明的调用:分类 ----------
66
+
67
+
68
+ @dataclass
69
+ class UnresolvedSite:
70
+ """一处无法判断目标的调用。"""
71
+
72
+ key: str # 所在函数的 key
73
+ file: str
74
+ line: int
75
+ name: str # 显示名,如 "svc.render"、"load_raw"
76
+
77
+
78
+ @dataclass
79
+ class UnresolvedGroups:
80
+ """目标不明的调用按"有没有可能落在项目代码上"分的四类。"""
81
+
82
+ blind: list[UnresolvedSite] = field(default_factory=list) # 名字在项目里有定义:可能就是项目内的调用,是真盲点
83
+ common: list[UnresolvedSite] = field(default_factory=list) # 名字太常见(get、append……):项目里虽有同名定义,多半是字典、列表的方法
84
+ outside: list[UnresolvedSite] = field(default_factory=list) # 项目里没有这个名字:第三方、标准库、内置,解析不了也不必解析
85
+ logs: list[UnresolvedSite] = field(default_factory=list) # 日志
86
+
87
+
88
+ def classify_unresolved(functions: dict[str, FunctionGraph],
89
+ noise_receivers: Sequence[str] = NOISE_RECEIVERS) -> UnresolvedGroups:
90
+ """把每处目标不明的调用分成 blind / common / outside / logs(四类之和等于 SelfCheck.unresolved_calls)。
91
+
92
+ 判断只看显示名:接收者是日志的算 logs;被调的名字(最后一段)项目里没有同名的函数或方法定义就算 outside
93
+ (第三方、标准库,不可能落在项目代码上);名字在引擎有意不推测的两份名单里(COMMON_NAMES、
94
+ BUILTIN_METHOD_NAMES:get、append 这些)就算 common,项目里碰巧有同名定义也多半是字典、列表的方法;
95
+ 剩下的才是 blind——真正可能落在项目代码上、值得逐条看的。
96
+ """
97
+ defined = {fg.qualname.rsplit(".", 1)[-1] for fg in functions.values()}
98
+ noise = set(noise_receivers)
99
+ groups = UnresolvedGroups()
100
+ for key, fg in functions.items():
101
+ for u in fg.unresolved:
102
+ site = UnresolvedSite(key, fg.file, u.line, u.name)
103
+ receiver, _, called = u.name.rpartition(".")
104
+ if receiver in noise:
105
+ groups.logs.append(site)
106
+ elif called not in defined:
107
+ groups.outside.append(site)
108
+ elif called in COMMON_NAMES or called in BUILTIN_METHOD_NAMES:
109
+ groups.common.append(site)
110
+ else:
111
+ groups.blind.append(site)
112
+ return groups
pystepmap/stale.py ADDED
@@ -0,0 +1,49 @@
1
+ """图是否过期:按出图时同样的规则重新算项目里每个 .py 的指纹,和图里记的 file_hashes 比对。只读,不解析源码。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from .config import ProjectConfig
10
+ from .index import iter_source_files
11
+
12
+
13
+ def current_hashes(root: Path, config: ProjectConfig) -> dict[str, str]:
14
+ """相对路径 → 文件内容的 sha256,按路径排序;和图的 file_hashes 同口径:同样的排除目录、同样不读的路径(指到项目
15
+ 之外的链接、FIFO 等),读不出来的文件(失效的链接、没有权限)不在里面,解析不了的照样在。
16
+ 和分析一样不报错:root 不存在(或不是目录)时得到 {},读不了的文件直接不在结果里——拿去和记录比对,会显示成
17
+ "删掉了"。要区分"没法检查"的调用方(平台的过期检查)先自己检查 root 是不是一个目录,再来比对。"""
18
+ out: dict[str, str] = {}
19
+ for rel, path, _ in iter_source_files(root, config):
20
+ if path is None:
21
+ continue
22
+ try:
23
+ raw = path.read_bytes()
24
+ except OSError:
25
+ continue
26
+ out[rel] = hashlib.sha256(raw).hexdigest()
27
+ return dict(sorted(out.items()))
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class FileChanges:
32
+ """两份指纹的差别,各自按路径排序。"""
33
+
34
+ changed: list[str] # 两边都有、内容变了
35
+ added: list[str] # 只在现在有
36
+ removed: list[str] # 只在记录里有
37
+
38
+ @property
39
+ def any(self) -> bool:
40
+ return bool(self.changed or self.added or self.removed)
41
+
42
+
43
+ def compare_hashes(recorded: dict[str, str], current: dict[str, str]) -> FileChanges:
44
+ """recorded:图里记的指纹;current:现在算出来的(current_hashes)。"""
45
+ return FileChanges(
46
+ changed=sorted(p for p in recorded.keys() & current.keys() if recorded[p] != current[p]),
47
+ added=sorted(current.keys() - recorded.keys()),
48
+ removed=sorted(recorded.keys() - current.keys()),
49
+ )
pystepmap/titles.py ADDED
@@ -0,0 +1,65 @@
1
+ """节点标题的辅助:取语句上方的注释、清理要显示的文字。"""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def comment_above(lines: list[str], lineno: int) -> str:
7
+ """语句(从 1 起的行号 lineno)正上方连续注释块的第一行,去掉 # 和首尾空白;没有则 ""。
8
+
9
+ 注释块与语句之间隔了空行或代码就不算;块里只有 # 的空注释行跳过。
10
+ """
11
+ block: list[str] = []
12
+ i = lineno - 2
13
+ while 0 <= i < len(lines):
14
+ text = lines[i].strip()
15
+ if not text.startswith("#"):
16
+ break
17
+ block.append(text.lstrip("#").strip())
18
+ i -= 1
19
+ for text in reversed(block): # 从上往下第一条非空注释
20
+ if text:
21
+ return text
22
+ return ""
23
+
24
+
25
+ FULL_LIMIT = 2000 # 完整形式(Node.title_full 等)的上限:异常长的文档注释、源码不会把图撑大
26
+
27
+
28
+ def cut(s: str, limit: int) -> str:
29
+ """超过 limit 时截断,末尾加 "…"(总长为 limit)。"""
30
+ return s[: limit - 1] + "…" if len(s) > limit else s
31
+
32
+
33
+ def clean(text: str, limit: int = 0) -> str:
34
+ """合并空白、去掉反引号和 **;limit 大于 0 且超长时截断,末尾加 "…"(总长为 limit)。"""
35
+ s = " ".join(text.replace("`", "").replace("**", "").split())
36
+ return cut(s, limit) if limit else s
37
+
38
+
39
+ def clean_full(text: str, limit: int) -> str:
40
+ """clean(text, limit) 截断了时的完整形式:同样清理,不按 limit 截断(最长 FULL_LIMIT);没截断时为 ""。"""
41
+ s = clean(text)
42
+ return cut(s, FULL_LIMIT) if len(s) > limit else ""
43
+
44
+
45
+ _OPEN, _CLOSE = "((「『《[【{", "))」』》]】}"
46
+ SENTENCE_MIN = 4 # 第一句至少这么长才在那里断("注:……" 这样的开头不算一句)
47
+
48
+
49
+ def first_sentence(text: str) -> str:
50
+ """文档注释第一行的第一句:到第一个句号(。)、分号(;;)、破折号(——)或后面跟着空白的英文句号为止,不含它;
51
+ 括号、引号里面的不算,断出来不到 SENTENCE_MIN 个字的不算。没有这些标点时就是整行。图上节点的标题用它(整行在
52
+ title_full 里,悬停能看到)。"""
53
+ depth = 0
54
+ for i, ch in enumerate(text):
55
+ if ch in _OPEN:
56
+ depth += 1
57
+ elif ch in _CLOSE:
58
+ depth = max(0, depth - 1)
59
+ elif depth == 0 and i >= SENTENCE_MIN and (
60
+ ch in "。;;" or text.startswith("——", i)
61
+ or (ch == "." and (i + 1 == len(text) or text[i + 1].isspace()))):
62
+ head = text[:i].rstrip()
63
+ if len(head) >= SENTENCE_MIN:
64
+ return head
65
+ return text