Spaces:
Configuration error
Configuration error
| import ast, re | |
| def detect_language(filename): | |
| if not filename or "." not in filename: | |
| return "text" | |
| ext = filename.split(".")[-1].lower() | |
| mapping = {"py":"python","js":"javascript","ts":"typescript","java":"java","cs":"csharp","html":"html","css":"css","json":"json","md":"markdown"} | |
| return mapping.get(ext, ext) | |
| def analyze_python(code: str): | |
| try: | |
| tree = ast.parse(code) | |
| except Exception as e: | |
| return {"ok": False, "error": f"Syntax Error: {e}", "suggestion": "Check indentation or syntax near the reported location."} | |
| issues = [] | |
| class FuncVisitor(ast.NodeVisitor): | |
| def visit_FunctionDef(self, node): | |
| start = node.lineno | |
| end = node.lineno | |
| for n in ast.walk(node): | |
| if hasattr(n, "lineno"): | |
| end = max(end, n.lineno) | |
| length = end - start + 1 | |
| if length > 200: | |
| issues.append({"type":"large_function","message":f"Function '{node.name}' is {length} lines; consider refactoring."}) | |
| self.generic_visit(node) | |
| FuncVisitor().visit(tree) | |
| return {"ok": True, "issues": issues, "summary": "Parsed AST successfully."} | |
| def analyze_javascript(code: str): | |
| if "console.log" in code and "debugger" in code: | |
| return {"ok": True, "notes":"Found console.log and debugger. Remove before prod."} | |
| if "function(" not in code and "=>" not in code: | |
| return {"ok": True, "notes":"No obvious function constructs found."} | |
| return {"ok": True, "notes":"Basic JS analysis complete."} | |
| def analyze_code(filename, code): | |
| lang = detect_language(filename) | |
| if lang == "python": | |
| return analyze_python(code) | |
| if lang in ("javascript","typescript"): | |
| return analyze_javascript(code) | |
| return {"ok": True, "notes": f"Language {lang} not deeply analyzed. Size {len(code)} bytes.", "head": code[:800]} | |