MCPcopy Create free account
hub / github.com/ParzivalHack/PySpector / run_pyspector

Function run_pyspector

tests/unit/test_false_positive_reductions.py:23–67  ·  view source on GitHub ↗

Write code to a temp file, run pyspector, return findings as list of dicts.

(code: str, *, filename: str = "sample_code.py", in_tests_dir: bool = False)

Source from the content-addressed store, hash-verified

21# ---------------------------------------------------------------------------
22
23def run_pyspector(code: str, *, filename: str = "sample_code.py", in_tests_dir: bool = False) -> list[dict]:
24 """Write code to a temp file, run pyspector, return findings as list of dicts."""
25 from pyspector._rust_core import run_scan
26 from pyspector.config import get_default_rules
27
28 rules_toml = get_default_rules()
29
30 with tempfile.TemporaryDirectory() as tmpdir:
31 if in_tests_dir:
32 subdir = os.path.join(tmpdir, "tests")
33 os.makedirs(subdir)
34 file_path = os.path.join(subdir, filename)
35 else:
36 file_path = os.path.join(tmpdir, filename)
37
38 Path(file_path).write_text(textwrap.dedent(code))
39
40 import ast as _ast, json as _json, warnings
41
42 with warnings.catch_warnings():
43 warnings.filterwarnings("ignore")
44 try:
45 tree = _ast.parse(Path(file_path).read_text())
46 import sys
47 # Use AstEncoder from cli
48 sys.path.insert(0, str(Path(__file__).parents[2] / "src"))
49 from pyspector.cli import AstEncoder
50 ast_json = _json.dumps(tree, cls=AstEncoder)
51 except Exception:
52 ast_json = "{}"
53
54 rel_path = os.path.basename(file_path) if not in_tests_dir else f"tests/{filename}"
55 python_files = [{"file_path": rel_path, "content": Path(file_path).read_text(), "ast_json": ast_json}]
56
57 results = run_scan(
58 tmpdir if not in_tests_dir else str(Path(tmpdir)),
59 rules_toml,
60 {"exclude": []},
61 python_files,
62 )
63
64 return [
65 {"rule_id": r.rule_id, "file_path": r.file_path, "line_number": r.line_number, "code": r.code}
66 for r in results
67 ]
68
69
70def findings_for_rule(code: str, rule_id: str, **kwargs) -> list[dict]:

Calls 1

get_default_rulesFunction · 0.90

Tested by

no test coverage detected