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
- ποΈSmart Project Traversal π Recursively scans a specified project directory
π Identifies all .py source files for analysis
$ python refactor_advisor.py --path ./my_project
- βοΈ 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
- π€ 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
- π 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
- Customizable CLI π§ͺ Simple and flexible interface using argparse
$ python refactor_advisor.py \
--path ./project_dir \
--output ./analysis_reports \
--chunk-size 120
Demo
Screenshots and Report Files
π» Chunking the Python file with Amazon Q π
π» Chunking, Give Code and Function Summary, Code Fixes and Refactoring Suggestionsπ
- Below Attached the Brief reports on the file which was analyzed in the below drive in .txt and .md format generated by the tool
Code Snippets
π§© Part 1: Imports and Setup
import os
import argparse
import subprocess
from pathlib import Path
π 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
π 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
π 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
π 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')
π 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).
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`...")
- 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]
- 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
β
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)
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)