DEV Community

Cover image for Refactor Advisor and Analysis Automation Tool- Smart Code Amazon Q CLI Tool
SHREYA
SHREYA

Posted on

Refactor Advisor and Analysis Automation Tool- Smart Code Amazon Q CLI Tool

This is a submission for the Amazon Q Developer "Quack The Code" Challenge: Crushing the Command Line

What I Built

I built RefactorAdvisor because I often found myself overwhelmed revisiting old Python projects πŸ§ πŸ’» β€” the kind where functions stretch hundreds of lines, imports pile up, and clarity fades away. Like many developers, I wanted to clean things up but didn’t always have the time (or patience) for deep manual reviews. Traditional linters felt too shallow, and I wanted something smarter. That’s when I discovered Amazon Q πŸ€– β€” a tool that could understand context and suggest meaningful improvements. So, I created RefactorAdvisor: a CLI tool that walks through your project πŸ“, splits long files into manageable chunks βœ‚οΈ, sends them to Amazon Q for analysis, and returns actionable refactoring tips πŸ› οΈ. Whether you just want quick insights or a full Markdown report πŸ“„, it helps bring order back to your code β€” one chunk at a time.

Key Features of RefactorAdvisor

  1. πŸ—‚οΈSmart Project Traversal πŸ” Recursively scans a specified project directory

πŸ“„ Identifies all .py source files for analysis

$ python refactor_advisor.py --path ./my_project

Enter fullscreen mode Exit fullscreen mode
  1. βœ‚οΈ Chunking Large Files 🧩 Breaks large files into ~100-line chunks (adjustable via CLI)

πŸ”„ Keeps analysis consistent with Amazon Q’s input limits

$ python refactor_advisor.py --path ./app --chunk-size 80

Enter fullscreen mode Exit fullscreen mode
  1. πŸ€– Amazon Q Integration πŸ“€ Sends each chunk to Amazon Q CLI via subprocess

🧠 Asks Q to:

Summarize the chunk

Identify code smells

Suggest refactorings based on:

  • DRY
  • SOLID
  • Readability
  • Performance

⚠️ Requires AWS CLI & Amazon Q setup
Uses aws q or amazon-q under the hood

  1. πŸ“Š Organized Output 🎨 Displays feedback in the terminal with:

βœ… Sectioned summaries

🎯 Color-coded highlights

πŸ“ Optionally writes reports in Markdown per file:

Example: analysis/utils_refactor_report.md

$ python refactor_advisor.py --path ./api --output ./refactor_reports

Enter fullscreen mode Exit fullscreen mode
  1. Customizable CLI πŸ§ͺ Simple and flexible interface using argparse
$ python refactor_advisor.py \
    --path ./project_dir \
    --output ./analysis_reports \
    --chunk-size 120

Enter fullscreen mode Exit fullscreen mode

Demo

Screenshots and Report Files
πŸ’» Chunking the Python file with Amazon Q 🐍

Image_1
πŸ’» Chunking, Give Code and Function Summary, Code Fixes and Refactoring Suggestions🐍
Image_2

- Below Attached the Brief reports on the file which was analyzed in the below drive in .txt and .md format generated by the tool

Brief Analysis Report

Code Snippets
🧩 Part 1: Imports and Setup

import os
import argparse
import subprocess
from pathlib import Path
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Explanation:

Imports necessary modules:

  • os, Path for filesystem operations
  • argparse for CLI argument parsing
  • subprocess for interacting with Amazon Q via terminal

🧩 Part 2: Find Python Files

def find_python_files(directory):
    """Recursively finds all .py files in the given directory."""
    py_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.py'):
                py_files.append(os.path.join(root, file))
    return py_files
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Explanation:

  • Walks through the given directory and subfolders
  • Collects paths of all .py files for later analysis

🧩 Part 3: Chunking Source Code


