diff --git a/format.sh b/format.sh index d567d79..0230092 100755 --- a/format.sh +++ b/format.sh @@ -3,6 +3,9 @@ ./check_iwyu.sh ./fix_iwyu_auto.sh +# Reorder includes to put corresponding header first +./reorder_includes.sh + find webserv -name "*.hpp" -o -name "*.cpp" | xargs sed -i -E 's/#include "(.*)"/#include <\1>/g' find webserv -name "*.cpp" -o -name "*.hpp" | xargs clang-format -i find webserv -name "*.hpp" -exec sh -c 'if ! grep -q "#pragma once" "$1"; then echo "Missing #pragma once in $1"; fi' _ {} \; \ No newline at end of file diff --git a/reorder_includes.sh b/reorder_includes.sh new file mode 100755 index 0000000..a3c268a --- /dev/null +++ b/reorder_includes.sh @@ -0,0 +1,88 @@ +#!/bin/bash + +# Script to reorder includes in .cpp files: +# 1. Move the corresponding .hpp include to the top of includes +# 2. Add a blank line after it (avoiding multiple blank lines) + +find webserv -name "*.cpp" | while read -r cpp_file; do + # Get the base name without extension (e.g., "Client" from "Client.cpp") + base_name=$(basename "$cpp_file" .cpp) + + # Use Python for reliable processing + python3 << EOF +import re +import sys + +cpp_file = "$cpp_file" +base_name = "$base_name" + +# Read the file +try: + with open(cpp_file, 'r') as f: + lines = f.readlines() +except Exception as e: + print(f"Error reading {cpp_file}: {e}") + sys.exit(1) + +# Find the corresponding header include pattern +header_pattern = re.compile(rf'#include <.*/{re.escape(base_name)}\.hpp>') +header_include_line = None + +# Look for the header include +for line in lines: + if header_pattern.search(line.strip()): + header_include_line = line + break + +if not header_include_line: + print(f"No corresponding header found for: {cpp_file}") + sys.exit(0) + +print(f"Processing: {cpp_file}") + +# Process the file +result_lines = [] +includes_started = False +header_added = False +last_line_was_empty = False + +for i, line in enumerate(lines): + stripped = line.strip() + is_empty_line = stripped == "" + + # Check if this is the start of includes section + if stripped.startswith('#include') and not includes_started: + includes_started = True + # Add the header include first (with blank line after) + if not header_added: + result_lines.append(header_include_line) + result_lines.append('\n') + header_added = True + last_line_was_empty = True + + # Skip the header include line (we already added it) + if stripped.startswith('#include') and header_pattern.search(stripped): + continue + + # Handle empty lines: avoid multiple consecutive empty lines + if is_empty_line: + if not last_line_was_empty: + result_lines.append(line) + last_line_was_empty = True + else: + result_lines.append(line) + last_line_was_empty = False + +# Write the result back +try: + with open(cpp_file, 'w') as f: + f.writelines(result_lines) +except Exception as e: + print(f"Error writing {cpp_file}: {e}") + sys.exit(1) + +EOF + +done + +echo "Include reordering complete!" \ No newline at end of file