#!/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 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 to avoid loops/dups if filepath == output_file: continue # Skip .git directory to avoid massive useless outputs if ".git" in filepath.parts: continue # Calculate relative path for the header 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 content and add spacing before the next file out_f.write(content) # Ensure the file ends with a newline before next file if not content.endswith("\n"): out_f.write("\n") out_f.write("\n") except (OSError, UnicodeDecodeError) as e: out_f.write(f"[Error reading file: {e}]\n\n") print("Done!") except OSError 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()