| 1 | 1 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 2 | # Parse flags |
| 3 | line_numbers = '-n' in flags |
| 4 | files_only = '-l' in flags |
| 5 | case_insensitive = '-i' in flags |
| 6 | invert_match = '-v' in flags |
| 7 | exact_match = '-x' in flags |
| 8 | |
| 9 | results = [] |
| 10 | matched_files = set() |
| 11 | |
| 12 | # Edge Case: Empty file list |
| 13 | if not files: |
| 14 | return "" |
| 15 | |
| 16 | # Edge Case: Empty pattern |
| 17 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 18 | |
| 19 | for file_path in files: |
| 20 | try: |
| 21 | with open(file_path, 'r', encoding='utf-8') as file: |
| 22 | lines = file.readlines() |
| 23 | except FileNotFoundError: |
| 24 | # Edge Case: File not found - skip file |
| 25 | continue |
| 26 | except Exception: |
| 27 | # Edge Case: Other file reading errors - skip file |
| 28 | continue |
| 29 | |
| 30 | file_has_match = False |
| 31 | |
| 32 | for line_num, line in enumerate(lines, 1): |
| 33 | # Process line for comparison |
| 34 | compare_line = line.lower().rstrip('\n') if case_insensitive else line.rstrip('\n') |
| 35 | |
| 36 | # Determine if line matches |
| 37 | if exact_match: |
| 38 | matches = (search_pattern == compare_line) |
| 39 | else: |
| 40 | matches = (search_pattern in compare_line) |
| 41 | |
| 42 | # Apply invert flag |
| 43 | if invert_match: |
| 44 | matches = not matches |
| 45 | |
| 46 | if matches: |
| 47 | file_has_match = True |
| 48 | |
| 49 | # Edge Case: Only file names requested |
| 50 | if files_only: |
| 51 | matched_files.add(file_path) |
| 52 | break # No need to check more lines in this file |
| 53 | |
| 54 | # Build output line |
| 55 | output_line = "" |
| 56 | |
| 57 | # Add filename prefix if multiple files |
| 58 | if len(files) > 1: |
| 59 | output_line += f"{file_path}:" |
| 60 | |
| 61 | # Add line number if requested |
| 62 | if line_numbers: |
| 63 | output_line += f"{line_num}:" |
| 64 | |
| 65 | # Add actual line content |
| 66 | output_line += line |
| 67 | |
| 68 | results.append(output_line) |
| 69 | |
| 70 | # Edge Case: File has no matches but -l flag is used |
| 71 | if not file_has_match and files_only: |
| 72 | continue |
| 73 | |
| 74 | # Edge Case: Only file names requested |
| 75 | if files_only: |
| 76 | return "\n".join(sorted(matched_files)) + ("\n" if matched_files else "") |
| 77 | |
| 78 | # Edge Case: No matches found |
| 79 | return "".join(results) |
| 80 | |
| 81 | # Handled Edge Cases: Empty file list, Empty pattern, File not found, Other file reading errors, Only file names requested, File has no matches but -l flag is used, No matches found |