|
| 1 | +import os |
| 2 | +import sys |
| 3 | + |
| 4 | +def find_and_extract_code(root_dir, output_filename="code_summary.txt"): |
| 5 | + """ |
| 6 | + Recursively finds all files in a directory and its subdirectories, |
| 7 | + extracts their content, and writes it to a summary text file. |
| 8 | +
|
| 9 | + Args: |
| 10 | + root_dir (str): The path to the root directory to start searching from. |
| 11 | + output_filename (str): The name of the text file to generate. |
| 12 | + """ |
| 13 | + # --- Input Validation --- |
| 14 | + if not os.path.isdir(root_dir): |
| 15 | + print(f"Error: The provided path '{root_dir}' is not a valid directory.") |
| 16 | + sys.exit(1) # Exit the script if the path is invalid |
| 17 | + |
| 18 | + # --- Initialization --- |
| 19 | + all_file_data = [] |
| 20 | + file_counter = 0 |
| 21 | + separator = "\n" * 11 # 10 line breaks means 11 newline characters |
| 22 | + |
| 23 | + print(f"Starting search in: {root_dir}") |
| 24 | + print(f"Output will be saved to: {output_filename}") |
| 25 | + |
| 26 | + # --- Recursive Traversal --- |
| 27 | + for dirpath, dirnames, filenames in os.walk(root_dir): |
| 28 | + # Optional: Skip certain directories if needed (e.g., .git, node_modules) |
| 29 | + # dirnames[:] = [d for d in dirnames if d not in ['.git', 'node_modules', '__pycache__']] |
| 30 | + |
| 31 | + for filename in filenames: |
| 32 | + file_counter += 1 |
| 33 | + full_path = os.path.join(dirpath, filename) |
| 34 | + |
| 35 | + # Calculate relative path |
| 36 | + try: |
| 37 | + relative_path = os.path.relpath(full_path, root_dir) |
| 38 | + # Normalize path separators for consistency (optional but good practice) |
| 39 | + relative_path = relative_path.replace(os.path.sep, '/') |
| 40 | + except ValueError as e: |
| 41 | + print(f"Warning: Could not determine relative path for {full_path} (maybe on different drives?): {e}") |
| 42 | + relative_path = full_path # Fallback to full path if relative fails |
| 43 | + |
| 44 | + print(f" Processing file {file_counter}: {relative_path}") |
| 45 | + |
| 46 | + # --- Read File Content --- |
| 47 | + file_content = "" |
| 48 | + try: |
| 49 | + # Open with utf-8 encoding, ignore errors for binary/non-standard files |
| 50 | + with open(full_path, 'r', encoding='utf-8', errors='ignore') as f: |
| 51 | + file_content = f.read() |
| 52 | + except IOError as e: |
| 53 | + file_content = f"[Error reading file: {e}]" |
| 54 | + print(f" -> Error reading file: {relative_path} - {e}") |
| 55 | + except Exception as e: # Catch other potential errors |
| 56 | + file_content = f"[Unexpected error reading file: {e}]" |
| 57 | + print(f" -> Unexpected error reading file: {relative_path} - {e}") |
| 58 | + |
| 59 | + |
| 60 | + # --- Format Output for this file --- |
| 61 | + # Using a slightly more readable format with ``` block, |
| 62 | + # adjust if you strictly need CODE:"..." |
| 63 | + # file_entry = f"File {file_counter}: path= {relative_path}\nCODE:\"{file_content}\"" # Original request format |
| 64 | + file_entry = f"File {file_counter}: path= {relative_path}\n\nCODE:\n```\n{file_content}\n```" # More readable format |
| 65 | + |
| 66 | + all_file_data.append(file_entry) |
| 67 | + |
| 68 | + # --- Write to Output File --- |
| 69 | + if not all_file_data: |
| 70 | + print("No files found in the specified directory.") |
| 71 | + return |
| 72 | + |
| 73 | + print(f"\nFound {len(all_file_data)} files. Writing to {output_filename}...") |
| 74 | + try: |
| 75 | + with open(output_filename, 'w', encoding='utf-8') as outfile: |
| 76 | + # Join all entries with the specified separator |
| 77 | + outfile.write(separator.join(all_file_data)) |
| 78 | + print(f"Successfully created {output_filename}") |
| 79 | + except IOError as e: |
| 80 | + print(f"Error: Could not write to output file '{output_filename}': {e}") |
| 81 | + except Exception as e: |
| 82 | + print(f"An unexpected error occurred while writing the file: {e}") |
| 83 | + |
| 84 | + |
| 85 | +# --- Main Execution --- |
| 86 | +if __name__ == "__main__": |
| 87 | + input_path = input("Enter the directory path to scan: ") |
| 88 | + output_file = input("Enter the desired name for the output file (e.g., code_summary.txt): ") |
| 89 | + |
| 90 | + # Basic validation for output filename (optional) |
| 91 | + if not output_file: |
| 92 | + output_file = "code_summary.txt" |
| 93 | + elif not output_file.lower().endswith('.txt'): |
| 94 | + output_file += ".txt" # Ensure it has a .txt extension |
| 95 | + |
| 96 | + find_and_extract_code(input_path, output_file) |
0 commit comments