All Toolsโ€บSmart Code Refactoring Tool
๐Ÿ”ง AI-Powered Coding AssistantsMay 16, 2026โœ… Tests passing

Smart Code Refactoring Tool

This tool uses AI coding assistants to perform intelligent code refactoring. It can optimize code for readability, performance, or specific coding standards with suggested changes. Developers can focus on logic while the tool improves maintainability.

What It Does

  • Refactor code for readability, performance, or coding standards.
  • View differences between original and refactored code.
  • Save refactored code to a file or display it directly in the terminal.

Installation

  • Python 3.7+
  • openai
  • python-dotenv
  • diff-match-patch
  • pytest

Usage

Run the tool using the following command:

python smart_code_refactor.py --file <path_to_code_file> --goal <refactoring_goal> [--output <output_file>]

Arguments

  • --file: Path to the code file to refactor (required).
  • --goal: Refactoring goal. Choose from readability, performance, or standards (required).
  • --output: Path to save the refactored code. If not provided, the refactored code will be displayed in the terminal.

Example

python smart_code_refactor.py --file example.py --goal readability --output refactored_example.py

Source Code

import argparse
import os
import openai
from dotenv import load_dotenv
from diff_match_patch import diff_match_patch

def load_api_key():
    load_dotenv()
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        raise ValueError("OPENAI_API_KEY not found in environment variables.")
    return api_key

def refactor_code(file_path, goal):
    """
    Refactor the code in the given file based on the specified goal.

    Args:
        file_path (str): Path to the code file to refactor.
        goal (str): Refactoring goal (e.g., readability, performance, standards).

    Returns:
        str: Refactored code.
    """
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"The file {file_path} does not exist.")

    with open(file_path, 'r') as file:
        original_code = file.read()

    if not original_code.strip():
        raise ValueError("The input file is empty.")

    openai.api_key = load_api_key()

    try:
        response = openai.Completion.create(
            engine="text-davinci-003",
            prompt=(
                f"Refactor the following code to optimize for {goal}:\n\n"
                f"{original_code}\n"
            ),
            max_tokens=1500,
            temperature=0.7
        )
        refactored_code = response["choices"][0]["text"].strip()
    except openai.error.OpenAIError as e:
        raise RuntimeError(f"Error while communicating with OpenAI API: {e}")

    return refactored_code

def display_diff(original_code, refactored_code):
    """
    Display the differences between the original and refactored code.

    Args:
        original_code (str): The original code.
        refactored_code (str): The refactored code.

    Returns:
        str: A unified diff string.
    """
    dmp = diff_match_patch()
    diffs = dmp.diff_main(original_code, refactored_code)
    dmp.diff_cleanupSemantic(diffs)
    return dmp.diff_prettyHtml(diffs)

def main():
    parser = argparse.ArgumentParser(
        description="Smart Code Refactoring Tool: Optimize your code for readability, performance, or standards."
    )
    parser.add_argument(
        "--file",
        required=True,
        help="Path to the code file to refactor."
    )
    parser.add_argument(
        "--goal",
        required=True,
        choices=["readability", "performance", "standards"],
        help="Refactoring goal: readability, performance, or standards."
    )
    parser.add_argument(
        "--output",
        help="Path to save the refactored code. If not provided, the refactored code will be displayed."
    )
    args = parser.parse_args()

    try:
        with open(args.file, 'r') as file:
            original_code = file.read()

        refactored_code = refactor_code(args.file, args.goal)

        if args.output:
            with open(args.output, 'w') as output_file:
                output_file.write(refactored_code)
            print(f"Refactored code saved to {args.output}")
        else:
            print("Refactored Code:")
            print(refactored_code)

        print("\nChanges:")
        print(display_diff(original_code, refactored_code))

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()

Community

Downloads

ยทยทยท

Rate this tool

No ratings yet โ€” be the first!

Details

Tool Name
smart_code_refactor
Category
AI-Powered Coding Assistants
Generated
May 16, 2026
Tests
Passing โœ…
Fix Loops
5

Quick Install

Clone just this tool:

git clone --depth 1 --filter=blob:none --sparse \
  https://github.com/ptulin/autoaiforge.git
cd autoaiforge
git sparse-checkout set generated_tools/2026-05-16/smart_code_refactor
cd generated_tools/2026-05-16/smart_code_refactor
pip install -r requirements.txt 2>/dev/null || true
python smart_code_refactor.py
Smart Code Refactoring Tool โ€” AI Tools by AutoAIForge