errorlens 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.
Potentially problematic release.
This version of errorlens might be problematic. Click here for more details.
- errorlens/__init__.py +1 -0
- errorlens/cli.py +147 -0
- errorlens/core/__init__.py +0 -0
- errorlens/core/analyzer.py +123 -0
- errorlens/core/config.py +88 -0
- errorlens/providers/__init__.py +0 -0
- errorlens/providers/anthropic_provider.py +103 -0
- errorlens/providers/groq_provider.py +109 -0
- errorlens/providers/mistral_provider.py +134 -0
- errorlens/providers/mock_provider.py +120 -0
- errorlens/tui.py +230 -0
- errorlens-0.1.0.dist-info/METADATA +256 -0
- errorlens-0.1.0.dist-info/RECORD +16 -0
- errorlens-0.1.0.dist-info/WHEEL +5 -0
- errorlens-0.1.0.dist-info/entry_points.txt +3 -0
- errorlens-0.1.0.dist-info/top_level.txt +1 -0
errorlens/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
errorlens/cli.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
ErrorLens CLI — non-interactive analysis mode
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from errorlens.core.analyzer import CodeAnalyzer
|
|
13
|
+
from errorlens.core.config import Config
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main():
|
|
17
|
+
parser = argparse.ArgumentParser(
|
|
18
|
+
description="ErrorLens - Find bugs and security issues in your codebase"
|
|
19
|
+
)
|
|
20
|
+
parser.add_argument(
|
|
21
|
+
"path", nargs="?", default=".",
|
|
22
|
+
help="Path to file or directory to analyze (default: current directory)"
|
|
23
|
+
)
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"--provider", choices=["anthropic", "mistral", "groq", "mock", "all"],
|
|
26
|
+
default="all", help="AI provider to use (default: all)"
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument(
|
|
29
|
+
"--output", choices=["console", "json", "markdown"],
|
|
30
|
+
default="console", help="Output format (default: console)"
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
|
|
33
|
+
parser.add_argument("--config", help="Path to configuration file")
|
|
34
|
+
|
|
35
|
+
args = parser.parse_args()
|
|
36
|
+
config = Config(args.config)
|
|
37
|
+
|
|
38
|
+
logging.basicConfig(
|
|
39
|
+
level=logging.INFO if args.verbose or config.get("output.verbose") else logging.WARNING,
|
|
40
|
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
target_path = Path(args.path)
|
|
44
|
+
if not target_path.exists():
|
|
45
|
+
print(f"Error: Path '{args.path}' does not exist")
|
|
46
|
+
sys.exit(1)
|
|
47
|
+
|
|
48
|
+
provider_list = ["anthropic", "mistral", "groq"] if args.provider == "all" else [args.provider]
|
|
49
|
+
|
|
50
|
+
analyzer = CodeAnalyzer()
|
|
51
|
+
analyzer.initialize_providers(provider_list)
|
|
52
|
+
|
|
53
|
+
print(f"ErrorLens — analyzing: {args.path} provider: {args.provider}")
|
|
54
|
+
results = analyzer.analyze_path(target_path, provider_list)
|
|
55
|
+
_output_results(results, args.output)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _output_results(results: dict, output_format: str):
|
|
59
|
+
if output_format == "json":
|
|
60
|
+
print(json.dumps(results, indent=2))
|
|
61
|
+
elif output_format == "markdown":
|
|
62
|
+
_output_markdown(results)
|
|
63
|
+
else:
|
|
64
|
+
_output_console(results)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _output_console(results: dict):
|
|
68
|
+
print("\n" + "=" * 50)
|
|
69
|
+
print("ERRORLENS ANALYSIS RESULTS")
|
|
70
|
+
print("=" * 50)
|
|
71
|
+
if "directory" in results:
|
|
72
|
+
print(f"Directory: {results['directory']}")
|
|
73
|
+
print(f"Files analyzed: {len(results['files'])}")
|
|
74
|
+
print(f"Successful: {results['summary']['successful_analyses']}")
|
|
75
|
+
print(f"Failed: {results['summary']['failed_analyses']}")
|
|
76
|
+
for file_result in results['files']:
|
|
77
|
+
_print_file_result(file_result)
|
|
78
|
+
else:
|
|
79
|
+
_print_file_result(results)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _print_file_result(file_result: dict):
|
|
83
|
+
print(f"\nFile: {file_result['file']}")
|
|
84
|
+
print(f"Language: {file_result.get('language', 'unknown')}")
|
|
85
|
+
if not file_result.get('success'):
|
|
86
|
+
print(f"Error: {file_result.get('error', 'Unknown error')}")
|
|
87
|
+
return
|
|
88
|
+
for provider_name, provider_result in file_result['providers'].items():
|
|
89
|
+
print(f"\n--- {provider_name.upper()} ---")
|
|
90
|
+
if provider_result.get('success'):
|
|
91
|
+
analysis = provider_result.get('analysis', {})
|
|
92
|
+
for label, key in [
|
|
93
|
+
("Security Issues", "security_issues"),
|
|
94
|
+
("Potential Bugs", "bugs"),
|
|
95
|
+
("Code Quality", "code_quality"),
|
|
96
|
+
("Suggestions", "suggestions"),
|
|
97
|
+
]:
|
|
98
|
+
items = analysis.get(key, [])
|
|
99
|
+
if items:
|
|
100
|
+
print(f"{label}:")
|
|
101
|
+
for item in items:
|
|
102
|
+
print(f" - {item}")
|
|
103
|
+
else:
|
|
104
|
+
print(f"Error: {provider_result.get('error', 'Unknown error')}")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _output_markdown(results: dict):
|
|
108
|
+
print("# ErrorLens Analysis Results\n")
|
|
109
|
+
if "directory" in results:
|
|
110
|
+
print(f"## Directory: {results['directory']}")
|
|
111
|
+
print(f"- Files: {len(results['files'])}")
|
|
112
|
+
print(f"- OK: {results['summary']['successful_analyses']}")
|
|
113
|
+
print(f"- Failed: {results['summary']['failed_analyses']}\n")
|
|
114
|
+
for file_result in results['files']:
|
|
115
|
+
_print_file_markdown(file_result)
|
|
116
|
+
else:
|
|
117
|
+
_print_file_markdown(results)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _print_file_markdown(file_result: dict):
|
|
121
|
+
status = "✅" if file_result.get('success') else "❌"
|
|
122
|
+
print(f"## {status} {file_result['file']}")
|
|
123
|
+
if not file_result.get('success'):
|
|
124
|
+
print(f"**Error:** {file_result.get('error', 'Unknown error')}\n")
|
|
125
|
+
return
|
|
126
|
+
for provider_name, provider_result in file_result['providers'].items():
|
|
127
|
+
print(f"### {provider_name.upper()}")
|
|
128
|
+
if provider_result.get('success'):
|
|
129
|
+
analysis = provider_result.get('analysis', {})
|
|
130
|
+
for label, key in [
|
|
131
|
+
("Security Issues", "security_issues"),
|
|
132
|
+
("Potential Bugs", "bugs"),
|
|
133
|
+
("Code Quality Issues", "code_quality"),
|
|
134
|
+
("Suggestions", "suggestions"),
|
|
135
|
+
]:
|
|
136
|
+
items = analysis.get(key, [])
|
|
137
|
+
if items:
|
|
138
|
+
print(f"**{label}:**")
|
|
139
|
+
for item in items:
|
|
140
|
+
print(f"- {item}")
|
|
141
|
+
else:
|
|
142
|
+
print(f"**Error:** {provider_result.get('error', 'Unknown error')}")
|
|
143
|
+
print()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
if __name__ == "__main__":
|
|
147
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core Analysis Engine
|
|
3
|
+
Handles file discovery, code extraction, and analysis orchestration
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import List, Dict, Any, Optional, Union
|
|
9
|
+
import logging
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
11
|
+
|
|
12
|
+
from errorlens.providers.anthropic_provider import AnthropicProvider
|
|
13
|
+
from errorlens.providers.mistral_provider import MistralProvider
|
|
14
|
+
from errorlens.providers.groq_provider import GroqProvider
|
|
15
|
+
from errorlens.providers.mock_provider import MockProvider
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CodeAnalyzer:
|
|
19
|
+
def __init__(self):
|
|
20
|
+
self.providers = {
|
|
21
|
+
"anthropic": None,
|
|
22
|
+
"mistral": None,
|
|
23
|
+
"groq": None
|
|
24
|
+
}
|
|
25
|
+
self.logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
def initialize_providers(self, provider_names: List[str] = None):
|
|
28
|
+
provider_names = provider_names or ["anthropic", "mistral", "groq"]
|
|
29
|
+
for name in provider_names:
|
|
30
|
+
try:
|
|
31
|
+
if name == "anthropic":
|
|
32
|
+
self.providers["anthropic"] = AnthropicProvider()
|
|
33
|
+
elif name == "mistral":
|
|
34
|
+
self.providers["mistral"] = MistralProvider()
|
|
35
|
+
elif name == "groq":
|
|
36
|
+
self.providers["groq"] = GroqProvider()
|
|
37
|
+
elif name == "mock":
|
|
38
|
+
self.providers["mock"] = MockProvider()
|
|
39
|
+
self.logger.info(f"Initialized {name} provider")
|
|
40
|
+
except Exception as e:
|
|
41
|
+
self.logger.warning(f"Failed to initialize {name} provider: {e}")
|
|
42
|
+
self.providers[name] = None
|
|
43
|
+
|
|
44
|
+
def analyze_path(self, path: Union[str, Path],
|
|
45
|
+
providers: List[str] = None) -> Dict[str, Any]:
|
|
46
|
+
path = Path(path)
|
|
47
|
+
if path.is_file():
|
|
48
|
+
return self._analyze_file(path, providers)
|
|
49
|
+
return self._analyze_directory(path, providers)
|
|
50
|
+
|
|
51
|
+
def _analyze_file(self, file_path: Path,
|
|
52
|
+
providers: List[str] = None) -> Dict[str, Any]:
|
|
53
|
+
try:
|
|
54
|
+
with open(file_path, 'r', encoding='utf-8') as f:
|
|
55
|
+
content = f.read()
|
|
56
|
+
language = self._get_language_from_extension(file_path.suffix)
|
|
57
|
+
provider_results = self._analyze_with_providers(content, language, providers)
|
|
58
|
+
return {
|
|
59
|
+
"file": str(file_path),
|
|
60
|
+
"language": language,
|
|
61
|
+
"providers": provider_results,
|
|
62
|
+
"success": True
|
|
63
|
+
}
|
|
64
|
+
except Exception as e:
|
|
65
|
+
return {"file": str(file_path), "error": str(e), "success": False}
|
|
66
|
+
|
|
67
|
+
def _analyze_directory(self, directory_path: Path,
|
|
68
|
+
providers: List[str] = None) -> Dict[str, Any]:
|
|
69
|
+
results = {"directory": str(directory_path), "files": [], "summary": {}}
|
|
70
|
+
code_files = self._find_code_files(directory_path)
|
|
71
|
+
|
|
72
|
+
with ThreadPoolExecutor(max_workers=4) as executor:
|
|
73
|
+
futures = [
|
|
74
|
+
executor.submit(self._analyze_file, fp, providers)
|
|
75
|
+
for fp in code_files
|
|
76
|
+
]
|
|
77
|
+
for future in as_completed(futures):
|
|
78
|
+
results["files"].append(future.result())
|
|
79
|
+
|
|
80
|
+
results["summary"] = self._generate_summary(results["files"])
|
|
81
|
+
return results
|
|
82
|
+
|
|
83
|
+
def _analyze_with_providers(self, code: str, language: str,
|
|
84
|
+
providers: List[str] = None) -> Dict[str, Any]:
|
|
85
|
+
providers = providers or ["anthropic", "mistral", "groq"]
|
|
86
|
+
results = {}
|
|
87
|
+
for provider_name in providers:
|
|
88
|
+
provider = self.providers.get(provider_name)
|
|
89
|
+
if not provider:
|
|
90
|
+
continue
|
|
91
|
+
try:
|
|
92
|
+
results[provider_name] = provider.analyze_code(code, language)
|
|
93
|
+
except Exception as e:
|
|
94
|
+
results[provider_name] = {"error": str(e), "success": False}
|
|
95
|
+
return results
|
|
96
|
+
|
|
97
|
+
def _find_code_files(self, directory_path: Path) -> List[Path]:
|
|
98
|
+
code_extensions = {
|
|
99
|
+
'.py', '.js', '.ts', '.java', '.c', '.cpp', '.go',
|
|
100
|
+
'.rb', '.php', '.swift', '.kt', '.rs', '.cs'
|
|
101
|
+
}
|
|
102
|
+
return [
|
|
103
|
+
p for p in directory_path.rglob('*')
|
|
104
|
+
if p.is_file() and p.suffix in code_extensions
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
def _get_language_from_extension(self, extension: str) -> str:
|
|
108
|
+
extension_map = {
|
|
109
|
+
'.py': 'python', '.js': 'javascript', '.ts': 'typescript',
|
|
110
|
+
'.java': 'java', '.c': 'c', '.cpp': 'cpp', '.go': 'go',
|
|
111
|
+
'.rb': 'ruby', '.php': 'php', '.swift': 'swift',
|
|
112
|
+
'.kt': 'kotlin', '.rs': 'rust', '.cs': 'csharp'
|
|
113
|
+
}
|
|
114
|
+
return extension_map.get(extension.lower(), 'unknown')
|
|
115
|
+
|
|
116
|
+
def _generate_summary(self, file_results: List[Dict]) -> Dict[str, Any]:
|
|
117
|
+
summary = {
|
|
118
|
+
"total_files": len(file_results),
|
|
119
|
+
"successful_analyses": sum(1 for r in file_results if r.get("success")),
|
|
120
|
+
"failed_analyses": sum(1 for r in file_results if not r.get("success")),
|
|
121
|
+
"findings_by_severity": {"critical": 0, "high": 0, "medium": 0, "low": 0}
|
|
122
|
+
}
|
|
123
|
+
return summary
|
errorlens/core/config.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration System
|
|
3
|
+
Handles loading and managing configuration from various sources
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Dict, Any, Optional
|
|
10
|
+
from dotenv import load_dotenv
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Config:
|
|
14
|
+
def __init__(self, config_file: Optional[str] = None):
|
|
15
|
+
load_dotenv()
|
|
16
|
+
|
|
17
|
+
self.config = {
|
|
18
|
+
"api_keys": {
|
|
19
|
+
"anthropic": os.getenv("ANTHROPIC_API_KEY"),
|
|
20
|
+
"mistral": os.getenv("MISTRAL_API_KEY"),
|
|
21
|
+
"groq": os.getenv("GROQ_API_KEY")
|
|
22
|
+
},
|
|
23
|
+
"analysis": {
|
|
24
|
+
"max_file_size_kb": int(os.getenv("MAX_FILE_SIZE_KB", "1000")),
|
|
25
|
+
"timeout_seconds": int(os.getenv("TIMEOUT_SECONDS", "30")),
|
|
26
|
+
"concurrent_workers": 4,
|
|
27
|
+
"default_providers": ["anthropic", "mistral", "groq"]
|
|
28
|
+
},
|
|
29
|
+
"models": {
|
|
30
|
+
"anthropic": os.getenv("ANTHROPIC_MODEL", "claude-3-opus-20240229"),
|
|
31
|
+
"mistral": os.getenv("MISTRAL_MODEL", "mistral-large-latest"),
|
|
32
|
+
"groq": os.getenv("GROQ_MODEL", "llama3-70b-8192")
|
|
33
|
+
},
|
|
34
|
+
"output": {
|
|
35
|
+
"format": "console",
|
|
36
|
+
"verbose": False,
|
|
37
|
+
"show_raw_responses": False
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if config_file:
|
|
42
|
+
self.load_config_file(config_file)
|
|
43
|
+
|
|
44
|
+
def load_config_file(self, config_file: str):
|
|
45
|
+
try:
|
|
46
|
+
config_path = Path(config_file)
|
|
47
|
+
if not config_path.exists():
|
|
48
|
+
raise FileNotFoundError(f"Config file {config_file} not found")
|
|
49
|
+
with open(config_path, 'r', encoding='utf-8') as f:
|
|
50
|
+
file_config = json.load(f)
|
|
51
|
+
self._deep_update(self.config, file_config)
|
|
52
|
+
except Exception as e:
|
|
53
|
+
raise RuntimeError(f"Failed to load config file: {e}")
|
|
54
|
+
|
|
55
|
+
def _deep_update(self, original: Dict, update: Dict):
|
|
56
|
+
for key, value in update.items():
|
|
57
|
+
if isinstance(value, dict) and key in original and isinstance(original[key], dict):
|
|
58
|
+
self._deep_update(original[key], value)
|
|
59
|
+
else:
|
|
60
|
+
original[key] = value
|
|
61
|
+
|
|
62
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
63
|
+
keys = key.split('.')
|
|
64
|
+
config = self.config
|
|
65
|
+
for k in keys:
|
|
66
|
+
if k in config:
|
|
67
|
+
config = config[k]
|
|
68
|
+
else:
|
|
69
|
+
return default
|
|
70
|
+
return config
|
|
71
|
+
|
|
72
|
+
def set(self, key: str, value: Any):
|
|
73
|
+
keys = key.split('.')
|
|
74
|
+
config = self.config
|
|
75
|
+
for k in keys[:-1]:
|
|
76
|
+
if k not in config:
|
|
77
|
+
config[k] = {}
|
|
78
|
+
config = config[k]
|
|
79
|
+
config[keys[-1]] = value
|
|
80
|
+
|
|
81
|
+
def validate(self) -> bool:
|
|
82
|
+
errors = []
|
|
83
|
+
for provider in self.config["analysis"]["default_providers"]:
|
|
84
|
+
if not self.config["api_keys"].get(provider):
|
|
85
|
+
errors.append(f"Missing API key for {provider}")
|
|
86
|
+
if errors:
|
|
87
|
+
raise RuntimeError("Configuration validation failed: " + ", ".join(errors))
|
|
88
|
+
return True
|
|
File without changes
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Anthropic API Provider Integration
|
|
3
|
+
Handles communication with Anthropic's API for code analysis
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from typing import Dict, Any, Optional
|
|
8
|
+
import anthropic
|
|
9
|
+
from dotenv import load_dotenv
|
|
10
|
+
|
|
11
|
+
# Load environment variables
|
|
12
|
+
load_dotenv()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AnthropicProvider:
|
|
16
|
+
def __init__(self, api_key: Optional[str] = None):
|
|
17
|
+
"""Initialize Anthropic provider with API key"""
|
|
18
|
+
self.api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
|
|
19
|
+
if not self.api_key:
|
|
20
|
+
raise ValueError("Anthropic API key not provided and ANTHROPIC_API_KEY environment variable not set")
|
|
21
|
+
|
|
22
|
+
self.client = anthropic.Anthropic(api_key=self.api_key)
|
|
23
|
+
self.model = "claude-3-opus-20240229" # Default model
|
|
24
|
+
|
|
25
|
+
def analyze_code(self, code: str, language: str = "python",
|
|
26
|
+
analysis_type: str = "security_and_bugs") -> Dict[str, Any]:
|
|
27
|
+
"""
|
|
28
|
+
Analyze code for bugs and security issues using Anthropic API
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
code: The source code to analyze
|
|
32
|
+
language: Programming language of the code
|
|
33
|
+
analysis_type: Type of analysis to perform
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
Dictionary containing analysis results
|
|
37
|
+
"""
|
|
38
|
+
prompt = self._build_analysis_prompt(code, language, analysis_type)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
response = self.client.messages.create(
|
|
42
|
+
model=self.model,
|
|
43
|
+
max_tokens=1024,
|
|
44
|
+
temperature=0.3,
|
|
45
|
+
system="You are a senior security engineer and code reviewer. Provide detailed analysis of code quality, security issues, and potential bugs.",
|
|
46
|
+
messages=[
|
|
47
|
+
{"role": "user", "content": prompt}
|
|
48
|
+
]
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
return self._parse_response(response)
|
|
52
|
+
|
|
53
|
+
except Exception as e:
|
|
54
|
+
return {
|
|
55
|
+
"error": str(e),
|
|
56
|
+
"success": False,
|
|
57
|
+
"provider": "anthropic"
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
def _build_analysis_prompt(self, code: str, language: str,
|
|
61
|
+
analysis_type: str) -> str:
|
|
62
|
+
"""Build the prompt for code analysis"""
|
|
63
|
+
base_prompt = f"""Analyze the following {language} code for {analysis_type}:
|
|
64
|
+
|
|
65
|
+
```{language}
|
|
66
|
+
{code}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Please provide:
|
|
70
|
+
1. Security vulnerabilities and risks
|
|
71
|
+
2. Potential bugs and edge cases
|
|
72
|
+
3. Code quality issues
|
|
73
|
+
4. Suggested improvements
|
|
74
|
+
|
|
75
|
+
Format your response as JSON with keys: security_issues, bugs, code_quality, suggestions"""
|
|
76
|
+
|
|
77
|
+
return base_prompt
|
|
78
|
+
|
|
79
|
+
def _parse_response(self, response: Any) -> Dict[str, Any]:
|
|
80
|
+
"""Parse the API response into structured data"""
|
|
81
|
+
result = {
|
|
82
|
+
"success": True,
|
|
83
|
+
"provider": "anthropic",
|
|
84
|
+
"raw_response": response.content,
|
|
85
|
+
"analysis": {}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
# Try to parse JSON response if available
|
|
89
|
+
try:
|
|
90
|
+
import json
|
|
91
|
+
content = response.content[0].text if hasattr(response.content[0], 'text') else str(response.content)
|
|
92
|
+
result["analysis"] = json.loads(content)
|
|
93
|
+
except (json.JSONDecodeError, IndexError, AttributeError):
|
|
94
|
+
# Fallback to raw text analysis
|
|
95
|
+
result["analysis"] = {
|
|
96
|
+
"raw_analysis": content
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return result
|
|
100
|
+
|
|
101
|
+
def set_model(self, model_name: str):
|
|
102
|
+
"""Set the model to use for analysis"""
|
|
103
|
+
self.model = model_name
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Groq API Provider Integration
|
|
3
|
+
Handles communication with Groq's API for code analysis
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from typing import Dict, Any, Optional
|
|
8
|
+
from groq import Groq
|
|
9
|
+
from dotenv import load_dotenv
|
|
10
|
+
|
|
11
|
+
# Load environment variables
|
|
12
|
+
load_dotenv()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GroqProvider:
|
|
16
|
+
def __init__(self, api_key: Optional[str] = None):
|
|
17
|
+
"""Initialize Groq provider with API key"""
|
|
18
|
+
self.api_key = api_key or os.getenv("GROQ_API_KEY")
|
|
19
|
+
if not self.api_key:
|
|
20
|
+
raise ValueError("Groq API key not provided and GROQ_API_KEY environment variable not set")
|
|
21
|
+
|
|
22
|
+
self.client = Groq(api_key=self.api_key)
|
|
23
|
+
self.model = "llama3-70b-8192" # Default model
|
|
24
|
+
|
|
25
|
+
def analyze_code(self, code: str, language: str = "python",
|
|
26
|
+
analysis_type: str = "security_and_bugs") -> Dict[str, Any]:
|
|
27
|
+
"""
|
|
28
|
+
Analyze code for bugs and security issues using Groq API
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
code: The source code to analyze
|
|
32
|
+
language: Programming language of the code
|
|
33
|
+
analysis_type: Type of analysis to perform
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
Dictionary containing analysis results
|
|
37
|
+
"""
|
|
38
|
+
prompt = self._build_analysis_prompt(code, language, analysis_type)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
response = self.client.chat.completions.create(
|
|
42
|
+
model=self.model,
|
|
43
|
+
messages=[
|
|
44
|
+
{
|
|
45
|
+
"role": "system",
|
|
46
|
+
"content": "You are a senior security engineer and code reviewer. Provide detailed analysis of code quality, security issues, and potential bugs."
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"role": "user",
|
|
50
|
+
"content": prompt
|
|
51
|
+
}
|
|
52
|
+
],
|
|
53
|
+
temperature=0.3,
|
|
54
|
+
max_tokens=1024
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
return self._parse_response(response)
|
|
58
|
+
|
|
59
|
+
except Exception as e:
|
|
60
|
+
return {
|
|
61
|
+
"error": str(e),
|
|
62
|
+
"success": False,
|
|
63
|
+
"provider": "groq"
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
def _build_analysis_prompt(self, code: str, language: str,
|
|
67
|
+
analysis_type: str) -> str:
|
|
68
|
+
"""Build the prompt for code analysis"""
|
|
69
|
+
base_prompt = f"""Analyze the following {language} code for {analysis_type}:
|
|
70
|
+
|
|
71
|
+
```{language}
|
|
72
|
+
{code}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Please provide:
|
|
76
|
+
1. Security vulnerabilities and risks
|
|
77
|
+
2. Potential bugs and edge cases
|
|
78
|
+
3. Code quality issues
|
|
79
|
+
4. Suggested improvements
|
|
80
|
+
|
|
81
|
+
Format your response as JSON with keys: security_issues, bugs, code_quality, suggestions"""
|
|
82
|
+
|
|
83
|
+
return base_prompt
|
|
84
|
+
|
|
85
|
+
def _parse_response(self, response: Any) -> Dict[str, Any]:
|
|
86
|
+
"""Parse the API response into structured data"""
|
|
87
|
+
result = {
|
|
88
|
+
"success": True,
|
|
89
|
+
"provider": "groq",
|
|
90
|
+
"raw_response": response.choices[0].message.content if response.choices else "",
|
|
91
|
+
"analysis": {}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
# Try to parse JSON response if available
|
|
95
|
+
try:
|
|
96
|
+
import json
|
|
97
|
+
content = result["raw_response"]
|
|
98
|
+
result["analysis"] = json.loads(content)
|
|
99
|
+
except (json.JSONDecodeError, IndexError):
|
|
100
|
+
# Fallback to raw text analysis
|
|
101
|
+
result["analysis"] = {
|
|
102
|
+
"raw_analysis": content
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return result
|
|
106
|
+
|
|
107
|
+
def set_model(self, model_name: str):
|
|
108
|
+
"""Set the model to use for analysis"""
|
|
109
|
+
self.model = model_name
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Mistral API Provider Integration
|
|
3
|
+
Handles communication with Mistral's API for code analysis
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from typing import Dict, Any, Optional
|
|
8
|
+
from dotenv import load_dotenv
|
|
9
|
+
|
|
10
|
+
# Load environment variables
|
|
11
|
+
load_dotenv()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MistralProvider:
|
|
15
|
+
def __init__(self, api_key: Optional[str] = None):
|
|
16
|
+
"""Initialize Mistral provider with API key"""
|
|
17
|
+
self.api_key = api_key or os.getenv("MISTRAL_API_KEY")
|
|
18
|
+
if not self.api_key:
|
|
19
|
+
raise ValueError("Mistral API key not provided and MISTRAL_API_KEY environment variable not set")
|
|
20
|
+
|
|
21
|
+
# Mock client for now - actual implementation would use Mistral API
|
|
22
|
+
self.client = None
|
|
23
|
+
self.model = "mistral-large-latest" # Default model
|
|
24
|
+
|
|
25
|
+
def analyze_code(self, code: str, language: str = "python",
|
|
26
|
+
analysis_type: str = "security_and_bugs") -> Dict[str, Any]:
|
|
27
|
+
"""
|
|
28
|
+
Analyze code for bugs and security issues using Mistral API
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
code: The source code to analyze
|
|
32
|
+
language: Programming language of the code
|
|
33
|
+
analysis_type: Type of analysis to perform
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
Dictionary containing analysis results
|
|
37
|
+
"""
|
|
38
|
+
prompt = self._build_analysis_prompt(code, language, analysis_type)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
# Mock response for testing
|
|
42
|
+
mock_response = {
|
|
43
|
+
"choices": [{
|
|
44
|
+
"message": {
|
|
45
|
+
"content": self._generate_mock_analysis(code, language)
|
|
46
|
+
}
|
|
47
|
+
}]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return self._parse_response(mock_response)
|
|
51
|
+
|
|
52
|
+
except Exception as e:
|
|
53
|
+
return {
|
|
54
|
+
"error": str(e),
|
|
55
|
+
"success": False,
|
|
56
|
+
"provider": "mistral"
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
def _generate_mock_analysis(self, code: str, language: str) -> str:
|
|
60
|
+
"""Generate mock analysis for testing"""
|
|
61
|
+
import json
|
|
62
|
+
|
|
63
|
+
# Simple analysis based on code content
|
|
64
|
+
analysis = {
|
|
65
|
+
"security_issues": [],
|
|
66
|
+
"bugs": [],
|
|
67
|
+
"code_quality": [],
|
|
68
|
+
"suggestions": []
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
# Check for common security issues
|
|
72
|
+
if "password" in code.lower() or "api_key" in code.lower():
|
|
73
|
+
analysis["security_issues"].append("Hardcoded credentials detected")
|
|
74
|
+
|
|
75
|
+
if "pickle" in code.lower():
|
|
76
|
+
analysis["security_issues"].append("Potential insecure deserialization using pickle")
|
|
77
|
+
|
|
78
|
+
if "request.args" in code or "request.data" in code:
|
|
79
|
+
analysis["security_issues"].append("Potential input validation issues")
|
|
80
|
+
|
|
81
|
+
# Check for common bugs
|
|
82
|
+
if "/" in code and "try:" not in code:
|
|
83
|
+
analysis["bugs"].append("Potential division by zero without error handling")
|
|
84
|
+
|
|
85
|
+
# Check for code quality issues
|
|
86
|
+
if "unused" in code.lower() or "todo" in code.lower():
|
|
87
|
+
analysis["code_quality"].append("Unused code or TODO comments found")
|
|
88
|
+
|
|
89
|
+
return json.dumps(analysis)
|
|
90
|
+
|
|
91
|
+
def _build_analysis_prompt(self, code: str, language: str,
|
|
92
|
+
analysis_type: str) -> str:
|
|
93
|
+
"""Build the prompt for code analysis"""
|
|
94
|
+
base_prompt = f"""Analyze the following {language} code for {analysis_type}:
|
|
95
|
+
|
|
96
|
+
```{language}
|
|
97
|
+
{code}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Please provide:
|
|
101
|
+
1. Security vulnerabilities and risks
|
|
102
|
+
2. Potential bugs and edge cases
|
|
103
|
+
3. Code quality issues
|
|
104
|
+
4. Suggested improvements
|
|
105
|
+
|
|
106
|
+
Format your response as JSON with keys: security_issues, bugs, code_quality, suggestions"""
|
|
107
|
+
|
|
108
|
+
return base_prompt
|
|
109
|
+
|
|
110
|
+
def _parse_response(self, response: Any) -> Dict[str, Any]:
|
|
111
|
+
"""Parse the API response into structured data"""
|
|
112
|
+
result = {
|
|
113
|
+
"success": True,
|
|
114
|
+
"provider": "mistral",
|
|
115
|
+
"raw_response": response["choices"][0]["message"]["content"] if response.get("choices") else "",
|
|
116
|
+
"analysis": {}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
# Try to parse JSON response if available
|
|
120
|
+
try:
|
|
121
|
+
import json
|
|
122
|
+
content = result["raw_response"]
|
|
123
|
+
result["analysis"] = json.loads(content)
|
|
124
|
+
except (json.JSONDecodeError, IndexError):
|
|
125
|
+
# Fallback to raw text analysis
|
|
126
|
+
result["analysis"] = {
|
|
127
|
+
"raw_analysis": content
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return result
|
|
131
|
+
|
|
132
|
+
def set_model(self, model_name: str):
|
|
133
|
+
"""Set the model to use for analysis"""
|
|
134
|
+
self.model = model_name
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Mock Provider for Testing
|
|
3
|
+
Provides mock analysis without requiring API keys
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from typing import Dict, Any, Optional
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MockProvider:
|
|
12
|
+
def __init__(self):
|
|
13
|
+
"""Initialize mock provider - no API key required"""
|
|
14
|
+
self.model = "mock-analysis-v1"
|
|
15
|
+
|
|
16
|
+
def analyze_code(self, code: str, language: str = "python",
|
|
17
|
+
analysis_type: str = "security_and_bugs") -> Dict[str, Any]:
|
|
18
|
+
"""
|
|
19
|
+
Analyze code for bugs and security issues using mock analysis
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
code: The source code to analyze
|
|
23
|
+
language: Programming language of the code
|
|
24
|
+
analysis_type: Type of analysis to perform
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
Dictionary containing analysis results
|
|
28
|
+
"""
|
|
29
|
+
try:
|
|
30
|
+
mock_response = {
|
|
31
|
+
"choices": [{
|
|
32
|
+
"message": {
|
|
33
|
+
"content": self._generate_mock_analysis(code, language)
|
|
34
|
+
}
|
|
35
|
+
}]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return self._parse_response(mock_response)
|
|
39
|
+
|
|
40
|
+
except Exception as e:
|
|
41
|
+
return {
|
|
42
|
+
"error": str(e),
|
|
43
|
+
"success": False,
|
|
44
|
+
"provider": "mock"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
def _generate_mock_analysis(self, code: str, language: str) -> str:
|
|
48
|
+
"""Generate mock analysis for testing"""
|
|
49
|
+
# Simple analysis based on code content
|
|
50
|
+
analysis = {
|
|
51
|
+
"security_issues": [],
|
|
52
|
+
"bugs": [],
|
|
53
|
+
"code_quality": [],
|
|
54
|
+
"suggestions": []
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
# Check for common security issues
|
|
58
|
+
if "password" in code.lower() or "api_key" in code.lower():
|
|
59
|
+
analysis["security_issues"].append("Hardcoded credentials detected")
|
|
60
|
+
|
|
61
|
+
if "pickle" in code.lower():
|
|
62
|
+
analysis["security_issues"].append("Potential insecure deserialization using pickle")
|
|
63
|
+
|
|
64
|
+
if "request.args" in code or "request.data" in code:
|
|
65
|
+
analysis["security_issues"].append("Potential input validation issues")
|
|
66
|
+
|
|
67
|
+
if "sql" in code.lower() or "query" in code.lower():
|
|
68
|
+
analysis["security_issues"].append("Potential SQL injection vulnerability")
|
|
69
|
+
|
|
70
|
+
# Check for common bugs
|
|
71
|
+
if "/" in code and "try:" not in code:
|
|
72
|
+
analysis["bugs"].append("Potential division by zero without error handling")
|
|
73
|
+
|
|
74
|
+
if "debug=true" in code.lower() or "debug=true" in code.lower():
|
|
75
|
+
analysis["bugs"].append("Debug mode enabled in production")
|
|
76
|
+
|
|
77
|
+
# Check for code quality issues
|
|
78
|
+
if "unused" in code.lower() or "todo" in code.lower():
|
|
79
|
+
analysis["code_quality"].append("Unused code or TODO comments found")
|
|
80
|
+
|
|
81
|
+
if len(code.split('\n')) > 100:
|
|
82
|
+
analysis["code_quality"].append("File is too long - consider breaking into smaller functions")
|
|
83
|
+
|
|
84
|
+
# Generate suggestions based on findings
|
|
85
|
+
if analysis["security_issues"]:
|
|
86
|
+
analysis["suggestions"].append("Use environment variables for sensitive data")
|
|
87
|
+
analysis["suggestions"].append("Implement input validation and sanitization")
|
|
88
|
+
|
|
89
|
+
if analysis["bugs"]:
|
|
90
|
+
analysis["suggestions"].append("Add proper error handling and edge case testing")
|
|
91
|
+
|
|
92
|
+
if analysis["code_quality"]:
|
|
93
|
+
analysis["suggestions"].append("Refactor code for better maintainability")
|
|
94
|
+
|
|
95
|
+
return json.dumps(analysis)
|
|
96
|
+
|
|
97
|
+
def _parse_response(self, response: Any) -> Dict[str, Any]:
|
|
98
|
+
"""Parse the API response into structured data"""
|
|
99
|
+
result = {
|
|
100
|
+
"success": True,
|
|
101
|
+
"provider": "mock",
|
|
102
|
+
"raw_response": response["choices"][0]["message"]["content"] if response.get("choices") else "",
|
|
103
|
+
"analysis": {}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
# Try to parse JSON response if available
|
|
107
|
+
try:
|
|
108
|
+
content = result["raw_response"]
|
|
109
|
+
result["analysis"] = json.loads(content)
|
|
110
|
+
except (json.JSONDecodeError, IndexError):
|
|
111
|
+
# Fallback to raw text analysis
|
|
112
|
+
result["analysis"] = {
|
|
113
|
+
"raw_analysis": content
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return result
|
|
117
|
+
|
|
118
|
+
def set_model(self, model_name: str):
|
|
119
|
+
"""Set the model to use for analysis"""
|
|
120
|
+
self.model = model_name
|
errorlens/tui.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
ErrorLens TUI — Terminal User Interface powered by Textual
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from textual.app import App, ComposeResult
|
|
9
|
+
from textual.containers import Horizontal, Vertical
|
|
10
|
+
from textual.widgets import (
|
|
11
|
+
Header, Footer, Input, Button, Label, Select,
|
|
12
|
+
Static, RadioSet, RadioButton, RichLog
|
|
13
|
+
)
|
|
14
|
+
from textual.reactive import reactive
|
|
15
|
+
from textual import work
|
|
16
|
+
|
|
17
|
+
from errorlens.core.analyzer import CodeAnalyzer
|
|
18
|
+
from errorlens.core.config import Config
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
PROVIDERS = ["anthropic", "mistral", "groq", "all"]
|
|
22
|
+
|
|
23
|
+
SEVERITY_STYLES = {
|
|
24
|
+
"Security Issues": "bold red",
|
|
25
|
+
"Potential Bugs": "bold yellow",
|
|
26
|
+
"Code Quality Issues": "bold cyan",
|
|
27
|
+
"Suggestions": "bold green",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ErrorLensApp(App):
|
|
32
|
+
CSS = """
|
|
33
|
+
Screen {
|
|
34
|
+
layout: vertical;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
#main {
|
|
38
|
+
layout: horizontal;
|
|
39
|
+
height: 1fr;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
#left-panel {
|
|
43
|
+
width: 30;
|
|
44
|
+
min-width: 28;
|
|
45
|
+
border: solid $primary;
|
|
46
|
+
padding: 1 2;
|
|
47
|
+
height: 100%;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
#left-panel Label {
|
|
51
|
+
margin-top: 1;
|
|
52
|
+
color: $text-muted;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
#path-input {
|
|
56
|
+
margin-top: 1;
|
|
57
|
+
width: 100%;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
#provider-set {
|
|
61
|
+
margin-top: 1;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
#run-btn {
|
|
65
|
+
margin-top: 2;
|
|
66
|
+
width: 100%;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
#status {
|
|
70
|
+
margin-top: 1;
|
|
71
|
+
color: $text-muted;
|
|
72
|
+
text-align: center;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
#right-panel {
|
|
76
|
+
width: 1fr;
|
|
77
|
+
border: solid $primary;
|
|
78
|
+
padding: 1 2;
|
|
79
|
+
height: 100%;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
RichLog {
|
|
83
|
+
height: 1fr;
|
|
84
|
+
}
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
BINDINGS = [
|
|
88
|
+
("r", "run_analysis", "Run"),
|
|
89
|
+
("c", "clear_results", "Clear"),
|
|
90
|
+
("q", "quit", "Quit"),
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
running = reactive(False)
|
|
94
|
+
|
|
95
|
+
def compose(self) -> ComposeResult:
|
|
96
|
+
yield Header(show_clock=True)
|
|
97
|
+
with Horizontal(id="main"):
|
|
98
|
+
with Vertical(id="left-panel"):
|
|
99
|
+
yield Label("Path")
|
|
100
|
+
yield Input(placeholder="file or directory", id="path-input")
|
|
101
|
+
yield Label("Provider")
|
|
102
|
+
with RadioSet(id="provider-set"):
|
|
103
|
+
for p in PROVIDERS:
|
|
104
|
+
yield RadioButton(p, value=(p == "all"))
|
|
105
|
+
yield Button("Run Analysis", id="run-btn", variant="primary")
|
|
106
|
+
yield Static("", id="status")
|
|
107
|
+
with Vertical(id="right-panel"):
|
|
108
|
+
yield RichLog(highlight=True, markup=True, id="results-log")
|
|
109
|
+
yield Footer()
|
|
110
|
+
|
|
111
|
+
def on_mount(self) -> None:
|
|
112
|
+
self.query_one("#path-input", Input).focus()
|
|
113
|
+
log = self.query_one(RichLog)
|
|
114
|
+
log.write("[bold]ErrorLens[/bold] — ready. Enter a path and press [bold]R[/bold] or click Run.")
|
|
115
|
+
|
|
116
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
117
|
+
if event.button.id == "run-btn":
|
|
118
|
+
self.action_run_analysis()
|
|
119
|
+
|
|
120
|
+
def action_run_analysis(self) -> None:
|
|
121
|
+
if self.running:
|
|
122
|
+
return
|
|
123
|
+
path_str = self.query_one("#path-input", Input).value.strip()
|
|
124
|
+
if not path_str:
|
|
125
|
+
self._set_status("Enter a path first.", error=True)
|
|
126
|
+
return
|
|
127
|
+
provider = self._selected_provider()
|
|
128
|
+
self._start_analysis(path_str, provider)
|
|
129
|
+
|
|
130
|
+
def action_clear_results(self) -> None:
|
|
131
|
+
self.query_one(RichLog).clear()
|
|
132
|
+
|
|
133
|
+
def _selected_provider(self) -> str:
|
|
134
|
+
radio_set = self.query_one("#provider-set", RadioSet)
|
|
135
|
+
if radio_set.pressed_button:
|
|
136
|
+
return str(radio_set.pressed_button.label)
|
|
137
|
+
return "all"
|
|
138
|
+
|
|
139
|
+
def _set_status(self, msg: str, error: bool = False) -> None:
|
|
140
|
+
style = "bold red" if error else "$text-muted"
|
|
141
|
+
self.query_one("#status", Static).update(f"[{style}]{msg}[/{style}]")
|
|
142
|
+
|
|
143
|
+
@work(thread=True)
|
|
144
|
+
def _start_analysis(self, path_str: str, provider: str) -> None:
|
|
145
|
+
self.running = True
|
|
146
|
+
self.call_from_thread(self._set_status, "Analyzing...")
|
|
147
|
+
log = self.query_one(RichLog)
|
|
148
|
+
|
|
149
|
+
target = Path(path_str)
|
|
150
|
+
if not target.exists():
|
|
151
|
+
self.call_from_thread(self._set_status, f"Path not found: {path_str}", error=True)
|
|
152
|
+
self.running = False
|
|
153
|
+
return
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
analyzer = CodeAnalyzer()
|
|
157
|
+
provider_list = ["anthropic", "mistral", "groq"] if provider == "all" else [provider]
|
|
158
|
+
analyzer.initialize_providers(provider_list)
|
|
159
|
+
|
|
160
|
+
self.call_from_thread(
|
|
161
|
+
log.write,
|
|
162
|
+
f"\n[bold cyan]Analyzing:[/bold cyan] {path_str} [bold cyan]Provider:[/bold cyan] {provider}\n"
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
results = analyzer.analyze_path(target, provider_list)
|
|
166
|
+
self.call_from_thread(self._render_results, results, log)
|
|
167
|
+
self.call_from_thread(self._set_status, "Done.")
|
|
168
|
+
except Exception as e:
|
|
169
|
+
self.call_from_thread(self._set_status, f"Error: {e}", error=True)
|
|
170
|
+
|
|
171
|
+
self.running = False
|
|
172
|
+
|
|
173
|
+
def _render_results(self, results: dict, log: RichLog) -> None:
|
|
174
|
+
log.write("=" * 60)
|
|
175
|
+
if "directory" in results:
|
|
176
|
+
log.write(f"[bold]Directory:[/bold] {results['directory']}")
|
|
177
|
+
log.write(
|
|
178
|
+
f"Files: {len(results['files'])} | "
|
|
179
|
+
f"OK: {results['summary']['successful_analyses']} | "
|
|
180
|
+
f"Failed: {results['summary']['failed_analyses']}"
|
|
181
|
+
)
|
|
182
|
+
for file_result in results["files"]:
|
|
183
|
+
self._render_file(file_result, log)
|
|
184
|
+
else:
|
|
185
|
+
self._render_file(results, log)
|
|
186
|
+
log.write("=" * 60)
|
|
187
|
+
|
|
188
|
+
def _render_file(self, file_result: dict, log: RichLog) -> None:
|
|
189
|
+
log.write("")
|
|
190
|
+
status_icon = "[bold green]✔[/bold green]" if file_result.get("success") else "[bold red]✘[/bold red]"
|
|
191
|
+
log.write(f"{status_icon} [bold]{file_result['file']}[/bold] [{file_result.get('language', 'unknown')}]")
|
|
192
|
+
|
|
193
|
+
if not file_result.get("success"):
|
|
194
|
+
log.write(f" [red]Error: {file_result.get('error', 'Unknown')}[/red]")
|
|
195
|
+
return
|
|
196
|
+
|
|
197
|
+
for provider_name, provider_result in file_result.get("providers", {}).items():
|
|
198
|
+
log.write(f"\n [bold magenta]── {provider_name.upper()} ──[/bold magenta]")
|
|
199
|
+
if not provider_result.get("success", True):
|
|
200
|
+
log.write(f" [red]{provider_result.get('error', 'Failed')}[/red]")
|
|
201
|
+
continue
|
|
202
|
+
|
|
203
|
+
analysis = provider_result.get("analysis", {})
|
|
204
|
+
sections = {
|
|
205
|
+
"Security Issues": analysis.get("security_issues", []),
|
|
206
|
+
"Potential Bugs": analysis.get("bugs", []),
|
|
207
|
+
"Code Quality Issues": analysis.get("code_quality", []),
|
|
208
|
+
"Suggestions": analysis.get("suggestions", []),
|
|
209
|
+
}
|
|
210
|
+
found_any = False
|
|
211
|
+
for section, items in sections.items():
|
|
212
|
+
if not items:
|
|
213
|
+
continue
|
|
214
|
+
found_any = True
|
|
215
|
+
style = SEVERITY_STYLES[section]
|
|
216
|
+
log.write(f" [{style}]{section}:[/{style}]")
|
|
217
|
+
for item in items:
|
|
218
|
+
log.write(f" • {item}")
|
|
219
|
+
|
|
220
|
+
if not found_any:
|
|
221
|
+
log.write(" [green]No issues found.[/green]")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def main():
|
|
225
|
+
app = ErrorLensApp()
|
|
226
|
+
app.run()
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
if __name__ == "__main__":
|
|
230
|
+
main()
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: errorlens
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: AI-powered CLI tool for finding bugs and security issues in codebases
|
|
5
|
+
Author-email: ErrorLens <info@errorlens.io>
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: security,static-analysis,ai,bugs,code-review
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Topic :: Security
|
|
11
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Requires-Dist: textual>=0.50.0
|
|
22
|
+
Requires-Dist: click>=8.0.0
|
|
23
|
+
Requires-Dist: requests>=2.25.0
|
|
24
|
+
Requires-Dist: python-dotenv>=0.19.0
|
|
25
|
+
Requires-Dist: anthropic>=0.20.0
|
|
26
|
+
Requires-Dist: mistralai>=0.1.0
|
|
27
|
+
Requires-Dist: groq>=0.4.0
|
|
28
|
+
|
|
29
|
+
# ErrorLens
|
|
30
|
+
|
|
31
|
+
A CLI and TUI tool that analyzes codebases for bugs and security issues using multiple AI providers.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Features
|
|
36
|
+
|
|
37
|
+
- **Multi-provider analysis** — Anthropic (Claude), Groq (Llama 3), and Mistral
|
|
38
|
+
- **Two interfaces** — a classic CLI for scripting and a rich Terminal UI (TUI) for interactive use
|
|
39
|
+
- **Parallel file processing** — analyzes directories concurrently
|
|
40
|
+
- **Multiple output formats** — console, JSON, and Markdown
|
|
41
|
+
- **12+ languages supported** — Python, JavaScript, TypeScript, Go, Rust, Java, and more
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Installation
|
|
46
|
+
|
|
47
|
+
**Requirements:** Python 3.8+
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
# Clone the repo
|
|
51
|
+
git clone https://github.com/your-repo/errorlens.git
|
|
52
|
+
cd errorlens
|
|
53
|
+
|
|
54
|
+
# Create and activate a virtual environment
|
|
55
|
+
python -m venv venv
|
|
56
|
+
source venv/bin/activate # Windows: venv\Scripts\activate
|
|
57
|
+
|
|
58
|
+
# Install dependencies
|
|
59
|
+
pip install -r requirements.txt
|
|
60
|
+
|
|
61
|
+
# Install the package (gives you the `errorlens` command)
|
|
62
|
+
pip install -e .
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Configuration
|
|
68
|
+
|
|
69
|
+
Create a `.env` file in the project root:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
cat > .env << 'EOF'
|
|
73
|
+
ANTHROPIC_API_KEY="your-anthropic-api-key"
|
|
74
|
+
MISTRAL_API_KEY="your-mistral-api-key"
|
|
75
|
+
GROQ_API_KEY="your-groq-api-key"
|
|
76
|
+
EOF
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
You only need keys for the providers you plan to use.
|
|
80
|
+
|
|
81
|
+
| Provider | Model | Notes |
|
|
82
|
+
|-----------|------------------------|------------------------|
|
|
83
|
+
| Anthropic | claude-3-opus-20240229 | Real API call |
|
|
84
|
+
| Groq | llama3-70b-8192 | Real API call |
|
|
85
|
+
| Mistral | mistral-large-latest | Pattern-based (mock) |
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## CLI Usage
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
# Analyze a single file (all providers)
|
|
93
|
+
python main.py path/to/file.py
|
|
94
|
+
|
|
95
|
+
# Analyze a directory
|
|
96
|
+
python main.py path/to/project/
|
|
97
|
+
|
|
98
|
+
# Choose a specific provider
|
|
99
|
+
python main.py file.py --provider anthropic
|
|
100
|
+
python main.py file.py --provider groq
|
|
101
|
+
python main.py file.py --provider mistral
|
|
102
|
+
|
|
103
|
+
# Change output format
|
|
104
|
+
python main.py file.py --output json
|
|
105
|
+
python main.py file.py --output markdown
|
|
106
|
+
|
|
107
|
+
# Verbose logging
|
|
108
|
+
python main.py file.py --verbose
|
|
109
|
+
|
|
110
|
+
# If installed via pip install -e .
|
|
111
|
+
errorlens file.py --provider anthropic
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### CLI Options
|
|
115
|
+
|
|
116
|
+
| Flag | Values | Default |
|
|
117
|
+
|--------------|-------------------------------------|----------|
|
|
118
|
+
| `--provider` | `anthropic`, `mistral`, `groq`, `all` | `all` |
|
|
119
|
+
| `--output` | `console`, `json`, `markdown` | `console`|
|
|
120
|
+
| `--verbose` | — | off |
|
|
121
|
+
| `--config` | path to JSON config file | — |
|
|
122
|
+
|
|
123
|
+
### Example console output
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
ErrorLens
|
|
127
|
+
Analyzing: example_test.py
|
|
128
|
+
Provider: groq
|
|
129
|
+
|
|
130
|
+
==================================================
|
|
131
|
+
ERRORLENS ANALYSIS RESULTS
|
|
132
|
+
==================================================
|
|
133
|
+
|
|
134
|
+
File: example_test.py
|
|
135
|
+
Language: python
|
|
136
|
+
Status: SUCCESS
|
|
137
|
+
|
|
138
|
+
--- GROQ ANALYSIS ---
|
|
139
|
+
Security Issues:
|
|
140
|
+
- Hardcoded credentials found in DB_PASSWORD and API_KEY variables
|
|
141
|
+
- SQL injection vulnerability in login() function
|
|
142
|
+
- Insecure deserialization using pickle.loads()
|
|
143
|
+
Potential Bugs:
|
|
144
|
+
- Division by zero possible in complex_calculation()
|
|
145
|
+
Code Quality Issues:
|
|
146
|
+
- Unused function detected
|
|
147
|
+
Suggestions:
|
|
148
|
+
- Use environment variables for credentials
|
|
149
|
+
- Use parameterized queries
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## TUI Usage
|
|
155
|
+
|
|
156
|
+
Launch the interactive terminal interface:
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
python tui.py
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### Layout
|
|
163
|
+
|
|
164
|
+
```
|
|
165
|
+
┌─────────────────────────────────────────────────────────┐
|
|
166
|
+
│ ErrorLens 12:00:00 │
|
|
167
|
+
├────────────────┬────────────────────────────────────────┤
|
|
168
|
+
│ │ │
|
|
169
|
+
│ Path │ Analyzing: example_test.py │
|
|
170
|
+
│ [___________] │ Provider: mistral │
|
|
171
|
+
│ │ ════════════════════════════════════ │
|
|
172
|
+
│ Provider │ │
|
|
173
|
+
│ ○ anthropic │ ✔ example_test.py [python] │
|
|
174
|
+
│ ○ mistral │ │
|
|
175
|
+
│ ○ groq │ ── MISTRAL ── │
|
|
176
|
+
│ ● all │ Security Issues: │
|
|
177
|
+
│ │ • Hardcoded credentials detected │
|
|
178
|
+
│ [Run Analysis]│ • Insecure pickle deserialization │
|
|
179
|
+
│ │ Potential Bugs: │
|
|
180
|
+
│ Analyzing... │ • Division by zero │
|
|
181
|
+
│ │ │
|
|
182
|
+
├────────────────┴────────────────────────────────────────┤
|
|
183
|
+
│ R Run C Clear Q Quit │
|
|
184
|
+
└─────────────────────────────────────────────────────────┘
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Keybindings
|
|
188
|
+
|
|
189
|
+
| Key | Action |
|
|
190
|
+
|-----|---------------|
|
|
191
|
+
| `R` | Run analysis |
|
|
192
|
+
| `C` | Clear results |
|
|
193
|
+
| `Q` | Quit |
|
|
194
|
+
|
|
195
|
+
Results are color-coded:
|
|
196
|
+
- **Red** — Security issues
|
|
197
|
+
- **Yellow** — Potential bugs
|
|
198
|
+
- **Cyan** — Code quality issues
|
|
199
|
+
- **Green** — Suggestions
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
## Supported Languages
|
|
204
|
+
|
|
205
|
+
| Language | Extension(s) |
|
|
206
|
+
|------------|----------------|
|
|
207
|
+
| Python | `.py` |
|
|
208
|
+
| JavaScript | `.js` |
|
|
209
|
+
| TypeScript | `.ts` |
|
|
210
|
+
| Java | `.java` |
|
|
211
|
+
| C / C++ | `.c`, `.cpp` |
|
|
212
|
+
| Go | `.go` |
|
|
213
|
+
| Rust | `.rs` |
|
|
214
|
+
| Ruby | `.rb` |
|
|
215
|
+
| PHP | `.php` |
|
|
216
|
+
| Swift | `.swift` |
|
|
217
|
+
| Kotlin | `.kt` |
|
|
218
|
+
| C# | `.cs` |
|
|
219
|
+
|
|
220
|
+
---
|
|
221
|
+
|
|
222
|
+
## Project Structure
|
|
223
|
+
|
|
224
|
+
```
|
|
225
|
+
errorlens/
|
|
226
|
+
├── main.py # CLI entry point
|
|
227
|
+
├── tui.py # TUI entry point
|
|
228
|
+
├── requirements.txt
|
|
229
|
+
├── setup.py
|
|
230
|
+
├── .env # API keys (not committed)
|
|
231
|
+
├── example_test.py # Sample file with intentional issues
|
|
232
|
+
├── core/
|
|
233
|
+
│ ├── analyzer.py # File discovery and analysis orchestration
|
|
234
|
+
│ └── config.py # Configuration and env loading
|
|
235
|
+
└── providers/
|
|
236
|
+
├── anthropic_provider.py # Anthropic Claude integration
|
|
237
|
+
├── groq_provider.py # Groq Llama 3 integration
|
|
238
|
+
├── mistral_provider.py # Mistral integration
|
|
239
|
+
└── mock_provider.py # Offline mock for testing
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## Testing with the Example File
|
|
245
|
+
|
|
246
|
+
`example_test.py` is bundled with intentional security flaws and bugs — use it to verify your setup:
|
|
247
|
+
|
|
248
|
+
```bash
|
|
249
|
+
python main.py example_test.py --provider groq
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
|
|
254
|
+
## License
|
|
255
|
+
|
|
256
|
+
MIT License — see LICENSE for details.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
errorlens/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
2
|
+
errorlens/cli.py,sha256=eDWjn4vfSYgOQzYpglMSnvJnXdV0B9VdnS9kGIPR0wE,5240
|
|
3
|
+
errorlens/tui.py,sha256=chj9ZZCxb_1CoyVofQITfb5Qq8Gkr_KICMZ782vfMaA,7262
|
|
4
|
+
errorlens/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
errorlens/core/analyzer.py,sha256=dQaVg70I0F5ZuV5BuQZPoxKaZfpaQgHe10VYmEmAiP4,5059
|
|
6
|
+
errorlens/core/config.py,sha256=HI5F-rT9j0TxoHmAP3jU_-GZfRmvLSmEClkZ5Y0DMeg,3057
|
|
7
|
+
errorlens/providers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
errorlens/providers/anthropic_provider.py,sha256=n8eopqLbQZbfxnCHvqbXF9dgRYuv8-S1czUFTyy9vps,3472
|
|
9
|
+
errorlens/providers/groq_provider.py,sha256=bsqk1hhqOnalclal9O3s397Yd1gp5w0o5Ro5_seqwD4,3543
|
|
10
|
+
errorlens/providers/mistral_provider.py,sha256=Yf4-yzkgl_uSSDnT4VA7yLOt91tZjs_nDuttErxIh7c,4568
|
|
11
|
+
errorlens/providers/mock_provider.py,sha256=rB4rnYWlXkeKWR9M9j7-KwStE4EDja_FvLnO7ImjZ8g,4400
|
|
12
|
+
errorlens-0.1.0.dist-info/METADATA,sha256=bikKSna76ouH2Um_RbKu6rEyj-SnC8Bvx-Tpl4yhf9g,8060
|
|
13
|
+
errorlens-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
14
|
+
errorlens-0.1.0.dist-info/entry_points.txt,sha256=G2cxbvEecWt4hxAJ468AlrgparRawAp9cYQbmMT2jU4,84
|
|
15
|
+
errorlens-0.1.0.dist-info/top_level.txt,sha256=QMgLF5we3Fb58D7JyPuufy-mf76Y5Amun60yu3e4vCI,10
|
|
16
|
+
errorlens-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
errorlens
|