impactscan 1.0.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.
Files changed (34) hide show
  1. impactscan/__init__.py +1 -0
  2. impactscan/application/__init__.py +1 -0
  3. impactscan/application/impact_analyzer.py +76 -0
  4. impactscan/application/scan_usecase.py +48 -0
  5. impactscan/cli/__init__.py +1 -0
  6. impactscan/cli/main.py +150 -0
  7. impactscan/dashboard/__init__.py +1 -0
  8. impactscan/dashboard/backend/__init__.py +1 -0
  9. impactscan/dashboard/backend/api.py +125 -0
  10. impactscan/dashboard/backend/main.py +26 -0
  11. impactscan/dashboard/frontend/dist/assets/index-C_wv7-Td.js +64 -0
  12. impactscan/dashboard/frontend/dist/assets/index-DBtkHC7D.css +1 -0
  13. impactscan/dashboard/frontend/dist/index.html +13 -0
  14. impactscan/domain/__init__.py +1 -0
  15. impactscan/domain/interfaces.py +39 -0
  16. impactscan/domain/models.py +62 -0
  17. impactscan/infrastructure/__init__.py +1 -0
  18. impactscan/infrastructure/db.py +64 -0
  19. impactscan/infrastructure/detectors/__init__.py +0 -0
  20. impactscan/infrastructure/detectors/dead_code.py +65 -0
  21. impactscan/infrastructure/detectors/hardcoded_secret.py +82 -0
  22. impactscan/infrastructure/detectors/sql_injection.py +71 -0
  23. impactscan/infrastructure/detectors/unused_import.py +70 -0
  24. impactscan/infrastructure/git_provider.py +32 -0
  25. impactscan/infrastructure/js_parser.py +56 -0
  26. impactscan/infrastructure/network_graph.py +22 -0
  27. impactscan/infrastructure/path_resolver.py +17 -0
  28. impactscan/infrastructure/python_parser.py +34 -0
  29. impactscan/infrastructure/safe_paths.py +23 -0
  30. impactscan-1.0.0.dist-info/METADATA +43 -0
  31. impactscan-1.0.0.dist-info/RECORD +34 -0
  32. impactscan-1.0.0.dist-info/WHEEL +5 -0
  33. impactscan-1.0.0.dist-info/entry_points.txt +2 -0
  34. impactscan-1.0.0.dist-info/top_level.txt +1 -0
