3 # AI-Fix: Code review and fixing tool
4 # Two-stage LLM workflow: review code, then apply fixes
6 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7 source "$SCRIPT_DIR/ai-common"
11 Usage: ai-fix [-r] PROMPT_FILE [FILE...]
12 Review code according to a prompt and optionally apply fixes.
15 PROMPT_FILE File containing the review prompt/instructions
18 -r, --review Review only mode (don't apply fixes)
19 -h Show this help message
22 # Review and fix code (default behavior)
23 ai-fix code-review-prompt.txt mycode.py
25 # In vim, review and fix selected text
26 :'<,'>!ai-fix code-review-prompt.txt
28 # Review only (no fixes applied)
29 ai-fix -r code-review-prompt.txt mycode.py
33 build_review_prompt() {
34 local review_instructions="$1"
36 echo "$review_instructions"
43 You are a code fixing tool. Apply straightforward high-priority fixes to the code based on the provided review feedback.
51 local review_only=false
54 local input review_instructions review fixed_code
57 while getopts "rh-:" opt; do
59 r) review_only=true ;;
60 h) handle_help_option show_usage ;;
63 review) review_only=true ;;
64 *) handle_invalid_option "--$OPTARG" ;;
67 \?) handle_invalid_option "$OPTARG" ;;
73 # Validate environment and arguments
75 ensure_argument_provided "Prompt file" "$1" show_usage
81 # Validate prompt file exists
82 ensure_files_exist "$prompt_file"
84 # Validate additional files if provided
85 [[ ${#files[@]} -gt 0 ]] && ensure_files_exist "${files[@]}"
87 # Read review instructions
88 if ! review_instructions=$(cat "$prompt_file"); then
89 print_error "Failed to read prompt file: $prompt_file"
90 exit "$EXIT_USAGE_ERROR"
94 if ! input=$(process_input_sources "${files[@]}"); then
98 # Stage 1: Generate code review
100 review_prompt=$(build_review_prompt "$review_instructions")
102 if ! review=$(execute_llm_request "$review_prompt" "$input"); then
104 "$EXIT_NO_MATCH") print_error "$(error_llm_no_response)" ;;
105 "$EXIT_API_ERROR") print_error "$(error_llm_api_error)" ;;
106 *) print_error "$(error_llm_command_failed)" ;;
111 # If review-only mode, output the review and exit
112 if $review_only; then
117 # Stage 2: Apply fixes based on review
119 fix_prompt=$(build_fix_prompt "$review")
121 if ! fixed_code=$(execute_llm_request "$fix_prompt" "$input"); then
123 "$EXIT_NO_MATCH") print_error "$(error_llm_no_response)" ;;
124 "$EXIT_API_ERROR") print_error "$(error_llm_api_error)" ;;
125 *) print_error "$(error_llm_command_failed)" ;;
130 # Output the fixed code