|
| 1 | +"""Company 에 없는 이름을 부르는 자리를 찾는다. |
| 2 | +
|
| 3 | +2026-07-28 하루에 같은 결함을 열두 번 만났다. 공개 계약을 좁히면서 옛 이름을 부르던 |
| 4 | +소비처를 같이 안 고쳤고, `getattr(company, "X", None)` 과 넓은 except 가 그 실패를 지웠다. |
| 5 | +예외가 안 나니 어느 게이트도 못 봤고, 사용자 표면 넷이 통째로 죽은 채 초록불이었다. |
| 6 | +
|
| 7 | + - `dartlab report` 가 빈 제목 네 개만 출력 (BS · IS · CF · ratios · insights) |
| 8 | + - 재무 차트 다섯이 매번 데이터 없음 예외 (IS · BS · CF · dividend) |
| 9 | + - 차트 spec 생성기 여덟 중 일곱이 늘 None (annual · ratioSeries · insights · dividend) |
| 10 | + - DCF 밸류에이션 도구가 모든 회사에서 실패 (finance · sharesOutstanding · currentPrice) |
| 11 | +
|
| 12 | +그래서 이 감사를 둔다. 회귀가 아니라 *이 계열의 재유입*을 막는 것이 목적이다. |
| 13 | +
|
| 14 | +판정 기준은 이름 하나다. `company.X` 또는 `getattr(company, "X", ...)` 로 부르는 X 가 |
| 15 | +Company 정의 어디에도 없으면 위반이다. 표면은 provider company 파일에서 정적으로 모은다 |
| 16 | +(클래스 메서드 · 클래스 변수 · `self.X =` 대입). 실행이 필요 없어 데이터 없이도 돈다. |
| 17 | +
|
| 18 | +사용법:: |
| 19 | +
|
| 20 | + python tests/audit/deadCompanyAccessor.py # 신규 위반만 차단 |
| 21 | + python tests/audit/deadCompanyAccessor.py --json # 기계 판독 |
| 22 | + python tests/audit/deadCompanyAccessor.py --update # 현재 상태를 원장으로 저장 |
| 23 | +
|
| 24 | +종료 코드: 0 신규 위반 없음 / 1 신규 위반 발견. |
| 25 | +""" |
| 26 | + |
| 27 | +from __future__ import annotations |
| 28 | + |
| 29 | +import argparse |
| 30 | +import ast |
| 31 | +import json |
| 32 | +import sys |
| 33 | +from pathlib import Path |
| 34 | + |
| 35 | +_ROOT = Path(__file__).resolve().parents[2] |
| 36 | +_SRC = _ROOT / "src" / "dartlab" |
| 37 | +_BASELINE = _ROOT / "tests" / "audit" / "_baselines" / "deadCompanyAccessor.json" |
| 38 | + |
| 39 | +# Company 표면을 정의하는 파일. 여기서 이름을 모은다. |
| 40 | +_SURFACE_FILES = ( |
| 41 | + "company.py", |
| 42 | + "providers/dart/company.py", |
| 43 | + "providers/edgar/company.py", |
| 44 | +) |
| 45 | + |
| 46 | +# 표면 파일 밖에서 붙는 이름. 정적 수집이 못 보는 것만 최소로 둔다. |
| 47 | +_EXTRA_SURFACE = frozenset({"_cache", "_hintedKeys"}) |
| 48 | + |
| 49 | +# `company` / `comp` 라는 이름이 Company 가 아닌 자리. 여기서 나온 속성은 세지 않는다. |
| 50 | +_NON_COMPANY_ATTRS = frozenset( |
| 51 | + { |
| 52 | + "get", |
| 53 | + "setdefault", |
| 54 | + "values", |
| 55 | + "keys", |
| 56 | + "items", |
| 57 | + "exists", |
| 58 | + "glob", |
| 59 | + "company", |
| 60 | + } |
| 61 | +) |
| 62 | + |
| 63 | +_TARGET_VARS = frozenset({"company", "comp"}) |
| 64 | + |
| 65 | + |
| 66 | +def collectSurface() -> set[str]: |
| 67 | + """Company 가 실제로 갖는 이름 전수 (정적).""" |
| 68 | + names: set[str] = set(_EXTRA_SURFACE) |
| 69 | + for rel in _SURFACE_FILES: |
| 70 | + path = _SRC / rel |
| 71 | + if not path.exists(): |
| 72 | + continue |
| 73 | + tree = ast.parse(path.read_text(encoding="utf-8")) |
| 74 | + for node in ast.walk(tree): |
| 75 | + if isinstance(node, ast.ClassDef): |
| 76 | + for item in node.body: |
| 77 | + if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 78 | + names.add(item.name) |
| 79 | + elif isinstance(item, ast.Assign): |
| 80 | + names.update(t.id for t in item.targets if isinstance(t, ast.Name)) |
| 81 | + elif isinstance(node, ast.Assign): |
| 82 | + for target in node.targets: |
| 83 | + if isinstance(target, ast.Attribute) and _isSelf(target.value): |
| 84 | + names.add(target.attr) |
| 85 | + return names |
| 86 | + |
| 87 | + |
| 88 | +def _isSelf(node: ast.expr) -> bool: |
| 89 | + return isinstance(node, ast.Name) and node.id == "self" |
| 90 | + |
| 91 | + |
| 92 | +class _Visitor(ast.NodeVisitor): |
| 93 | + """`company.X` 와 `getattr(company, "X", ...)` 를 모은다.""" |
| 94 | + |
| 95 | + def __init__(self, rel: str, surface: set[str]) -> None: |
| 96 | + self.rel = rel |
| 97 | + self.surface = surface |
| 98 | + self.hits: list[tuple[str, str, int]] = [] |
| 99 | + |
| 100 | + def _record(self, attr: str, lineno: int) -> None: |
| 101 | + if attr.startswith("__") or attr in self.surface or attr in _NON_COMPANY_ATTRS: |
| 102 | + return |
| 103 | + self.hits.append((attr, self.rel, lineno)) |
| 104 | + |
| 105 | + def visit_Attribute(self, node: ast.Attribute) -> None: |
| 106 | + if isinstance(node.value, ast.Name) and node.value.id in _TARGET_VARS: |
| 107 | + self._record(node.attr, node.lineno) |
| 108 | + self.generic_visit(node) |
| 109 | + |
| 110 | + def visit_Call(self, node: ast.Call) -> None: |
| 111 | + func = node.func |
| 112 | + if isinstance(func, ast.Name) and func.id == "getattr" and len(node.args) >= 2: |
| 113 | + target, name = node.args[0], node.args[1] |
| 114 | + if ( |
| 115 | + isinstance(target, ast.Name) |
| 116 | + and target.id in _TARGET_VARS |
| 117 | + and isinstance(name, ast.Constant) |
| 118 | + and isinstance(name.value, str) |
| 119 | + ): |
| 120 | + self._record(name.value, node.lineno) |
| 121 | + self.generic_visit(node) |
| 122 | + |
| 123 | + |
| 124 | +def scan() -> list[dict[str, object]]: |
| 125 | + """전 소스에서 위반 후보를 모은다.""" |
| 126 | + surface = collectSurface() |
| 127 | + found: list[dict[str, object]] = [] |
| 128 | + for path in sorted(_SRC.rglob("*.py")): |
| 129 | + rel = path.relative_to(_SRC).as_posix() |
| 130 | + try: |
| 131 | + tree = ast.parse(path.read_text(encoding="utf-8")) |
| 132 | + except (SyntaxError, UnicodeDecodeError): |
| 133 | + continue |
| 134 | + visitor = _Visitor(rel, surface) |
| 135 | + visitor.visit(tree) |
| 136 | + for attr, where, lineno in visitor.hits: |
| 137 | + found.append({"attr": attr, "file": where, "line": lineno}) |
| 138 | + return found |
| 139 | + |
| 140 | + |
| 141 | +def _key(item: dict[str, object]) -> str: |
| 142 | + return f"{item['attr']}@{item['file']}" |
| 143 | + |
| 144 | + |
| 145 | +def loadBaseline() -> set[str]: |
| 146 | + if not _BASELINE.exists(): |
| 147 | + return set() |
| 148 | + data = json.loads(_BASELINE.read_text(encoding="utf-8")) |
| 149 | + return set(data.get("known", [])) |
| 150 | + |
| 151 | + |
| 152 | +def main(argv: list[str] | None = None) -> int: |
| 153 | + parser = argparse.ArgumentParser(description=__doc__) |
| 154 | + parser.add_argument("--json", action="store_true", help="기계 판독 출력") |
| 155 | + parser.add_argument("--update", action="store_true", help="현재 상태를 원장으로 저장") |
| 156 | + args = parser.parse_args(argv) |
| 157 | + |
| 158 | + found = scan() |
| 159 | + if args.update: |
| 160 | + _BASELINE.parent.mkdir(parents=True, exist_ok=True) |
| 161 | + payload = { |
| 162 | + "policy": "no_new_violations", |
| 163 | + "note": "Company 에 없는 이름을 부르는 자리. 신규 추가만 차단한다.", |
| 164 | + "known": sorted({_key(item) for item in found}), |
| 165 | + } |
| 166 | + _BASELINE.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") |
| 167 | + print(f"[dead-company-accessor] 원장 저장 {len(payload['known'])} 건 -> {_BASELINE}") |
| 168 | + return 0 |
| 169 | + |
| 170 | + baseline = loadBaseline() |
| 171 | + fresh = [item for item in found if _key(item) not in baseline] |
| 172 | + |
| 173 | + if args.json: |
| 174 | + print(json.dumps({"total": len(found), "new": fresh}, indent=2, ensure_ascii=False)) |
| 175 | + return 1 if fresh else 0 |
| 176 | + |
| 177 | + if fresh: |
| 178 | + print(f"[dead-company-accessor] 신규 위반 {len(fresh)} 건 (원장 {len(baseline)} 건)") |
| 179 | + for item in fresh: |
| 180 | + print(f" {item['file']}:{item['line']} company.{item['attr']}") |
| 181 | + print("\nCompany 에 없는 이름이다. 공개 계약(panel · analysis · capital 등)으로 부르거나,") |
| 182 | + print("정말 Company 가 아니면 변수 이름을 바꿔라. 오탐이면 --update 로 원장에 올린다.") |
| 183 | + return 1 |
| 184 | + |
| 185 | + print(f"[dead-company-accessor] OK. 신규 위반 0 (원장 {len(baseline)} 건 / 현재 {len(found)} 건).") |
| 186 | + return 0 |
| 187 | + |
| 188 | + |
| 189 | +if __name__ == "__main__": |
| 190 | + sys.exit(main()) |
0 commit comments