File size: 2,896 Bytes
f2fe5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import ast
import logging
from database.models import DocumentAnalysis
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "sqlite:///document_analysis.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Configure logging
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

class CodeParser:
    def __init__(self, code):
        try:
            if not code.strip():
                raise ValueError("Input code cannot be empty")
            self.tree = ast.parse(code)
        except ValueError as e:
            logging.error(f"ValueError: {e}")
            raise
        except SyntaxError as e:
            logging.error(f"SyntaxError: {e}")
            raise
        except Exception as e:
            logging.error(f"Unexpected error in CodeParser constructor: {e}")
            raise

    def find_functions(self):
        try:
            return [node.name for node in ast.walk(self.tree) if isinstance(node, ast.FunctionDef)]
        except Exception as e:
            logging.error(f"Unexpected error in find_functions: {e}")
            return []

    def analyze_code(self):
        try:
            if not self.tree.body:
                return {"error": "Empty code input"}
            analysis = {
                "num_functions": len(self.find_functions()),
                "lines_of_code": len(self.tree.body),
            }
            return analysis
        except Exception as e:
            logging.error(f"Unexpected error in analyze_code: {e}")
            return {"error": "Analysis failed"}

    def save_analysis_to_db(self, source, title, links, error):
        session = SessionLocal()
        try:
            analysis_result = DocumentAnalysis(
                source=source,
                title=title,
                links=links,
                error=error
            )
            session.add(analysis_result)
            session.commit()
        except Exception as e:
            logging.error(f"Error saving analysis to database: {e}")
        finally:
            session.close()

    def verify_database_connection(self):
        try:
            session = SessionLocal()
            session.execute('SELECT 1')
            session.close()
            print("Database connection verified.")
        except Exception as e:
            print(f"Database connection verification failed: {e}")

if __name__ == "__main__":
    sample_code = "def example():\n    return True"
    parser = CodeParser(sample_code)
    analysis = parser.analyze_code()
    try:
        parser.save_analysis_to_db("sample_code.py", "Code Analysis", str(analysis), None)
    except Exception as e:
        logging.error(f"Unexpected error in save_analysis_to_db: {e}")
    parser.verify_database_connection()
    print(analysis)