| 1 | 1 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 2 | # Edge Case: Handle empty pattern |
| 3 | if not pattern: |
| 4 | return "" |
| 5 | |
| 6 | # Edge Case: Handle empty files list |
| 7 | if not files: |
| 8 | return "" |
| 9 | |
| 10 | # Parse flags |
| 11 | line_numbers = '-n' in flags |
| 12 | filenames_only = '-l' in flags |
| 13 | case_insensitive = '-i' in flags |
| 14 | invert_match = '-v' in flags |
| 15 | exact_match = '-x' in flags |
| 16 | |
| 17 | # Prepare pattern for comparison |
| 18 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 19 | |
| 20 | # Results |
| 21 | result_lines = [] |
| 22 | matching_files = set() |
| 23 | |
| 24 | # Edge Case: Handle file not found or unreadable files |
| 25 | for filename in files: |
| 26 | try: |
| 27 | with open(filename, 'r', encoding='utf-8') as file: |
| 28 | lines = file.readlines() |
| 29 | except FileNotFoundError: |
| 30 | # Skip files that don't exist |
| 31 | continue |
| 32 | except IOError: |
| 33 | # Skip files that can't be read |
| 34 | continue |
| 35 | |
| 36 | file_has_match = False |
| 37 | |
| 38 | for line_num, line in enumerate(lines, start=1): |
| 39 | # Prepare line for comparison |
| 40 | compare_line = line.lower() if case_insensitive else line |
| 41 | |
| 42 | # Determine if line matches |
| 43 | if exact_match: |
| 44 | matches = (compare_line.rstrip('\n') == search_pattern) |
| 45 | else: |
| 46 | matches = (search_pattern in compare_line) |
| 47 | |
| 48 | # Apply invert flag |
| 49 | if invert_match: |
| 50 | matches = not matches |
| 51 | |
| 52 | if matches: |
| 53 | file_has_match = True |
| 54 | |
| 55 | # If we only need filenames, we can break early |
| 56 | if filenames_only: |
| 57 | file_has_match = True |
| 58 | matching_files.add(filename) |
| 59 | break |
| 60 | |
| 61 | # Build output line |
| 62 | output_line = "" |
| 63 | |
| 64 | # Add filename prefix if multiple files |
| 65 | if len(files) > 1: |
| 66 | output_line += f"{filename}:" |
| 67 | |
| 68 | # Add line number if requested |
| 69 | if line_numbers: |
| 70 | output_line += f"{line_num}:" |
| 71 | |
| 72 | # Add the actual line |
| 73 | output_line += line |
| 74 | |
| 75 | result_lines.append(output_line) |
| 76 | |
| 77 | |
| 78 | |
| 79 | # Edge Case: Handle -l flag with no matches |
| 80 | if filenames_only: |
| 81 | # Return matching filenames in the order they appeared in files list |
| 82 | ordered_matches = [f for f in files if f in matching_files] |
| 83 | return "\n".join(ordered_matches) + ("\n" if ordered_matches else "") |
| 84 | |
| 85 | # Edge Case: Handle no matches found |
| 86 | return "".join(result_lines) |
| 87 | |
| 88 | # Handled Edge Cases: empty pattern, empty files list, file not found, unreadable files, -l flag with no matches, no matches found |