I'll create a Python script that generates a text file with a file tree and contents of your desired text files. Here's a comprehensive solution:
import os
import pathlib
from typing import Set, List, Tuple
class CodeDocumentGenerator:
def __init__(self):
# Define file extensions we want to include
self.wanted_text_extensions = {
'.html', '.js', '.jsx', '.css', '.scss', '.sass', '.less',
'.ts', '.tsx', '.vue', '.svelte', '.astro', '.php',
'.py', '.java', '.c', '.cpp', '.h', '.hpp', '.cs',
'.rb', '.go', '.rs', '.swift', '.kt', '.dart',
'.sql', '.sh', '.bash', '.ps1', '.bat', '.cmd',
'.md', '.txt', '.json', '.xml', '.csv', '.env',
'.yml', '.yaml' # Include yaml but we'll filter specific files
}
# Define files to exclude by name
self.excluded_files = {
'.gitignore', '.dockerignore', '.eslintignore',
'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',
'composer.lock', 'Gemfile.lock', 'poetry.lock',
'.eslintrc.json', '.eslintrc.js', '.prettierrc',
'tsconfig.json', 'jsconfig.json', 'babel.config.js',
'webpack.config.js', 'vite.config.js', 'rollup.config.js'
}
# Define directories to exclude
self.excluded_dirs = {
'node_modules', '.git', '.vscode', '.idea', '__pycache__',
'dist', 'build', 'out', 'target', '.next', '.nuxt',
'coverage', '.pytest_cache', '.mypy_cache', 'venv',
'.venv', 'env', '.env', 'virtualenv', 'bower_components',
'vendor', 'tmp', 'temp', 'cache', '.cache', 'logs',
'.DS_Store', 'Thumbs.db', '.svn', '.hg'
}
# Binary file extensions to skip
self.binary_extensions = {
'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.webp',
'.svg', '.mp4', '.mp3', '.wav', '.avi', '.mov', '.mkv',
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
'.zip', '.rar', '.7z', '.tar', '.gz', '.exe', '.dll',
'.so', '.dylib', '.bin', '.dat', '.db', '.sqlite'
}
def should_include_file(self, filepath: str) -> bool:
"""Determine if a file should be included in the output."""
filename = os.path.basename(filepath)
extension = pathlib.Path(filepath).suffix.lower()
# Skip binary files
if extension in self.binary_extensions:
return False
# Skip excluded files by name
if filename in self.excluded_files:
return False
# Skip files without wanted extensions
if extension and extension not in self.wanted_text_extensions:
return False
# Special case for specific yaml files
if extension in ['.yml', '.yaml']:
excluded_yaml = {'docker-compose.yml', 'docker-compose.yaml', '.gitlab-ci.yml', '.travis.yml'}
if filename in excluded_yaml:
return False
return True
def should_include_dir(self, dirname: str) -> bool:
"""Determine if a directory should be traversed."""
return dirname not in self.excluded_dirs
def build_tree(self, directory: str, prefix: str = "", is_last: bool = True) -> Tuple[List[str], List[str]]:
"""Build directory tree and collect file paths."""
tree_lines = []
file_paths = []
try:
entries = sorted(os.listdir(directory))
except PermissionError:
return tree_lines, file_paths
# Filter entries
dirs = [e for e in entries if os.path.isdir(os.path.join(directory, e)) and self.should_include_dir(e)]
files = [e for e in entries if os.path.isfile(os.path.join(directory, e))]
# Process files first
for i, file in enumerate(files):
filepath = os.path.join(directory, file)
if self.should_include_file(filepath):
is_last_item = (i == len(files) - 1) and len(dirs) == 0
tree_lines.append(f"{prefix}{'└── ' if is_last_item else '├── '}{file}")
file_paths.append(filepath)
# Process directories
for i, dir_name in enumerate(dirs):
is_last_dir = i == len(dirs) - 1
tree_lines.append(f"{prefix}{'└── ' if is_last_dir else '├── '}{dir_name}")
# Recursively process subdirectory
sub_prefix = prefix + (" " if is_last_dir else "│ ")
sub_tree, sub_files = self.build_tree(os.path.join(directory, dir_name), sub_prefix, is_last_dir)
tree_lines.extend(sub_tree)
file_paths.extend(sub_files)
return tree_lines, file_paths
def read_file_content(self, filepath: str) -> str:
"""Read file content with proper encoding handling."""
encodings = ['utf-8', 'utf-8-sig', 'latin-1', 'cp1252']
for encoding in encodings:
try:
with open(filepath, 'r', encoding=encoding) as f:
return f.read()
except (UnicodeDecodeError, UnicodeError):
continue
return "[Error: Could not decode file]"
def generate_documentation(self, source_dir: str, output_file: str = "code_documentation.txt"):
"""Generate the documentation file."""
# Normalize path
source_dir = os.path.abspath(source_dir)
if not os.path.exists(source_dir):
print(f"Error: Directory '{source_dir}' does not exist.")
return
print(f"Scanning directory: {source_dir}")
# Build tree and collect files
tree_lines, file_paths = self.build_tree(source_dir)
# Generate output
with open(output_file, 'w', encoding='utf-8') as f:
# Write header
f.write("=" * 80 + "\n")
f.write("CODE DOCUMENTATION\n")
f.write("=" * 80 + "\n\n")
f.write(f"Source Directory: {source_dir}\n")
f.write(f"Generated: {os.path.basename(output_file)}\n")
f.write(f"Total Files: {len(file_paths)}\n\n")
# Write file tree
f.write("FILE TREE STRUCTURE\n")
f.write("-" * 80 + "\n\n")
f.write(os.path.basename(source_dir) + "\n")
for line in tree_lines:
f.write(line + "\n")
f.write("\n\n")
# Write file contents
f.write("FILE CONTENTS\n")
f.write("=" * 80 + "\n\n")
for filepath in file_paths:
relative_path = os.path.relpath(filepath, source_dir)
f.write("-" * 80 + "\n")
f.write(f"File: {relative_path}\n")
f.write("-" * 80 + "\n\n")
content = self.read_file_content(filepath)
f.write(content)
if not content.endswith('\n'):
f.write('\n')
f.write("\n\n")
print(f"Documentation generated: {output_file}")
print(f"Total files processed: {len(file_paths)}")
def main():
# Example usage
generator = CodeDocumentGenerator()
# Get source directory from user or use current directory
source_dir = input("Enter the source directory path (or press Enter for current directory): ").strip()
if not source_dir:
source_dir = os.getcwd()
# Get output file name
output_file = input("Enter output file name (or press Enter for 'code_documentation.txt'): ").strip()
if not output_file:
output_file = "code_documentation.txt"
# Generate documentation
generator.generate_documentation(source_dir, output_file)
if __name__ == "__main__":
main()