| import os
|
| import argparse
|
|
|
| def is_code_file(filename, extensions):
|
| """Check if file has a code extension"""
|
| return any(filename.lower().endswith(ext) for ext in extensions)
|
|
|
| def scan_and_combine_code_files(root_dir, output_file, extensions=None):
|
| """Scan directory and combine code files into one output file"""
|
|
|
| # Default code file extensions
|
| if extensions is None:
|
| extensions = [
|
| '.py', '.js', '.java', '.c', '.cpp', '.h', '.hpp',
|
| '.cs', '.php', '.rb', '.go', '.rs', '.ts',
|
| '.html', '.css', '.xml', '.json', '.yml', '.yaml',
|
| '.sql', '.sh', '.bat', '.ps1', '.md', '.txt'
|
| ]
|
|
|
| try:
|
| with open(output_file, 'w', encoding='utf-8') as outfile:
|
| for root, dirs, files in os.walk(root_dir):
|
| for file in files:
|
| if is_code_file(file, extensions):
|
| file_path = os.path.join(root, file)
|
| relative_path = os.path.relpath(file_path, root_dir)
|
|
|
| try:
|
| with open(file_path, 'r', encoding='utf-8') as infile:
|
| content = infile.read()
|
|
|
| # Write file header
|
| outfile.write(f"\n{'='*80}\n")
|
| outfile.write(f"FILE: {relative_path}\n")
|
| outfile.write(f"{'='*80}\n\n")
|
|
|
| # Write file content
|
| outfile.write(content)
|
|
|
| # Add some spacing between files
|
| outfile.write("\n\n")
|
|
|
| print(f"Processed: {relative_path}")
|
|
|
| except UnicodeDecodeError:
|
| print(f"Skipping binary file: {relative_path}")
|
| except Exception as e:
|
| print(f"Error reading {relative_path}: {e}")
|
|
|
| print(f"\nAll code files have been combined into: {output_file}")
|
|
|
| except Exception as e:
|
| print(f"Error creating output file: {e}")
|
|
|
| def main():
|
| parser = argparse.ArgumentParser(description='Combine code files from directory into single file')
|
| parser.add_argument('directory', help='Directory to scan for code files')
|
| parser.add_argument('-o', '--output', default='combined_code.txt',
|
| help='Output file name (default: combined_code.txt)')
|
| parser.add_argument('-e', '--extensions', nargs='+',
|
| help='Custom file extensions to include (space separated)')
|
|
|
| args = parser.parse_args()
|
|
|
| if not os.path.isdir(args.directory):
|
| print(f"Error: Directory '{args.directory}' does not exist.")
|
| return
|
|
|
| scan_and_combine_code_files(args.directory, args.output, args.extensions)
|
|
|
| if __name__ == "__main__":
|
| main()
|