impactscan/__init__.py ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,76 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Dict
4
+ from impactscan.domain.models import ChangedItem, RiskLevel
5
+ from impactscan.domain.interfaces import BaseGitProvider, BaseGraph
6
+ from impactscan.infrastructure.python_parser import PythonParser
7
+ from impactscan.infrastructure.js_parser import TreeSitterJSParser
8
+ from impactscan.infrastructure.safe_paths import is_within, resolve_directory
9
+
10
+
11
+ class GitImpactUseCase:
12
+ def __init__(self, git_provider: BaseGitProvider, graph: BaseGraph):
13
+ self.git_provider = git_provider
14
+ self.graph = graph
15
+ self.parsers = {
16
+ '.py': PythonParser(),
17
+ '.js': TreeSitterJSParser(),
18
+ '.jsx': TreeSitterJSParser(),
19
+ '.ts': TreeSitterJSParser(),
20
+ '.tsx': TreeSitterJSParser()
21
+ }
22
+
23
+ def _build_graph(self, repo_path: Path) -> None:
24
+ for root, dirs, files in os.walk(repo_path):
25
+ dirs[:] = [d for d in dirs if d not in {'.git', 'node_modules', '__pycache__'}]
26
+ for file in files:
27
+ ext = os.path.splitext(file)[1]
28
+ if ext not in self.parsers:
29
+ continue
30
+ file_path = Path(root) / file
31
+ if not is_within(file_path, repo_path):
32
+ continue
33
+ try:
34
+ with open(file_path, encoding='utf-8', errors='ignore') as fh:
35
+ source = fh.read()
36
+ except OSError:
37
+ continue
38
+ nodes, edges = self.parsers[ext].parse(str(file_path), source)
39
+ for n in nodes:
40
+ self.graph.add_node(n)
41
+ for e in edges:
42
+ self.graph.add_edge(e)
43
+
44
+ def execute(self, repo_path: str, commit1: str, commit2: str) -> Dict:
45
+ root_anchor = resolve_directory(repo_path)
46
+ changed_files = self.git_provider.get_diff_files(commit1, commit2)
47
+ self._build_graph(root_anchor)
48
+
49
+ changed_items = []
50
+ impacted_node_ids = []
51
+
52
+ for display_path in changed_files:
53
+ file_path = str((root_anchor / display_path).resolve())
54
+ if not is_within(file_path, root_anchor):
55
+ continue
56
+ ext = os.path.splitext(display_path)[1]
57
+ if ext not in self.parsers:
58
+ continue
59
+ changed_lines = self.git_provider.get_changed_lines(commit1, commit2, display_path)
60
+
61
+ for node_id, node_data in self.graph.graph.nodes(data=True):
62
+ node = node_data.get("data")
63
+ if node and node["file_path"] == file_path:
64
+ if any(node["start_line"] <= line <= node["end_line"] for line in changed_lines):
65
+ risk = RiskLevel.HIGH if node["node_type"] == "CLASS" else RiskLevel.MEDIUM
66
+ changed_items.append(ChangedItem(
67
+ file_path=display_path, function_name=node["name"], risk_level=risk
68
+ ))
69
+ impacted_node_ids.append(node_id)
70
+
71
+ impacted = self.graph.find_impacted(impacted_node_ids)
72
+ return {
73
+ "changed_items": [item.dict() for item in changed_items],
74
+ "impacted_nodes": impacted,
75
+ "regression_suggestions": [f"Test {item}" for item in impacted]
76
+ }
@@ -0,0 +1,48 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import List
4
+ from impactscan.domain.interfaces import BaseScanner
5
+ from impactscan.domain.models import ScanResult, ScanIssue
6
+ from impactscan.infrastructure.detectors.unused_import import UnusedImportDetector
7
+ from impactscan.infrastructure.detectors.dead_code import DeadCodeDetector
8
+ from impactscan.infrastructure.detectors.sql_injection import SQLInjectionDetector
9
+ from impactscan.infrastructure.detectors.hardcoded_secret import HardcodedSecretDetector
10
+ from impactscan.infrastructure.safe_paths import is_within, resolve_directory
11
+
12
+ _SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", ".tox", "dist", "build"}
13
+
14
+
15
+ class ScanUseCase:
16
+ def __init__(self, detectors: List[BaseScanner] | None = None):
17
+ self._detectors: List[BaseScanner] = detectors or [
18
+ UnusedImportDetector(),
19
+ DeadCodeDetector(),
20
+ SQLInjectionDetector(),
21
+ HardcodedSecretDetector(),
22
+ ]
23
+
24
+ def execute(self, repo_path: str) -> ScanResult:
25
+ # Resolve and anchor the root to prevent path traversal
26
+ root_anchor = resolve_directory(repo_path)
27
+ issues: List[ScanIssue] = []
28
+ scanned = 0
29
+
30
+ for root, dirs, files in os.walk(root_anchor):
31
+ dirs[:] = [d for d in dirs if d not in _SKIP_DIRS]
32
+ for filename in files:
33
+ if not filename.endswith(".py"):
34
+ continue
35
+ file_path = Path(root) / filename
36
+ # Guard: ensure the file is still inside the anchored root
37
+ if not is_within(file_path, root_anchor):
38
+ continue
39
+ try:
40
+ with open(file_path, encoding="utf-8", errors="ignore") as fh:
41
+ source = fh.read()
42
+ except OSError:
43
+ continue
44
+ scanned += 1
45
+ for detector in self._detectors:
46
+ issues.extend(detector.scan(str(file_path), source))
47
+
48
+ return ScanResult(scanned_files=scanned, issues=issues)
@@ -0,0 +1 @@
1
+
impactscan/cli/main.py ADDED
@@ -0,0 +1,150 @@
1
+ import typer
2
+ import uvicorn
3
+ import webbrowser
4
+ import threading
5
+ from rich.console import Console
6
+ from rich.table import Table
7
+ from rich.panel import Panel
8
+ from rich import box
9
+
10
+ app = typer.Typer(help="ImpactScan: Code Impact Analysis Platform")
11
+ console = Console()
12
+
13
+ _SEVERITY_COLOR = {
14
+ "LOW": "dim white",
15
+ "MEDIUM": "yellow",
16
+ "HIGH": "bold red",
17
+ "CRITICAL": "bold magenta",
18
+ }
19
+
20
+
21
+ @app.command()
22
+ def git_check(commit1: str = typer.Option("HEAD~1"), commit2: str = typer.Option("HEAD")):
23
+ """Analyze git changes and output impacted files/functions."""
24
+ from impactscan.infrastructure.git_provider import GitPythonProvider
25
+ from impactscan.infrastructure.network_graph import NetworkXGraph
26
+ from impactscan.application.impact_analyzer import GitImpactUseCase
27
+
28
+ console.print(f"[bold blue]Running Git Impact Analysis: {commit1} -> {commit2}[/bold blue]")
29
+ git_provider = GitPythonProvider(".")
30
+ graph = NetworkXGraph()
31
+ use_case = GitImpactUseCase(git_provider, graph)
32
+ result = use_case.execute(".", commit1, commit2)
33
+
34
+ console.print("[bold green]Changed Items:[/bold green]")
35
+ for item in result["changed_items"]:
36
+ console.print(f" - {item['file_path']} ({item['risk_level']})")
37
+
38
+ console.print("\n[bold red]Impacted Nodes (Regression Targets):[/bold red]")
39
+ for node in result["impacted_nodes"]:
40
+ console.print(f" - {node}")
41
+
42
+
43
+ @app.command()
44
+ def scan(path: str = typer.Argument(".", help="Root path of the repository to scan.")):
45
+ """Run static analysis: unused imports, dead code, SQL injection, hardcoded secrets."""
46
+ from impactscan.application.scan_usecase import ScanUseCase
47
+ from impactscan.domain.models import RiskLevel
48
+
49
+ console.print(Panel(f"[bold blue]ImpactScan - Static Analysis[/bold blue]\nScanning: [cyan]{path}[/cyan]", expand=False))
50
+
51
+ result = ScanUseCase().execute(path)
52
+
53
+ if not result.issues:
54
+ console.print(f"[bold green]No issues found across {result.scanned_files} file(s).[/bold green]")
55
+ return
56
+
57
+ # Group by file for readable output
58
+ from collections import defaultdict
59
+ by_file: dict = defaultdict(list)
60
+ for issue in result.issues:
61
+ by_file[issue.file_path].append(issue)
62
+
63
+ for file_path, issues in sorted(by_file.items()):
64
+ table = Table(box=box.SIMPLE, show_header=True, header_style="bold cyan", expand=True)
65
+ table.add_column("Line", style="dim", width=6)
66
+ table.add_column("Severity", width=10)
67
+ table.add_column("Category", width=20)
68
+ table.add_column("Message")
69
+ table.add_column("Fix", style="italic green")
70
+
71
+ for issue in sorted(issues, key=lambda i: i.line):
72
+ color = _SEVERITY_COLOR.get(issue.severity, "white")
73
+ table.add_row(
74
+ str(issue.line),
75
+ f"[{color}]{issue.severity}[/{color}]",
76
+ issue.category,
77
+ issue.message,
78
+ issue.fix,
79
+ )
80
+
81
+ console.print(Panel(table, title=f"[bold]{file_path}[/bold]", border_style="blue"))
82
+
83
+ total = len(result.issues)
84
+ critical = sum(1 for i in result.issues if i.severity == RiskLevel.CRITICAL)
85
+ high = sum(1 for i in result.issues if i.severity == RiskLevel.HIGH)
86
+ console.print(
87
+ f"\n[bold]Summary:[/bold] {result.scanned_files} files scanned - "
88
+ f"[bold magenta]{critical} CRITICAL[/bold magenta], "
89
+ f"[bold red]{high} HIGH[/bold red], "
90
+ f"{total - critical - high} other issues."
91
+ )
92
+ if critical or high:
93
+ raise typer.Exit(code=1)
94
+
95
+
96
+ @app.command()
97
+ def ui():
98
+ """Starts the ImpactScan web dashboard in your browser."""
99
+ console.print("[bold green]Starting ImpactScan Dashboard at http://localhost:8000[/bold green]")
100
+
101
+ def open_browser():
102
+ import time
103
+ time.sleep(1.5)
104
+ webbrowser.open("http://localhost:8000")
105
+
106
+ threading.Thread(target=open_browser, daemon=True).start()
107
+ try:
108
+ uvicorn.run(
109
+ "impactscan.dashboard.backend.main:app",
110
+ host="127.0.0.1",
111
+ port=8000,
112
+ log_level="warning",
113
+ )
114
+ except KeyboardInterrupt:
115
+ # Ctrl+C is the expected way to stop the local dashboard. Uvicorn can
116
+ # surface the Windows asyncio cancellation as a traceback otherwise.
117
+ console.print("[dim]ImpactScan dashboard stopped.[/dim]")
118
+
119
+
120
+ @app.command()
121
+ def doctor():
122
+ """Check that all required dependencies and parsers are operational."""
123
+ import importlib.util
124
+
125
+ # Map display name -> importable module name (no user input, fully static)
126
+ checks = [
127
+ ("libcst", "libcst"),
128
+ ("tree_sitter", "tree_sitter"),
129
+ ("tree_sitter_js", "tree_sitter_javascript"),
130
+ ("networkx", "networkx"),
131
+ ("gitpython", "git"),
132
+ ("fastapi", "fastapi"),
133
+ ("pydantic", "pydantic"),
134
+ ]
135
+ all_ok = True
136
+ for display_name, module_name in checks:
137
+ found = importlib.util.find_spec(module_name) is not None
138
+ if found:
139
+ console.print(f" [bold green]OK[/bold green] {display_name}")
140
+ else:
141
+ console.print(f" [bold red]MISSING[/bold red] {display_name} - not installed")
142
+ all_ok = False
143
+ if not all_ok:
144
+ console.print("\n[bold red]Run: pip install impactscan[/bold red]")
145
+ raise typer.Exit(code=1)
146
+ console.print("\n[bold green]All dependencies OK.[/bold green]")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ app()
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,125 @@
1
+ from fastapi import APIRouter, HTTPException
2
+ from pathlib import Path
3
+ from pydantic import BaseModel
4
+ from typing import List, Optional
5
+ from impactscan.domain.models import RiskLevel, ScanIssue
6
+ from impactscan.infrastructure.git_provider import GitPythonProvider
7
+ from impactscan.infrastructure.network_graph import NetworkXGraph
8
+ from impactscan.application.impact_analyzer import GitImpactUseCase
9
+ from impactscan.application.scan_usecase import ScanUseCase
10
+ from impactscan.infrastructure.db import init_db, save_issues, load_issues, clear_issues
11
+ import logging
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ router = APIRouter(prefix="/api/v1", tags=["ImpactScan"])
16
+ init_db()
17
+
18
+
19
+ # ── Shared models ────────────────────────────────────────────────────────────
20
+
21
+ class GitCheckRequest(BaseModel):
22
+ repo_path: str = "."
23
+ commit1: str = "HEAD~1"
24
+ commit2: str = "HEAD"
25
+
26
+
27
+ class ScanRequest(BaseModel):
28
+ repo_path: str = "."
29
+ fresh: bool = True # if True, clears previous results before scanning
30
+
31
+
32
+ class IssueOut(BaseModel):
33
+ file_path: str
34
+ line: int
35
+ column: int
36
+ category: str
37
+ severity: str
38
+ message: str
39
+ fix: str
40
+
41
+
42
+ class ScanResponse(BaseModel):
43
+ scanned_files: int
44
+ issues: List[IssueOut]
45
+
46
+
47
+ class NodeData(BaseModel):
48
+ id: str
49
+ label: str
50
+ type: str
51
+ risk_level: Optional[RiskLevel] = None
52
+
53
+
54
+ class EdgeData(BaseModel):
55
+ source: str
56
+ target: str
57
+ type: str
58
+
59
+
60
+ class GraphResponse(BaseModel):
61
+ nodes: List[NodeData]
62
+ edges: List[EdgeData]
63
+ changed_files: List[str]
64
+ impacted_files: List[str]
65
+
66
+
67
+ # ── Endpoints ────────────────────────────────────────────────────────────────
68
+
69
+ @router.post("/scan", response_model=ScanResponse)
70
+ async def run_scan(request: ScanRequest):
71
+ try:
72
+ result = ScanUseCase().execute(request.repo_path)
73
+ if request.fresh:
74
+ clear_issues()
75
+ save_issues(result.issues)
76
+ return ScanResponse(
77
+ scanned_files=result.scanned_files,
78
+ issues=[IssueOut(**i.dict()) for i in result.issues],
79
+ )
80
+ except ValueError as exc:
81
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
82
+ except Exception:
83
+ logger.exception("Scan request failed")
84
+ raise HTTPException(status_code=500, detail="Unable to complete scan") from None
85
+
86
+
87
+ @router.get("/scan/issues", response_model=List[IssueOut])
88
+ async def get_issues():
89
+ return [IssueOut(**i.dict()) for i in load_issues()]
90
+
91
+
92
+ @router.post("/impact/git-check", response_model=GraphResponse)
93
+ async def run_git_check(request: GitCheckRequest):
94
+ try:
95
+ git_provider = GitPythonProvider(request.repo_path)
96
+ graph_engine = NetworkXGraph()
97
+ use_case = GitImpactUseCase(git_provider, graph_engine)
98
+ result = use_case.execute(request.repo_path, request.commit1, request.commit2)
99
+
100
+ nodes, edges = [], []
101
+ changed_files = [item["file_path"] for item in result["changed_items"]]
102
+ repo_root = Path(request.repo_path).expanduser().resolve()
103
+ changed_absolute = {
104
+ str((repo_root / file_path).resolve()) for file_path in changed_files
105
+ }
106
+ impacted_files = result["impacted_nodes"]
107
+
108
+ for node_id, node_data in graph_engine.graph.nodes(data=True):
109
+ data = node_data.get("data")
110
+ if not data:
111
+ continue
112
+ risk = RiskLevel.HIGH if data["file_path"] in changed_absolute else (
113
+ RiskLevel.MEDIUM if node_id in impacted_files else None
114
+ )
115
+ nodes.append(NodeData(id=node_id, label=data["name"], type=data["node_type"], risk_level=risk))
116
+
117
+ for source, target, edge_data in graph_engine.graph.edges(data=True):
118
+ edges.append(EdgeData(source=source, target=target, type=edge_data.get("type", "calls")))
119
+
120
+ return GraphResponse(nodes=nodes, edges=edges, changed_files=changed_files, impacted_files=impacted_files)
121
+ except ValueError as exc:
122
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
123
+ except Exception:
124
+ logger.exception("Git impact request failed")
125
+ raise HTTPException(status_code=500, detail="Unable to complete Git impact analysis") from None
@@ -0,0 +1,26 @@
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.staticfiles import StaticFiles
3
+ from fastapi.responses import FileResponse
4
+ from impactscan.dashboard.backend.api import router
5
+ from pathlib import Path
6
+
7
+ app = FastAPI(title="ImpactScan API", version="1.0.0")
8
+ app.include_router(router)
9
+
10
+ CURRENT_DIR = Path(__file__).resolve().parent
11
+ FRONTEND_DIST = CURRENT_DIR.parent / "frontend" / "dist"
12
+
13
+ if FRONTEND_DIST.exists():
14
+ assets_dir = FRONTEND_DIST / "assets"
15
+ if assets_dir.exists():
16
+ app.mount("/assets", StaticFiles(directory=str(assets_dir)), name="assets")
17
+
18
+ @app.get("/{full_path:path}")
19
+ async def serve_spa(full_path: str):
20
+ if full_path.startswith("api"):
21
+ raise HTTPException(status_code=404, detail="API endpoint not found")
22
+ return FileResponse(str(FRONTEND_DIST / "index.html"))
23
+ else:
24
+ @app.get("/")
25
+ async def ui_not_built():
26
+ return {"error": "ImpactScan UI is not bundled. Run 'npm run build' in frontend dir."}