File size: 14,556 Bytes
2bfb7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 9: tools/code_tools.py
with open(f"{base_dir}/tools/code_tools.py", "w") as f:
    f.write('''"""Code Development and Analysis Tools"""
import os
import re
import json
import subprocess
import tempfile
from typing import Dict, List, Optional
from config import Config
from utils import Logger, truncate

class CodeTools:
    """Code linting, formatting, git operations, and project analysis"""
    
    def __init__(self):
        self.logger = Logger()
    
    def code_lint(self, path: str = ".", language: str = "python", 
                  fix: bool = False, rules: List[str] = None) -> Dict:
        """Lint code for errors and style issues"""
        try:
            full_path = os.path.join(Config.SANDBOX_PATH, path)
            
            if language == "python":
                tools_to_try = [
                    ("flake8", f"flake8 {'--fix' if fix else ''} {full_path}"),
                    ("pylint", f"pylint {full_path}"),
                ]
                
                for tool_name, cmd in tools_to_try:
                    result = subprocess.run(
                        cmd, shell=True, capture_output=True, text=True, timeout=30
                    )
                    if result.returncode in [0, 1]:
                        issues = []
                        for line in (result.stdout + result.stderr).split("\n"):
                            if line.strip():
                                issues.append(line.strip())
                        
                        return {
                            "success": True,
                            "tool": tool_name,
                            "language": language,
                            "issues": issues[:50],
                            "total_issues": len(issues),
                            "fixed": fix,
                            "path": path
                        }
                
                if os.path.isfile(full_path):
                    with open(full_path, "r") as f:
                        code = f.read()
                    compile(code, full_path, "exec")
                    return {
                        "success": True,
                        "tool": "builtin",
                        "language": language,
                        "issues": [],
                        "total_issues": 0,
                        "message": "Syntax OK"
                    }
            
            elif language == "javascript":
                for tool, cmd in [("eslint", f"eslint {full_path}"), 
                                  ("jshint", f"jshint {full_path}")]:
                    result = subprocess.run(
                        cmd, shell=True, capture_output=True, text=True, timeout=30
                    )
                    if result.returncode in [0, 1, 2]:
                        return {
                            "success": True,
                            "tool": tool,
                            "language": language,
                            "output": (result.stdout + result.stderr)[:2000],
                            "path": path
                        }
            
            return {
                "success": True,
                "language": language,
                "message": "No linter available, basic syntax check passed",
                "path": path
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def code_format(self, path: str = ".", language: str = "python", 
                    check_only: bool = False) -> Dict:
        """Format code automatically"""
        try:
            full_path = os.path.join(Config.SANDBOX_PATH, path)
            
            formatters = {
                "python": ("black", f"black {'--check' if check_only else ''} {full_path}"),
                "javascript": ("prettier", f"prettier {'--check' if check_only else '--write'} {full_path}"),
                "html": ("prettier", f"prettier --parser html {'--check' if check_only else '--write'} {full_path}"),
                "css": ("prettier", f"prettier --parser css {'--check' if check_only else '--write'} {full_path}"),
            }
            
            if language in formatters:
                tool, cmd = formatters[language]
                result = subprocess.run(
                    cmd, shell=True, capture_output=True, text=True, timeout=30
                )
                
                return {
                    "success": result.returncode in [0, 1],
                    "tool": tool,
                    "language": language,
                    "formatted": not check_only and result.returncode == 0,
                    "needs_formatting": result.returncode == 1,
                    "output": (result.stdout + result.stderr)[:2000],
                    "path": path
                }
            
            return {"success": False, "error": f"No formatter for {language}"}
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def git_command(self, action: str = "status", args: str = "", 
                    repo_path: str = ".") -> Dict:
        """Execute git commands"""
        try:
            full_repo = os.path.join(Config.SANDBOX_PATH, repo_path)
            os.makedirs(full_repo, exist_ok=True)
            
            if action == "init":
                cmd = f"git init {args}"
            elif action == "clone":
                cmd = f"git clone {args}"
            elif action == "commit":
                cmd = f'git commit {args}'
            else:
                cmd = f"git {action} {args}"
            
            result = subprocess.run(
                cmd,
                shell=True,
                capture_output=True,
                text=True,
                timeout=60,
                cwd=full_repo
            )
            
            self.logger.log("git_command", {"action": action, "args": args, "repo": repo_path})
            
            return {
                "success": result.returncode == 0,
                "action": action,
                "command": cmd,
                "stdout": result.stdout[:3000],
                "stderr": result.stderr[:1000],
                "repo": repo_path
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def dependency_check(self, path: str = ".", manifest: str = "auto") -> Dict:
        """Check for outdated or vulnerable dependencies"""
        try:
            full_path = os.path.join(Config.SANDBOX_PATH, path)
            
            if manifest == "auto":
                for candidate in ["requirements.txt", "package.json", "pyproject.toml", "Pipfile"]:
                    if os.path.exists(os.path.join(full_path, candidate)):
                        manifest = candidate
                        break
            
            if manifest == "requirements.txt":
                req_file = os.path.join(full_path, "requirements.txt")
                result = subprocess.run(
                    f"pip list --outdated --format=json",
                    shell=True, capture_output=True, text=True, timeout=30
                )
                
                outdated = []
                try:
                    packages = json.loads(result.stdout)
                    with open(req_file, "r") as f:
                        required = [line.split("==")[0].strip().lower() for line in f if line.strip() and not line.startswith("#")]
                    
                    for pkg in packages:
                        if pkg["name"].lower() in required:
                            outdated.append(pkg)
                except:
                    pass
                
                return {
                    "success": True,
                    "manifest": manifest,
                    "outdated": outdated,
                    "total_outdated": len(outdated),
                    "path": path
                }
            
            elif manifest == "package.json":
                pkg_file = os.path.join(full_path, "package.json")
                result = subprocess.run(
                    "npm outdated --json",
                    shell=True, capture_output=True, text=True, timeout=30,
                    cwd=full_path
                )
                
                outdated = {}
                try:
                    outdated = json.loads(result.stdout) if result.stdout.strip() else {}
                except:
                    pass
                
                return {
                    "success": True,
                    "manifest": manifest,
                    "outdated": outdated,
                    "total_outdated": len(outdated),
                    "path": path
                }
            
            return {
                "success": True,
                "manifest": manifest,
                "message": "No manifest found or unsupported format",
                "path": path
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def project_structure(self, path: str = ".", max_depth: int = 4, 
                          exclude: List[str] = None) -> Dict:
        """Analyze project structure"""
        try:
            full_path = os.path.join(Config.SANDBOX_PATH, path)
            
            if not exclude:
                exclude = ["node_modules", ".git", "__pycache__", ".venv", "venv", ".env", ".trash"]
            
            structure = []
            file_count = 0
            dir_count = 0
            total_lines = 0
            languages = {}
            
            for root, dirs, files in os.walk(full_path):
                depth = root[len(full_path):].count(os.sep)
                if depth > max_depth:
                    del dirs[:]
                    continue
                
                dirs[:] = [d for d in dirs if d not in exclude and not d.startswith(".")]
                
                rel_root = os.path.relpath(root, full_path)
                if rel_root == ".":
                    rel_root = ""
                
                indent = "  " * depth
                structure.append(f"{indent}[DIR] {os.path.basename(root) or path}")
                
                for file in sorted(files):
                    if any(file.endswith(ext) for ext in [".pyc", ".pyo", ".class"]):
                        continue
                    
                    file_path = os.path.join(root, file)
                    file_indent = "  " * (depth + 1)
                    
                    try:
                        with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
                            lines = len(f.readlines())
                        total_lines += lines
                    except:
                        lines = 0
                    
                    ext = os.path.splitext(file)[1]
                    if ext:
                        languages[ext] = languages.get(ext, 0) + 1
                    
                    structure.append(f"{file_indent}{file} ({lines} lines)")
                    file_count += 1
                
                dir_count += 1
            
            top_langs = sorted(languages.items(), key=lambda x: x[1], reverse=True)[:10]
            
            self.logger.log("project_structure", {"path": path, "files": file_count, "dirs": dir_count})
            
            return {
                "success": True,
                "path": path,
                "structure": "\n".join(structure),
                "files": file_count,
                "directories": dir_count,
                "total_lines": total_lines,
                "top_languages": top_langs,
                "depth": max_depth
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def code_search(self, path: str = ".", query: str = "", 
                    language: str = "", max_results: int = 50) -> Dict:
        """Search codebase with regex"""
        try:
            full_path = os.path.join(Config.SANDBOX_PATH, path)
            
            results = []
            pattern = re.compile(query, re.IGNORECASE)
            
            for root, dirs, files in os.walk(full_path):
                dirs[:] = [d for d in dirs if not d.startswith(".") and d not in 
                          ["node_modules", "__pycache__", ".venv", "venv"]]
                
                for file in files:
                    if language:
                        ext_map = {
                            "python": ".py", "javascript": ".js", "typescript": ".ts",
                            "html": ".html", "css": ".css", "java": ".java",
                            "cpp": ".cpp", "c": ".c", "go": ".go", "rust": ".rs"
                        }
                        if not file.endswith(ext_map.get(language, language)):
                            continue
                    
                    file_path = os.path.join(root, file)
                    rel_path = os.path.relpath(file_path, full_path)
                    
                    try:
                        with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
                            lines = f.readlines()
                        
                        for i, line in enumerate(lines, 1):
                            if pattern.search(line):
                                results.append({
                                    "file": rel_path,
                                    "line": i,
                                    "text": line.strip()[:150],
                                    "context": "".join(lines[max(0,i-2):min(len(lines),i+1)]).strip()[:300]
                                })
                                
                                if len(results) >= max_results:
                                    break
                    except:
                        continue
                
                if len(results) >= max_results:
                    break
            
            return {
                "success": True,
                "query": query,
                "language": language,
                "results": results,
                "total": len(results),
                "path": path
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
''')

print("tools/code_tools.py done")