Advertisement
andreasoie

makefiles

Oct 16th, 2024
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. import os
  2. from typing import Callable, List, Set, Tuple
  3.  
  4.  
  5. def is_valid_file(filename: str, valid_extensions: Tuple[str, ...] = ('.py', '.yml', '.yaml')) -> bool:
  6.     return filename.endswith(valid_extensions)
  7.  
  8. def write_file_content(output_file: 'TextIO', file_path: str) -> None:
  9.     output_file.write(f"```{file_path}\n")
  10.     with open(file_path, 'r', encoding='utf-8') as f:
  11.         output_file.write(f.read())
  12.     output_file.write("\n```\n\n")
  13.  
  14. def process_files(
  15.     root_dir: str,
  16.     output_file: str,
  17.     file_filter: Callable[[str], bool],
  18.     file_processor: Callable[['TextIO', str], None],
  19.     skip_folders: Set[str] = set()
  20. ) -> None:
  21.     with open(output_file, 'w', encoding='utf-8') as out_file:
  22.         for root, dirs, files in os.walk(root_dir):
  23.             # Remove folders to skip from dirs to prevent os.walk from traversing them
  24.             dirs[:] = [d for d in dirs if d not in skip_folders]
  25.            
  26.             for file in files:
  27.                 if file_filter(file):
  28.                     file_path = os.path.join(root, file)
  29.                     rel_path = os.path.relpath(file_path, root_dir)  # Get relative path
  30.                     try:
  31.                         file_processor(out_file, rel_path)
  32.                     except Exception as e:
  33.                         print(f"Error processing {rel_path}: {str(e)}")
  34.  
  35. def main(
  36.     root_dir: str = '.',
  37.     output_file: str = 'files.txt',
  38.     valid_extensions: Tuple[str, ...] = ('.py', '.yml', '.yaml'),
  39.     skip_folders: Set[str] = set()
  40. ) -> None:
  41.     file_filter = lambda f: is_valid_file(f, valid_extensions)
  42.     process_files(root_dir, output_file, file_filter, write_file_content, skip_folders)
  43.     print(f"{output_file} has been created with the content of all {', '.join(valid_extensions)} files.")
  44.     if skip_folders:
  45.         print(f"Skipped folders: {', '.join(skip_folders)}")
  46.  
  47. if __name__ == "__main__":
  48.     main(
  49.         root_dir='.',
  50.         output_file='makefiles.txt',
  51.         valid_extensions=('.py', '.yml', '.yaml'),
  52.         skip_folders={"makefiles", 'venv', '.git', '__pycache__', 'node_modules', "python-sdk-v1", "infra", "infrastructure", "data", "trashbin", "data_science"}
  53.     )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement