-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathiamnotacoder.py
More file actions
1876 lines (1678 loc) · 71.5 KB
/
Copy pathiamnotacoder.py
File metadata and controls
1876 lines (1678 loc) · 71.5 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# iamnotacoder.py (with extensive improvements)
import git
import os
import tempfile
import subprocess
import click
import time
import difflib
import uuid
import logging
import asyncio
import aiohttp
import shutil
import re
import ast
import json
import datetime
import hashlib
import sys
from rich.console import Console
from rich.progress import (
Progress,
SpinnerColumn,
TimeElapsedColumn,
TextColumn,
BarColumn,
MofNCompleteColumn,
)
from rich.table import Table
from rich.logging import RichHandler
from collections import Counter
from io import StringIO
from rich import box
import toml
import aiofiles # type: ignore
from openai import AsyncOpenAI # Using AsyncOpenAI for asynchronous API calls
from github import Github
from typing import List, Dict, Any, Optional, Tuple # <-- ADDED
# Optionally import rate limit error if available:
# from openai.error import RateLimitError
# Import helper functions from helpers.py
from helpers import (
load_config,
get_prompt,
create_backup,
restore_backup,
get_cli_config_priority,
validate_python_syntax,
extract_code_from_response,
format_llm_summary,
)
console = Console()
# Configure logging with Rich handler
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[RichHandler(rich_tracebacks=True)],
)
# Constants
DEFAULT_LLM_MODEL = "gpt-3.5-turbo-1106"
DEFAULT_LLM_TEMPERATURE = 0.2
MAX_SYNTAX_RETRIES = 5
MAX_LLM_RETRIES = 3
OPENAI_TIMEOUT = 120.0
MAX_PUSH_RETRIES = 3
DEFAULT_LINE_LENGTH = 79
CONFIG_ENCODING = "utf-8"
CACHE_ENCODING = "utf-8"
REPORT_ENCODING = "utf-8"
FORCED_API_BASE = "http://localhost:1234/v1" # <-- New: Forced endpoint URL constant
FOOTER_MARKDOWN = (
" \nYou are welcome to improve the project any time by sending back a PR ❤️"
)
class CommandExecutionError(Exception):
"""Custom exception for command execution failures."""
def __init__(self, command: str, returncode: int, stdout: str, stderr: str):
super().__init__(
f"Command `{command}` failed with return code {returncode}.\n"
f"Stderr: {stderr}\nStdout: {stdout}"
)
self.command = command
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
# Add custom exception for API timeouts
class APITimeoutError(Exception):
pass
async def run_command_async(
command: List[str], cwd: Optional[str] = None
) -> Tuple[str, str, int]:
"""Executes a shell command asynchronously and returns stdout, stderr,
and return code."""
cmd_str = " ".join(command)
try:
start_time = time.time()
proc = await asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=cwd,
)
stdout, stderr = await proc.communicate()
end_time = time.time()
stdout_str = stdout.decode()
stderr_str = stderr.decode()
if proc.returncode != 0:
raise CommandExecutionError(
cmd_str, proc.returncode, stdout_str, stderr_str
)
logging.info(
f"Command `{cmd_str}` executed in {end_time - start_time:.2f} seconds."
)
return stdout_str, stderr_str, proc.returncode
except FileNotFoundError as e:
logging.error(f"Command not found: {e}")
return "", str(e), 127
except CommandExecutionError as e:
logging.error(str(e))
return e.stdout, e.stderr, e.returncode
except Exception as e:
logging.exception(f"Unhandled error executing command `{cmd_str}`: {e}")
return "", str(e), 1
# Alias run_command to the async version
run_command = run_command_async
async def clone_repository(repo_url: str, token: str) -> Tuple[git.Repo, str]:
"""Clones a repository (shallow clone) to a temporary directory."""
temp_dir = tempfile.mkdtemp()
auth_repo_url = repo_url.replace("https://", f"https://{token}@")
try:
with Progress(
SpinnerColumn(),
TextColumn("[bold blue]Cloning repository (shallow)..."),
TimeElapsedColumn(),
transient=True,
) as progress:
task = progress.add_task("Cloning repository...", start=True)
start_time = time.time()
repo = await asyncio.to_thread(
git.Repo.clone_from, auth_repo_url, temp_dir, depth=1
)
end_time = time.time()
progress.update(
task,
description=f"Repository cloned in {end_time - start_time:.2f} seconds",
completed=100,
)
return repo, temp_dir
except git.exc.GitCommandError as e:
logging.exception(f"Error cloning repository from {repo_url}")
shutil.rmtree(temp_dir, ignore_errors=True) # Clean up temp dir
sys.exit(1)
async def checkout_branch(repo: git.Repo, branch_name: str) -> None:
"""Checks out a specific branch, fetching if necessary."""
try:
with Progress(
SpinnerColumn(),
TextColumn("[bold blue]Checking out branch..."),
TimeElapsedColumn(),
transient=True,
) as progress:
task = progress.add_task("Checking out branch...", start=True)
start_time = time.time()
await asyncio.to_thread(repo.git.fetch, "--all", "--prune")
await asyncio.to_thread(repo.git.checkout, branch_name)
end_time = time.time()
progress.update(
task,
description=f"Checked out branch in {end_time - start_time:.2f} seconds",
completed=100,
)
except git.exc.GitCommandError:
try:
logging.warning(f"Attempting to fetch remote branch {branch_name}")
with Progress(
SpinnerColumn(),
TextColumn("[bold blue]Checking out remote branch..."),
TimeElapsedColumn(),
transient=True,
) as progress:
task = progress.add_task(
"Checking out remote branch...", start=True
)
start_time = time.time()
await asyncio.to_thread(repo.git.fetch, "origin", branch_name)
await asyncio.to_thread(
repo.git.checkout, f"origin/{branch_name}"
)
end_time = time.time()
progress.update(
task,
description=f"Checked out remote branch in {end_time - start_time:.2f} seconds",
completed=100,
)
except git.exc.GitCommandError as e:
logging.exception(f"Error checking out branch {branch_name}")
sys.exit(1)
def create_branch(repo: git.Repo, files: List[str], file_purpose: str = "") -> str:
"""Creates a new, uniquely-named branch for the given files."""
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
sanitized_file_names = "_".join(
"".join(c if c.isalnum() else "_" for c in file) for file in files
)
unique_id = uuid.uuid4().hex[:8] # Shorten UUID for branch name
branch_name = (
f"improvement-{sanitized_file_names}-{file_purpose}-{timestamp}-{unique_id}"
)
try:
with Progress(
SpinnerColumn(),
TextColumn("[bold blue]Creating branch..."),
TimeElapsedColumn(),
transient=True,
) as progress:
task = progress.add_task("Creating branch...", start=True)
start_time = time.time()
repo.git.checkout("-b", branch_name)
end_time = time.time()
progress.update(
task,
description=f"Created branch in {end_time - start_time:.2f} seconds",
completed=100,
)
return branch_name
except git.exc.GitCommandError as e:
logging.exception(f"Error creating branch {branch_name}")
sys.exit(1)
def infer_file_purpose(file_path: str) -> str:
"""Infers file's purpose (function, class, or script)."""
try:
with open(file_path, "r", encoding=CONFIG_ENCODING) as f:
first_line = f.readline()
if "def " in first_line:
return "function"
elif "class " in first_line:
return "class"
return "script"
except Exception:
logging.exception(f"Error inferring purpose for {file_path}")
return "" # Consistent return type
def _create_analysis_table(
results: Dict[str, Dict[str, Any]], analysis_verbose: bool
) -> Table:
"""Creates a Rich Table for static analysis results. Helper function."""
table = Table(title="Static Analysis Summary", box=box.ROUNDED)
table.add_column("Tool", justify="left", style="cyan", no_wrap=True)
table.add_column("Status", justify="center")
table.add_column("Errors/Warnings", justify="left")
for tool, result in results.items():
returncode = result["returncode"]
errors = result.get("errors", "").strip()
output = result.get("output", "").strip()
if returncode == 0:
status = "[green]Passed[/green]"
error_summary = "-"
else:
# Default error display; may be refined below
status = "[red]Issues[/red]"
error_summary = errors
if tool in ["pylint", "flake8"]:
# In non-verbose mode, extract top error codes and file:line hints
if not analysis_verbose:
# find error codes (e.g., C0301) and file:line references (e.g., filename.py:23)
codes = re.findall(r"([A-Z]\d{3,4})", output)
locations = re.findall(r"(\S+:\d+)", output)
unique_locations = list(set(locations))
top_codes = ", ".join(
code for code, _ in Counter(codes).most_common(3)
)
loc_summary = f" at {', '.join(unique_locations[:3])}" if unique_locations else ""
error_summary = f"{len(codes)} ({top_codes}){loc_summary}" if codes else "-"
elif tool == "black":
# Mark purely as informational reformat suggestions.
if "would reformat" in output:
status = "[blue]Reformat suggested[/blue]"
error_summary = "Reformat changes suggested."
elif tool == "isort":
if "ERROR:" in output:
status = "[blue]Reformat suggested[/blue]"
error_summary = f"{output.count('ERROR:')} issues found."
elif tool == "mypy":
# For mypy, extract error summaries with file:line hints.
if not analysis_verbose:
locations = re.findall(r"(\S+:\d+)", output)
unique_locations = list(set(locations))
error_count = output.count("error:")
loc_summary = f" at {', '.join(unique_locations[:3])}" if unique_locations else ""
error_summary = f"{error_count}{loc_summary}" if error_count > 0 else "-"
else:
error_summary = errors
table.add_row(tool, status, error_summary)
return table
async def analyze_project(
repo_path: str,
file_path: str,
tools: List[str],
exclude_tools: List[str],
cache_dir: Optional[str] = None,
debug: bool = False,
analysis_verbose: bool = False,
line_length: int = 79,
) -> Dict[str, Dict[str, Any]]:
"""Runs static analysis tools, caching results. Returns results dict."""
cache_key_data = f"{file_path}-{','.join(sorted(tools))}-{','.join(sorted(exclude_tools))}-{line_length}".encode(
CACHE_ENCODING
)
cache_key = hashlib.sha256(cache_key_data).hexdigest()
cache_file = (
os.path.join(cache_dir, f"{cache_key}.json") if cache_dir else None
)
if cache_file and os.path.exists(cache_file):
try:
with open(cache_file, "r", encoding=CACHE_ENCODING) as f:
cached_results = json.load(f)
logging.info("Using static analysis results from cache.")
return cached_results
except (json.JSONDecodeError, Exception) as e:
logging.warning(f"Error loading cache, re-running analysis: {e}")
results: Dict[str, Dict[str, Any]] = {}
with Progress(
SpinnerColumn(),
TextColumn("[bold blue]{task.description}"),
TimeElapsedColumn(),
MofNCompleteColumn(), # Show "M of N"
console=console,
transient=True,
) as progress:
analysis_task = progress.add_task("Analyzing...", total=len(tools))
for tool in tools:
progress.update(analysis_task, description=f"Running {tool}...")
if tool in exclude_tools:
results[tool] = {
"output": "",
"errors": "Tool excluded.",
"returncode": 0, # Treat exclusion as success
}
progress.update(analysis_task, advance=1)
continue
if not shutil.which(tool):
results[tool] = {
"output": "",
"errors": "Tool not found.",
"returncode": 127, # Standard code for command not found
}
progress.update(analysis_task, advance=1)
continue
commands = {
"pylint": ["pylint", file_path],
"flake8": ["flake8", file_path],
"black": [
"black",
"--check",
"--diff",
f"--line-length={line_length}",
file_path,
],
"isort": ["isort", "--check-only", "--diff", file_path],
"mypy": ["mypy", file_path],
}
if tool in commands:
command = commands[tool]
try:
stdout, stderr, returncode = await run_command(
command, cwd=repo_path
)
results[tool] = {
"output": stdout,
"errors": stderr,
"returncode": returncode, # Store the return code
}
except CommandExecutionError as e: # Catch custom exception
results[tool] = {
"output": e.stdout,
"errors": e.stderr,
"returncode": e.returncode,
}
else:
results[tool] = {
"output": "",
"errors": "Unknown analysis tool.",
"returncode": 1,
}
progress.update(analysis_task, advance=1)
if cache_file:
try:
with open(cache_file, "w", encoding=CACHE_ENCODING) as f:
json.dump(results, f, indent=4)
logging.info("Static analysis results saved to cache.")
except Exception as e:
logging.warning(f"Error saving to cache: {e}")
return results # Return the results dictionary
async def get_llm_improvements_summary(
original_code: str,
improved_code: str,
categories: List[str],
client: AsyncOpenAI,
llm_model: str,
llm_temperature: float,
config: Dict, # Pass the config
) -> Dict[str, List[str]]:
"""Generates a summary of LLM improvements by category using the LLM."""
diff_lines = list(
difflib.unified_diff(
original_code.splitlines(), improved_code.splitlines(), lineterm=""
)
)
diff_text = "\n".join(diff_lines)
improvements_summary = {}
for category in categories:
prompt = (
f"Analyze the following code diff and list specific improvements in '{category}' category.\n"
f"Focus only on direct code improvements without introductory or concluding sentences.\n\n"
f"```diff\n{diff_text}\n```\n\n"
f"Improvements in '{category}':\n"
)
try:
response = await client.chat.completions.create( # CHANGED from acreate
model=llm_model,
messages=[
{
"role": "system",
"content": "You are a coding assistant summarizing code improvements.",
},
{"role": "user", "content": prompt},
],
temperature=min(llm_temperature, 0.2),
max_tokens=512,
)
summary = response.choices[0].message.content.strip()
improvements = [
line.strip() for line in summary.splitlines() if line.strip()
]
improvements = [
re.sub(r"^[\-\*\+] |\d+\.\s*", "", line)
for line in improvements
] # Clean list markers
improvements_summary[category] = improvements
except Exception as e:
logging.exception(
f"Error getting LLM improvements summary for category {category}"
)
improvements_summary[category] = ["Error retrieving improvements."]
return improvements_summary
async def format_code_with_tools(file_path: str, line_length: int) -> None:
"""Formats the code using black and isort, if available."""
if shutil.which("black"):
await run_command(
["black", f"--line-length={line_length}", file_path],
cwd=os.path.dirname(file_path),
)
if shutil.which("isort"):
await run_command(["isort", file_path], cwd=os.path.dirname(file_path))
async def _process_category_improvement(
category,
code_snippet,
start_line,
end_line,
config,
custom_prompt_dir,
client,
llm_model,
llm_temperature,
debug,
progress,
task_id,
analysis_data: Optional[Dict[str, Any]] = None # <-- NEW parameter for error info
):
"""
Processes improvement for one category with granular progress updates.
Now uses dynamic prompt selection, multi-stage improvement chaining, and category-specific syntax checks.
"""
# Mapping from error code to specific prompt file
error_prompt_mapping = {
"C0114": f"{custom_prompt_dir}/prompts/missing_docstring.txt",
"C0116": f"{custom_prompt_dir}/prompts/missing_function_docstring.txt",
# ...add more mappings as needed...
}
# Dynamic prompt selection based on analysis_data error codes
selected_prompt = None
if analysis_data:
for err_code, prompt_file in error_prompt_mapping.items():
if err_code in analysis_data.get("errors", ""):
try:
with open(prompt_file, "r", encoding="utf-8") as pf:
selected_prompt = pf.read()
if debug:
logging.debug(f"Using dynamic prompt from {prompt_file} for error code {err_code}")
break
except Exception as e:
logging.warning(f"Could not load prompt for {err_code}: {e}")
# Fallback generic prompt if no dynamic prompt found
if not selected_prompt:
selected_prompt = get_prompt(config, category, custom_prompt_dir)
# Append code context and a formatting constraint.
base_prompt = selected_prompt.replace("{code}", code_snippet)
base_prompt += f"\nMaintain a maximum line length of {DEFAULT_LINE_LENGTH} characters."
# Multi-stage prompt chain: Stage 1 - Identify Problem, Stage 2 - Plan Solution, Stage 3 - Implement Solution.
stages = [
("Identify the problem in the code:", base_prompt),
("Plan a step-by-step solution to fix the issue:", f"{base_prompt}\nConsider breaking down the solution into smaller steps."),
("Implement the solution based on the plan:", f"{base_prompt}\nApply the planned solution."),
]
retry_count = 0
improved_code_snippet = None
for stage_label, stage_prompt in stages:
for attempt in range(MAX_LLM_RETRIES):
retry_count = attempt + 1
progress.update(task_id, description=f"[blue]Improving {category} - {stage_label} (attempt {attempt+1}/{MAX_LLM_RETRIES})[/blue]", fields={"status": "In progress..."})
current_prompt = stage_prompt
if attempt > 0:
# Chained prompt with enriched error context.
current_prompt = (
f"Previous attempt produced syntax errors or did not resolve the issue.\n"
f"Re-evaluate the following code snippet between lines {start_line} and {end_line}:\n{code_snippet}\n"
f"Static analysis reports:\n{analysis_data.get('errors', 'No errors')}\n"
f"{stage_prompt}"
)
if debug:
logging.debug(f"LLM prompt for {category} - {stage_label} (attempt {attempt+1}):\n{current_prompt}")
try:
response = await client.chat.completions.create( # CHANGED from acreate
model=llm_model,
messages=[
{"role": "system", "content": "You are a helpful coding assistant that improves code quality."},
{"role": "user", "content": current_prompt},
],
temperature=llm_temperature,
max_tokens=1024,
timeout=OPENAI_TIMEOUT,
)
candidate_code = extract_code_from_response(response.choices[0].message.content)
# Validate syntax and perform category-specific checks.
if not validate_python_syntax(candidate_code):
logging.warning(f"Syntax error in LLM response for {category} at stage '{stage_label}' on attempt {attempt+1}")
continue
# Category-specific syntax check for 'security'.
if category.lower() == "security" and not is_security_compliant(candidate_code):
logging.warning(f"Security issues detected in improved code for {category} at stage '{stage_label}' on attempt {attempt+1}")
continue
# (Optional) Re-run static analysis for the category to validate improvement.
if analysis_data and not validate_category_improvement(candidate_code, analysis_data, category):
logging.warning(f"Static analysis check failed for {category} at stage '{stage_label}' on attempt {attempt+1}")
continue
improved_code_snippet = candidate_code
progress.update(task_id, fields={"status": f"Stage '{stage_label}' completed"})
break # Successful improvement at this stage.
except Exception as e:
logging.exception(f"LLM error in category {category} at stage '{stage_label}' on attempt {attempt+1}: {e}")
if improved_code_snippet is None:
progress.update(task_id, fields={"status": f"Stage '{stage_label}' failed"})
break # Exit if current stage failed.
else:
# For chaining, use the improved output as the new code snippet for the next stage.
code_snippet = improved_code_snippet
if improved_code_snippet:
progress.update(task_id, fields={"status": "Completed"})
else:
progress.update(task_id, fields={"status": "Failed"})
return improved_code_snippet, retry_count
# New helper function for security check (example implementation)
def is_security_compliant(code: str) -> bool:
"""
Performs basic security checks on the improved code.
Example: checks for usage of unsafe functions like eval or exec.
"""
insecure_patterns = [r"\beval\(", r"\bexec\("]
for pattern in insecure_patterns:
if re.search(pattern, code):
return False
return True
# New helper function for validating category-specific improvements (stub)
def validate_category_improvement(code: str, analysis_data: Dict[str, Any], category: str) -> bool:
"""
Placeholder for re-running static analysis for a specific category.
Returns True if the improvement is validated.
"""
# ...existing code or integration with analysis tools...
return True
async def apply_llm_improvements(
file_path: str,
client: AsyncOpenAI,
llm_model: str,
llm_temperature: float,
categories: List[str],
config: Dict,
custom_prompt_dir: str,
line_length: int,
progress: Progress,
improve_task_id: int,
debug: bool,
analysis_results: Dict[str, Dict[str, Any]],
) -> Tuple[str, bool, Dict[str, int]]:
"""Applies LLM improvements, handling retries, and tracking per-category attempts."""
total_success = True
improvements_by_category = {}
retry_counts: Dict[str, int] = {category: 0 for category in categories} # Track retries
with open(file_path, "r", encoding="utf-8") as f:
source_code = f.read()
tree = ast.parse(source_code)
updated_code = source_code
progress_amount = 1 / len(categories) # calculate fixed advance amount
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef)):
code_snippet = ast.get_source_segment(source_code, node)
if code_snippet is None:
continue # Skip if source segment not found
start_line = node.lineno
end_line = node.end_lineno
for category in categories:
relevant_errors = False
if analysis_results:
for tool_results in analysis_results.values():
if tool_results["returncode"] != 0:
for error_line in tool_results["errors"].splitlines():
match = re.search(r":(\d+):", error_line)
if match:
error_line_num = int(match.group(1))
if start_line <= error_line_num <= end_line:
relevant_errors = True
break
if relevant_errors:
break
if not relevant_errors and category not in ["general", "tests"]:
logging.info(f"Skipping LLM call for {category} due to no relevant errors.")
progress.advance(improve_task_id, progress_amount)
continue
improved_snippet, attempts = await _process_category_improvement(
category, code_snippet, start_line, end_line, config, custom_prompt_dir,
client, llm_model, llm_temperature, debug, progress, improve_task_id,
analysis_results.get(category) # Pass analysis data for the category
)
retry_counts[category] = attempts
if improved_snippet:
original_lines = updated_code.splitlines()
updated_lines = original_lines[:start_line - 1] + improved_snippet.splitlines() + original_lines[end_line:]
updated_code = "\n".join(updated_lines)
improvements_by_category[category] = improved_snippet
else:
total_success = False
progress.advance(improve_task_id, progress_amount)
return updated_code, total_success, retry_counts
async def improve_file(
file_path: str,
client: AsyncOpenAI,
llm_model: str,
llm_temperature: float,
categories: List[str],
config: Dict,
custom_prompt_dir: str,
analysis_results: Dict[str, Dict[str, Any]],
debug: bool = False,
line_length: int = DEFAULT_LINE_LENGTH,
) -> Tuple[str, bool]:
"""Improves file using LLM across categories, with retries."""
backup_path = create_backup(file_path)
if not backup_path:
logging.error("Failed to create backup. Aborting file improvement.")
return "", False
await format_code_with_tools(file_path, line_length)
# Track file-level status (added missing keys)
file_status = {
"changed": False,
"restored": False,
"llm_success": False, # Overall LLM success
"categories_attempted": [],
"categories_skipped": [],
}
try:
with Progress(
SpinnerColumn("earth"), # Keep the spinner
TextColumn("[bold blue]{task.description}"),
BarColumn(), # Keep basic bar for overall file progress
TimeElapsedColumn(),
TextColumn("[bold green]{task.fields[status]}"),
console=console,
transient=True,
refresh_per_second=10, # Adjust refresh rate as needed
) as progress:
improve_task_id = progress.add_task(
"Improving file...", total=len(categories), status="Starting..."
)
improved_code, llm_success, retry_counts = await apply_llm_improvements(
file_path,
client,
llm_model,
llm_temperature,
categories,
config,
custom_prompt_dir,
line_length,
progress,
improve_task_id,
debug,
analysis_results
)
file_status["llm_success"] = llm_success
for category in categories:
if retry_counts.get(category, 0) > 0:
file_status["categories_attempted"].append(category)
else:
file_status["categories_skipped"].append(category)
if not llm_success:
restore_backup(file_path, backup_path)
file_status["restored"] = True
return "", False
try:
with open(file_path, "w", encoding=CONFIG_ENCODING) as f:
f.write(improved_code)
# Check if the file was actually changed
with open(file_path, "r", encoding=CONFIG_ENCODING) as f:
new_code = f.read()
with open(backup_path, "r", encoding=CONFIG_ENCODING) as f:
old_code = f.read()
if new_code.strip() != old_code.strip():
file_status["changed"] = True
else:
console.print(f"[yellow]No changes detected after LLM processing for {file_path}.[/yellow]")
except Exception as e:
logging.exception(f"Error writing improved code to {file_path}")
restore_backup(file_path, backup_path)
file_status["restored"] = True
return "", False # Empty string on failure
return improved_code, True
except Exception as e:
logging.exception(
f"Unexpected error during file improvement for {file_path}"
)
restore_backup(file_path, backup_path)
file_status["restored"] = True
return "", False # Empty string on failure
async def fix_tests_syntax_error(
generated_tests: str,
file_base_name: str,
client: AsyncOpenAI,
llm_model: str,
llm_temperature: float,
) -> Tuple[str, bool]:
"""Attempts to fix syntax errors in generated tests using LLM."""
try:
ast.parse(generated_tests)
return generated_tests, False # No errors
except SyntaxError as e:
logging.warning(f"Syntax error in test generation: {e}")
line_number = e.lineno
error_message = str(e)
code_lines = generated_tests.splitlines()
context_start = max(0, line_number - 3)
context_end = min(len(code_lines), line_number + 2)
context = "\n".join(code_lines[context_start:context_end])
highlighted_context = context.replace(
code_lines[line_number - 1], f"#>>> {code_lines[line_number - 1]}"
)
error_message_for_llm = (
f"Syntax error in generated tests for {file_base_name}.py, line {line_number}: {error_message}.\n"
f"Fix the following code:\n```python\n{highlighted_context}\n```\n"
f"Return only the corrected code, no intro/outro text, no markdown fences."
)
return error_message_for_llm, True # Error message and flag
async def generate_tests(
file_path: str,
client: AsyncOpenAI,
llm_model: str,
llm_temperature: float,
test_framework: str,
config: Dict, # Pass config
custom_prompt_dir: str,
debug: bool = False,
line_length: int = DEFAULT_LINE_LENGTH,
) -> str:
"""Generates tests using LLM with syntax error handling and retry."""
try:
with open(file_path, "r", encoding=CONFIG_ENCODING) as f:
code = f.read()
except FileNotFoundError:
logging.error(f"File not found: {file_path}, cannot generate tests.")
return "" # Return empty string for consistency
file_base_name = os.path.basename(file_path).split(".")[0]
prompt = get_prompt(config, "tests", custom_prompt_dir) # Use get_prompt
if "{code}" not in prompt or "{file_base_name}" not in prompt:
logging.error(
"Test prompt missing {code} or {file_base_name} placeholder."
)
return ""
prompt = (
prompt.replace("{code}", code).replace("{file_base_name}", file_base_name)
)
prompt += f"\nMaintain {line_length} chars max line length.\n"
prompt += (
"Return only test code, no intro/outro text, no markdown fences."
) # Outside
if debug:
logging.debug(f"LLM prompt for test generation:\n{prompt}")
generated_tests = ""
try:
start_time = time.time()
response = await client.chat.completions.create( # CHANGED from acreate
model=llm_model,
messages=[
{
"role": "system",
"content": "You are a helpful coding assistant that generates tests.",
},
{"role": "user", "content": prompt},
],
temperature=llm_temperature,
max_tokens=2048, # Reduced max_tokens
timeout=OPENAI_TIMEOUT,
)
end_time = time.time()
logging.info(
f"LLM test generation request took {end_time - start_time:.2f} seconds."
)
generated_tests = extract_code_from_response(
response.choices[0].message.content
)
fixed_tests, has_syntax_errors = await fix_tests_syntax_error(
generated_tests, file_base_name, client, llm_model, llm_temperature
)
syntax_error_attempts = 0
while has_syntax_errors and syntax_error_attempts < MAX_SYNTAX_RETRIES:
logging.warning("Attempting to fix syntax errors in generated tests...")
start_time = time.time()
error_message = fixed_tests # Error message contains code and error
try:
response = await client.chat.completions.create( # CHANGED from acreate
model=llm_model,
messages=[
{
"role": "system",
"content": "You are a coding assistant fixing syntax errors in tests.",
},
{"role": "user", "content": error_message},
],
temperature=min(llm_temperature, 0.2), # Lower temp for fixes
max_tokens=2048, # Reduced max_tokens
timeout=OPENAI_TIMEOUT,
)
end_time = time.time()
logging.info(
f"LLM test syntax fix attempt {syntax_error_attempts + 1} took {end_time - start_time:.2f} seconds."
)
generated_tests = extract_code_from_response(
response.choices[0].message.content
)
fixed_tests, has_syntax_errors = await fix_tests_syntax_error(
generated_tests, file_base_name, client, llm_model, llm_temperature
)
syntax_error_attempts += 1
except APITimeoutError: # Corrected exception type
logging.warning(
f"Timeout during test syntax correction (attempt {syntax_error_attempts + 1})"
)
if syntax_error_attempts == MAX_SYNTAX_RETRIES:
logging.error(
"Max syntax retries for tests reached. Skipping test generation."
)
return "" # Give up on generating tests
continue
if has_syntax_errors:
logging.error(
"Max syntax retries for tests reached. Skipping test generation."
)
return "" # Give up on generating tests if still errors
except APITimeoutError: # Corrected exception type
logging.warning("Timeout during initial LLM test generation call.")
return ""
except Exception as e:
logging.exception(f"Error during LLM test generation call for {file_path}")
return "" # Return empty string
tests_dir = os.path.join(os.path.dirname(file_path), "..", "tests")
os.makedirs(tests_dir, exist_ok=True)
test_file_name = f"test_{os.path.basename(file_path)}"
test_file_path = os.path.join(tests_dir, test_file_name)
# Always overwrite (or create) the test file.
try:
with open(test_file_path, "w", encoding=CONFIG_ENCODING) as f:
f.write(generated_tests)
logging.info(f"Test file written to: {test_file_path}")
return generated_tests # Return the generated tests
except Exception as e:
logging.exception(f"Error writing test file: {test_file_path}")
return "" # Consistent error handling
async def run_tests(
repo_path: str,
original_file_path: str,
test_framework: str,
min_coverage: Optional[float],
coverage_fail_action: str,
debug: bool = False,
) -> Dict[str, Any]:
"""Runs tests (pytest only currently) and checks/enforces code coverage."""
test_results: Dict[str, Any] = {}
tests_dir = os.path.join(repo_path, "tests")