3 # AI-Grep: Semantic search tool
4 # Beautiful implementation using composable functions
6 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7 source "$SCRIPT_DIR/ai-common"
11 Usage: ai-grep [OPTIONS] PATTERN [FILE...]
12 Semantic search based on meaning rather than exact string matching.
15 -v Select non-matching lines (semantic inverse)
17 -c Show only count of matching lines
18 -h Show this help message
24 local invert_match="$2"
25 local show_numbers="$3"
28 local match_instruction
29 if [[ "$invert_match" == "true" ]]; then
30 match_instruction="Find lines that do NOT semantically match this pattern. Return only those non-matching lines, one per line."
32 match_instruction="Find lines that semantically match this pattern. Return only those matching lines, one per line."
35 local output_instruction
36 if [[ "$count_only" == "true" ]]; then
37 output_instruction="Output only a single number - the count of matching lines."
38 elif [[ "$show_numbers" == "true" ]]; then
39 output_instruction="Prefix each line with its line number followed by a colon (format: 'N:line')."
41 output_instruction="Output only the lines themselves, no prefixes or formatting."
45 You are a semantic grep tool. Analyze the following text and find lines that semantically match the pattern '$pattern'.
47 CRITICAL: Output ONLY the requested lines or count. Do not include explanations, introductory text, or analysis.
55 process_grep_response() {
59 if [[ "$count_only" == "true" ]]; then
61 if ! count=$(process_count_response "$response"); then
66 if [[ "$count" -gt 0 ]]; then
69 return "$EXIT_NO_MATCH"
72 process_filtered_response "$response"
76 validate_and_setup() {
82 ensure_argument_provided "Pattern" "$pattern" show_usage
84 [[ ${#files[@]} -gt 0 ]] && ensure_files_exist "${files[@]}"
88 local invert_match="false"
89 local show_numbers="false"
90 local count_only="false"
95 while getopts "vnch" opt; do
97 v) invert_match="true" ;;
98 n) show_numbers="true" ;;
99 c) count_only="true" ;;
100 h) handle_help_option show_usage ;;
101 \?) handle_invalid_option "$OPTARG" ;;
110 # Early validation with immediate exit on failure
111 validate_and_setup "$pattern" "${files[@]}"
113 # Process input with early exit
115 input=$(process_input_sources "${files[@]}") || exit "$EXIT_NO_MATCH"
117 # Execute LLM request with early exit
118 local prompt response
119 prompt=$(build_grep_prompt "$pattern" "$invert_match" "$show_numbers" "$count_only")
120 response=$(execute_llm_request "$prompt" "$input") || handle_llm_error $?
122 # Process response with early exit
124 result=$(process_grep_response "$response" "$count_only") || exit $?