def chunk_file(file_path, chunk_size=100):
    """Splits a Python file into chunks of N lines."""
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    chunks = []
    for i in range(0, len(lines), chunk_size):
        chunk = lines[i:i + chunk_size]
        chunks.append((i // chunk_size + 1, ''.join(chunk)))
    return chunks
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Explanation:

  • Reads the content of a file
  • Divides it into chunks of chunk_size lines (default is 100)
  • Returns a list of tuples: (chunk_number, code_text)

🧩 Part 4: Analyze Chunk with Amazon Q

def analyze_chunk(chunk_code):
    """Sends a chunk of code to Amazon Q CLI for analysis."""
    process = subprocess.Popen(
        ['amazon-q', 'analyze'],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    stdout, stderr = process.communicate(chunk_code)
    return stdout if stdout else stderr
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Explanation:

  • Uses subprocess.Popen() to call the Amazon Q CLI
  • Sends a chunk of code for analysis
  • Captures and returns either the standard output or error

🧩 Part 5: Write Results to Files

def write_report(file_name, results, output_dir):
    """Writes the analysis results to Markdown and TXT files."""
    output_path_md = Path(output_dir) / f"{Path(file_name).stem}_refactor_report.md"
    output_path_txt = Path(output_dir) / f"{Path(file_name).stem}_refactor_report.txt"

    with open(output_path_md, 'w', encoding='utf-8') as f_md, open(output_path_txt, 'w', encoding='utf-8') as f_txt:
        for result in results:
            f_md.write(result + '\n\n')
            f_txt.write(result + '\n\n')
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Explanation:

  • Writes the combined results of all chunks from one file into:
  • .md for rich text reports
  • .txt for plain text output
  • Uses the file name as the base for the report name

Code Repository

πŸ” Explore the complete source code on GitHub:
πŸ’» Built with Python 🐍 and designed to integrate smoothly with Amazon Q πŸ€– for smarter code reviews and refactoring advice!

Refactor Advisor & Analysis Automation Tool

How I Used Amazon Q Developer

Scenario:
You are tasked with refactoring a large Python codebase that spans multiple files and has accumulated technical debt over time. The code is hard to maintain, and improving its quality manually seems time-consuming. To automate the process and ensure you don't miss any potential improvements, you decide to use the Refactor Advisor, a tool powered by Amazon Q Developer.

Solution: Refactor Advisor with Amazon Q Developer CLI
Tool Setup and Initialization
πŸ› οΈ

The Refactor Advisor Python script (refactor_advisor.py) is designed to automate the process of analyzing and refactoring Python code.

The script uses Amazon Q Developer CLI to send code chunks to Amazon Q for analysis and improvement suggestions.

The tool is set up with the following command-line arguments:

--path: Path to the project directory you want to analyze.

--output: (Optional) Path to store the output Markdown report.

--chunk-size: Defines the number of lines in each chunk for Amazon Q to process (default is 100).
Enter fullscreen mode Exit fullscreen mode

Project Traversal and File Detection πŸ”

You run the following command to start the analysis:


python refactor_advisor.py --path ./my_project --output ./analysis
The tool recursively traverses the ./my_project directory to find all Python files (.py).

Result: The tool identifies 30 Python files in the project directory that need analysis.

Breaking Files into Chunks πŸ”¨

  • Each Python file is read and broken into smaller chunks of approximately 100 lines (the chunk size is adjustable).
  • Large functions or classes may be split across multiple chunks to ensure each part is manageable and fits Amazon Q's input size.
  • Sending Chunks to Amazon Q for Analysis πŸ“€
  • For each chunk, the script sends a request to Amazon Q Developer CLI with a prompt asking for:
  • A summary of the code: A high-level overview of what the chunk of code is doing.
  • Detected code smells or anti-patterns: Issues like duplicated code, overly complex functions, long methods, or violation of best practices.
  • Refactoring suggestions: Based on DRY (Don’t Repeat Yourself), SOLID principles, readability, and performance, Amazon Q suggests how to improve the code.
  • Each chunk is processed individually to ensure detailed feedback for each section of the code.

Receiving Feedback from Amazon Q πŸ”„

Amazon Q returns structured feedback in response to each chunk, which includes:

  • A brief summary of the code.
  • Code smells detected in the chunk (e.g., code duplication, long methods).
  • Suggestions for improvement, including:
  • Refactoring functions to be smaller.
  • Improving variable names for clarity.
  • Combining duplicate code to follow the DRY principle.
  • Breaking down large classes or functions to adhere to SOLID principles.
  • Displaying the Results πŸ–₯️
  • The tool collects all the feedback from Amazon Q and displays it in the terminal.
  • Color-coding and sectioning are used to distinguish between:
  • Green: Suggested improvements.
  • Yellow: Warnings (code smells detected).
  • Blue: Code summaries.
  • The results are presented in a clear and structured way, making it easy for developers to understand and take action.
  • Optional Markdown Reports πŸ“„ The results are presented in a clear and structured way, making it easy for developers to understand and take action.

πŸ” Learnings & Challenges Faced

βœ… Learnings

  • Integrated Amazon Q Developer CLI with Python using subprocess.
  • Built a flexible CLI tool using argparse.
  • Implemented file chunking logic for large Python files.
  • Parsed and formatted Q’s output for terminal and markdown.
  • Learned prompt engineering for code summarization and refactoring advice .

⚠️ Challenges

  • Handling multiline and unstructured Q responses.
  • Managing subprocess timeouts and rate limits.
  • Ensuring accurate chunk splits without breaking logic.
  • Dealing with file encoding errors.
  • Validating Amazon Q CLI installation and user configuration.

Challenges & βœ… Solutions

- Unstructured Q Responses

βœ… Solution: Used textwrap, regex, and custom parsing logic to extract summaries, issues, and suggestions reliably from mixed Q outputs.

- Subprocess Timeouts / Rate Limits

βœ… Solution: Added try/except around subprocess.run() with timeout parameters. Implemented delays between chunk requests if needed using time.sleep().

try:
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
except subprocess.TimeoutExpired:
    print("⚠️ Amazon Q CLI timed out. Retrying`...")
Enter fullscreen mode Exit fullscreen mode

- Chunking Logic Accuracy

βœ… Solution: Used a line counter and buffer to break files logically without splitting mid-function or mid-class (where possible). Configurable chunk size ensures flexibility.

for i in range(0, len(lines), chunk_size):
    chunk = lines[i:i + chunk_size]

Enter fullscreen mode Exit fullscreen mode

- File Encoding Issues

βœ… Solution: Opened files using encoding='utf-8' and handled UnicodeDecodeError gracefully.

   with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
except UnicodeDecodeError:
    print(f"⚠️ Skipping {file_path} due to encoding error.")
Q CLI Configuration Validation
Enter fullscreen mode Exit fullscreen mode

βœ… Solution: Checked if q CLI is installed using shutil.which() and printed a friendly error if not found.


if shutil.which("q") is None:
    print("❌ Amazon Q CLI not found. Please install and configure it first.")
    sys.exit(1)
Enter fullscreen mode Exit fullscreen mode

Conclusion
This tool revealed common issues such as lack of classes, long functions, inconsistent naming, and missing documentation. Many chunks contain code smells like hardcoded values, redundant logic, and poor error handling.

To improve the codebase, refactor large functions, adopt consistent naming, improve documentation, and apply object-oriented design where possible. Addressing these areas will enhance maintainability, readability, and reduce technical debt.

Reachout : Gmail : Shreyan11111@gmail.com

Top comments (0)