Rob200/LegacyCodeDocumentAgent
0
1"""
2File handling utilities for the Legacy Code Documentation Agent.
3Reads code files and detects their language.
4"""
5
6import os
7
8# Map file extensions to language names
9EXTENSION_MAP = {
10 ".sql": "SQL",
11 ".py": "Python",
12 ".cpp": "C++",
13 ".h": "C++",
14 ".dax": "DAX",
15 ".m": "DAX", # Power BI measure files sometimes use .m
16}
17
18
19def get_language_from_extension(filepath: str) -> str:
20 """
21 Determine the programming language based on file extension.
22
23 Args:
24 filepath: Path to the code file
25
26 Returns:
27 Language name as a string (e.g., "SQL", "Python")
28 """
29 _, extension = os.path.splitext(filepath)
30 extension = extension.lower()
31
32 return EXTENSION_MAP.get(extension, "Unknown")
33
34
35def read_code_file(filepath: str) -> dict:
36 """
37 Read a code file and return its contents with metadata.
38
39 Args:
40 filepath: Path to the code file
41
42 Returns:
43 Dictionary with keys: 'filename', 'language', 'content', 'success', 'error'
44 """
45 result = {
46 "filename": os.path.basename(filepath),
47 "language": None,
48 "content": None,
49 "success": False,
50 "error": None
51 }
52
53 # Check if file exists
54 if not os.path.exists(filepath):
55 result["error"] = f"File not found: {filepath}"
56 return result
57
58 # Get the language
59 result["language"] = get_language_from_extension(filepath)
60
61 # Read the file contents
62 try:
63 with open(filepath, "r", encoding="utf-8") as f:
64 result["content"] = f.read()
65 result["success"] = True
66 except Exception as e:
67 result["error"] = f"Error reading file: {str(e)}"
68
69 return result
70
71
72def get_code_files_from_folder(folder_path: str) -> list:
73 """
74 Scan a folder and return a list of supported code files.
75
76 Args:
77 folder_path: Path to the folder to scan
78
79 Returns:
80 List of file paths for supported code files
81 """
82 supported_files = []
83
84 # Check if folder exists
85 if not os.path.isdir(folder_path):
86 return supported_files
87
88 # Walk through the folder
89 for root, dirs, files in os.walk(folder_path):
90 for filename in files:
91 filepath = os.path.join(root, filename)
92 language = get_language_from_extension(filepath)
93
94 # Only include files we know how to handle
95 if language != "Unknown":
96 supported_files.append(filepath)
97
98 return supported_files