Автоматическая починка багов

Автоматическая починка багов


import sys

import subprocess

import difflib

import traceback

import os

import re


# === Чтение кода из файла ===

def read_code(path):

  with open(path, "r", encoding="utf-8") as f:

    return f.readlines()


# === Попытка выполнить код и поймать ошибку ===

def run_and_catch(code_path):

  try:

    subprocess.check_output(["python", code_path], stderr=subprocess.STDOUT)

    return None

  except subprocess.CalledProcessError as e:

    return e.output.decode()


# === Парсим traceback и извлекаем строку с ошибкой ===

def extract_error_line(error_text):

  # Ищем что-то вроде "File "broken.py", line 3"

  match = re.search(r'File ".*", line (\d+)', error_text)

  if not match:

    return None, None

  line_no = int(match.group(1))

  lines = error_text.strip().splitlines()

  last_line = lines[-1] # тип ошибки

  return line_no, last_line


# === Предлагаем замену (простая логика: ищем опечатки в словах) ===

def suggest_fix(line, known_words):

  tokens = re.findall(r'\b\w+\b', line)

  for token in tokens:

    matches = difflib.get_close_matches(token, known_words)

    if matches and token != matches[0]:

      return token, matches[0]

  return None, None


# === Главная функция ===

def auto_fix(path):

  print(f"🔍 Проверка файла: {path}")

  original_code = read_code(path)

  error_output = run_and_catch(path)


  if error_output is None:

    print("✅ Ошибок не найдено.")

    return


  print("❌ Ошибка найдена:")

  print(error_output)


  line_no, error_type = extract_error_line(error_output)

  if not line_no:

    print("⚠️ Не удалось распознать строку ошибки.")

    return


  error_line = original_code[line_no - 1]

  print(f"🧠 Анализируем строку {line_no}: {error_line.strip()}")


  # Список известных слов (можно расширить)

  known_words = ["print", "len", "input", "range", "int", "str", "for", "if", "else", "elif", "def", "return", "import"]


  wrong, suggestion = suggest_fix(error_line, known_words)

  if not suggestion:

    print("🤷 Не удалось предложить исправление.")

    return


  print(f"🛠 Предлагаем: '{wrong}' → '{suggestion}'")

  fixed_line = error_line.replace(wrong, suggestion)

  original_code[line_no - 1] = fixed_line


  # Сохраняем исправленную версию

  fixed_path = "fixed_" + os.path.basename(path)

  with open(fixed_path, "w", encoding="utf-8") as f:

    f.writelines(original_code)


  print(f"✅ Готово! Исправленный файл: {fixed_path}")

Report Page