diff --git a/modules/user/scripts/bundle_project.py b/modules/user/scripts/bundle_project.py new file mode 100644 index 0000000..f708615 --- /dev/null +++ b/modules/user/scripts/bundle_project.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +""" +Repository Bundler Utility. + +This script compresses the structure and file contents of a target directory +into a single text file. It places a visual directory tree generated by 'eza' +at the top, followed by the contents of all text-based files, prefixed by +markdown headers indicating their relative paths. +""" + +import argparse +import subprocess +import sys +from pathlib import Path + + +def is_binary(file_path: Path) -> bool: + """ + Checks if a file is binary by attempting to read its beginning. + """ + try: + with open(file_path, "tr", encoding="utf-8") as f: + f.read(1024) + return False + except UnicodeDecodeError: + return True + + +def create_bundle(target_dir: Path, output_file: Path) -> None: + """ + Creates a single text bundle of a directory structure and its file contents. + + Args: + target_dir: The directory to bundle. + output_file: The path to write the bundled text file to. + """ + # 1. Generate the eza tree output + try: + # --color=never ensures we don't write terminal escape codes into our text file + tree_output = subprocess.check_output( + ["eza", "--tree", "--color=never", str(target_dir)], + text=True, + stderr=subprocess.STDOUT, + ) + except FileNotFoundError: + print("Error: 'eza' is not installed or not in your PATH.", file=sys.stderr) + sys.exit(1) + except subprocess.CalledProcessError as e: + print(f"Error running eza: {e.output}", file=sys.stderr) + sys.exit(1) + + print(f"Bundling files from '{target_dir}' into '{output_file}'...") + + try: + with open(output_file, "w", encoding="utf-8") as out_f: + # Write the tree output at the top + out_f.write(tree_output) + out_f.write("\n\n") + + # 3. Traverse directory and append file contents + # rglob('*') finds all files recursively. We sort them to ensure consistent ordering. + for filepath in sorted(target_dir.rglob("*")): + # Skip directories + if filepath.is_dir(): + continue + + # Skip the output file itself so we don't get an infinite loop or duplicate data + if filepath == output_file: + continue + + # Optional: Skip .git directory to avoid massive useless outputs + if ".git" in filepath.parts: + continue + + # Calculate relative path for the header (e.g., bin/dep_check) + relative_path = filepath.relative_to(target_dir) + + # Write the header + out_f.write(f"## {relative_path}\n\n") + + # Try to read and write the content + if is_binary(filepath): + out_f.write("[Binary or non-UTF-8 file skipped]\n\n") + continue + + try: + with open(filepath, "r", encoding="utf-8") as in_f: + content = in_f.read() + + # Write the content and add spacing before the next file + out_f.write(content) + + # Ensure the file ends with a newline before appending the next one + if not content.endswith("\n"): + out_f.write("\n") + out_f.write("\n") + + except Exception as e: + out_f.write(f"[Error reading file: {e}]\n\n") + + print("Done!") + except Exception as e: + print(f"Error writing output file: {e}", file=sys.stderr) + sys.exit(1) + + +def main() -> None: + """ + Main entry point parsing arguments and calling create_bundle. + """ + parser = argparse.ArgumentParser( + description="Bundle a directory structure and its files into a single text document." + ) + parser.add_argument( + "directory", + nargs="?", + default=".", + help="Target directory to bundle (default: current directory)", + ) + parser.add_argument( + "-o", + "--output", + default="output.txt", + help="Output filename/path (default: output.txt in current directory)", + ) + + args = parser.parse_args() + + target_dir = Path(args.directory).resolve() + output_file = Path(args.output).resolve() + + if not target_dir.is_dir(): + print(f"Error: Target directory '{target_dir}' does not exist.", file=sys.stderr) + sys.exit(1) + + create_bundle(target_dir, output_file) + + +if __name__ == "__main__": + main()